|
| 1 | +import fs from "fs"; |
| 2 | +import { ProxyAgent } from "proxy-agent"; |
| 3 | +import { type WorkspaceConfiguration } from "vscode"; |
| 4 | +import { getProxyForUrl } from "../proxy"; |
| 5 | +import { expandPath } from "../util"; |
| 6 | + |
| 7 | +/** |
| 8 | + * Return whether the API will need a token for authorization. |
| 9 | + * If mTLS is in use (as specified by the cert or key files being set) then |
| 10 | + * token authorization is disabled. Otherwise, it is enabled. |
| 11 | + */ |
| 12 | +export function needToken(cfg: WorkspaceConfiguration): boolean { |
| 13 | + const certFile = expandPath( |
| 14 | + String(cfg.get("coder.tlsCertFile") ?? "").trim(), |
| 15 | + ); |
| 16 | + const keyFile = expandPath(String(cfg.get("coder.tlsKeyFile") ?? "").trim()); |
| 17 | + return !certFile && !keyFile; |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Create a new HTTP agent based on the current VS Code settings. |
| 22 | + * Configures proxy, TLS certificates, and security options. |
| 23 | + */ |
| 24 | +export function createHttpAgent(cfg: WorkspaceConfiguration): ProxyAgent { |
| 25 | + const insecure = Boolean(cfg.get("coder.insecure")); |
| 26 | + const certFile = expandPath( |
| 27 | + String(cfg.get("coder.tlsCertFile") ?? "").trim(), |
| 28 | + ); |
| 29 | + const keyFile = expandPath(String(cfg.get("coder.tlsKeyFile") ?? "").trim()); |
| 30 | + const caFile = expandPath(String(cfg.get("coder.tlsCaFile") ?? "").trim()); |
| 31 | + const altHost = expandPath(String(cfg.get("coder.tlsAltHost") ?? "").trim()); |
| 32 | + |
| 33 | + return new ProxyAgent({ |
| 34 | + // Called each time a request is made. |
| 35 | + getProxyForUrl: (url: string) => { |
| 36 | + return getProxyForUrl( |
| 37 | + url, |
| 38 | + cfg.get("http.proxy"), |
| 39 | + cfg.get("coder.proxyBypass"), |
| 40 | + ); |
| 41 | + }, |
| 42 | + cert: certFile === "" ? undefined : fs.readFileSync(certFile), |
| 43 | + key: keyFile === "" ? undefined : fs.readFileSync(keyFile), |
| 44 | + ca: caFile === "" ? undefined : fs.readFileSync(caFile), |
| 45 | + servername: altHost === "" ? undefined : altHost, |
| 46 | + // rejectUnauthorized defaults to true, so we need to explicitly set it to |
| 47 | + // false if we want to allow self-signed certificates. |
| 48 | + rejectUnauthorized: !insecure, |
| 49 | + }); |
| 50 | +} |
0 commit comments