chore: add mobile app

This commit is contained in:
2026-02-07 22:33:02 +01:00
parent db34640acc
commit e89384ad4e
29327 changed files with 3886944 additions and 12 deletions
+286
View File
@@ -0,0 +1,286 @@
# ngrok [![Tests](https://github.com/bubenshchykov/ngrok/workflows/Tests/badge.svg)](https://github.com/bubenshchykov/ngrok/actions) ![TypeScript compatible](https://img.shields.io/badge/typescript-compatible-brightgreen.svg) [![npm](https://img.shields.io/npm/v/ngrok.svg)](https://www.npmjs.com/package/ngrok) [![npm](https://img.shields.io/npm/dm/ngrok.svg)](https://www.npmjs.com/package/ngrok)
![alt ngrok.com](https://ngrok.com/static/img/overview.png)
* [Usage](#usage)
* [Local install](#local-install)
* [Global install](#global-install)
* [Auth Token](#auth-token)
* [Connect](#connect)
* [Options](#options)
* [Disconnect](#disconnect)
* [Config](#config)
* [Inspector](#inspector)
* [API](#api)
* [List tunnels](#list-tunnels)
* [Start tunnel](#start-tunnel)
* [Get tunnel details](#get-tunnel-details)
* [Stop tunnel](#stop-tunnel)
* [List requests](#list-requests)
* [Replay request](#replay-request)
* [Delete all requests](#delete-all-requests)
* [Request detail](#request-detail)
* [Proxy](#proxy)
* [Expo changes](#expo-changes)
* [How it works](#how-it-works)
* [ngrok binary update](#ngrok-binary-update)
* [Using with nodemon](#using-with-nodemon)
* [Contributors](#contributors)
* [Upgrading to version 4](#upgrading-to-version-4)
* [TypeScript](#typescript)
## Usage
### Local install
Install the package with npm:
```bash
npm install ngrok
```
Then use `ngrok.connect()` to start ngrok and open a tunnel.
```javascript
const ngrok = require('ngrok');
(async function() {
const url = await ngrok.connect();
})();
```
This module uses `node>=10.19.0` with async/await. For a callback-based version use [2.3.0](https://github.com/bubenshchykov/ngrok/blob/330674233e3ec77688bb692bf1eb007810c4e30d/README.md).
### Global install
```bash
npm install ngrok -g
ngrok http 8080
```
For global install on Linux, you might need to run `sudo npm install --unsafe-perm -g ngrok` due to the [nature](https://github.com/bubenshchykov/ngrok/issues/115#issuecomment-380927124) of npm postinstall script.
### Auth Token
You can create basic http-https-tcp tunnel without an [authtoken](https://ngrok.com/docs#authtoken). For custom subdomains and more you should obtain an authtoken by [signing up at ngrok.com](https://ngrok.com). Once you set the authtoken, it is stored in ngrok config and used for all tunnels. You can set the authtoken directly:
```javascript
await ngrok.authtoken(token);
```
Or pass the authtoken to the `connect` method like so:
```javascript
await ngrok.connect({authtoken: token, ...});
```
### Connect
There are a number of ways to create a tunnel with ngrok using the `connect` method.
By default, `connect` will open an HTTP tunnel to port 80
```javascript
const url = await ngrok.connect(); // https://757c1652.ngrok.io -> http://localhost:80
```
You can pass the port number to `connect` to specify that port:
```javascript
const url = await ngrok.connect(9090); // https://757c1652.ngrok.io -> http://localhost:9090
```
Or you can pass an object of options, for example:
```javascript
const url = await ngrok.connect({proto: 'tcp', addr: 22}); // tcp://0.tcp.ngrok.io:48590
const url = await ngrok.connect(opts);
```
#### Options
There are many options that you can pass to `connect`, here are some examples:
```javascript
const url = await ngrok.connect({
proto: 'http', // http|tcp|tls, defaults to http
addr: 8080, // port or network address, defaults to 80
auth: 'user:pwd', // http basic authentication for tunnel
subdomain: 'alex', // reserved tunnel name https://alex.ngrok.io
authtoken: '12345', // your authtoken from ngrok.com
region: 'us', // one of ngrok regions (us, eu, au, ap, sa, jp, in), defaults to us
configPath: '~/git/project/ngrok.yml', // custom path for ngrok config file
binPath: path => path.replace('app.asar', 'app.asar.unpacked'), // custom binary path, eg for prod in electron
onStatusChange: status => {}, // 'closed' - connection is lost, 'connected' - reconnected
onLogEvent: data => {}, // returns stdout messages from ngrok process
});
```
See [the ngrok documentation for all of the tunnel definition options](https://ngrok.com/docs#tunnel-definitions) including: `name, inspect, host_header, bind_tls, hostname, crt, key, client_cas, remote_addr`.
Note on regions: the region used in the first tunnel will be used for all the following tunnels.
### Disconnect
The ngrok process and all tunnels will be killed when node process is complete. To stop the tunnels manually use:
```javascript
await ngrok.disconnect(url); // stops one
await ngrok.disconnect(); // stops all
await ngrok.kill(); // kills ngrok process
```
Note on HTTP tunnels: by default bind_tls is true, so whenever you use HTTP proto two tunnels are created - HTTP and HTTPS. If you disconnect the HTTPS tunnel, the HTTP tunnel remains open. You might want to close them both by passing the HTTP-version url, or simply by disconnecting all in one go `ngrok.disconnect()`.
### Config
You can use ngrok's [configurations files](https://ngrok.com/docs#config), and pass `name` option when making a tunnel. Configuration files allow to store tunnel options. Ngrok looks for them here:
```
OS X /Users/example/.ngrok2/ngrok.yml
Linux /home/example/.ngrok2/ngrok.yml
Windows C:\Users\example\.ngrok2\ngrok.yml
```
You can specify a custom `configPath` when making a tunnel.
### Inspector
When a tunnel is established you can use the ngrok interface hosted at http://127.0.0.1:4040 to inspect the webhooks made via ngrok.
The same URL hosts the internal [client api](https://ngrok.com/docs#client-api). This package exposes an API client that wraps the API which you can use to manage tunnels yourself.
```javascript
const url = await ngrok.connect();
const api = ngrok.getApi();
const tunnels = await api.listTunnels();
```
You can also get the URL of the internal API:
```javascript
const url = await ngrok.connect();
const apiUrl = ngrok.getUrl();
```
### API
The API wrapper gives access to all the [ngrok client API](https://ngrok.com/docs#client-api) methods:
```javascript
const url = await ngrok.connect();
const api = ngrok.getApi();
```
#### [List tunnels](https://ngrok.com/docs#list-tunnels)
```javascript
const tunnels = await api.listTunnels();
```
#### [Start tunnel](https://ngrok.com/docs#start-tunnel)
```javascript
const tunnel = await api.startTunnel(opts);
```
#### [Get tunnel details](https://ngrok.com/docs#tunnel-detail)
```javascript
const tunnel = await api.tunnelDetail(tunnelName);
```
#### [Stop tunnel](https://ngrok.com/docs#stop-tunnel)
```javascript
await api.stopTunnel(tunnelName);
```
#### [List requests](https://ngrok.com/docs#list-requests)
```javascript
await api.listRequests(options);
```
#### [Replay request](https://ngrok.com/docs#replay-request)
```javascript
await api.replayRequest(requestId, tunnelName);
```
#### [Delete all requests](https://ngrok.com/docs#delete-requests)
```javascript
await api.deleteAllRequests();
```
#### [Request detail](https://ngrok.com/docs#request-detail)
```javascript
const request = await api.requestDetail(requestId);
```
### Proxy
- If you are behind a corporate proxy and have issues installing ngrok, you can set ```HTTPS_PROXY``` env var to fix it. ngrok's postinstall scripts uses the [`got`](https://www.npmjs.com/package/got) module to fetch the binary and the [`hpagent`](https://github.com/delvedor/hpagent) module to support HTTPS proxies. You will need to install the `hpagent` module as a dependency
- If you are using a CA file, set the path in the environment variable `NGROK_ROOT_CA_PATH`. The path is needed for downloading the ngrok binary in the postinstall script
## Expo changes
### Get active process handle
To get a handle to the spawned ngrok process use
```javascript
ngrok.getActiveProcess(); // returns ChildProcess
```
### Use @expo/ngrok-bin to manage ngrok binaries
Benefit for versioning the binaries. The `binPath` option is unsupported then.
## How it works
```npm install``` downloads the ngrok binary for your platform from the official ngrok hosting. To host binaries yourself set the `NGROK_CDN_URL` environment variable before installing ngrok. To force specific platform set `NGROK_ARCH`, eg `NGROK_ARCH=freebsdia32`.
The first time you create a tunnel the ngrok process is spawned and runs until you disconnect or when the parent process is killed. All further tunnels are connected or disconnected through the internal ngrok API which usually runs on http://127.0.0.1:4040.
## ngrok binary update
If you would like to force an update of the ngrok binary directly from your software, you can require the `ngrok/download` module and call the `downloadNgrok` function directly:
```javascript
const downloadNgrok = require('ngrok/download');
downloadNgrok(myCallbackFunc, { ignoreCache: true });
```
## Using with nodemon
If you want your application to restart as you make changes to it, you may use [nodemon](https://nodemon.io/). This blog post shows [how to use nodemon and ngrok together so your server restarts but your tunnel doesn't](https://philna.sh/blog/2021/03/15/restart-app-not-tunnel-ngrok-nodemon/).
## Contributors
Please run ```git update-index --assume-unchanged bin/ngrok``` to not override [ngrok stub](https://github.com/bubenshchykov/ngrok/blob/master/bin/ngrok) in your PR. Unfortunately it can't be gitignored.
The test suite covers the basic usage without an authtoken, as well as features available for free and paid authtokens. You can supply your own tokens as environment variables, otherwise a warning is given and some specs are ignored (locally and in PR builds). GitHub Actions supplies real tokens to master branch and runs all specs always.
## Upgrading to version 4
The main impetus to update the package was to remove the dependency on the deprecated `request` module. `request` was replaced with `got`. Calls to the main `ngrok` functions, `connect`, `authtoken`, `disconnect`, `kill`, `getVersion` and `getUrl` respond the same as in version 3.
Updating the HTTP library, meant that the wrapped API would change, so a client class was created with methods for the available API calls. See the documentation above [for how to use the API client](#api).
The upside is that you no longer have to know the path to the API method you need. For example, to list the active tunnels in version 3 you would do:
```javascript
const api = ngrok.getApi();
const tunnels = await api.get('api/tunnels');
```
Now you can call the `listTunnels` function:
```javascript
const api = ngrok.getApi();
const tunnels = await api.listTunnels();
```
### TypeScript
From version 3 to version 4 the bundled types were also overhauled. Most types live within the `Ngrok` namespace, particularly `Ngrok.Options` which replaces `INgrokOptions`.
+84
View File
@@ -0,0 +1,84 @@
const { NgrokClient, NgrokClientError } = require("./src/client");
const uuid = require("uuid");
const {
getProcess,
getActiveProcess,
killProcess,
setAuthtoken,
getVersion,
} = require("./src/process");
const { defaults, validate, isRetriable } = require("./src/utils");
let processUrl = null;
let ngrokClient = null;
async function connect(opts) {
opts = defaults(opts);
validate(opts);
if (opts.authtoken) {
await setAuthtoken(opts);
}
processUrl = await getProcess(opts);
ngrokClient = new NgrokClient(processUrl);
return connectRetry(opts);
}
async function connectRetry(opts, retryCount = 0) {
opts.name = String(opts.name || uuid.v4());
try {
const response = await ngrokClient.startTunnel(opts);
return response.public_url;
} catch (err) {
if (!isRetriable(err) || retryCount >= 100) {
throw err;
}
await new Promise((resolve) => setTimeout(resolve, 200));
return connectRetry(opts, ++retryCount);
}
}
async function disconnect(publicUrl) {
if (!ngrokClient) return;
const tunnels = (await ngrokClient.listTunnels()).tunnels;
if (!publicUrl) {
const disconnectAll = tunnels.map((tunnel) =>
disconnect(tunnel.public_url)
);
return Promise.all(disconnectAll);
}
const tunnelDetails = tunnels.find(
(tunnel) => tunnel.public_url === publicUrl
);
if (!tunnelDetails) {
throw new Error(`there is no tunnel with url: ${publicUrl}`);
}
return ngrokClient.stopTunnel(tunnelDetails.name);
}
async function kill() {
if (!ngrokClient) return;
await killProcess();
ngrokClient = null;
tunnels = {};
}
function getUrl() {
return processUrl;
}
function getApi() {
return ngrokClient;
}
module.exports = {
connect,
disconnect,
authtoken: setAuthtoken,
kill,
getUrl,
getApi,
getVersion,
getActiveProcess,
NgrokClientError
};
+249
View File
@@ -0,0 +1,249 @@
import { ChildProcess } from "child_process";
import { Response } from "got";
declare module "ngrok" {
/**
* Creates a ngrok tunnel.
* E.g:
* const url = await ngrok.connect(); // https://757c1652.ngrok.io -> http://localhost:80
* const url = await ngrok.connect(9090); // https://757c1652.ngrok.io -> http://localhost:9090
* const url = await ngrok.connect({ proto: 'tcp', addr: 22 }); // tcp://0.tcp.ngrok.io:48590
*
* @param options Optional. Port number or options.
*/
export function connect(options?: number | Ngrok.Options): Promise<string>;
/**
* Stops a tunnel, or all of them if no URL is passed.
*
* /!\ ngrok and all opened tunnels will be killed when the node process is done.
*
* /!\ Note on HTTP tunnels: by default bind_tls is true, so whenever you use http proto two tunnels are created:
* http and https. If you disconnect https tunnel, http tunnel remains open.
* You might want to close them both by passing http-version url, or simply by disconnecting all in one,
* with ngrok.disconnect().
*
* @param url The URL of the specific tunnel to disconnect -- if not passed, kills them all.
*/
export function disconnect(url?: string): Promise<void>;
/**
* Kills the ngrok process.
*/
export function kill(): Promise<void>;
/**
* Gets the ngrok client URL.
*/
export function getUrl(): string | null;
/**
* Gets the ngrok client API.
*/
export function getApi(): NgrokClient | null;
/**
* Gets the ngrok active process handle.
*/
export function getActiveProcess(): ChildProcess | null;
/**
* You can create basic http-https-tcp tunnel without authtoken.
* For custom subdomains and more you should obtain authtoken by signing up at ngrok.com.
* E.g:
* await ngrok.authtoken(token);
* // or
* await ngrok.authtoken({ authtoken: token, ... });
* // or
* const url = await ngrok.connect({ authtoken: token, ... });
*
* @param token
*/
export function authtoken(token: string | Ngrok.Options): Promise<void>;
/**
*
* Gets the version of the ngrok binary.
*/
export function getVersion(options?: Ngrok.Options): Promise<string>;
namespace Ngrok {
type Protocol = "http" | "tcp" | "tls";
type Region = "us" | "eu" | "au" | "ap" | "sa" | "jp" | "in";
interface Options {
/**
* Other "custom", indirectly-supported ngrok process options.
*
* @see {@link https://ngrok.com/docs}
*/
[customOption: string]: any;
/**
* The tunnel type to put in place.
*
* @default 'http'
*/
proto?: Protocol;
/**
* Port or network address to redirect traffic on.
*
* @default opts.port || opts.host || 80
*/
addr?: string | number;
/**
* HTTP Basic authentication for tunnel.
*
* @default opts.httpauth
*/
auth?: string;
/**
* Reserved tunnel name (e.g. https://alex.ngrok.io)
*/
subdomain?: string;
/**
* Your authtoken from ngrok.com
*/
authtoken?: string;
/**
* One of ngrok regions.
* Note: region used in first tunnel will be used for all next tunnels too.
*
* @default 'us'
*/
region?: Region;
/**
* Custom path for ngrok config file.
*/
configPath?: string;
/**
* Callback called when ngrok logs an event.
*/
onLogEvent?: (logEventMessage: string) => any;
/**
* Callback called when session status is changed.
* When connection is lost, ngrok will keep trying to reconnect.
*/
onStatusChange?: (status: "connected" | "closed") => any;
}
interface Metrics {
count: number;
rate1: number;
rate5: number;
rate15: number;
p50: number;
p90: number;
p95: number;
p99: number;
}
interface Connections extends Metrics {
gauge: number;
}
interface HTTPRequests extends Metrics {}
interface Tunnel {
name: string;
uri: string;
public_url: string;
proto: Ngrok.Protocol;
metrics: {
conns: Connections;
http: HTTPRequests;
};
}
interface TunnelsResponse {
tunnels: Tunnel[];
uri: string;
}
interface CapturedRequestOptions {
limit: number;
tunnel_name: string;
}
interface Request {
uri: string;
id: string;
tunnel_name: string;
remote_addr: string;
start: string;
duration: number;
request: {
method: string;
proto: string;
headers: {
[header: string]: string;
};
uri: string;
raw: string;
};
response: {
status: string;
status_code: number;
proto: string;
headers: {
[header: string]: string;
};
raw: string;
};
}
interface RequestsResponse {
requests: Request[];
uri: string;
}
}
class NgrokClient {
constructor(processUrl: string);
listTunnels(): Promise<Ngrok.TunnelsResponse>;
startTunnel(options: Ngrok.Options): Promise<Ngrok.Tunnel>;
tunnelDetail(name: string): Promise<Ngrok.Tunnel>;
stopTunnel(name: string): Promise<boolean>;
listRequests(
options: Ngrok.CapturedRequestOptions
): Promise<Ngrok.RequestsResponse>;
replayRequest(id: string, tunnelName: string): Promise<boolean>;
deleteAllRequests(): Promise<boolean>;
requestDetail(id: string): Promise<Ngrok.Request>;
}
type ErrorBody = {
error_code: number;
status_code: number;
msg: string;
details: { [key: string]: string }
}
class NgrokClientError extends Error {
constructor(message: string, response: Response, body: ErrorBody | string);
get response(): Response;
get body(): ErrorBody | string;
}
}
declare module "ngrok/download" {
function downloadNgrok(
callback: (err?: Error) => void,
options?: {
cafilePath: string;
arch: string;
cdnUrl: string;
cdnPath: string;
ignoreCache: boolean;
}
): void;
export = downloadNgrok;
}
+48
View File
@@ -0,0 +1,48 @@
{
"name": "@expo/ngrok",
"version": "4.1.3",
"description": "node wrapper for ngrok",
"main": "index.js",
"types": "ngrok.d.ts",
"scripts": {
"test": "mocha --exit"
},
"files": [
"index.js",
"ngrok.d.ts",
"src/client.js",
"src/process.js",
"src/utils.js"
],
"repository": {
"type": "git",
"url": "https://github.com/expo/ngrok.git"
},
"keywords": [
"ngrok",
"localhost",
"tunneling",
"localtunnel",
"webhook"
],
"author": "bubenshchykov",
"license": "BSD-2-Clause",
"bugs": {
"url": "https://github.com/expo/ngrok/issues"
},
"devDependencies": {
"@types/node": "^8.10.50",
"chai": "^4.3.4",
"colors": "^1.4.0",
"mocha": "^8.3.2"
},
"dependencies": {
"@expo/ngrok-bin": "2.3.42",
"got": "^11.5.1",
"uuid": "^3.3.2",
"yaml": "^1.10.0"
},
"engines": {
"node": ">=10.19.0"
}
}
+99
View File
@@ -0,0 +1,99 @@
const got = require("got");
class NgrokClientError extends Error {
constructor(message, response, body) {
super(message);
this.name = "NgrokClientError";
this.response = response;
this.body = body;
}
}
class NgrokClient {
constructor(processUrl) {
this.internalApi = got.extend({
prefixUrl: processUrl,
retry: 0,
});
}
async request(method, path, options = {}) {
try {
if (method === "get") {
return await this.internalApi
.get(path, { searchParams: options })
.json();
} else {
return await this.internalApi[method](path, { json: options }).json();
}
} catch (error) {
let clientError;
try {
const response = JSON.parse(error.response.body);
clientError = new NgrokClientError(
response.msg,
error.response,
response
);
} catch (e) {
clientError = new NgrokClientError(
error.response.body,
error.response,
error.response.body
);
}
throw clientError;
}
}
async booleanRequest(method, path, options = {}) {
try {
return await this.internalApi[method](path, { json: options }).then(
(response) => response.statusCode === 204
);
} catch (error) {
const response = JSON.parse(error.response.body);
throw new NgrokClientError(response.msg, error.response, response);
}
}
listTunnels() {
return this.request("get", "api/tunnels");
}
startTunnel(options = {}) {
return this.request("post", "api/tunnels", options);
}
tunnelDetail(name) {
return this.request("get", `api/tunnels/${name}`);
}
stopTunnel(name) {
if (typeof name === "undefined" || name.length === 0) {
throw new Error("To stop a tunnel, please provide a name.");
}
return this.booleanRequest("delete", `api/tunnels/${name}`);
}
listRequests(options) {
return this.request("get", "api/requests/http", options);
}
replayRequest(id, tunnelName) {
return this.booleanRequest("post", "api/requests/http", { id, tunnelName });
}
deleteAllRequests() {
return this.booleanRequest("delete", "api/requests/http");
}
requestDetail(id) {
if (typeof id === "undefined" || id.length === 0) {
throw new Error("To get the details of a request, please provide an id.");
}
return this.request("get", `api/requests/http/${id}`);
}
}
module.exports = { NgrokClient, NgrokClientError };
+166
View File
@@ -0,0 +1,166 @@
const { promisify } = require("util");
const { spawn, exec: execCallback } = require("child_process");
const exec = promisify(execCallback);
const bin = require("@expo/ngrok-bin");
const ready = /starting web service.*addr=(\d+\.\d+\.\d+\.\d+:\d+)/;
const inUse = /address already in use/;
let processPromise, activeProcess;
/*
ngrok process runs internal ngrok api
and should be spawned only ONCE
(respawn allowed if it fails or .kill method called)
*/
async function getProcess(opts) {
if (processPromise) return processPromise;
try {
processPromise = startProcess(opts);
return await processPromise;
} catch (ex) {
processPromise = null;
throw ex;
}
}
function getActiveProcess() {
return activeProcess;
}
function parseAddr(message) {
if (message[0] === "{") {
const parsed = JSON.parse(message);
return parsed.addr
} else {
const parsed = message.match(ready);
if (parsed) {
return parsed[1];
}
}
}
async function startProcess(opts) {
const start = ["start", "--none", "--log=stdout"];
if (opts.region) start.push("--region=" + opts.region);
if (opts.configPath) start.push("--config=" + opts.configPath);
const ngrok = spawn(bin, start, { windowsHide: true });
let resolve, reject;
const apiUrl = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
ngrok.stdout.on("data", (data) => {
const msg = data.toString().trim();
if (opts.onLogEvent) {
opts.onLogEvent(msg);
}
if (opts.onStatusChange) {
if (msg.match("client session established")) {
opts.onStatusChange("connected");
} else if (msg.match("session closed, starting reconnect loop")) {
opts.onStatusChange("closed");
}
}
const msgs = msg.split(/\n/);
msgs.forEach(msg => {
const addr = parseAddr(msg);
if (addr) {
resolve(`http://${addr}`);
} else if (msg.match(inUse)) {
reject(new Error(msg.substring(0, 10000)));
}
})
});
ngrok.stderr.on("data", (data) => {
const msg = data.toString().substring(0, 10000);
reject(new Error(msg));
});
ngrok.on("exit", () => {
processPromise = null;
activeProcess = null;
});
ngrok.on("error", (err) => {
reject(err);
});
try {
const url = await apiUrl;
activeProcess = ngrok;
return url;
} catch (ex) {
ngrok.kill();
throw ex;
} finally {
// Remove the stdout listeners if nobody is interested in the content.
if (!opts.onLogEvent && !opts.onStatusChange) {
ngrok.stdout.removeAllListeners("data");
}
ngrok.stderr.removeAllListeners("data");
}
}
function killProcess() {
if (!activeProcess) {
return Promise.resolve();
}
return new Promise((resolve) => {
activeProcess.on("exit", () => resolve());
activeProcess.kill();
});
}
process.on("exit", () => {
if (activeProcess) {
activeProcess.kill();
}
});
/**
* @param {string | Ngrok.Options} optsOrToken
*/
async function setAuthtoken(optsOrToken) {
const isOpts = typeof optsOrToken !== "string";
const opts = isOpts ? optsOrToken : {};
const token = isOpts ? opts.authtoken : optsOrToken;
const authtoken = ["authtoken", token];
if (opts.configPath) authtoken.push("--config=" + opts.configPath);
const ngrok = spawn(bin, authtoken, { windowsHide: true });
const killed = new Promise((resolve, reject) => {
ngrok.stdout.once("data", () => resolve());
ngrok.stderr.once("data", () => reject(new Error("cant set authtoken")));
ngrok.on("error", (err) => reject(err));
});
try {
return await killed;
} finally {
ngrok.kill();
}
}
/**
* @param {Ngrok.Options | undefined} opts
*/
async function getVersion(opts = {}) {
const { stdout } = await exec(`${bin} --version`);
return stdout.replace("ngrok version", "").trim();
}
module.exports = {
getProcess,
getActiveProcess,
killProcess,
setAuthtoken,
getVersion,
};
+58
View File
@@ -0,0 +1,58 @@
const { homedir } = require("os");
const { join } = require("path");
const { parse } = require("yaml");
const { readFileSync } = require("fs");
function defaultConfigPath() {
return join(homedir(), ".ngrok2", "ngrok.yml");
}
function defaults(opts) {
opts = opts || { proto: "http", addr: 80 };
if (opts.name) {
const configPath = opts.configPath || defaultConfigPath();
const config = parse(readFileSync(configPath, "utf8"));
if (config.tunnels && config.tunnels[opts.name]) {
opts = Object.assign(opts, config.tunnels[opts.name]);
}
}
if (typeof opts === "function") opts = { proto: "http", addr: 80 };
if (typeof opts !== "object") opts = { proto: "http", addr: opts };
if (!opts.proto) opts.proto = "http";
if (!opts.addr) opts.addr = opts.port || opts.host || 80;
if (opts.httpauth) opts.auth = opts.httpauth;
return opts;
}
function validate(opts) {
if (opts.web_addr === false || opts.web_addr === "false") {
throw new Error(
"web_addr:false is not supported, module depends on internal ngrok api"
);
}
}
function isRetriable(err) {
if (!err.response) {
return false;
}
const statusCode = err.response.statusCode;
const body = err.body;
const notReady500 = statusCode === 500 && /panic/.test(body);
const notReady502 =
statusCode === 502 &&
body.details &&
body.details.err === "tunnel session not ready yet";
const notReady503 =
statusCode === 503 &&
body.details &&
body.details.err ===
"a successful ngrok tunnel session has not yet been established";
return notReady500 || notReady502 || notReady503;
}
module.exports = {
defaults,
validate,
isRetriable,
};