@ngrok/ngrok 0.5.2 → 0.6.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 (55) hide show
  1. package/CHANGELOG.md +36 -28
  2. package/CODE_OF_CONDUCT.md +45 -0
  3. package/Cargo.toml +5 -2
  4. package/README.md +161 -21
  5. package/docs/assets/highlight.css +13 -6
  6. package/docs/assets/search.js +1 -1
  7. package/docs/classes/NgrokHttpTunnelBuilder.html +25 -22
  8. package/docs/classes/NgrokLabeledTunnelBuilder.html +8 -5
  9. package/docs/classes/NgrokSession.html +24 -9
  10. package/docs/classes/NgrokSessionBuilder.html +20 -17
  11. package/docs/classes/NgrokTcpTunnelBuilder.html +12 -9
  12. package/docs/classes/NgrokTlsTunnelBuilder.html +14 -11
  13. package/docs/classes/NgrokTunnel.html +21 -35
  14. package/docs/classes/UpdateRequest.html +7 -4
  15. package/docs/functions/authtoken.html +5 -2
  16. package/docs/functions/connect.html +5 -2
  17. package/docs/functions/consoleLog.html +5 -2
  18. package/docs/functions/disconnect.html +5 -2
  19. package/docs/functions/getTunnel.html +88 -0
  20. package/docs/functions/getTunnelByUrl.html +88 -0
  21. package/docs/functions/kill.html +5 -2
  22. package/docs/functions/listen.html +5 -2
  23. package/docs/functions/listenable.html +5 -2
  24. package/docs/functions/loggingCallback.html +5 -2
  25. package/docs/functions/tunnels.html +83 -0
  26. package/docs/index.html +74 -13
  27. package/docs/interfaces/Config.html +57 -54
  28. package/docs/modules.html +7 -1
  29. package/examples/fastify/ngrok-fastify.js +1 -1
  30. package/examples/hapi/ngrok-hapi.js +1 -1
  31. package/examples/nestjs/src/main.ts +1 -1
  32. package/examples/nextjs/ngrok.config.js +1 -1
  33. package/examples/ngrok-connect-full.js +22 -23
  34. package/examples/ngrok-connect-minimal.js +3 -2
  35. package/examples/ngrok-http-full.js +1 -1
  36. package/examples/ngrok-http-minimum.js +1 -1
  37. package/examples/ngrok-labeled.js +1 -1
  38. package/examples/ngrok-tcp.js +1 -1
  39. package/examples/ngrok-tls.js +1 -1
  40. package/examples/ngrok-typescript.ts +1 -1
  41. package/examples/ngrok-windows-pipe.js +1 -1
  42. package/examples/remix/ngrok.config.js +1 -1
  43. package/examples/svelte/ngrok.config.cjs +1 -1
  44. package/examples/vue/ngrok.config.ts +1 -1
  45. package/index.d.ts +12 -6
  46. package/index.js +89 -23
  47. package/package.json +14 -14
  48. package/scripts/gc-node-drop.js +1 -1
  49. package/scripts/gc-rust-drop.js +1 -1
  50. package/src/connect.rs +13 -8
  51. package/src/lib.rs +21 -0
  52. package/src/session.rs +17 -6
  53. package/src/tunnel.rs +139 -104
  54. package/src/tunnel_builder.rs +2 -2
  55. package/trailer.js +85 -22
package/docs/modules.html CHANGED
@@ -35,10 +35,13 @@
35
35
  <a href="functions/connect.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>connect</span></a>
36
36
  <a href="functions/consoleLog.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>console<wbr/>Log</span></a>
37
37
  <a href="functions/disconnect.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>disconnect</span></a>
38
+ <a href="functions/getTunnel.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>get<wbr/>Tunnel</span></a>
39
+ <a href="functions/getTunnelByUrl.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>get<wbr/>Tunnel<wbr/>By<wbr/>Url</span></a>
38
40
  <a href="functions/kill.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>kill</span></a>
39
41
  <a href="functions/listen.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>listen</span></a>
40
42
  <a href="functions/listenable.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>listenable</span></a>
41
43
  <a href="functions/loggingCallback.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>logging<wbr/>Callback</span></a>
44
+ <a href="functions/tunnels.html" class="tsd-index-link"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>tunnels</span></a>
42
45
  </div></section>
43
46
  <section class="tsd-index-section">
44
47
  <h3 class="tsd-index-heading">Classes</h3>
@@ -86,10 +89,13 @@
86
89
  <li><a href="functions/connect.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>connect</span></a></li>
87
90
  <li><a href="functions/consoleLog.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>console<wbr/>Log</span></a></li>
88
91
  <li><a href="functions/disconnect.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>disconnect</span></a></li>
92
+ <li><a href="functions/getTunnel.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>get<wbr/>Tunnel</span></a></li>
93
+ <li><a href="functions/getTunnelByUrl.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>get<wbr/>Tunnel<wbr/>By<wbr/>Url</span></a></li>
89
94
  <li><a href="functions/kill.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>kill</span></a></li>
90
95
  <li><a href="functions/listen.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>listen</span></a></li>
91
96
  <li><a href="functions/listenable.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>listenable</span></a></li>
92
- <li><a href="functions/loggingCallback.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>logging<wbr/>Callback</span></a></li></ul></div></details></li>
97
+ <li><a href="functions/loggingCallback.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>logging<wbr/>Callback</span></a></li>
98
+ <li><a href="functions/tunnels.html"><svg class="tsd-kind-icon" width="24" height="24" viewBox="0 0 24 24"><use href="#icon-64-path"></use><use href="#icon-64-text"></use></svg><span>tunnels</span></a></li></ul></div></details></li>
93
99
  <li>
94
100
  <details class="tsd-index-accordion" data-key="Classes"><summary class="tsd-accordion-summary"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M4.93896 8.531L12 15.591L19.061 8.531L16.939 6.409L12 11.349L7.06098 6.409L4.93896 8.531Z" fill="var(--color-text)"></path></svg><span>Classes</span></summary>
95
101
  <div class="tsd-accordion-details">
@@ -16,7 +16,7 @@ const start = async () => {
16
16
  // Establish ingress
17
17
  const session = await new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect();
18
18
  const tunnel = await session.httpEndpoint().listen();
19
- tunnel.forwardTcp(`localhost:${port}`);
19
+ tunnel.forward(`localhost:${port}`);
20
20
  fastify.log.info(`Ingress established at: ${tunnel.url()}`);
21
21
  } catch (err) {
22
22
  fastify.log.error(err);
@@ -24,7 +24,7 @@ const init = async () => {
24
24
  const session = await new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect();
25
25
  const tunnel = await session.httpEndpoint().listen();
26
26
  console.log(`Ingress established at: ${tunnel.url()}`);
27
- tunnel.forwardTcp(`localhost:${port}`);
27
+ tunnel.forward(`localhost:${port}`);
28
28
  };
29
29
 
30
30
  process.on("unhandledRejection", (err) => {
@@ -12,6 +12,6 @@ async function bootstrap() {
12
12
  const session = await new NgrokSessionBuilder().authtokenFromEnv().connect();
13
13
  const tunnel = await session.httpEndpoint().listen();
14
14
  new Logger('main').log(`Ingress established at ${tunnel.url()}`);
15
- tunnel.forwardTcp(`localhost:${port}`);
15
+ tunnel.forward(`localhost:${port}`);
16
16
  }
17
17
  bootstrap();
@@ -17,7 +17,7 @@ async function setup() {
17
17
  const session = await new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect();
18
18
  const tunnel = await session.httpEndpoint().listen();
19
19
  console.log(`Forwarding to: ${host}:${port} from ingress at: ${tunnel.url()}`);
20
- tunnel.forwardTcp(`${host}:${port}`);
20
+ tunnel.forward(`${host}:${port}`);
21
21
  }
22
22
 
23
23
  if (makeTunnel) setup();
@@ -19,8 +19,8 @@ console.log(`Node.js web server at ${UNIX_SOCKET} is running..`);
19
19
  const ngrok = require("@ngrok/ngrok");
20
20
  ngrok.consoleLog("INFO"); // turn on info logging
21
21
 
22
- ngrok
23
- .connect({
22
+ (async function () {
23
+ const url = await ngrok.connect({
24
24
  // session configuration
25
25
  addr: `pipe:${UNIX_SOCKET}`,
26
26
  // addr: `localhost:8080`,
@@ -35,30 +35,29 @@ ngrok
35
35
  circuit_breaker: 0.1,
36
36
  compression: true,
37
37
  // domain: "<domain>",
38
- "ip_restriction.allow_cidrs": ["0.0.0.0/0"],
39
- "ip_restriction.deny_cidrs": ["10.1.1.1/32"],
38
+ ip_restriction_allow_cidrs: ["0.0.0.0/0"],
39
+ ip_restriction_deny_cidrs: ["10.1.1.1/32"],
40
40
  metadata: "example tunnel metadata from nodejs",
41
41
  // mutual_tls_cas: [fs.readFileSync('ca.crt', 'utf8')],
42
- // "oauth.provider": "google",
43
- // "oauth.allow_domains": ["<domain>"],
44
- // "oauth.allow_emails": ["<email>"],
45
- // "oauth.scopes": ["<scope>"],
46
- // "oidc.issuer_url": "<url>",
47
- // "oidc.client_id": "<id>",
48
- // "oidc.client_secret": "<secret>",
49
- // "oidc.allow_domains": ["<domain>"],
50
- // "oidc.allow_emails": ["<email>"],
51
- // "oidc.scopes": ["<scope>"],
42
+ // oauth_provider: "google",
43
+ // oauth_allow_domains: ["<domain>"],
44
+ // oauth_allow_emails: ["<email>"],
45
+ // oauth_scopes: ["<scope>"],
46
+ // oidc_issuer_url: "<url>",
47
+ // oidc_client_id: "<id>",
48
+ // oidc_client_secret: "<secret>",
49
+ // oidc_allow_domains: ["<domain>"],
50
+ // oidc_allow_emails: ["<email>"],
51
+ // oidc_scopes": ["<scope>"],
52
52
  proxy_proto: "", // One of: "", "1", "2"
53
- "request_header.remove": ["X-Req-Nope"],
54
- "response_header.remove": ["X-Res-Nope"],
55
- "request_header.add": ["X-Req-Yup:true"],
56
- "response_header.add": ["X-Res-Yup:true"],
53
+ request_header_remove: ["X-Req-Nope"],
54
+ response_header_remove: ["X-Res-Nope"],
55
+ request_header_add: ["X-Req-Yup:true"],
56
+ response_header_add: ["X-Res-Yup:true"],
57
57
  schemes: ["HTTPS"],
58
- // "verify_webhook.provider": "twilio",
59
- // "verify_webhook.secret": "asdf",
58
+ // verify_webhook_provider: "twilio",
59
+ // verify_webhook_secret: "asdf",
60
60
  // websocket_tcp_converter: true,
61
- })
62
- .then((url) => {
63
- console.log(`Ingress established at: ${url}`);
64
61
  });
62
+ console.log(`Ingress established at: ${url}`);
63
+ })();
@@ -11,6 +11,7 @@ console.log(`Node.js web server at 8080 is running..`);
11
11
 
12
12
  // setup ngrok
13
13
  const ngrok = require("@ngrok/ngrok");
14
- ngrok.connect({ addr: 8080, authtoken_from_env: true }).then((url) => {
14
+ (async function () {
15
+ const url = await ngrok.connect({ addr: 8080, authtoken_from_env: true });
15
16
  console.log(`Ingress established at: ${url}`);
16
- });
17
+ })();
@@ -73,6 +73,6 @@ builder.connect().then((session) => {
73
73
  .listen()
74
74
  .then((tunnel) => {
75
75
  console.log("Ingress established at:", tunnel.url());
76
- tunnel.forwardPipe(UNIX_SOCKET);
76
+ tunnel.forward(UNIX_SOCKET);
77
77
  });
78
78
  });
@@ -13,6 +13,6 @@ async function create_tunnel() {
13
13
  const session = await new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect();
14
14
  const tunnel = await session.httpEndpoint().listen();
15
15
  console.log("Ingress established at:", tunnel.url());
16
- tunnel.forwardTcp("localhost:8081");
16
+ tunnel.forward("localhost:8081");
17
17
  }
18
18
  create_tunnel();
@@ -29,7 +29,7 @@ builder.connect().then((session) => {
29
29
  .listen()
30
30
  .then((tunnel) => {
31
31
  console.log("Ingress established at: " + JSON.stringify(tunnel.labels()));
32
- tunnel.forwardPipe(UNIX_SOCKET);
32
+ tunnel.forward(UNIX_SOCKET);
33
33
  });
34
34
  });
35
35
 
@@ -32,6 +32,6 @@ builder.connect().then((session) => {
32
32
  .listen()
33
33
  .then((tunnel) => {
34
34
  console.log("Ingress established at:", tunnel.url());
35
- tunnel.forwardPipe(UNIX_SOCKET);
35
+ tunnel.forward(UNIX_SOCKET);
36
36
  });
37
37
  });
@@ -35,6 +35,6 @@ builder.connect().then((session) => {
35
35
  .listen()
36
36
  .then((tunnel) => {
37
37
  console.log("Ingress established at:", tunnel.url());
38
- tunnel.forwardPipe(UNIX_SOCKET);
38
+ tunnel.forward(UNIX_SOCKET);
39
39
  });
40
40
  });
@@ -60,7 +60,7 @@ async function standardConfig() {
60
60
  const tunnel = await session.httpEndpoint().listen();
61
61
  console.log("Ingress established at:", tunnel.url());
62
62
  httpServer.listen(8081);
63
- tunnel.forwardTcp("localhost:8081");
63
+ tunnel.forward("localhost:8081");
64
64
 
65
65
  // unregister logging callback
66
66
  ngrok.loggingCallback();
@@ -20,6 +20,6 @@ new ngrok.NgrokSessionBuilder()
20
20
  .listen()
21
21
  .then((tunnel) => {
22
22
  console.log("Ingress established at:", tunnel.url());
23
- tunnel.forwardPipe(PIPE);
23
+ tunnel.forward(PIPE);
24
24
  });
25
25
  });
@@ -10,7 +10,7 @@ async function setup() {
10
10
  const session = await new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect();
11
11
  const tunnel = await session.httpEndpoint().listen();
12
12
  console.log(`Forwarding to: localhost:${port} from ingress at: ${tunnel.url()}`);
13
- tunnel.forwardTcp(`localhost:${port}`);
13
+ tunnel.forward(`localhost:${port}`);
14
14
  }
15
15
 
16
16
  setup();
@@ -14,7 +14,7 @@ async function setup() {
14
14
  const session = await new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect();
15
15
  const tunnel = await session.httpEndpoint().listen();
16
16
  console.log(`Forwarding to: ${host}:${port} from ingress at: ${tunnel.url()}`);
17
- tunnel.forwardTcp(`${host}:${port}`);
17
+ tunnel.forward(`${host}:${port}`);
18
18
  }
19
19
 
20
20
  if (run) setup();
@@ -12,7 +12,7 @@ async function setup() {
12
12
  const session = await new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect();
13
13
  const tunnel = await session.httpEndpoint().listen();
14
14
  console.log(`Forwarding to: ${host}:${port} from ingress at: ${tunnel.url()}`);
15
- tunnel.forwardTcp(`${host}:${port}`);
15
+ tunnel.forward(`${host}:${port}`);
16
16
  }
17
17
 
18
18
  setup();
package/index.d.ts CHANGED
@@ -182,6 +182,12 @@ export function kill(): Promise<void>
182
182
  export function loggingCallback(callback?: (level: string, target: string, message: string) => void, level?: string): void
183
183
  /** Set the default auth token to use for any future sessions. */
184
184
  export function authtoken(authtoken: string): Promise<void>
185
+ /** Retrieve a list of non-closed tunnels, in no particular order. */
186
+ export function tunnels(): Promise<Array<NgrokTunnel>>
187
+ /** Retrieve tunnel using the id */
188
+ export function getTunnel(id: string): Promise<NgrokTunnel | null>
189
+ /** Retrieve tunnel using the url */
190
+ export function getTunnelByUrl(url: string): Promise<NgrokTunnel | null>
185
191
  /**
186
192
  * The builder for an ngrok session.
187
193
  *
@@ -346,6 +352,8 @@ export class NgrokSession {
346
352
  tlsEndpoint(): NgrokTlsTunnelBuilder
347
353
  /** Start building a labeled tunnel. */
348
354
  labeledTunnel(): NgrokLabeledTunnelBuilder
355
+ /** Retrieve a list of this session's non-closed tunnels, in no particular order. */
356
+ tunnels(): Promise<Array<NgrokTunnel>>
349
357
  /** Close a tunnel with the given ID. */
350
358
  closeTunnel(id: string): Promise<void>
351
359
  /** Close the ngrok session. */
@@ -381,14 +389,12 @@ export class NgrokTunnel {
381
389
  forwardsTo(): string
382
390
  /** Returns the arbitrary metadata string for this tunnel. */
383
391
  metadata(): string
384
- /** Forward incoming tunnel connections to the provided TCP address. */
385
- forwardTcp(addr: string): Promise<void>
386
392
  /**
387
- * Forward incoming tunnel connections to the provided file socket path.
388
- * On Linux/Darwin addr can be a unix domain socket path, e.g. "/tmp/ngrok.sock"
389
- * On Windows addr can be a named pipe, e.e. "\\.\pipe\an_ngrok_pipe"
393
+ * Forward incoming tunnel connections. This can be either a TCP address or a file socket path.
394
+ * For file socket paths on Linux/Darwin, addr can be a unix domain socket path, e.g. "/tmp/ngrok.sock"
395
+ * On Windows, addr can be a named pipe, e.e. "\\\\.\\pipe\\an_ngrok_pipe
390
396
  */
391
- forwardPipe(addr: string): Promise<void>
397
+ forward(addr: string): Promise<void>
392
398
  /**
393
399
  * Close the tunnel.
394
400
  *
package/index.js CHANGED
@@ -252,7 +252,7 @@ if (!nativeBinding) {
252
252
  throw new Error(`Failed to load native binding`)
253
253
  }
254
254
 
255
- const { connect, disconnect, kill, loggingCallback, authtoken, NgrokSessionBuilder, NgrokSession, UpdateRequest, NgrokTunnel, NgrokHttpTunnelBuilder, NgrokTcpTunnelBuilder, NgrokTlsTunnelBuilder, NgrokLabeledTunnelBuilder } = nativeBinding
255
+ const { connect, disconnect, kill, loggingCallback, authtoken, NgrokSessionBuilder, NgrokSession, UpdateRequest, NgrokTunnel, tunnels, getTunnel, getTunnelByUrl, NgrokHttpTunnelBuilder, NgrokTcpTunnelBuilder, NgrokTlsTunnelBuilder, NgrokLabeledTunnelBuilder } = nativeBinding
256
256
 
257
257
  module.exports.connect = connect
258
258
  module.exports.disconnect = disconnect
@@ -263,6 +263,9 @@ module.exports.NgrokSessionBuilder = NgrokSessionBuilder
263
263
  module.exports.NgrokSession = NgrokSession
264
264
  module.exports.UpdateRequest = UpdateRequest
265
265
  module.exports.NgrokTunnel = NgrokTunnel
266
+ module.exports.tunnels = tunnels
267
+ module.exports.getTunnel = getTunnel
268
+ module.exports.getTunnelByUrl = getTunnelByUrl
266
269
  module.exports.NgrokHttpTunnelBuilder = NgrokHttpTunnelBuilder
267
270
  module.exports.NgrokTcpTunnelBuilder = NgrokTcpTunnelBuilder
268
271
  module.exports.NgrokTlsTunnelBuilder = NgrokTlsTunnelBuilder
@@ -274,6 +277,11 @@ module.exports.NgrokLabeledTunnelBuilder = NgrokLabeledTunnelBuilder
274
277
  const net = require("net");
275
278
  const fs = require("fs");
276
279
  const os = require("os");
280
+ const path = require("path");
281
+
282
+ // wrap connect with the code for extending exception with error code
283
+ NgrokSessionBuilder.prototype._connect = NgrokSessionBuilder.prototype.connect;
284
+ NgrokSessionBuilder.prototype.connect = ngrokSessionConnect;
277
285
 
278
286
  // wrap listen with the bind code for passing to net.Server.listen()
279
287
  NgrokHttpTunnelBuilder.prototype._listen = NgrokHttpTunnelBuilder.prototype.listen;
@@ -286,17 +294,42 @@ NgrokTcpTunnelBuilder.prototype.listen = ngrokBind;
286
294
  NgrokTlsTunnelBuilder.prototype.listen = ngrokBind;
287
295
  NgrokLabeledTunnelBuilder.prototype.listen = ngrokBind;
288
296
 
297
+ // Wrap session connect to fill in exception's errorCode
298
+ async function ngrokSessionConnect() {
299
+ try {
300
+ return await this._connect();
301
+ } catch (err) {
302
+ populateErrorCode(err);
303
+ throw err;
304
+ }
305
+ }
306
+
289
307
  // Begin listening for new connections on this tunnel,
290
308
  // and bind to a local socket so this tunnel can be
291
309
  // passed into net.Server.listen().
292
310
  async function ngrokBind(bind) {
293
- const tunnel = await this._listen();
294
- if (bind !== false) {
295
- const socket = await randomTcpSocket();
296
- tunnel.socket = socket;
297
- defineTunnelHandle(tunnel, socket);
311
+ try {
312
+ const tunnel = await this._listen();
313
+ if (bind !== false) {
314
+ const socket = await randomTcpSocket();
315
+ tunnel.socket = socket;
316
+ defineTunnelHandle(tunnel, socket);
317
+ }
318
+ return tunnel;
319
+ } catch (err) {
320
+ populateErrorCode(err);
321
+ throw err;
322
+ }
323
+ }
324
+
325
+ function populateErrorCode(err) {
326
+ if (err.message) {
327
+ const regex = /error_code: (ERR_NGROK_\d+)$/;
328
+ const errorCode = err.message.match(regex);
329
+ if (errorCode && errorCode.length > 1) {
330
+ err.errorCode = errorCode[1];
331
+ }
298
332
  }
299
- return tunnel;
300
333
  }
301
334
 
302
335
  // add a 'handle' getter to the tunnel so it can be
@@ -307,7 +340,7 @@ function defineTunnelHandle(tunnel, socket) {
307
340
  Object.defineProperty(tunnel, "handle", {
308
341
  get: function () {
309
342
  // turn on forwarding now that it has been requested
310
- tunnel.forwardTcp("localhost:" + socket.address().port);
343
+ tunnel.forward("localhost:" + socket.address().port);
311
344
  return socket._handle;
312
345
  },
313
346
  });
@@ -382,30 +415,56 @@ async function ngrokLinkTcp(tunnel, server) {
382
415
  // random local port
383
416
  const socket = await asyncListen(server, { host: "localhost", port: 0 });
384
417
  // forward to socket
385
- tunnel.forwardTcp("localhost:" + socket.address().port);
418
+ tunnel.forward("localhost:" + socket.address().port);
386
419
  return socket;
387
420
  }
388
421
 
389
- async function ngrokLinkPipe(tunnel, server) {
422
+ function generatePipeFilename(tunnel, server) {
390
423
  var proposed = "tun-" + tunnel.id() + ".sock";
424
+
425
+ // windows leaves little choice
391
426
  if (platform == "win32") {
392
- proposed = "\\\\.\\pipe\\" + proposed;
427
+ return "\\\\.\\pipe\\" + proposed;
393
428
  }
394
- var filename;
429
+
430
+ // try to make a directory in the current working directory
431
+ const dir = ".ngrok";
395
432
  try {
396
- fs.accessSync(process.cwd(), fs.constants.W_OK);
397
- filename = proposed;
433
+ fs.mkdirSync(dir);
398
434
  } catch (err) {
399
- console.debug("Cannot write to: " + process.cwd());
400
- // try tmp. allow any exception to propagate
401
- fs.accessSync(os.tmpdir(), fs.constants.W_OK);
402
- filename = os.tmpdir() + proposed;
435
+ // move on
436
+ }
437
+ try {
438
+ fs.accessSync(dir, fs.constants.W_OK);
439
+ return dir + path.sep + proposed;
440
+ } catch (err) {
441
+ // move on
403
442
  }
404
443
 
405
- if (!filename) {
406
- throw new Error("no writeable directory found");
444
+ // try the OS temp directory, being careful not to exceed the maximum path length for unix sockets
445
+ // https://linux.die.net/man/7/unix
446
+ // https://unix.stackexchange.com/a/367012
447
+ if (os.tmpdir().length < 90) {
448
+ try {
449
+ fs.accessSync(os.tmpdir(), fs.constants.W_OK);
450
+ filepath = os.tmpdir() + path.sep + proposed;
451
+ if (filepath.length > 100) {
452
+ // truncate
453
+ filepath = filepath.substring(0, 100);
454
+ }
455
+ return filepath;
456
+ } catch (err) {
457
+ // move on
458
+ }
407
459
  }
408
460
 
461
+ // fallback to current working directory. allow any exception to propagate
462
+ fs.accessSync(process.cwd(), fs.constants.W_OK);
463
+ return proposed;
464
+ }
465
+
466
+ async function ngrokLinkPipe(tunnel, server) {
467
+ var filename = generatePipeFilename(tunnel);
409
468
  // begin listening
410
469
  const socket = await asyncListen(server, { path: filename });
411
470
  // tighten permissions
@@ -417,7 +476,8 @@ async function ngrokLinkPipe(tunnel, server) {
417
476
  console.debug("Cannot change permissions of file: " + filename);
418
477
  }
419
478
  // forward tunnel
420
- tunnel.forwardPipe(filename);
479
+ const proto = platform == "win32" ? "pipe:" : "unix:";
480
+ tunnel.forward(proto + filename);
421
481
  socket.path = filename; // surface to caller
422
482
 
423
483
  return socket;
@@ -457,9 +517,10 @@ function consoleLog(level) {
457
517
  // wrap connect with code to vectorize and split out functions
458
518
  const _connect = connect;
459
519
  async function ngrokConnect(config) {
520
+ if (config == undefined) config = 80;
460
521
  if (Number.isInteger(config) || typeof config === "string" || config instanceof String) {
461
522
  address = String(config);
462
- if (!address.includes(":")) {
523
+ if (Number.isInteger(config) && !address.includes(":")) {
463
524
  address = `localhost:${address}`;
464
525
  }
465
526
  config = { addr: address };
@@ -533,7 +594,12 @@ async function ngrokConnect(config) {
533
594
  config["onStatusChange"] = true;
534
595
  }
535
596
  // call into rust
536
- return await _connect(config, on_log_event, on_connection, on_disconnection);
597
+ try {
598
+ return await _connect(config, on_log_event, on_connection, on_disconnection);
599
+ } catch (err) {
600
+ populateErrorCode(err);
601
+ throw err;
602
+ }
537
603
  }
538
604
 
539
605
  function undot(config, dotKey) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngrok/ngrok",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "main": "index.js",
5
5
  "types": "index.d.ts",
6
6
  "napi": {
@@ -55,18 +55,18 @@
55
55
  "description": "The ngrok agent in library form, suitable for integrating directly into your NodeJS application.",
56
56
  "repository": "https://github.com/ngrok/ngrok-nodejs",
57
57
  "optionalDependencies": {
58
- "@ngrok/ngrok-win32-x64-msvc": "0.5.2",
59
- "@ngrok/ngrok-darwin-x64": "0.5.2",
60
- "@ngrok/ngrok-linux-x64-gnu": "0.5.2",
61
- "@ngrok/ngrok-darwin-arm64": "0.5.2",
62
- "@ngrok/ngrok-android-arm64": "0.5.2",
63
- "@ngrok/ngrok-linux-arm64-gnu": "0.5.2",
64
- "@ngrok/ngrok-linux-arm64-musl": "0.5.2",
65
- "@ngrok/ngrok-linux-arm-gnueabihf": "0.5.2",
66
- "@ngrok/ngrok-linux-x64-musl": "0.5.2",
67
- "@ngrok/ngrok-freebsd-x64": "0.5.2",
68
- "@ngrok/ngrok-win32-ia32-msvc": "0.5.2",
69
- "@ngrok/ngrok-android-arm-eabi": "0.5.2",
70
- "@ngrok/ngrok-darwin-universal": "0.5.2"
58
+ "@ngrok/ngrok-win32-x64-msvc": "0.6.0",
59
+ "@ngrok/ngrok-darwin-x64": "0.6.0",
60
+ "@ngrok/ngrok-linux-x64-gnu": "0.6.0",
61
+ "@ngrok/ngrok-darwin-arm64": "0.6.0",
62
+ "@ngrok/ngrok-android-arm64": "0.6.0",
63
+ "@ngrok/ngrok-linux-arm64-gnu": "0.6.0",
64
+ "@ngrok/ngrok-linux-arm64-musl": "0.6.0",
65
+ "@ngrok/ngrok-linux-arm-gnueabihf": "0.6.0",
66
+ "@ngrok/ngrok-linux-x64-musl": "0.6.0",
67
+ "@ngrok/ngrok-freebsd-x64": "0.6.0",
68
+ "@ngrok/ngrok-win32-ia32-msvc": "0.6.0",
69
+ "@ngrok/ngrok-android-arm-eabi": "0.6.0",
70
+ "@ngrok/ngrok-darwin-universal": "0.6.0"
71
71
  }
72
72
  }
@@ -28,7 +28,7 @@ new ngrok.NgrokSessionBuilder()
28
28
  .httpEndpoint()
29
29
  .listen()
30
30
  .then((tunnel) => {
31
- tunnel.forwardTcp("localhost:8081").await;
31
+ tunnel.forward("localhost:8081").await;
32
32
  console.log("tunnel: " + tunnel.url() + " id: " + tunnel.id());
33
33
  setTimeout(function () {
34
34
  console.log("\n\n=====> running gc");
@@ -28,7 +28,7 @@ new ngrok.NgrokSessionBuilder()
28
28
  .httpEndpoint()
29
29
  .listen()
30
30
  .then((tunnel) => {
31
- tunnel.forwardTcp("localhost:8081").await;
31
+ tunnel.forward("localhost:8081").await;
32
32
  const tun_id = tunnel.id();
33
33
  console.log("tunnel: " + tunnel.url() + " id: " + tun_id);
34
34
  console.log("\n\n=====> nulling tunnel");
package/src/connect.rs CHANGED
@@ -23,6 +23,8 @@ lazy_static! {
23
23
  pub(crate) static ref SESSION: Mutex<Option<NgrokSession>> = Mutex::new(None);
24
24
  }
25
25
 
26
+ pub(crate) const PIPE_PREFIX: &str = "pipe:";
27
+
26
28
  /// Single string configuration
27
29
  macro_rules! plumb {
28
30
  ($builder:tt, $config:tt, $name:tt) => {
@@ -146,17 +148,14 @@ async fn async_connect(s_builder: NgrokSessionBuilder, config: Config) -> Result
146
148
  _ => return Err(napi_err(format!("unhandled protocol {proto}"))),
147
149
  };
148
150
 
149
- let url = tunnel::get_url(&id).await.unwrap_or(id.clone());
151
+ let url = tunnel::get_tunnel(id.clone())
152
+ .await
153
+ .and_then(|t| t.url())
154
+ .unwrap_or(id.clone());
150
155
 
151
156
  // move forwarding to another task
152
157
  if let Some(addr) = config.addr {
153
- tokio::spawn(async move {
154
- if addr.starts_with("pipe:") {
155
- tunnel::forward_pipe(&id, addr.clone().split_off(5)).await
156
- } else {
157
- tunnel::forward_tcp(&id, addr).await
158
- }
159
- });
158
+ tokio::spawn(async move { tunnel::forward(&id, addr).await });
160
159
  }
161
160
 
162
161
  Ok(url)
@@ -268,6 +267,12 @@ fn set_defaults(config: &mut Config) {
268
267
  config.addr.replace("80".to_string());
269
268
  }
270
269
  }
270
+ if let Some(addr) = &config.addr {
271
+ if addr.parse::<i32>().is_ok() {
272
+ // the string is a number, interpret it as a port
273
+ config.addr.replace(format!("localhost:{addr}"));
274
+ }
275
+ }
271
276
  }
272
277
 
273
278
  /// Warn about unused configuration values
package/src/lib.rs CHANGED
@@ -2,6 +2,7 @@ use napi::{
2
2
  Error,
3
3
  Status,
4
4
  };
5
+ use ngrok::prelude::NgrokError;
5
6
 
6
7
  pub mod config;
7
8
  pub mod connect;
@@ -16,3 +17,23 @@ pub mod tunnel_builder;
16
17
  pub(crate) fn napi_err(message: impl Into<String>) -> Error {
17
18
  Error::new(Status::GenericFailure, message.into())
18
19
  }
20
+
21
+ pub(crate) fn napi_ngrok_err(message: impl Into<String>, err: &impl NgrokError) -> Error {
22
+ let py_err = if let Some(error_code) = err.error_code() {
23
+ Error::new(
24
+ Status::GenericFailure,
25
+ format!(
26
+ "{}: {} error_code: {}",
27
+ message.into(),
28
+ err.msg(),
29
+ error_code
30
+ ),
31
+ )
32
+ } else {
33
+ Error::new(
34
+ Status::GenericFailure,
35
+ format!("{}: {}", message.into(), err.msg()),
36
+ )
37
+ };
38
+ py_err
39
+ }