@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/tunnel.rs CHANGED
@@ -32,7 +32,14 @@ lazy_static! {
32
32
  // tunnel references to be kept until explicit close to prevent nodejs gc from dropping them.
33
33
  // the tunnel wrapper object, and the underlying tunnel, both have references to the Session
34
34
  // so the Session is safe from premature dropping.
35
- static ref GLOBAL_TUNNELS: Mutex<HashMap<String,Arc<Mutex<dyn ExtendedTunnel>>>> = Mutex::new(HashMap::new());
35
+ static ref GLOBAL_TUNNELS: Mutex<HashMap<String,Arc<Storage>>> = Mutex::new(HashMap::new());
36
+ }
37
+
38
+ /// Stores the tunnel and session references to be kept until explicit close.
39
+ struct Storage {
40
+ tunnel: Arc<Mutex<dyn ExtendedTunnel>>,
41
+ session: Arc<Mutex<Session>>,
42
+ url: Option<String>,
36
43
  }
37
44
 
38
45
  /// The TunnelExt cannot be turned into an object since it contains generics, so implementing
@@ -70,7 +77,12 @@ macro_rules! make_tunnel_type {
70
77
  let proto = raw_tunnel.proto().to_string();
71
78
  info!("Created tunnel {id:?} with url {url:?}");
72
79
  // keep a tunnel reference until an explicit call to close to prevent nodejs gc dropping it
73
- GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Mutex::new(raw_tunnel)));
80
+ GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Storage {
81
+ tunnel: Arc::new(Mutex::new(raw_tunnel)),
82
+ session: Arc::new(Mutex::new(session.clone())),
83
+ url: Some(url.clone()),
84
+ }));
85
+ // create the user-facing object
74
86
  $wrapper {
75
87
  id,
76
88
  forwards_to,
@@ -120,7 +132,12 @@ macro_rules! make_tunnel_type {
120
132
  let labels = raw_tunnel.labels().clone();
121
133
  info!("Created tunnel {id:?} with labels {labels:?}");
122
134
  // keep a tunnel reference until an explicit call to close to prevent nodejs gc dropping it
123
- GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Mutex::new(raw_tunnel)));
135
+ GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Storage {
136
+ tunnel: Arc::new(Mutex::new(raw_tunnel)),
137
+ session: Arc::new(Mutex::new(session.clone())),
138
+ url: None,
139
+ }));
140
+ // create the user-facing object
124
141
  $wrapper {
125
142
  id,
126
143
  forwards_to,
@@ -179,23 +196,7 @@ macro_rules! make_tunnel_type {
179
196
  /// Forward incoming tunnel connections to the provided TCP address.
180
197
  #[napi]
181
198
  pub async fn forward_tcp(&self, addr: String) -> Result<()> {
182
- info!("Tunnel {:?} TCP forwarding to {addr:?}", &self.id);
183
- // we must clone the Arc before locking so we have a local reference
184
- // to the mutex to unlock if this struct is dropped.
185
- let arc = GLOBAL_TUNNELS.lock().await
186
- .get(&self.id)
187
- .ok_or(napi_err("Tunnel is no longer running"))?
188
- .clone(); // required clone
189
-
190
- // doing this as a seperate statement so the GLOBAL_TUNNELS lock is dropped
191
- let res = arc
192
- .lock()
193
- .await
194
- .fwd_tcp(addr)
195
- .await
196
- .map_err(|e| napi_err(format!("cannot forward tcp: {e:?}")));
197
- debug!("forward_tcp returning");
198
- res
199
+ forward_tcp(&self.id, addr).await
199
200
  }
200
201
 
201
202
  /// Forward incoming tunnel connections to the provided file socket path.
@@ -203,23 +204,7 @@ macro_rules! make_tunnel_type {
203
204
  /// On Windows addr can be a named pipe, e.e. "\\.\pipe\an_ngrok_pipe"
204
205
  #[napi]
205
206
  pub async fn forward_pipe(&self, addr: String) -> Result<()> {
206
- info!("Tunnel {:?} Pipe forwarding to {addr:?}", &self.id);
207
- // we must clone the Arc before locking so we have a local reference
208
- // to the mutex to unlock if this struct is dropped.
209
- let arc = GLOBAL_TUNNELS.lock().await
210
- .get(&self.id)
211
- .ok_or(napi_err("Tunnel is no longer running"))?
212
- .clone(); // required clone
213
-
214
- // doing this as a seperate statement so the GLOBAL_TUNNELS lock is dropped
215
- let res = arc
216
- .lock()
217
- .await
218
- .fwd_pipe(addr)
219
- .await
220
- .map_err(|e| napi_err(format!("cannot forward pipe: {e:?}")));
221
- debug!("forward_pipe returning");
222
- res
207
+ forward_pipe(&self.id, addr).await
223
208
  }
224
209
 
225
210
  /// Close the tunnel.
@@ -256,22 +241,105 @@ macro_rules! make_tunnel_type {
256
241
 
257
242
  make_tunnel_type! {
258
243
  /// An ngrok tunnel backing an HTTP endpoint.
244
+ ///
245
+ /// @group Tunnels
259
246
  NgrokHttpTunnel, HttpTunnel, common
260
247
  }
261
248
  make_tunnel_type! {
262
249
  /// An ngrok tunnel backing a TCP endpoint.
250
+ ///
251
+ /// @group Tunnels
263
252
  NgrokTcpTunnel, TcpTunnel, common
264
253
  }
265
254
  make_tunnel_type! {
266
255
  /// An ngrok tunnel bcking a TLS endpoint.
256
+ ///
257
+ /// @group Tunnels
267
258
  NgrokTlsTunnel, TlsTunnel, common
268
259
  }
269
260
  make_tunnel_type! {
270
261
  /// A labeled ngrok tunnel.
262
+ ///
263
+ /// @group Tunnels
271
264
  NgrokLabeledTunnel, LabeledTunnel, label
272
265
  }
273
266
 
267
+ pub async fn forward_tcp(id: &String, addr: String) -> Result<()> {
268
+ info!("Tunnel {id:?} TCP forwarding to {addr:?}");
269
+ let res = get_storage_by_id(id)
270
+ .await?
271
+ .tunnel
272
+ .lock()
273
+ .await
274
+ .fwd_tcp(addr)
275
+ .await
276
+ .map_err(|e| napi_err(format!("cannot forward tcp: {e:?}")));
277
+ debug!("forward_tcp returning");
278
+ res
279
+ }
280
+
281
+ pub async fn forward_pipe(id: &String, addr: String) -> Result<()> {
282
+ info!("Tunnel {id:?} Pipe forwarding to {addr:?}");
283
+ let res = get_storage_by_id(id)
284
+ .await?
285
+ .tunnel
286
+ .lock()
287
+ .await
288
+ .fwd_pipe(addr)
289
+ .await
290
+ .map_err(|e| napi_err(format!("cannot forward pipe: {e:?}")));
291
+ debug!("forward_pipe returning");
292
+ res
293
+ }
294
+
295
+ /// Delete any reference to the tunnel id
296
+ pub(crate) async fn get_url(id: &String) -> Option<String> {
297
+ GLOBAL_TUNNELS
298
+ .lock()
299
+ .await
300
+ .get(id)
301
+ .and_then(|s| s.url.clone())
302
+ }
303
+
304
+ async fn get_storage_by_id(id: &String) -> Result<Arc<Storage>> {
305
+ // we must clone the Arc before any locking so there is a local reference
306
+ // to the mutex to unlock if the tunnel wrapper struct is dropped.
307
+ Ok(GLOBAL_TUNNELS
308
+ .lock()
309
+ .await
310
+ .get(id)
311
+ .ok_or(napi_err("Tunnel is no longer running"))?
312
+ .clone()) // required clone
313
+ }
314
+
274
315
  /// Delete any reference to the tunnel id
275
316
  pub(crate) async fn remove_global_tunnel(id: &String) {
276
317
  GLOBAL_TUNNELS.lock().await.remove(id);
277
318
  }
319
+
320
+ /// Close a tunnel with the given url, or all tunnels if no url is defined.
321
+ pub(crate) async fn close_url(url: Option<String>) -> Result<()> {
322
+ let mut close_ids: Vec<String> = vec![];
323
+ let tunnels = GLOBAL_TUNNELS.lock().await;
324
+ for (id, storage) in tunnels.iter() {
325
+ debug!("tunnel: {}", id);
326
+ if url.as_ref().is_none() || url == storage.url {
327
+ debug!("closing tunnel: {}", id);
328
+ storage
329
+ .session
330
+ .lock()
331
+ .await
332
+ .close_tunnel(id)
333
+ .await
334
+ .map_err(|e| napi_err(format!("error closing tunnel: {e:?}")))?;
335
+ close_ids.push(id.clone());
336
+ }
337
+ }
338
+ drop(tunnels); // unlock GLOBAL_TUNNELS
339
+
340
+ // remove references entirely
341
+ for id in close_ids {
342
+ remove_global_tunnel(&id).await;
343
+ }
344
+ Ok(())
345
+ }
@@ -143,17 +143,25 @@ macro_rules! make_tunnel_builder {
143
143
 
144
144
  make_tunnel_builder! {
145
145
  /// An ngrok tunnel backing an HTTP endpoint.
146
+ ///
147
+ /// @group Tunnel Builders
146
148
  NgrokHttpTunnelBuilder, HttpTunnelBuilder, NgrokHttpTunnel, common
147
149
  }
148
150
  make_tunnel_builder! {
149
151
  /// An ngrok tunnel backing a TCP endpoint.
152
+ ///
153
+ /// @group Tunnel Builders
150
154
  NgrokTcpTunnelBuilder, TcpTunnelBuilder, NgrokTcpTunnel, common
151
155
  }
152
156
  make_tunnel_builder! {
153
157
  /// An ngrok tunnel backing a TLS endpoint.
158
+ ///
159
+ /// @group Tunnel Builders
154
160
  NgrokTlsTunnelBuilder, TlsTunnelBuilder, NgrokTlsTunnel, common
155
161
  }
156
162
  make_tunnel_builder! {
157
163
  /// A labeled ngrok tunnel.
164
+ ///
165
+ /// @group Tunnel Builders
158
166
  NgrokLabeledTunnelBuilder, LabeledTunnelBuilder, NgrokLabeledTunnel, label
159
167
  }
package/trailer.d.ts CHANGED
@@ -1,9 +1,14 @@
1
1
  /** Generate, or convert a given tunnel, into one that can be passed into net.Server.listen(). */
2
- export function listenable(tunnel?: (NgrokHttpTunnel|NgrokTcpTunnel|NgrokTlsTunnel|NgrokLabeledTunnel)): (NgrokHttpTunnel|NgrokTcpTunnel|NgrokTlsTunnel|NgrokLabeledTunnel)
2
+ export function listenable(
3
+ tunnel?: NgrokHttpTunnel | NgrokTcpTunnel | NgrokTlsTunnel | NgrokLabeledTunnel
4
+ ): NgrokHttpTunnel | NgrokTcpTunnel | NgrokTlsTunnel | NgrokLabeledTunnel;
3
5
  /** Start the given net.Server listening to a generated, or passed in, tunnel. */
4
- export function listen(server: import("net").Server, tunnel?: (NgrokHttpTunnel|NgrokTcpTunnel|NgrokTlsTunnel|NgrokLabeledTunnel)): (NgrokHttpTunnel|NgrokTcpTunnel|NgrokTlsTunnel|NgrokLabeledTunnel)
5
- /**
6
+ export function listen(
7
+ server: import("net").Server,
8
+ tunnel?: NgrokHttpTunnel | NgrokTcpTunnel | NgrokTlsTunnel | NgrokLabeledTunnel
9
+ ): NgrokHttpTunnel | NgrokTcpTunnel | NgrokTlsTunnel | NgrokLabeledTunnel;
10
+ /**
6
11
  * Register a console.log callback for ngrok INFO logging.
7
12
  * Optionally set the logging level to one of ERROR, WARN, INFO, DEBUG, or TRACE.
8
13
  */
9
- export function consoleLog(level?: String)
14
+ export function consoleLog(level?: String);
package/trailer.js CHANGED
@@ -2,9 +2,9 @@
2
2
  // javascript trailer
3
3
  //
4
4
 
5
- const net = require('net');
6
- const fs = require('fs');
7
- const os = require('os');
5
+ const net = require("net");
6
+ const fs = require("fs");
7
+ const os = require("os");
8
8
 
9
9
  // wrap listen with the bind code for passing to net.Server.listen()
10
10
  NgrokHttpTunnelBuilder.prototype._listen = NgrokHttpTunnelBuilder.prototype.listen;
@@ -18,7 +18,7 @@ NgrokTlsTunnelBuilder.prototype.listen = ngrokBind;
18
18
  NgrokLabeledTunnelBuilder.prototype.listen = ngrokBind;
19
19
 
20
20
  // Begin listening for new connections on this tunnel,
21
- // and bind to a local socket so this tunnel can be
21
+ // and bind to a local socket so this tunnel can be
22
22
  // passed into net.Server.listen().
23
23
  async function ngrokBind(bind) {
24
24
  const tunnel = await this._listen();
@@ -35,30 +35,31 @@ async function ngrokBind(bind) {
35
35
  function defineTunnelHandle(tunnel, socket) {
36
36
  // NodeJS net.Server asks passed-in object for 'handle',
37
37
  // Return the native TCP object so the pre-existing socket is used.
38
- Object.defineProperty( tunnel, 'handle', {
39
- get: function() {
38
+ Object.defineProperty(tunnel, "handle", {
39
+ get: function () {
40
40
  // turn on forwarding now that it has been requested
41
- tunnel.forwardTcp('localhost:' + socket.address().port);
41
+ tunnel.forwardTcp("localhost:" + socket.address().port);
42
42
  return socket._handle;
43
- }
43
+ },
44
44
  });
45
45
  }
46
46
 
47
47
  // generate a net.Server listening to a random port
48
48
  async function randomTcpSocket() {
49
- return await asyncListen(new net.Server(), {host:'localhost', port:0});
49
+ return await asyncListen(new net.Server(), { host: "localhost", port: 0 });
50
50
  }
51
51
 
52
52
  // NodeJS has not promisified 'net': https://github.com/nodejs/node/issues/21482
53
53
  function asyncListen(server, options) {
54
54
  return new Promise((resolve, reject) => {
55
55
  const socket = server.listen(options);
56
- socket.once('listening', () => {
57
- resolve(socket);
58
- })
59
- .once('error', (err) => {
60
- reject(err);
61
- });
56
+ socket
57
+ .once("listening", () => {
58
+ resolve(socket);
59
+ })
60
+ .once("error", (err) => {
61
+ reject(err);
62
+ });
62
63
  });
63
64
  }
64
65
 
@@ -110,16 +111,16 @@ async function ngrokListen(server, tunnel) {
110
111
 
111
112
  async function ngrokLinkTcp(tunnel, server) {
112
113
  // random local port
113
- const socket = await asyncListen(server, {host:'localhost', port:0});
114
+ const socket = await asyncListen(server, { host: "localhost", port: 0 });
114
115
  // forward to socket
115
- tunnel.forwardTcp('localhost:' + socket.address().port);
116
+ tunnel.forwardTcp("localhost:" + socket.address().port);
116
117
  return socket;
117
118
  }
118
119
 
119
120
  async function ngrokLinkPipe(tunnel, server) {
120
121
  var proposed = "tun-" + tunnel.id() + ".sock";
121
- if (platform == 'win32') {
122
- proposed = '\\\\.\\pipe\\' + proposed;
122
+ if (platform == "win32") {
123
+ proposed = "\\\\.\\pipe\\" + proposed;
123
124
  }
124
125
  var filename;
125
126
  try {
@@ -137,10 +138,10 @@ async function ngrokLinkPipe(tunnel, server) {
137
138
  }
138
139
 
139
140
  // begin listening
140
- const socket = await asyncListen(server, {path: filename});
141
+ const socket = await asyncListen(server, { path: filename });
141
142
  // tighten permissions
142
143
  try {
143
- if (platform != 'win32') {
144
+ if (platform != "win32") {
144
145
  fs.chmodSync(filename, fs.constants.S_IRWXU);
145
146
  }
146
147
  } catch (err) {
@@ -154,21 +155,21 @@ async function ngrokLinkPipe(tunnel, server) {
154
155
  }
155
156
 
156
157
  function registerCleanup(tunnel, socket) {
157
- process.on('SIGINT', function() {
158
- if (process.listenerCount('SIGINT') > 1) {
158
+ process.on("SIGINT", function () {
159
+ if (process.listenerCount("SIGINT") > 1) {
159
160
  // user has registered a handler, abort this one
160
161
  return;
161
162
  }
162
163
  // close tunnel
163
164
  if (tunnel) {
164
- tunnel.close().then(()=>{
165
- console.debug('ngrok closed tunnel: ' + tunnel.id());
165
+ tunnel.close().then(() => {
166
+ console.debug("ngrok closed tunnel: " + tunnel.id());
166
167
  });
167
168
  }
168
169
  // close webserver's socket
169
170
  if (socket) {
170
171
  socket.close(function () {
171
- console.debug('ngrok closed socket');
172
+ console.debug("ngrok closed socket");
172
173
  });
173
174
  }
174
175
  // unregister any logging callback
@@ -182,6 +183,117 @@ function consoleLog(level) {
182
183
  }, level);
183
184
  }
184
185
 
185
- module.exports.listenable = listenable;
186
- module.exports.listen = ngrokListen;
186
+ // wrap connect with code to vectorize and split out functions
187
+ const _connect = connect;
188
+ async function ngrokConnect(config) {
189
+ if (Number.isInteger(config) || typeof config === "string" || config instanceof String) {
190
+ address = String(config);
191
+ if (!address.includes(":")) {
192
+ address = `localhost:${address}`;
193
+ }
194
+ config = { addr: address };
195
+ }
196
+ // Convert addr to string to allow for numeric port numbers
197
+ const addr = config["addr"];
198
+ if (Number.isInteger(addr)) config["addr"] = "localhost:" + String(config["addr"]);
199
+ // convert scalar values to arrays to meet what napi-rs expects
200
+ [
201
+ "auth",
202
+ "basic_auth",
203
+ "ip_restriction.allow_cidrs",
204
+ "ip_restriction.deny_cidrs",
205
+ "labels",
206
+ "oauth.allow_domains",
207
+ "oauth.allow_emails",
208
+ "oauth.scopes",
209
+ "oidc.scopes",
210
+ "oidc.allow_domains",
211
+ "oidc.allow_emails",
212
+ "request_header.add",
213
+ "request_header.remove",
214
+ "response_header.add",
215
+ "response_header.remove",
216
+ "schemes",
217
+ ].forEach((key) => {
218
+ vectorize(config, key);
219
+ });
220
+ // convert dotted values to underscores for backwards compatibility
221
+ [
222
+ "ip_restriction.allow_cidrs",
223
+ "ip_restriction.deny_cidrs",
224
+ "oauth.allow_domains",
225
+ "oauth.allow_emails",
226
+ "oauth.scopes",
227
+ "oauth.provider",
228
+ "oidc.client_id",
229
+ "oidc.client_secret",
230
+ "oidc.scopes",
231
+ "oidc.issuer_url",
232
+ "oidc.allow_domains",
233
+ "oidc.allow_emails",
234
+ "request_header.add",
235
+ "request_header.remove",
236
+ "response_header.add",
237
+ "response_header.remove",
238
+ "verify_webhook.provider",
239
+ "verify_webhook.secret",
240
+ ].forEach((key) => {
241
+ undot(config, key);
242
+ });
243
+ // break out the logging callback function to meet what napi-rs expects
244
+ var on_log_event;
245
+ if (config["onLogEvent"]) {
246
+ const onLogEvent = config.onLogEvent;
247
+ on_log_event = (level, target, message) => {
248
+ onLogEvent(`${level} ${target} - ${message}`);
249
+ };
250
+ config["onLogEvent"] = true;
251
+ }
252
+ // break out the status change callback functions to what napi-rs expects
253
+ var on_connection, on_disconnection;
254
+ if (config["onStatusChange"]) {
255
+ const onStatusChange = config.onStatusChange;
256
+ on_connection = (status, err) => {
257
+ onStatusChange(status);
258
+ };
259
+ on_disconnection = (addr, err) => {
260
+ onStatusChange("closed");
261
+ };
262
+ config["onStatusChange"] = true;
263
+ }
264
+ // call into rust
265
+ return await _connect(config, on_log_event, on_connection, on_disconnection);
266
+ }
267
+
268
+ function undot(config, dotKey) {
269
+ const noDotKey = dotKey.replace(".", "_");
270
+ if (config[dotKey] == null) return; // no dotKey value, done
271
+ if (config[noDotKey] == null) {
272
+ // nothing at destination, just set and be done
273
+ config[noDotKey] = config[dotKey];
274
+ return;
275
+ }
276
+ if (config[dotKey] instanceof Array && config[noDotKey] instanceof Array) {
277
+ // merge arrays
278
+ for (const obj of config[dotKey]) {
279
+ config[noDotKey].push(obj);
280
+ }
281
+ }
282
+ // destination exists and is not an array, do nothing so noDotKey can take precedence
283
+ }
284
+
285
+ function vectorize(config, key) {
286
+ // backwards compatible keys are passed in, check the new style as well
287
+ const noDotKey = key.replace(".", "_");
288
+ if (key != noDotKey) vectorize(config, noDotKey);
289
+
290
+ if (config[key] == null) return; // no value, done
291
+ if (!(config[key] instanceof Array)) {
292
+ config[key] = [config[key]];
293
+ }
294
+ }
295
+
296
+ module.exports.connect = ngrokConnect;
187
297
  module.exports.consoleLog = consoleLog;
298
+ module.exports.listen = ngrokListen;
299
+ module.exports.listenable = listenable;
@@ -1,11 +0,0 @@
1
- const express = require('express')
2
- const ngrok = require('@ngrok/ngrok')
3
- const app = express()
4
-
5
- app.get('/', (req, res) => {
6
- res.send('Hello World!')
7
- })
8
-
9
- ngrok.listen(app).then(() => {
10
- console.log("established tunnel at: " + app.tunnel.url());
11
- });
@@ -1,26 +0,0 @@
1
- const express = require('express')
2
- const ngrok = require('@ngrok/ngrok')
3
- const app = express()
4
-
5
- app.get('/', (req, res) => {
6
- res.send('Hello World!')
7
- })
8
-
9
- async function setup() {
10
- // create session
11
- const session = await new ngrok.NgrokSessionBuilder()
12
- .authtokenFromEnv()
13
- .metadata("Online in One Line")
14
- .connect();
15
- // create tunnel
16
- const tunnel = await session.httpEndpoint()
17
- .allowCidr("0.0.0.0/0")
18
- .oauth("google")
19
- .requestHeader("X-Req-Yup", "true")
20
- .listen();
21
- console.log("tunnel established at: " + tunnel.url());
22
- // link tunnel to app
23
- ngrok.listen(app, tunnel)
24
- }
25
-
26
- setup();