@ngrok/ngrok 0.9.0 → 1.0.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 (146) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/CONTRIBUTING.md +4 -4
  3. package/README.md +176 -142
  4. package/index.d.ts +75 -15
  5. package/index.js +8 -6
  6. package/package.json +37 -16
  7. package/.envrc +0 -1
  8. package/.gitattributes +0 -3
  9. package/.prettierrc.json +0 -3
  10. package/.yarnrc.yml +0 -3
  11. package/Cargo.toml +0 -34
  12. package/RELEASE.md +0 -26
  13. package/build.rs +0 -5
  14. package/docs/.nojekyll +0 -1
  15. package/docs/assets/highlight.css +0 -92
  16. package/docs/assets/main.js +0 -58
  17. package/docs/assets/search.js +0 -1
  18. package/docs/assets/style.css +0 -1367
  19. package/docs/classes/HttpListenerBuilder.html +0 -594
  20. package/docs/classes/LabeledListenerBuilder.html +0 -206
  21. package/docs/classes/Listener.html +0 -241
  22. package/docs/classes/Session.html +0 -207
  23. package/docs/classes/SessionBuilder.html +0 -465
  24. package/docs/classes/TcpListenerBuilder.html +0 -281
  25. package/docs/classes/TlsListenerBuilder.html +0 -322
  26. package/docs/classes/UpdateRequest.html +0 -131
  27. package/docs/functions/authtoken.html +0 -89
  28. package/docs/functions/connect.html +0 -89
  29. package/docs/functions/consoleLog.html +0 -90
  30. package/docs/functions/disconnect.html +0 -89
  31. package/docs/functions/getListener.html +0 -89
  32. package/docs/functions/getListenerByUrl.html +0 -89
  33. package/docs/functions/kill.html +0 -84
  34. package/docs/functions/listen.html +0 -92
  35. package/docs/functions/listenable.html +0 -85
  36. package/docs/functions/listeners.html +0 -84
  37. package/docs/functions/loggingCallback.html +0 -108
  38. package/docs/index.html +0 -292
  39. package/docs/interfaces/Config.html +0 -734
  40. package/docs/modules.html +0 -106
  41. package/examples/domain.crt +0 -18
  42. package/examples/domain.key +0 -27
  43. package/examples/express/ngrok-express-quickstart.js +0 -11
  44. package/examples/express/ngrok-express.js +0 -28
  45. package/examples/express/package.json +0 -7
  46. package/examples/fastify/ngrok-fastify.js +0 -26
  47. package/examples/fastify/package.json +0 -7
  48. package/examples/hapi/ngrok-hapi.js +0 -35
  49. package/examples/hapi/package.json +0 -7
  50. package/examples/koa/ngrok-koa.js +0 -12
  51. package/examples/koa/package.json +0 -7
  52. package/examples/nestjs/.eslintrc.js +0 -25
  53. package/examples/nestjs/.prettierrc +0 -4
  54. package/examples/nestjs/README.md +0 -73
  55. package/examples/nestjs/nest-cli.json +0 -8
  56. package/examples/nestjs/package.json +0 -70
  57. package/examples/nestjs/src/app.controller.spec.ts +0 -22
  58. package/examples/nestjs/src/app.controller.ts +0 -12
  59. package/examples/nestjs/src/app.module.ts +0 -10
  60. package/examples/nestjs/src/app.service.ts +0 -8
  61. package/examples/nestjs/src/main.ts +0 -17
  62. package/examples/nestjs/test/app.e2e-spec.ts +0 -24
  63. package/examples/nestjs/test/jest-e2e.json +0 -9
  64. package/examples/nestjs/tsconfig.build.json +0 -4
  65. package/examples/nestjs/tsconfig.json +0 -21
  66. package/examples/nextjs/README.md +0 -3
  67. package/examples/nextjs/next.config.js +0 -12
  68. package/examples/nextjs/ngrok.config.js +0 -23
  69. package/examples/nextjs/package.json +0 -6
  70. package/examples/nextjs/pages/index.js +0 -5
  71. package/examples/ngrok-connect-full.js +0 -67
  72. package/examples/ngrok-connect-minimal.js +0 -17
  73. package/examples/ngrok-http-full.js +0 -81
  74. package/examples/ngrok-http-minimum.js +0 -18
  75. package/examples/ngrok-labeled.js +0 -43
  76. package/examples/ngrok-listen.js +0 -11
  77. package/examples/ngrok-tcp.js +0 -37
  78. package/examples/ngrok-tls.js +0 -40
  79. package/examples/ngrok-typescript.ts +0 -69
  80. package/examples/ngrok-windows-pipe.js +0 -25
  81. package/examples/ngrok-winston.js +0 -24
  82. package/examples/package.json +0 -15
  83. package/examples/remix/.eslintrc.js +0 -4
  84. package/examples/remix/README.md +0 -53
  85. package/examples/remix/app/entry.client.tsx +0 -18
  86. package/examples/remix/app/entry.server.tsx +0 -101
  87. package/examples/remix/app/root.tsx +0 -20
  88. package/examples/remix/app/routes/_index.tsx +0 -30
  89. package/examples/remix/ngrok.config.js +0 -16
  90. package/examples/remix/package.json +0 -30
  91. package/examples/remix/public/favicon.ico +0 -0
  92. package/examples/remix/remix.config.js +0 -16
  93. package/examples/remix/remix.env.d.ts +0 -2
  94. package/examples/remix/tsconfig.json +0 -22
  95. package/examples/svelte/README.md +0 -38
  96. package/examples/svelte/jsconfig.json +0 -17
  97. package/examples/svelte/ngrok.config.cjs +0 -20
  98. package/examples/svelte/package.json +0 -22
  99. package/examples/svelte/src/app.d.ts +0 -12
  100. package/examples/svelte/src/app.html +0 -12
  101. package/examples/svelte/src/routes/+page.svelte +0 -2
  102. package/examples/svelte/static/favicon.png +0 -0
  103. package/examples/svelte/svelte.config.js +0 -14
  104. package/examples/svelte/vite.config.js +0 -6
  105. package/examples/vue/.vscode/extensions.json +0 -3
  106. package/examples/vue/README.md +0 -40
  107. package/examples/vue/env.d.ts +0 -1
  108. package/examples/vue/index.html +0 -13
  109. package/examples/vue/ngrok.config.ts +0 -18
  110. package/examples/vue/package.json +0 -25
  111. package/examples/vue/public/favicon.ico +0 -0
  112. package/examples/vue/src/App.vue +0 -47
  113. package/examples/vue/src/assets/base.css +0 -74
  114. package/examples/vue/src/assets/logo.svg +0 -1
  115. package/examples/vue/src/assets/main.css +0 -35
  116. package/examples/vue/src/components/HelloWorld.vue +0 -40
  117. package/examples/vue/src/components/TheWelcome.vue +0 -86
  118. package/examples/vue/src/components/WelcomeItem.vue +0 -86
  119. package/examples/vue/src/components/icons/IconCommunity.vue +0 -7
  120. package/examples/vue/src/components/icons/IconDocumentation.vue +0 -7
  121. package/examples/vue/src/components/icons/IconEcosystem.vue +0 -7
  122. package/examples/vue/src/components/icons/IconSupport.vue +0 -7
  123. package/examples/vue/src/components/icons/IconTooling.vue +0 -19
  124. package/examples/vue/src/main.ts +0 -6
  125. package/examples/vue/tsconfig.json +0 -16
  126. package/examples/vue/tsconfig.node.json +0 -8
  127. package/examples/vue/vite.config.ts +0 -15
  128. package/flake.lock +0 -82
  129. package/flake.nix +0 -111
  130. package/post-build.js +0 -45
  131. package/scripts/gc-node-drop.js +0 -49
  132. package/scripts/gc-rust-drop.js +0 -53
  133. package/src/config.rs +0 -285
  134. package/src/connect.rs +0 -342
  135. package/src/http.rs +0 -244
  136. package/src/lib.rs +0 -39
  137. package/src/listener.rs +0 -495
  138. package/src/listener_builder.rs +0 -204
  139. package/src/logging.rs +0 -140
  140. package/src/session.rs +0 -551
  141. package/src/tcp.rs +0 -18
  142. package/src/tls.rs +0 -44
  143. package/trailer.d.ts +0 -15
  144. package/trailer.js +0 -382
  145. package/tsconfig.json +0 -8
  146. package/typedoc.json +0 -3
package/src/logging.rs DELETED
@@ -1,140 +0,0 @@
1
- use lazy_static::lazy_static;
2
- use napi::{
3
- bindgen_prelude::*,
4
- threadsafe_function::{
5
- ErrorStrategy,
6
- ThreadSafeCallContext,
7
- ThreadsafeFunction,
8
- ThreadsafeFunctionCallMode,
9
- },
10
- };
11
- use napi_derive::napi;
12
- use parking_lot::Mutex;
13
- use tracing::metadata::LevelFilter;
14
- use tracing_subscriber::{
15
- prelude::*,
16
- Layer,
17
- };
18
-
19
- use crate::napi_err;
20
-
21
- // keep a reference to the javascript logging callback function.
22
- // uses synchronous parking_lot mutex to avoid needing napi Env, and encourage maintaining log sequence.
23
- lazy_static! {
24
- static ref GLOBAL_DATA: Mutex<Option<ThreadsafeFunction<Vec<String>, ErrorStrategy::Fatal>>> =
25
- Mutex::new(None);
26
- }
27
-
28
- /// tracing subscriber layer to plumb events to javascript
29
- struct CustomLayer;
30
-
31
- impl<S> Layer<S> for CustomLayer
32
- where
33
- S: tracing::Subscriber,
34
- {
35
- fn on_event(
36
- &self,
37
- event: &tracing::Event<'_>,
38
- _ctx: tracing_subscriber::layer::Context<'_, S>,
39
- ) {
40
- let mut visitor = EventVisitor {
41
- ..Default::default()
42
- };
43
- event.record(&mut visitor);
44
- if let Err(err) = log_to_callback(
45
- event.metadata().level().to_string(),
46
- event.metadata().target().to_string(),
47
- visitor.message,
48
- ) {
49
- println!("Error logging to javascript function: {err:?}");
50
- }
51
- }
52
- }
53
-
54
- /// Visitor to record the message from the event record
55
- #[derive(Default)]
56
- struct EventVisitor {
57
- message: String,
58
- }
59
-
60
- impl tracing::field::Visit for EventVisitor {
61
- // everything currently used comes through as a fmt debug
62
- fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
63
- if field.name() == "message" {
64
- self.message = format!("{value:?}");
65
- }
66
- }
67
- }
68
-
69
- /// Send the strings to the javascript callback, if one is registered
70
- pub fn log_to_callback(level: String, target: String, message: String) -> Result<()> {
71
- if let Some(tsfn) = GLOBAL_DATA.lock().as_ref() {
72
- let status = tsfn.call(
73
- vec![level, target, message],
74
- ThreadsafeFunctionCallMode::NonBlocking,
75
- );
76
- if status != Status::Ok {
77
- return Err(napi_err(status.to_string()));
78
- }
79
- }
80
- Ok(())
81
- }
82
-
83
- /// Register a callback function that will receive logging event information.
84
- /// An absent callback will unregister an existing callback function.
85
- /// The log level defaults to INFO, it can be set to one of ERROR, WARN, INFO, DEBUG, or TRACE.
86
- #[napi(
87
- ts_args_type = "callback?: (level: string, target: string, message: string) => void, level?: string"
88
- )]
89
- pub fn logging_callback(
90
- env: Env,
91
- callback: Option<JsFunction>,
92
- level: Option<String>,
93
- ) -> Result<()> {
94
- if callback.is_none() {
95
- // clear out any registered callback
96
- GLOBAL_DATA.lock().take();
97
- return Ok(());
98
- }
99
-
100
- // create the threadsafe function wrapper
101
- let mut tsfn: ThreadsafeFunction<Vec<String>, ErrorStrategy::Fatal> = callback
102
- .unwrap()
103
- .create_threadsafe_function(0, |ctx: ThreadSafeCallContext<Vec<String>>| {
104
- Ok(ctx
105
- .value
106
- .iter()
107
- .map(|s| ctx.env.create_string_from_std(s.clone()))
108
- .collect())
109
- })?;
110
- // tell the runtime it can exit while this callback exists
111
- tsfn.unref(&env)?;
112
-
113
- // store the global callback
114
- let _ = GLOBAL_DATA.lock().insert(tsfn);
115
-
116
- let tracing_level = if let Some(level) = level {
117
- match level.to_uppercase().as_str() {
118
- "ERROR" => LevelFilter::ERROR,
119
- "WARN" => LevelFilter::WARN,
120
- "INFO" => LevelFilter::INFO,
121
- "DEBUG" => LevelFilter::DEBUG,
122
- "TRACE" => LevelFilter::TRACE,
123
- _ => return Err(napi_err("Unknown log level: {level:?}")),
124
- }
125
- } else {
126
- LevelFilter::INFO
127
- };
128
-
129
- if let Err(err) = tracing_subscriber::registry()
130
- .with(CustomLayer)
131
- .with(tracing_level)
132
- .try_init()
133
- {
134
- if !err.to_string().contains("already been set") {
135
- return Err(napi_err(format!("Failed to subscribe logger, {err:?}")));
136
- }
137
- }
138
-
139
- Ok(())
140
- }
package/src/session.rs DELETED
@@ -1,551 +0,0 @@
1
- use std::{
2
- env,
3
- sync::Arc,
4
- time::Duration,
5
- };
6
-
7
- use async_rustls::rustls::ClientConfig;
8
- use bytes::Bytes;
9
- use lazy_static::lazy_static;
10
- use napi::{
11
- bindgen_prelude::*,
12
- threadsafe_function::{
13
- ErrorStrategy,
14
- ThreadSafeCallContext,
15
- ThreadsafeFunction,
16
- ThreadsafeFunctionCallMode,
17
- },
18
- };
19
- use napi_derive::napi;
20
- use ngrok::{
21
- session::{
22
- default_connect,
23
- ConnectError,
24
- SessionBuilder as NgrokSessionBuilder,
25
- Update,
26
- },
27
- tunnel::AcceptError,
28
- Session as NgrokSession,
29
- };
30
- use parking_lot::Mutex as SyncMutex;
31
- use tokio::sync::Mutex;
32
- use tracing::{
33
- debug,
34
- info,
35
- };
36
-
37
- use crate::{
38
- listener::{
39
- remove_global_listener,
40
- search_listeners,
41
- Listener,
42
- },
43
- listener_builder::{
44
- HttpListenerBuilder,
45
- LabeledListenerBuilder,
46
- TcpListenerBuilder,
47
- TlsListenerBuilder,
48
- },
49
- napi_err,
50
- napi_ngrok_err,
51
- };
52
-
53
- const CLIENT_TYPE: &str = "ngrok-nodejs";
54
- const VERSION: &str = env!("CARGO_PKG_VERSION");
55
-
56
- // appease clippy
57
- type TsfnOption = Option<Arc<Mutex<ThreadsafeFunction<Vec<String>, ErrorStrategy::Fatal>>>>;
58
-
59
- lazy_static! {
60
- // Allow user to store a default auth token to use for all sessions
61
- static ref AUTH_TOKEN: Mutex<Option<String>> = Mutex::new(None);
62
- }
63
-
64
- /// Set the default auth token to use for any future sessions.
65
- #[napi]
66
- #[allow(dead_code)]
67
- pub async fn authtoken(authtoken: String) {
68
- let mut token = AUTH_TOKEN.lock().await;
69
- token.replace(authtoken);
70
- }
71
-
72
- /// The builder for an ngrok session.
73
- ///
74
- /// @group Listener and Sessions
75
- #[napi]
76
- #[allow(dead_code)]
77
- #[derive(Default)]
78
- pub(crate) struct SessionBuilder {
79
- raw_builder: Arc<SyncMutex<NgrokSessionBuilder>>,
80
- connect_handler: TsfnOption,
81
- disconnect_handler: TsfnOption,
82
- auth_token_set: bool,
83
- }
84
-
85
- #[napi]
86
- #[cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))]
87
- #[allow(dead_code)]
88
- impl SessionBuilder {
89
- /// Create a new session builder
90
- #[napi(constructor)]
91
- pub fn new() -> Self {
92
- SessionBuilder {
93
- raw_builder: Arc::new(SyncMutex::new(
94
- NgrokSession::builder()
95
- .client_info(CLIENT_TYPE, VERSION, None::<String>)
96
- .clone(),
97
- )),
98
- ..Default::default()
99
- }
100
- }
101
-
102
- /// Configures the session to authenticate with the provided authtoken. You
103
- /// can [find your existing authtoken] or [create a new one] in the ngrok
104
- /// dashboard.
105
- ///
106
- /// See the [authtoken parameter in the ngrok docs] for additional details.
107
- ///
108
- /// [find your existing authtoken]: https://dashboard.ngrok.com/get-started/your-authtoken
109
- /// [create a new one]: https://dashboard.ngrok.com/tunnels/authtokens
110
- /// [authtoken parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#authtoken
111
- #[napi]
112
- pub fn authtoken(&mut self, authtoken: String) -> &Self {
113
- let mut builder = self.raw_builder.lock();
114
- builder.authtoken(authtoken);
115
- self.auth_token_set = true;
116
- self
117
- }
118
-
119
- /// Shortcut for calling [SessionBuilder::authtoken] with the value of the
120
- /// NGROK_AUTHTOKEN environment variable.
121
- #[napi]
122
- pub fn authtoken_from_env(&mut self) -> &Self {
123
- let mut builder = self.raw_builder.lock();
124
- builder.authtoken_from_env();
125
- if let Ok(token) = env::var("NGROK_AUTHTOKEN") {
126
- if !token.is_empty() {
127
- self.auth_token_set = true;
128
- }
129
- }
130
- self
131
- }
132
-
133
- /// Add client type and version information for a client application.
134
- ///
135
- /// This is a way for applications and library consumers of this crate
136
- /// identify themselves.
137
- ///
138
- /// This will add a new entry to the `User-Agent` field in the "most significant"
139
- /// (first) position. Comments must follow [RFC 7230] or a connection error may occur.
140
- ///
141
- /// [RFC 7230]: https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6
142
- #[napi]
143
- pub fn client_info(
144
- &mut self,
145
- client_type: String,
146
- version: String,
147
- comments: Option<String>,
148
- ) -> &Self {
149
- let mut builder = self.raw_builder.lock();
150
- builder.client_info(client_type, version, comments);
151
- self
152
- }
153
-
154
- /// Configures how often the session will send heartbeat messages to the ngrok
155
- /// service to check session liveness.
156
- ///
157
- /// See the [heartbeat_interval parameter in the ngrok docs] for additional
158
- /// details.
159
- ///
160
- /// [heartbeat_interval parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#heartbeat_interval
161
- #[napi]
162
- pub fn heartbeat_interval(&mut self, heartbeat_interval: u32) -> Result<&Self> {
163
- let mut builder = self.raw_builder.lock();
164
- builder
165
- .heartbeat_interval(Duration::new(heartbeat_interval.into(), 0))
166
- .map_err(|e| napi_err(format!("{e}")))?;
167
- Ok(self)
168
- }
169
-
170
- /// Configures the duration to wait for a response to a heartbeat before
171
- /// assuming the session connection is dead and attempting to reconnect.
172
- ///
173
- /// See the [heartbeat_tolerance parameter in the ngrok docs] for additional
174
- /// details.
175
- ///
176
- /// [heartbeat_tolerance parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#heartbeat_tolerance
177
- #[napi]
178
- pub fn heartbeat_tolerance(&mut self, heartbeat_tolerance: u32) -> Result<&Self> {
179
- let mut builder = self.raw_builder.lock();
180
- builder
181
- .heartbeat_tolerance(Duration::new(heartbeat_tolerance.into(), 0))
182
- .map_err(|e| napi_err(format!("{e}")))?;
183
- Ok(self)
184
- }
185
-
186
- /// Configures the opaque, machine-readable metadata string for this session.
187
- /// Metadata is made available to you in the ngrok dashboard and the Agents API
188
- /// resource. It is a useful way to allow you to uniquely identify sessions. We
189
- /// suggest encoding the value in a structured format like JSON.
190
- ///
191
- /// See the [metdata parameter in the ngrok docs] for additional details.
192
- ///
193
- /// [metdata parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#metadata
194
- #[napi]
195
- pub fn metadata(&mut self, metadata: String) -> &Self {
196
- let mut builder = self.raw_builder.lock();
197
- builder.metadata(metadata);
198
- self
199
- }
200
-
201
- /// Configures the network address to dial to connect to the ngrok service.
202
- /// Use this option only if you are connecting to a custom agent ingress.
203
- ///
204
- /// See the [server_addr parameter in the ngrok docs] for additional details.
205
- ///
206
- /// [server_addr parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#server_addr
207
- #[napi]
208
- pub fn server_addr(&mut self, addr: String) -> Result<&Self> {
209
- let mut builder = self.raw_builder.lock();
210
- builder
211
- .server_addr(addr)
212
- .map_err(|e| napi_err(format!("{e}")))?;
213
- Ok(self)
214
- }
215
-
216
- /// Configures the TLS certificate used to connect to the ngrok service while
217
- /// establishing the session. Use this option only if you are connecting through
218
- /// a man-in-the-middle or deep packet inspection proxy. Pass in the bytes of the certificate
219
- /// to be used to validate the connection, then override the address to connect to via
220
- /// the server_addr call.
221
- ///
222
- /// Roughly corresponds to the [root_cas parameter in the ngrok docs].
223
- ///
224
- /// [root_cas parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#root_cas
225
- #[napi]
226
- pub fn ca_cert(&mut self, cert_bytes: Uint8Array) -> &Self {
227
- let mut builder = self.raw_builder.lock();
228
- builder.ca_cert(Bytes::from(cert_bytes.to_vec()));
229
- self
230
- }
231
-
232
- /// Configures a function which is called to after a disconnection to the
233
- /// ngrok service. In the event of network disruptions, it will be called each time
234
- /// the session reconnects. The handler is given the address that will be used to
235
- /// connect the session to, e.g. "example.com:443", and the message from the error
236
- /// that occurred. Returning true from the handler will cause the session to
237
- /// reconnect, returning false will cause the Session to throw an uncaught error.
238
- #[napi(ts_args_type = "handler: (addr: string, error: string) => boolean")]
239
- pub fn handle_disconnection(&mut self, env: Env, handler: JsFunction) -> &Self {
240
- // create threadsafe function
241
- let tsfn = create_tsfn(env, handler);
242
- self.disconnect_handler = Some(tsfn);
243
- self.update_connector()
244
- }
245
-
246
- pub fn handle_connection(&mut self, env: Env, handler: JsFunction) -> &Self {
247
- // create threadsafe function
248
- let tsfn = create_tsfn(env, handler);
249
- self.connect_handler = Some(tsfn);
250
- self.update_connector()
251
- }
252
-
253
- /// Update the connector callback in the upstream rust sdk.
254
- fn update_connector(&mut self) -> &Self {
255
- // register connect handler. this needs the return value, so cannot use call_tsfn().
256
- let mut builder = self.raw_builder.lock();
257
- // clone for move to connector function
258
- let connect_handler = self.connect_handler.clone();
259
- let disconnect_handler = self.disconnect_handler.clone();
260
- builder.connector(
261
- move |host: String,
262
- port: u16,
263
- tls_config: Arc<ClientConfig>,
264
- err: Option<AcceptError>| {
265
- // clone for async move out of environment
266
- let conn_tsfn = connect_handler.clone();
267
- let disconn_tsfn = disconnect_handler.clone();
268
- async move {
269
- // call disconnect javascript handler
270
- if let Some(handler) = disconn_tsfn {
271
- if let Some(err) = err.clone() {
272
- // call javascript handler
273
- let resp: Option<bool> = handler
274
- .clone()
275
- .lock()
276
- .await
277
- .call_async(vec![format!("{host}:{port}"), err.to_string()])
278
- .await
279
- .map_err(|_e| ConnectError::Canceled)?;
280
-
281
- if let Some(reconnect) = resp {
282
- if !reconnect {
283
- info!("Aborting connection to {host}:{port}");
284
- println!("Aborting connection to {host}:{port}"); // still shown if this takes down the process
285
- return Err(ConnectError::Canceled);
286
- }
287
- }
288
- };
289
- }
290
- // call the upstream connector
291
- let res = default_connect(host, port, tls_config, err).await;
292
-
293
- // call connect handler
294
- if let Some(handler) = conn_tsfn {
295
- let args = match &res {
296
- Ok(_) => vec!["connected".to_string()],
297
- Err(err) => vec!["closed".to_string(), err.to_string()],
298
- };
299
- // call javascript handler
300
- handler
301
- .clone()
302
- .lock()
303
- .await
304
- .call_async(args)
305
- .await
306
- .map_err(|_e| ConnectError::Canceled)?;
307
- }
308
- res
309
- }
310
- },
311
- );
312
- self
313
- }
314
-
315
- /// Configures a function which is called when the ngrok service requests that
316
- /// this [Session] stops. Your application may choose to interpret this callback
317
- /// as a request to terminate the [Session] or the entire process.
318
- ///
319
- /// Errors returned by this function will be visible to the ngrok dashboard or
320
- /// API as the response to the Stop operation.
321
- ///
322
- /// Do not block inside this callback. It will cause the Dashboard or API
323
- /// stop operation to time out. Do not call [std::process::exit] inside this
324
- /// callback, it will also cause the operation to time out.
325
- #[napi(ts_args_type = "handler: () => void")]
326
- pub fn handle_stop_command(&mut self, env: Env, handler: JsFunction) -> &Self {
327
- // create threadsafe function
328
- let tsfn = create_tsfn(env, handler);
329
- // register stop handler
330
- let mut builder = self.raw_builder.lock();
331
- builder.handle_stop_command(move |_req| call_tsfn(tsfn.clone(), vec![()]));
332
- self
333
- }
334
-
335
- /// Configures a function which is called when the ngrok service requests
336
- /// that this [Session] updates. Your application may choose to interpret
337
- /// this callback as a request to restart the [Session] or the entire
338
- /// process.
339
- ///
340
- /// Errors returned by this function will be visible to the ngrok dashboard or
341
- /// API as the response to the Restart operation.
342
- ///
343
- /// Do not block inside this callback. It will cause the Dashboard or API
344
- /// stop operation to time out. Do not call [std::process::exit] inside this
345
- /// callback, it will also cause the operation to time out.
346
- #[napi(ts_args_type = "handler: () => void")]
347
- pub fn handle_restart_command(&mut self, env: Env, handler: JsFunction) -> &Self {
348
- // create threadsafe function
349
- let tsfn = create_tsfn(env, handler);
350
- // register restart handler
351
- let mut builder = self.raw_builder.lock();
352
- builder.handle_restart_command(move |_req| call_tsfn(tsfn.clone(), vec![()]));
353
- self
354
- }
355
-
356
- /// Configures a function which is called when the ngrok service requests
357
- /// that this [Session] updates. Your application may choose to interpret
358
- /// this callback as a request to update its configuration, itself, or to
359
- /// invoke some other application-specific behavior.
360
- ///
361
- /// Errors returned by this function will be visible to the ngrok dashboard or
362
- /// API as the response to the Restart operation.
363
- ///
364
- /// Do not block inside this callback. It will cause the Dashboard or API
365
- /// stop operation to time out. Do not call [std::process::exit] inside this
366
- /// callback, it will also cause the operation to time out.
367
- #[napi(ts_args_type = "handler: (update: UpdateRequest) => void")]
368
- pub fn handle_update_command(&mut self, env: Env, handler: JsFunction) -> &Self {
369
- // create threadsafe function
370
- let tsfn = create_tsfn(env, handler);
371
- // register update handler
372
- let mut builder = self.raw_builder.lock();
373
- builder.handle_update_command(move |req: Update| {
374
- let update = UpdateRequest {
375
- version: req.version,
376
- permit_major_version: req.permit_major_version,
377
- };
378
- call_tsfn(tsfn.clone(), vec![update])
379
- });
380
- self
381
- }
382
-
383
- /// Call the provided handler whenever a heartbeat response is received,
384
- /// with the latency in milliseconds.
385
- ///
386
- /// If the handler returns an error, the heartbeat task will exit, resulting
387
- /// in the session eventually dying as well.
388
- #[napi(ts_args_type = "handler: (latency: number) => void")]
389
- pub fn handle_heartbeat(&mut self, env: Env, handler: JsFunction) -> &Self {
390
- // create threadsafe function
391
- let tsfn = create_tsfn(env, handler);
392
-
393
- // register heartbeat handler
394
- let mut builder = self.raw_builder.lock();
395
- builder.handle_heartbeat(move |latency: Option<Duration>| {
396
- call_tsfn(
397
- tsfn.clone(),
398
- vec![latency.map(|d| u32::try_from(d.as_millis()).ok())],
399
- )
400
- });
401
- self
402
- }
403
-
404
- /// Attempt to establish an ngrok session using the current configuration.
405
- #[napi]
406
- pub async fn connect(&self) -> Result<Session> {
407
- let mut builder = self.raw_builder.lock().clone();
408
- // set default auth token if it exists
409
- let default_auth_token = AUTH_TOKEN.lock().await;
410
- let mut auth_token_set = self.auth_token_set;
411
- if default_auth_token.is_some() && !self.auth_token_set {
412
- builder.authtoken(default_auth_token.as_ref().unwrap());
413
- auth_token_set = true;
414
- }
415
- // connect to ngrok
416
- builder
417
- .connect()
418
- .await
419
- .map(|s| {
420
- let maybe_with = if auth_token_set { "with" } else { "without" };
421
- info!("Session created {:?}, {maybe_with} auth token", s.id());
422
- Session {
423
- raw_session: Arc::new(SyncMutex::new(s)),
424
- }
425
- })
426
- .map_err(|e| napi_ngrok_err("failed to connect session", &e))
427
- }
428
- }
429
-
430
- /// An ngrok session.
431
- ///
432
- /// @group Listener and Sessions
433
- #[napi(custom_finalize)]
434
- pub(crate) struct Session {
435
- #[allow(dead_code)]
436
- raw_session: Arc<SyncMutex<NgrokSession>>,
437
- }
438
-
439
- #[napi]
440
- #[allow(dead_code)]
441
- impl Session {
442
- /// Start building a listener backing an HTTP endpoint.
443
- #[napi]
444
- pub fn http_endpoint(&self) -> HttpListenerBuilder {
445
- let session = self.raw_session.lock().clone();
446
- HttpListenerBuilder::new(session.clone(), session.http_endpoint())
447
- }
448
-
449
- /// Start building a listener backing a TCP endpoint.
450
- #[napi]
451
- pub fn tcp_endpoint(&self) -> TcpListenerBuilder {
452
- let session = self.raw_session.lock().clone();
453
- TcpListenerBuilder::new(session.clone(), session.tcp_endpoint())
454
- }
455
-
456
- /// Start building a listener backing a TLS endpoint.
457
- #[napi]
458
- pub fn tls_endpoint(&self) -> TlsListenerBuilder {
459
- let session = self.raw_session.lock().clone();
460
- TlsListenerBuilder::new(session.clone(), session.tls_endpoint())
461
- }
462
-
463
- /// Start building a labeled listener.
464
- #[napi]
465
- pub fn labeled_listener(&self) -> LabeledListenerBuilder {
466
- let session = self.raw_session.lock().clone();
467
- LabeledListenerBuilder::new(session.clone(), session.labeled_tunnel())
468
- }
469
-
470
- /// Retrieve a list of this session's non-closed listeners, in no particular order.
471
- #[napi]
472
- pub async fn listeners(&self) -> Vec<Listener> {
473
- let session_id = self.raw_session.lock().id();
474
- search_listeners(Some(session_id), None).await
475
- }
476
-
477
- /// Close a listener with the given ID.
478
- #[napi]
479
- pub async fn close_listener(&self, id: String) -> Result<()> {
480
- let session = self.raw_session.lock().clone();
481
- // close listener
482
- let res = session
483
- .close_tunnel(id.clone())
484
- .await
485
- .map_err(|e| napi_ngrok_err("failed to close listener", &e));
486
-
487
- if res.is_ok() {
488
- // remove our reference to allow it to drop
489
- remove_global_listener(&id).await;
490
- }
491
- res
492
- }
493
-
494
- /// Close the ngrok session.
495
- #[napi]
496
- pub async fn close(&self) -> Result<()> {
497
- let mut session = self.raw_session.lock().clone();
498
- session
499
- .close()
500
- .await
501
- .map_err(|e| napi_ngrok_err("failed to close session", &e))
502
- }
503
- }
504
-
505
- impl ObjectFinalize for Session {
506
- fn finalize(self, mut _env: Env) -> Result<()> {
507
- debug!("Session finalize");
508
- Ok(())
509
- }
510
- }
511
-
512
- /// Container for UpdateRequest information.
513
- #[derive(Clone)]
514
- #[napi]
515
- pub struct UpdateRequest {
516
- /// The version that the agent is requested to update to.
517
- pub version: String,
518
- /// Whether or not updating to the same major version is sufficient.
519
- pub permit_major_version: bool,
520
- }
521
-
522
- pub(crate) fn create_tsfn<A>(
523
- env: Env,
524
- handler: JsFunction,
525
- ) -> Arc<Mutex<ThreadsafeFunction<Vec<A>, ErrorStrategy::Fatal>>>
526
- where
527
- A: ToNapiValue,
528
- {
529
- Arc::new(Mutex::new({
530
- let mut tsfn = handler
531
- .create_threadsafe_function(0, |ctx: ThreadSafeCallContext<Vec<A>>| Ok(ctx.value))
532
- .expect("Failed to create update callback function");
533
- // tell the runtime it can exit while this callback exists
534
- tsfn.unref(&env).expect("Failed to unref callback function");
535
- tsfn
536
- }))
537
- }
538
-
539
- /// Call a threadsafe function that has the given argument type and no return value.
540
- pub(crate) async fn call_tsfn<A, E>(
541
- tsfn: Arc<Mutex<ThreadsafeFunction<A, ErrorStrategy::Fatal>>>,
542
- arg: A,
543
- ) -> core::result::Result<(), E>
544
- where
545
- A: ToNapiValue,
546
- {
547
- tsfn.lock()
548
- .await
549
- .call(arg, ThreadsafeFunctionCallMode::NonBlocking);
550
- Ok(())
551
- }