-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
CliProxyAgent.ts
100 lines (85 loc) 路 2.56 KB
/
CliProxyAgent.ts
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
import tunnel from "tunnel";
import {Configuration, Inject, Injectable, Value} from "@tsed/di";
import {CliExeca} from "./CliExeca";
import {camelCase} from "change-case";
import {URL} from "url";
import {coerce} from "../utils/coerce";
import {ProjectPackageJson} from "./ProjectPackageJson";
export interface CliProxySettings {
url: string;
strictSsl: boolean;
}
@Injectable()
@Configuration({
proxy: {
url: process.env.HTTPS_PROXY || process.env.HTTP_PROXY,
strictSsl: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== undefined ? process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0" : true
}
})
export class CliProxyAgent {
@Value("proxy", {})
proxySettings: CliProxySettings;
@Inject()
protected projectPackageJson: ProjectPackageJson;
@Inject()
protected cliExeca: CliExeca;
hasProxy() {
return !!this.proxySettings.url;
}
get(type: "http" | "https") {
if (this.hasProxy()) {
const {strictSsl = true} = this.proxySettings;
const url = new URL(this.proxySettings.url);
const protocol = url.protocol.replace(":", "");
const options = {
proxy: {
host: url.hostname,
port: (url.port ? +url.port : undefined) as any,
proxyAuth: url.username && url.password ? `${url.username}:${url.password}` : undefined,
rejectUnauthorized: strictSsl
}
};
const method = camelCase([type, "over", protocol].join(" "));
if ((tunnel as any)[method]) {
return (tunnel as any)[method](options);
}
}
return null;
}
async resolveProxySettings(): Promise<void> {
const hasProxy = this.hasProxy();
if (hasProxy) {
return;
}
const result = await Promise.all([
this.cliExeca
.getAsync("npm", ["config", "get", "proxy"], {
cwd: this.projectPackageJson.dir
})
.catch(() => ""),
this.cliExeca
.getAsync("npm", ["config", "get", "http-proxy"], {
cwd: this.projectPackageJson.dir
})
.catch(() => ""),
this.cliExeca
.getAsync("npm", ["config", "get", "https-proxy"], {
cwd: this.projectPackageJson.dir
})
.catch(() => ""),
this.cliExeca
.getAsync("npm", ["config", "get", "strict-ssl"], {
cwd: this.projectPackageJson.dir
})
.catch(() => "")
]);
const [proxy, httpProxy, httpsProxy, strictSsl] = result.map(coerce);
const url = httpsProxy || httpProxy || proxy;
if (url) {
this.proxySettings = {
url,
strictSsl: coerce(strictSsl) !== false
};
}
}
}