forked from bubenshchykov/ngrok
-
Notifications
You must be signed in to change notification settings - Fork 4
/
download.js
195 lines (174 loc) · 6.1 KB
/
download.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/*
- downloads archived binary from ngrok cdn (if not found in local cache)
- stores it in home dir as a local cache
- extracts executable to module's bin folder
*/
function downloadNgrok(callback, options) {
options = options || {};
const os = require('os');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const Zip = require('decompress-zip');
const got = require('got');
const cafilePath = options.cafilePath || process.env.NGROK_ROOT_CA_PATH;
const cdnUrl = getCdnUrl();
const cacheUrl = getCacheUrl();
const maxAttempts = 3;
let attempts = 0;
if (hasCache()) {
console.error('ngrok - cached download found at ' + cacheUrl);
extract(retry);
} else {
download(retry);
}
function getCdnUrl() {
const arch = options.arch || process.env.NGROK_ARCH || os.platform() + os.arch();
const cdn = options.cdnUrl || process.env.NGROK_CDN_URL || 'https://bin.equinox.io';
const cdnPath = options.cdnPath || process.env.NGROK_CDN_PATH || '/c/4VmDzA7iaHb/ngrok-stable-';
const cdnFiles = {
darwinia32: cdn + cdnPath + 'darwin-386.zip',
darwinx64: cdn + cdnPath + 'darwin-amd64.zip',
darwinarm64: cdn + cdnPath + 'darwin-amd64.zip',
linuxarm: cdn + cdnPath + 'linux-arm.zip',
linuxarm64: cdn + cdnPath + 'linux-arm64.zip',
androidarm: cdn + cdnPath + 'linux-arm.zip',
androidarm64: cdn + cdnPath + 'linux-arm64.zip',
linuxia32: cdn + cdnPath + 'linux-386.zip',
linuxx64: cdn + cdnPath + 'linux-amd64.zip',
win32ia32: cdn + cdnPath + 'windows-386.zip',
win32x64: cdn + cdnPath + 'windows-amd64.zip',
freebsdia32: cdn + cdnPath + 'freebsd-386.zip',
freebsdx64: cdn + cdnPath + 'freebsd-amd64.zip'
};
const url = cdnFiles[arch];
if (!url) {
console.error('ngrok - platform ' + arch + ' is not supported.');
process.exit(1);
}
return url;
}
function getCacheUrl() {
let dir;
try {
dir = os.platform() === 'win32' && process.env.APPDATA
? path.join(process.env.APPDATA, 'ngrok')
: path.join(os.homedir(), '.ngrok');
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
fs.mkdirSync(dir);
}
} catch (err) {
dir = path.join(__dirname, 'bin');
}
const name = Buffer.from(cdnUrl).toString('base64');
return path.join(dir, name + '.zip');
}
function hasCache() {
if (options.ignoreCache || process.env.NGROK_IGNORE_CACHE === 'true') {
return false;
}
return fs.existsSync(cacheUrl) && fs.statSync(cacheUrl).size;
}
function download(cb) {
console.error('ngrok - downloading binary ' + cdnUrl);
const certificateAuthority = tryToReadCaFile();
const gotOptions = { https: { certificateAuthority }};
if (process.env.HTTPS_PROXY) {
try {
const {HttpsProxyAgent} = require('hpagent');
gotOptions.agent = {
https: new HttpsProxyAgent({ proxy: process.env.HTTPS_PROXY })
}
} catch(error) {
throw new Error('You have the HTTPS_PROXY environment variable set, but you are missing the optional dependency hpagent. Please install hpagent as a dependency and try again.');
}
}
const downloadStream = got.stream(cdnUrl, gotOptions);
process.stderr.write("ngrok - downloading progress: ");
downloadStream
.on('response', (res) => {
if (!/2\d\d/.test(res.statusCode)) {
res.pause();
return downloadStream.emit('error', new Error('wrong status code: ' + res.statusCode));
}
})
.on("downloadProgress", ({ percent, transferred, total }) => {
readline.clearLine(process.stderr, 0, () => {
readline.cursorTo(process.stderr, 0, () => {
process.stderr.write(
`ngrok - downloading progress: ${transferred}/${total} (${(
percent * 100
).toFixed(2)}%)`
);
});
});
})
.on("error", (error) => {
console.error("\nngrok - error downloading from URL", error);
cb(error);
});
const outputStream = fs
.createWriteStream(cacheUrl)
.on('error', e => {
console.error('ngrok - error storing binary to local file', e);
cb(e);
})
.on('finish', () => {
console.error('\nngrok - binary downloaded to ' + cacheUrl);
extract(cb);
});
downloadStream.pipe(outputStream);
}
function extract(cb) {
console.error('ngrok - unpacking binary');
const moduleBinPath = path.join(__dirname, 'bin');
new Zip(cacheUrl)
.extract({ path: moduleBinPath })
.once('error', error)
.once('extract', () => {
const suffix = os.platform() === 'win32' ? '.exe' : '';
if (suffix === '.exe') {
fs.writeFileSync(path.join(moduleBinPath, 'ngrok.cmd'), 'ngrok.exe');
}
const target = path.join(moduleBinPath, 'ngrok' + suffix);
fs.chmodSync(target, 0755);
if (!fs.existsSync(target) || fs.statSync(target).size <= 0) {
return error(new Error('corrupted file ' + target));
}
console.log('ngrok - binary unpacked to ' + target);
cb(null);
});
function error(e) {
console.error('ngrok - error unpacking binary', e);
cb(e);
}
}
function retry(err) {
attempts++;
if (err && attempts === maxAttempts) {
console.error('ngrok - install failed', err);
return callback(err);
}
if (err) {
console.warn('ngrok - install failed, retrying');
return setTimeout(download, 500, retry);
}
callback();
}
function tryToReadCaFile() {
try {
const caString = fs.existsSync(cafilePath) && fs.readFileSync(cafilePath).toString();
const caContents =
caString &&
caString
.split('-----END CERTIFICATE-----')
.filter(c => c.trim().startsWith('-----BEGIN CERTIFICATE-----'))
.map(c => `${c}-----END CERTIFICATE-----`);
return caContents.length > 0 ? caContents : undefined;
} catch (error) {
console.warn(error);
return undefined;
}
}
}
module.exports = downloadNgrok;