包详细信息

@ngrok/ngrok

ngrok689.6k(MIT OR Apache-2.0)1.5.1

The ngrok agent in library form, suitable for integrating directly into your NodeJS application.

ngrok, nodejs, ingress, networking

自述文件

JavaScript SDK for ngrok

npm.rs MIT licensed Apache-2.0 licensed Continuous integration

ngrok-javascript is the official Node.js SDK for ngrok that requires no binaries. Quickly enable secure production-ready connectivity to your applications and services directly from your code.

ngrok is a globally distributed gateway that provides secure connectivity for applications and services running in any environment.

Installation

Using npm:

npm install @ngrok/ngrok

Using yarn:

yarn add @ngrok/ngrok

Using pnpm:

pnpm add @ngrok/ngrok

Quickstart

  1. Install @ngrok/ngrok
  2. Export your authtoken from the ngrok dashboard as NGROK_AUTHTOKEN in your terminal
  3. Add the following code to your application to establish connectivity via the forward method through port 8080 over localhost:

     // Require ngrok javascript sdk
     const ngrok = require("@ngrok/ngrok");
     // import ngrok from '@ngrok/ngrok' // if inside a module
    
     (async function() {
       // Establish connectivity
       const listener = await ngrok.forward({ addr: 8080, authtoken_from_env: true });
    
       // Output ngrok url to console
       console.log(`Ingress established at: ${listener.url()}`);
     })();
    
     process.stdin.resume();
    

That's it! Your application should now be available through the url output in your terminal.

Note You can find more examples in the examples directory.

Documentation

A quickstart guide and a full API reference are included in the ngrok-javascript documentation.

Authorization

To use ngrok you'll need an authtoken. To obtain one, sign up for free at ngrok.com and retrieve it from the authtoken page of your ngrok dashboard. Once you have copied your authtoken, you can reference it in several ways.

You can set it in the NGROK_AUTHTOKEN environment variable and pass authtoken_from_env: true to the forward method:

await ngrok.forward({ authtoken_from_env: true, ... });

Or pass the authtoken directly to the forward method:

await ngrok.forward({ authtoken: token, ... });

Or set it for all connections with the authtoken method:

await ngrok.authtoken(token);

Connection

The forward method is the easiest way to start an ngrok session and establish a listener to a specified address. The forward method returns a promise that resolves to the public URL of the listener.

With no arguments the forward method will start an HTTP listener to localhost port 80:

const ngrok = require("@ngrok/ngrok");
// import ngrok from '@ngrok/ngrok' // if inside a module

(async function() {
  console.log( (await ngrok.forward()).url() );
})();

You can pass the port number to forward on localhost:

const listener = await ngrok.forward(4242);

Or you can specify the host and port via a string:

const listener = await ngrok.forward("localhost:4242");

More options can be passed to the forward method to customize the connection:

const listener = await ngrok.forward({ addr: 8080, basic_auth: "ngrok:online1line" });
const listener = await ngrok.forward({ addr: 8080, oauth_provider: "google", oauth_allow_domains: "example.com" });

The (optional) proto parameter is the listener type, which defaults to http. To create a TCP listener:

const listener = await ngrok.forward({ proto: 'tcp', addr: 25565 });

See Full Configuration for the list of possible configuration options.

Disconnection

The close method on a listener will shut it down, and also stop the ngrok session if it is no longer needed. This method returns a promise that resolves when the listener is closed.

const listener = await ngrok.getListenerByUrl(url);
await listener.close();

Or use the disconnect method with the url() of the listener to close (or id() for a Labeled Listener):

await ngrok.disconnect(listener.url());

Or omit the url() to close all listeners:

await ngrok.disconnect();

Listing Listeners

To list all current non-closed listeners use the listeners method:

const listeners = await ngrok.listeners();

Builders

For more control over Sessions and Listeners, the builder classes can be used.

A minimal example using the builder class looks like the following:

async function create_listener() {
  const session = await new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect();
  const listener = await session.httpEndpoint().listen();
  console.log("Ingress established at:", listener.url());
  listener.forward("localhost:8081");
}

See here for a Full Configuration Example

TLS Backends

As of version 0.7.0 there is backend TLS connection support, validated by a filepath specified in the SSL_CERT_FILE environment variable, or falling back to the host OS installed trusted certificate authorities. So it is now possible to do this to forward:

await ngrok.forward({ addr: "https://127.0.0.1:3000", authtoken_from_env: true });

If the service is using certs not trusted by the OS, such as self-signed certificates, add an environment variable like this before running: SSL_CERT_FILE=/path/to/ca.crt. There is also a verify_upstream_tls: false option to disable certification verification.

Async Programming

All methods return a Promise and are suitable for use in asynchronous programming. You can use callback chaining with .then() and .catch() syntax or the await keyword to wait for completion of an API call.

Error Handling

All asynchronous functions will throw an error on failure to set up a session or listener, which can be caught and dealt with using try/catch or then/catch statements:

new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect()
    .then((session) => {
        session.httpEndpoint().listen()
            .then((tun) => {})
            .catch(err => console.log('listener setup error: ' + err))
    })
    .catch(err => console.log('session setup error: ' + err))
    .await;

Full Configuration

This example shows all the possible configuration items of ngrok.forward:

const listener = await ngrok.forward({
  // session configuration
  addr: `localhost:8080`, // or `8080` or `unix:${UNIX_SOCKET}`
  authtoken: "<authtoken>",
  authtoken_from_env: true,
  on_status_change: (addr, error) => {
    console.log(`disconnected, addr ${addr} error: ${error}`);
  },
  session_metadata: "Online in One Line",
  // advanced session connection configuration
  server_addr: "example.com:443",
  root_cas: "trusted",
  session_ca_cert: fs.readFileSync("ca.pem", "utf8"),  
  // listener configuration
  metadata: "example listener metadata from javascript",
  domain: "<domain>",
  proto: "http",
  proxy_proto: "", // One of: "", "1", "2"
  schemes: ["HTTPS"],
  labels: "edge:edghts_2G...",  // Along with proto="labeled"
  app_protocol: "http2",
  // module configuration
  basic_auth: ["ngrok:online1line"],
  circuit_breaker: 0.1,
  compression: true,
  allow_user_agent: "^mozilla.*",
  deny_user_agent: "^curl.*",
  ip_restriction_allow_cidrs: ["0.0.0.0/0"],
  ip_restriction_deny_cidrs: ["10.1.1.1/32"],
  crt: fs.readFileSync("crt.pem", "utf8"),
  key: fs.readFileSync("key.pem", "utf8"),
  mutual_tls_cas: [fs.readFileSync('ca.crt', 'utf8')],
  oauth_provider: "google",
  oauth_allow_domains: ["<domain>"],
  oauth_allow_emails: ["<email>"],
  oauth_scopes: ["<scope>"],
  oauth_client_id: "<id>",
  oauth_client_secret: "<secret>",
  oidc_issuer_url: "<url>",
  oidc_client_id: "<id>",
  oidc_client_secret: "<secret>",
  oidc_allow_domains: ["<domain>"],
  oidc_allow_emails: ["<email>"],
  oidc_scopes: ["<scope>"],
  pooling_enabled: false,
  traffic_policy: "<policy_json>",
  request_header_remove: ["X-Req-Nope"],
  response_header_remove: ["X-Res-Nope"],
  request_header_add: ["X-Req-Yup:true"],
  response_header_add: ["X-Res-Yup:true"],
  verify_upstream_tls: false,
  verify_webhook_provider: "twilio",
  verify_webhook_secret: "asdf",
  websocket_tcp_converter: true,
});

The Config interface also shows all the available options.

Examples

Degit can be used for cloning and running an example directory like this:

npx degit github:ngrok/ngrok-javascript/examples/<example> <folder-name>
cd <folder-name>
npm i

For example:

npx degit github:ngrok/ngrok-javascript/examples/express express && cd express && npm i

Frameworks

Listeners

Platform Support

Pre-built binaries are provided on NPM for the following platforms:

OS i686 x64 aarch64 arm
Windows
MacOS
Linux
Linux musl
FreeBSD
Android

Note ngrok-javascript, and ngrok-rust which it depends on, are open source, so it may be possible to build them for other platforms.

On Windows, ensure you have Microsoft Visual C++ Redistributable installed.

We currently support MacOS 10.13+.

Dependencies

  • NAPI-RS, an excellent system to ease development and building of Rust plugins for NodeJS.

Changelog

Changes to ngrok-javascript are tracked under CHANGELOG.md.

Join the ngrok Community

License

This work is dual-licensed under Apache, Version 2.0 and MIT. You can choose between one of them if you use this work.

Contributions

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in ngrok-javascript by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

更新日志

1.5.0

Adds poolingEnabled to listener builders, allowing the endpoint to pool with other endpoints with the same host/port/binding

1.4.1

  • Fix traffic_policy naming for ngrok.forward

1.4.0

  • Rename policy to traffic_policy
  • Fix quickstart example in README
  • Add Microsoft Visual C++ Redistributable requirement for Windows to documentation

1.3.0:

  • Add rootCas to session builder and root_cas to ngrok.forward. Setting this to host will use the host's trusted certificates to connect for the ngrok session.
  • Add session_ca_cert and server_addr to ngrok.forward, which correspond to the same functions in the session builder.

1.2.0:

  • Add verifyUpstreamTls to listener builders and verify_upstream_tls to ngrok.forward. Setting this to false will skip verification of the upstream application's TLS certificate.

1.1.1:

  • Add appProtocol(string) to the labeled listener builder. Setting this to "http2" will enable HTTP/2 support to the backend application.

1.1.0:

  • Add appProtocol(string) to http listener builder, and app_protocol: string as a ngrok.forward() argument. Setting this to "http2" will enable HTTP/2 support to the backend application.

1.0.0:

  • Add policy support to Listener builders and ngrok.forward

0.9.1:

  • Move to ngrok.forward from ngrok.connect, keeping an alias.
  • Rename to ngrok-javascript.
  • Smaller number of files packaged.

0.9.0:

  • ngrok.connect now returns the full Listener object.

0.8.0:

  • Add allowUserAgent and denyUserAgent options to HTTP listeners.
  • Add clientId and clientSecret options to OAuth.

0.7.1:

  • Fix for windows pipe pathing.

0.7.0:

  • Add listen_and_forward and listen_and_serve to listener builders.
  • Update to latest version of underlying rust library, allowing TLS backends.

0.6.0:

  • Flattened listener.forwardPipe() and listener.forwardTcp() into listener.forward(). Determination will be made based on addr input.
  • Add ngrok.listeners() and session.listeners() to get a list of current non-closed listeners for the process or session, respectively.
  • Add errorCode field to thrown errors, where possible.
  • More heuristics for automatic unix socket file placement.
  • Connect heuristic improved for strings parseable as numbers.

0.5.2:

  • Cleanly return from a listener forward call after a session.close().

0.5.1:

  • consoleLog return signature.

0.5.0:

  • Add Session.clientInfo().
  • Rename to ngrok-nodejs.

0.4.1:

  • Clean shutdown when run from npm.
  • Unblock Svelte postinstall script.

0.4.0:

  • Move to a single listener type for simplicity.
  • Documentation updates.

0.3.0:

  • Added ngrok.connect(Config), ngrok.authtoken(), and ngrok.disconnect(url).
  • Examples cleanup.

0.2.0:

  • Now have examples for Express, Fastify, Hapi, Koa, Nest.js, Next.js, Remix, Svelte, and Vue.
  • Add prettier auto code formatting.

0.1.1:

  • Bump ngrok-rust to 0.11.3.
  • Migrate ca_cert to the upstream call in ngrok-rust.

0.1.0:

  • Added ca_cert, handle_heartbeat, and handle_disconnection to Session.

0.0.12:

  • Added Session.close().
  • Cleanly shutdown when listen is called with a pre-configured listener.

0.0.11:

  • Cleanly shutdown on all platforms when there are callbacks registered.

0.0.10:

  • Child client versioning support.

0.0.9:

  • Support for named pipes on Windows.

0.0.8:

  • Support callbacks for logging, include console.log and Winston handlers.
  • Can now pass listeners directly to net.Server.listen().
  • Clean shutdown on SIGINT after ngrok.listen(server).
  • Typedoc generation of documentation.

0.0.7:

  • Improved memory management, removing need to keep NodeJS from garbage collecting certain objects.
  • Support callbacks for remote operations (stop, restart, update).
  • Typescript support for getSocket and listen.

0.0.6:

  • Initial public release.