-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtunnel.ts
More file actions
170 lines (148 loc) · 4.82 KB
/
tunnel.ts
File metadata and controls
170 lines (148 loc) · 4.82 KB
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
// src/lib/tunnel.ts
//
// Functions: buildProxyUrl, createProxyAgent, proxyFetch, buildProxyAgentFromSettings
// Exports: VALID_PROXY_TYPES, PROXY_HOST_PATTERN, ProxyType, ProxyConfig, ProxyFetchResult, ProxySettings
import type { Agent as HttpAgent } from "node:http"
import https from "node:https"
import { HttpsProxyAgent } from "https-proxy-agent"
import { SocksProxyAgent } from "socks-proxy-agent"
import { decrypt } from "@/lib/crypto"
import { log } from "@/lib/logger"
export type ProxyType = "socks5" | "http" | "https"
export interface ProxyConfig {
type: ProxyType
host: string
port: number
username?: string | null
password?: string | null
}
export const VALID_PROXY_TYPES = new Set<string>(["socks5", "http", "https"])
// Shared hostname validation — alphanumeric, dots, hyphens, colons/brackets (IPv6)
export const PROXY_HOST_PATTERN = /^[\w.\-:[\]]+$/
export function buildProxyUrl(config: ProxyConfig): string {
if (!VALID_PROXY_TYPES.has(config.type)) {
throw new Error(`Invalid proxy type: ${config.type}`)
}
const scheme = config.type === "socks5" ? "socks5" : config.type
const auth =
config.username && config.password
? `${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@`
: config.username
? `${encodeURIComponent(config.username)}@`
: ""
return `${scheme}://${auth}${config.host}:${config.port}`
}
export function createProxyAgent(config: ProxyConfig): HttpAgent {
const url = buildProxyUrl(config)
if (config.type === "socks5") {
return new SocksProxyAgent(url)
}
return new HttpsProxyAgent(url)
}
export interface ProxyFetchResult {
ok: boolean
status: number
statusText: string
json: () => Promise<unknown>
buffer: () => Promise<Buffer>
}
export function proxyFetch(
url: string,
agent: HttpAgent,
options: { timeoutMs?: number; headers?: Record<string, string>; maxBytes?: number } = {}
): Promise<ProxyFetchResult> {
return new Promise((resolve, reject) => {
const parsed = new URL(url)
if (parsed.protocol !== "https:") {
reject(new Error("proxyFetch only supports HTTPS URLs"))
return
}
const timeoutMs = options.timeoutMs ?? 15000
const maxBytes = options.maxBytes ?? 0
const req = https.request(
{
hostname: parsed.hostname,
port: parsed.port || 443,
path: parsed.pathname + parsed.search,
method: "GET",
agent,
headers: {
Accept: "application/json",
...options.headers,
},
timeout: timeoutMs,
},
(res) => {
const chunks: Buffer[] = []
let totalBytes = 0
res.on("data", (chunk: Buffer) => {
totalBytes += chunk.length
if (maxBytes > 0 && totalBytes > maxBytes) {
req.destroy()
reject(new Error(`Response exceeded ${maxBytes} byte limit`))
return
}
chunks.push(chunk)
})
res.on("end", () => {
const raw = Buffer.concat(chunks)
resolve({
ok: (res.statusCode ?? 0) >= 200 && (res.statusCode ?? 0) < 300,
status: res.statusCode ?? 0,
statusText: res.statusMessage ?? "",
// security-audit-ignore: async wrapper converts JSON.parse throw to rejected promise — caller handles via await/catch
json: async () => JSON.parse(raw.toString("utf8")),
buffer: () => Promise.resolve(raw),
})
})
}
)
req.on("timeout", () => {
req.destroy()
reject(new Error(`Request timed out after ${timeoutMs}ms`))
})
req.on("error", (err) => {
reject(err)
})
req.end()
})
}
export interface ProxySettings {
proxyEnabled: boolean
proxyType: string
proxyHost: string | null
proxyPort: number | null
proxyUsername: string | null
encryptedProxyPassword: string | null
}
export function buildProxyAgentFromSettings(
settings: ProxySettings,
encryptionKey: Buffer
): HttpAgent | undefined {
if (!settings.proxyEnabled || !settings.proxyHost) return undefined
if (!VALID_PROXY_TYPES.has(settings.proxyType)) {
log.error(`Invalid proxy type in settings: "${settings.proxyType}", skipping proxy`)
return undefined
}
let password: string | null = null
if (settings.encryptedProxyPassword) {
try {
password = decrypt(settings.encryptedProxyPassword, encryptionKey)
} catch {
log.error("Failed to decrypt proxy password, proceeding without auth")
}
}
const config: ProxyConfig = {
type: settings.proxyType as ProxyType,
host: settings.proxyHost,
port: settings.proxyPort ?? 1080,
username: settings.proxyUsername,
password,
}
try {
return createProxyAgent(config)
} catch (_err) {
log.error("Failed to create proxy agent (check proxy host/port configuration)")
return undefined
}
}