@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/post-build.js CHANGED
@@ -7,25 +7,32 @@ var trailer_prefix = args[0];
7
7
  var output_prefix = args[1];
8
8
  var input_path = args[2];
9
9
 
10
- // remove this abort when adding to typescript is needed
10
+ // skipping the typescript file since it actually isn't written before the call to pipe:
11
+ // https://github.com/napi-rs/napi-rs/issues/1188
11
12
  if (input_path.endsWith('.d.ts')) {
12
13
  console.log("skipping .d.ts file: " + input_path);
13
14
  return;
14
15
  }
15
16
 
16
- console.log("trailer_prefix: '" + trailer_prefix + "' output_prefix: '" + output_prefix
17
- + "' input_path: '" + input_path + "'");
18
- path = require("path");
19
- input_filename = path.basename(input_path);
20
- input_suffix = input_filename.substring(input_filename.indexOf('.'), input_filename.length);
21
- output_filename = output_prefix + input_suffix
17
+ // run for .js and .d.ts
18
+ concat_files(trailer_prefix, output_prefix, input_path);
19
+ concat_files(trailer_prefix, output_prefix, input_path.replace(/\.js/, ".d.ts"));
22
20
 
23
- console.log("writing: " + output_filename);
24
- var fs = require('fs');
25
- // input to output
26
- var data = fs.readFileSync(input_path, 'utf8');
27
- fs.writeFileSync(output_filename, data, {encoding: 'utf8', flag: 'w'});
28
- // trailer to output
29
- data = fs.readFileSync(trailer_prefix + input_suffix, 'utf8');
30
- fs.writeFileSync(output_filename, data, {encoding: 'utf8', flag: 'a'});
31
- console.log("post-build complete");
21
+ function concat_files (trailer_prefix, output_prefix, input_path) {
22
+ console.log("trailer_prefix: '" + trailer_prefix + "' output_prefix: '" + output_prefix
23
+ + "' input_path: '" + input_path + "'");
24
+ path = require("path");
25
+ input_filename = path.basename(input_path);
26
+ input_suffix = input_filename.substring(input_filename.indexOf('.'), input_filename.length);
27
+ output_filename = output_prefix + input_suffix;
28
+
29
+ console.log("writing: " + output_filename);
30
+ var fs = require('fs');
31
+ // input to output
32
+ var data = fs.readFileSync(input_path, 'utf8');
33
+ fs.writeFileSync(output_filename, data, {encoding: 'utf8', flag: 'w'});
34
+ // trailer to output
35
+ data = fs.readFileSync(trailer_prefix + input_suffix, 'utf8');
36
+ fs.writeFileSync(output_filename, data, {encoding: 'utf8', flag: 'a'});
37
+ console.log("post-build complete");
38
+ }
@@ -0,0 +1,42 @@
1
+ // run with: node --trace-gc --expose-gc
2
+ if (typeof global.gc !== 'function') {
3
+ console.log("must run with '--expose-gc'");
4
+ process.exit();
5
+ };
6
+
7
+ const SegfaultHandler = require('../node_modules/segfault-handler');
8
+ SegfaultHandler.registerHandler('crash.log');
9
+
10
+ const http = require('http');
11
+ http.createServer(
12
+ function(req,res){res.writeHead(200);
13
+ res.write('Hello');
14
+ res.end();
15
+ } ).listen(8081);
16
+
17
+ var ngrok = require('..');
18
+ // turn on debug
19
+ ngrok.consoleLog();
20
+
21
+ new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect().then((session) => {
22
+ session.httpEndpoint().listen().then((tunnel) => {
23
+ tunnel.forwardTcp('localhost:8081').await;
24
+ console.log("tunnel: " + tunnel.url() + " id: " + tunnel.id());
25
+ setTimeout(function () {
26
+ console.log('\n\n=====> running gc');
27
+ global.gc();
28
+ }, 2000);
29
+
30
+ setTimeout(function () {
31
+ console.log('\n\n=====> closing and nulling tunnel');
32
+ tunnel.close().await;
33
+ tunnel = null;
34
+ }, 4000);
35
+
36
+ setTimeout(function () {
37
+ console.log('\n\n=====> running gc');
38
+ global.gc();
39
+ }, 6000);
40
+
41
+ });
42
+ }).await;
@@ -0,0 +1,47 @@
1
+ // run with: node --trace-gc --expose-gc
2
+ if (typeof global.gc !== 'function') {
3
+ console.log("must run with '--expose-gc'");
4
+ process.exit();
5
+ };
6
+
7
+ const SegfaultHandler = require('../node_modules/segfault-handler');
8
+ SegfaultHandler.registerHandler('crash.log');
9
+
10
+ const http = require('http');
11
+ http.createServer(
12
+ function(req,res){res.writeHead(200);
13
+ res.write('Hello');
14
+ res.end();
15
+ } ).listen(8081);
16
+
17
+ var ngrok = require('..');
18
+ // turn on debug
19
+ ngrok.consoleLog();
20
+
21
+ new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect().then((session) => {
22
+ session.httpEndpoint().listen().then((tunnel) => {
23
+ tunnel.forwardTcp('localhost:8081').await;
24
+ const tun_id = tunnel.id();
25
+ console.log("tunnel: " + tunnel.url() + " id: " + tun_id);
26
+ console.log('\n\n=====> nulling tunnel');
27
+ tunnel = null; // nodejs can gc
28
+
29
+ setTimeout(function () {
30
+ console.log('\n\n=====> running gc');
31
+ global.gc();
32
+ }, 2000);
33
+
34
+ setTimeout(function () {
35
+ console.log('\n\n=====> closing tunnel');
36
+ session.closeTunnel(tun_id).await;
37
+ }, 4000);
38
+
39
+ setTimeout(function () {
40
+ console.log('\n\n=====> nulling session, running gc');
41
+ session = null;
42
+ global.gc();
43
+ }, 6000);
44
+
45
+ });
46
+ }).await;
47
+
package/src/http.rs CHANGED
@@ -18,7 +18,8 @@ impl NgrokHttpTunnelBuilder {
18
18
  /// Defaults to [Scheme::HTTPS].
19
19
  #[napi]
20
20
  pub fn scheme(&mut self, scheme: String) -> &Self {
21
- self.tunnel_builder = self.tunnel_builder.clone().scheme(
21
+ let mut builder = self.tunnel_builder.lock();
22
+ *builder = builder.clone().scheme(
22
23
  Scheme::from_str(scheme.as_str())
23
24
  .unwrap_or_else(|_| panic!("Unknown scheme: {scheme:?}")),
24
25
  );
@@ -27,14 +28,15 @@ impl NgrokHttpTunnelBuilder {
27
28
  /// The domain to request for this edge.
28
29
  #[napi]
29
30
  pub fn domain(&mut self, domain: String) -> &Self {
30
- self.tunnel_builder = self.tunnel_builder.clone().domain(domain);
31
+ let mut builder = self.tunnel_builder.lock();
32
+ *builder = builder.clone().domain(domain);
31
33
  self
32
34
  }
33
35
  /// Certificates to use for client authentication at the ngrok edge.
34
36
  #[napi]
35
37
  pub fn mutual_tlsca(&mut self, mutual_tlsca: Uint8Array) -> &Self {
36
- self.tunnel_builder = self
37
- .tunnel_builder
38
+ let mut builder = self.tunnel_builder.lock();
39
+ *builder = builder
38
40
  .clone()
39
41
  .mutual_tlsca(Bytes::from(mutual_tlsca.to_vec()));
40
42
  self
@@ -42,45 +44,52 @@ impl NgrokHttpTunnelBuilder {
42
44
  /// Enable gzip compression for HTTP responses.
43
45
  #[napi]
44
46
  pub fn compression(&mut self) -> &Self {
45
- self.tunnel_builder = self.tunnel_builder.clone().compression();
47
+ let mut builder = self.tunnel_builder.lock();
48
+ *builder = builder.clone().compression();
46
49
  self
47
50
  }
48
51
  /// Convert incoming websocket connections to TCP-like streams.
49
52
  #[napi]
50
53
  pub fn websocket_tcp_conversion(&mut self) -> &Self {
51
- self.tunnel_builder = self.tunnel_builder.clone().websocket_tcp_conversion();
54
+ let mut builder = self.tunnel_builder.lock();
55
+ *builder = builder.clone().websocket_tcp_conversion();
52
56
  self
53
57
  }
54
58
  /// Reject requests when 5XX responses exceed this ratio.
55
59
  /// Disabled when 0.
56
60
  #[napi]
57
61
  pub fn circuit_breaker(&mut self, circuit_breaker: f64) -> &Self {
58
- self.tunnel_builder = self.tunnel_builder.clone().circuit_breaker(circuit_breaker);
62
+ let mut builder = self.tunnel_builder.lock();
63
+ *builder = builder.clone().circuit_breaker(circuit_breaker);
59
64
  self
60
65
  }
61
66
 
62
67
  /// with_request_header adds a header to all requests to this edge.
63
68
  #[napi]
64
69
  pub fn request_header(&mut self, name: String, value: String) -> &Self {
65
- self.tunnel_builder = self.tunnel_builder.clone().request_header(name, value);
70
+ let mut builder = self.tunnel_builder.lock();
71
+ *builder = builder.clone().request_header(name, value);
66
72
  self
67
73
  }
68
74
  /// with_response_header adds a header to all responses coming from this edge.
69
75
  #[napi]
70
76
  pub fn response_header(&mut self, name: String, value: String) -> &Self {
71
- self.tunnel_builder = self.tunnel_builder.clone().response_header(name, value);
77
+ let mut builder = self.tunnel_builder.lock();
78
+ *builder = builder.clone().response_header(name, value);
72
79
  self
73
80
  }
74
81
  /// with_remove_request_header removes a header from requests to this edge.
75
82
  #[napi]
76
83
  pub fn remove_request_header(&mut self, name: String) -> &Self {
77
- self.tunnel_builder = self.tunnel_builder.clone().remove_request_header(name);
84
+ let mut builder = self.tunnel_builder.lock();
85
+ *builder = builder.clone().remove_request_header(name);
78
86
  self
79
87
  }
80
88
  /// with_remove_response_header removes a header from responses from this edge.
81
89
  #[napi]
82
90
  pub fn remove_response_header(&mut self, name: String) -> &Self {
83
- self.tunnel_builder = self.tunnel_builder.clone().remove_response_header(name);
91
+ let mut builder = self.tunnel_builder.lock();
92
+ *builder = builder.clone().remove_response_header(name);
84
93
  self
85
94
  }
86
95
 
@@ -88,7 +97,8 @@ impl NgrokHttpTunnelBuilder {
88
97
  /// If not called, basic authentication is disabled.
89
98
  #[napi]
90
99
  pub fn basic_auth(&mut self, username: String, password: String) -> &Self {
91
- self.tunnel_builder = self.tunnel_builder.clone().basic_auth(username, password);
100
+ let mut builder = self.tunnel_builder.lock();
101
+ *builder = builder.clone().basic_auth(username, password);
92
102
  self
93
103
  }
94
104
 
@@ -98,22 +108,29 @@ impl NgrokHttpTunnelBuilder {
98
108
  pub fn oauth(
99
109
  &mut self,
100
110
  provider: String,
101
- allow_emails: Vec<String>,
102
- allow_domains: Vec<String>,
103
- scopes: Vec<String>,
111
+ allow_emails: Option<Vec<String>>,
112
+ allow_domains: Option<Vec<String>>,
113
+ scopes: Option<Vec<String>>,
104
114
  ) -> &Self {
105
115
  let mut oauth = OauthOptions::new(provider);
106
- allow_emails.iter().for_each(|v| {
107
- oauth = oauth.clone().allow_email(v);
108
- });
109
- allow_domains.iter().for_each(|v| {
110
- oauth = oauth.clone().allow_domain(v);
111
- });
112
- scopes.iter().for_each(|v| {
113
- oauth = oauth.clone().scope(v);
114
- });
116
+ if let Some(allow_emails) = allow_emails {
117
+ allow_emails.iter().for_each(|v| {
118
+ oauth = oauth.clone().allow_email(v);
119
+ });
120
+ }
121
+ if let Some(allow_domains) = allow_domains {
122
+ allow_domains.iter().for_each(|v| {
123
+ oauth = oauth.clone().allow_domain(v);
124
+ });
125
+ }
126
+ if let Some(scopes) = scopes {
127
+ scopes.iter().for_each(|v| {
128
+ oauth = oauth.clone().scope(v);
129
+ });
130
+ }
115
131
 
116
- self.tunnel_builder = self.tunnel_builder.clone().oauth(oauth);
132
+ let mut builder = self.tunnel_builder.lock();
133
+ *builder = builder.clone().oauth(oauth);
117
134
  self
118
135
  }
119
136
 
@@ -125,22 +142,29 @@ impl NgrokHttpTunnelBuilder {
125
142
  issuer_url: String,
126
143
  client_id: String,
127
144
  client_secret: String,
128
- allow_emails: Vec<String>,
129
- allow_domains: Vec<String>,
130
- scopes: Vec<String>,
145
+ allow_emails: Option<Vec<String>>,
146
+ allow_domains: Option<Vec<String>>,
147
+ scopes: Option<Vec<String>>,
131
148
  ) -> &Self {
132
149
  let mut oidc = OidcOptions::new(issuer_url, client_id, client_secret);
133
- allow_emails.iter().for_each(|v| {
134
- oidc = oidc.clone().allow_email(v);
135
- });
136
- allow_domains.iter().for_each(|v| {
137
- oidc = oidc.clone().allow_domain(v);
138
- });
139
- scopes.iter().for_each(|v| {
140
- oidc = oidc.clone().scope(v);
141
- });
150
+ if let Some(allow_emails) = allow_emails {
151
+ allow_emails.iter().for_each(|v| {
152
+ oidc = oidc.clone().allow_email(v);
153
+ });
154
+ }
155
+ if let Some(allow_domains) = allow_domains {
156
+ allow_domains.iter().for_each(|v| {
157
+ oidc = oidc.clone().allow_domain(v);
158
+ });
159
+ }
160
+ if let Some(scopes) = scopes {
161
+ scopes.iter().for_each(|v| {
162
+ oidc = oidc.clone().scope(v);
163
+ });
164
+ }
142
165
 
143
- self.tunnel_builder = self.tunnel_builder.clone().oidc(oidc);
166
+ let mut builder = self.tunnel_builder.lock();
167
+ *builder = builder.clone().oidc(oidc);
144
168
  self
145
169
  }
146
170
 
@@ -148,10 +172,8 @@ impl NgrokHttpTunnelBuilder {
148
172
  /// If not called, WebhookVerification is disabled.
149
173
  #[napi]
150
174
  pub fn webhook_verification(&mut self, provider: String, secret: String) -> &Self {
151
- self.tunnel_builder = self
152
- .tunnel_builder
153
- .clone()
154
- .webhook_verification(provider, secret);
175
+ let mut builder = self.tunnel_builder.lock();
176
+ *builder = builder.clone().webhook_verification(provider, secret);
155
177
  self
156
178
  }
157
179
  }
package/src/lib.rs CHANGED
@@ -1,6 +1,16 @@
1
+ use napi::{
2
+ Error,
3
+ Status,
4
+ };
5
+
1
6
  pub mod http;
7
+ pub mod logging;
2
8
  pub mod session;
3
9
  pub mod tcp;
4
10
  pub mod tls;
5
11
  pub mod tunnel;
6
12
  pub mod tunnel_builder;
13
+
14
+ pub(crate) fn napi_err(message: impl Into<String>) -> Error {
15
+ Error::new(Status::GenericFailure, message.into())
16
+ }
package/src/logging.rs ADDED
@@ -0,0 +1,134 @@
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(callback: Option<JsFunction>, level: Option<String>) -> Result<()> {
90
+ if callback.is_none() {
91
+ // clear out any registered callback
92
+ GLOBAL_DATA.lock().take();
93
+ return Ok(());
94
+ }
95
+
96
+ // create the threadsafe function wrapper
97
+ let tsfn: ThreadsafeFunction<Vec<String>, ErrorStrategy::Fatal> = callback
98
+ .unwrap()
99
+ .create_threadsafe_function(0, |ctx: ThreadSafeCallContext<Vec<String>>| {
100
+ Ok(ctx
101
+ .value
102
+ .iter()
103
+ .map(|s| ctx.env.create_string_from_std(s.clone()))
104
+ .collect())
105
+ })?;
106
+
107
+ // store the global callback
108
+ let _ = GLOBAL_DATA.lock().insert(tsfn);
109
+
110
+ let tracing_level = if let Some(level) = level {
111
+ match level.to_uppercase().as_str() {
112
+ "ERROR" => LevelFilter::ERROR,
113
+ "WARN" => LevelFilter::WARN,
114
+ "INFO" => LevelFilter::INFO,
115
+ "DEBUG" => LevelFilter::DEBUG,
116
+ "TRACE" => LevelFilter::TRACE,
117
+ _ => return Err(napi_err("Unknown log level: {level:?}")),
118
+ }
119
+ } else {
120
+ LevelFilter::INFO
121
+ };
122
+
123
+ if let Err(err) = tracing_subscriber::registry()
124
+ .with(CustomLayer)
125
+ .with(tracing_level)
126
+ .try_init()
127
+ {
128
+ if !err.to_string().contains("already been set") {
129
+ return Err(napi_err(format!("Failed to subscribe logger, {err:?}")));
130
+ }
131
+ }
132
+
133
+ Ok(())
134
+ }