@lucky_zone/net-proxy 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +48 -2
- package/client.js +773 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +11 -0
- package/index.js +699 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +45 -4
package/index.js
ADDED
|
@@ -0,0 +1,699 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of the network-proxy plugin: route only the domains the user lists
|
|
3
|
+
* through the configured proxy server, and everything else directly.
|
|
4
|
+
*
|
|
5
|
+
* Neither an environment variable nor an undici dispatcher can express an
|
|
6
|
+
* allowlist: `NO_PROXY` only removes hosts, it cannot add them. This plugin
|
|
7
|
+
* therefore starts a loopback router and points the harness's own proxy policy
|
|
8
|
+
* (undici's global dispatcher plus the child environment) at that router. The
|
|
9
|
+
* router decides per connection: a listed host is tunnelled through the user's
|
|
10
|
+
* proxy, any other host is reached directly.
|
|
11
|
+
*
|
|
12
|
+
* Editing the proxy or the domain list updates the running router in place, so
|
|
13
|
+
* the installed policy and every child environment keep pointing at one stable
|
|
14
|
+
* loopback port; only switching the plugin off, or clearing the list or the
|
|
15
|
+
* proxy, releases the policy.
|
|
16
|
+
* @module @lucky_zone/net-proxy
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import http from 'node:http'
|
|
20
|
+
import https from 'node:https'
|
|
21
|
+
import net from 'node:net'
|
|
22
|
+
import tls from 'node:tls'
|
|
23
|
+
import { createRequire } from 'node:module'
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
import { pathToFileURL } from 'node:url'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Import one package that the running installation owns.
|
|
29
|
+
*
|
|
30
|
+
* A bundle installed from a directory is a link, and the linked package has no
|
|
31
|
+
* `node_modules` of its own; the profile's module-resolution interception routes
|
|
32
|
+
* the names this package lists in `peerDependencies` to the installation. When a
|
|
33
|
+
* deployment resolves those names by another route, the installation anchor is
|
|
34
|
+
* the second attempt.
|
|
35
|
+
* @param specifier - bare package specifier to load.
|
|
36
|
+
* @returns the module namespace.
|
|
37
|
+
*/
|
|
38
|
+
async function importInstallationPackage(specifier) {
|
|
39
|
+
try {
|
|
40
|
+
return await import(specifier)
|
|
41
|
+
} catch (error) {
|
|
42
|
+
const anchor = process.env.DSH_INSTALL_DIR
|
|
43
|
+
if (anchor !== undefined && anchor !== '') {
|
|
44
|
+
try {
|
|
45
|
+
const anchorRequire = createRequire(join(anchor, 'package.json'))
|
|
46
|
+
return await import(pathToFileURL(anchorRequire.resolve(specifier)).href)
|
|
47
|
+
} catch {
|
|
48
|
+
// Report the plain import failure: it names the missing package.
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
throw error
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const Schema = (await importInstallationPackage('@deepseek-ai/schemastery')).default
|
|
56
|
+
const httpProxy = await importInstallationPackage('@deepseek-ai/dsh-http-proxy')
|
|
57
|
+
|
|
58
|
+
/** Settings this plugin exposes to the Plugins page and its sidebar panel. */
|
|
59
|
+
export const Config = Schema.object({
|
|
60
|
+
enabled: Schema.boolean()
|
|
61
|
+
.default(false)
|
|
62
|
+
.description('Route the listed domains through the proxy server.')
|
|
63
|
+
.volatile(),
|
|
64
|
+
proxyUrl: Schema.string()
|
|
65
|
+
.default('')
|
|
66
|
+
.description('Proxy address with an http:// or https:// scheme, such as http://127.0.0.1:7890.')
|
|
67
|
+
.volatile(),
|
|
68
|
+
domains: Schema.string()
|
|
69
|
+
.default('github.com\ngithubusercontent.com')
|
|
70
|
+
.description('Hosts routed through the proxy, one per line or comma-separated; each matches its subdomains. Everything else connects directly.')
|
|
71
|
+
.volatile(),
|
|
72
|
+
fallback: Schema.boolean()
|
|
73
|
+
.default(true)
|
|
74
|
+
.description('When a host outside the list cannot be reached directly, retry once through the proxy server.')
|
|
75
|
+
.volatile(),
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
/** Largest proxy response head the router accepts before giving up. */
|
|
79
|
+
const MAX_RESPONSE_HEAD = 64 * 1024
|
|
80
|
+
|
|
81
|
+
/** How long a direct connection may take before the proxy fallback is used. */
|
|
82
|
+
const DIRECT_CONNECT_TIMEOUT_MS = 10_000
|
|
83
|
+
|
|
84
|
+
/** Client bytes kept for replay when a direct tunnel is switched to the proxy. */
|
|
85
|
+
const MAX_TUNNEL_PENDING = 64 * 1024
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Split configured text into domains.
|
|
89
|
+
* @param text - the configured value, separated by newlines, commas, or spaces.
|
|
90
|
+
* @returns domain entries without duplicates, in the order written.
|
|
91
|
+
*/
|
|
92
|
+
function parseDomains(text) {
|
|
93
|
+
const seen = new Set()
|
|
94
|
+
const entries = []
|
|
95
|
+
for (const raw of String(text).split(/[\s,]+/)) {
|
|
96
|
+
const entry = raw.trim()
|
|
97
|
+
if (entry === '') continue
|
|
98
|
+
const key = entry.toLowerCase()
|
|
99
|
+
if (seen.has(key)) continue
|
|
100
|
+
seen.add(key)
|
|
101
|
+
entries.push(entry)
|
|
102
|
+
}
|
|
103
|
+
return entries
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Whether the harness can route through this address. */
|
|
107
|
+
function supportedProxyUrl(value) {
|
|
108
|
+
try {
|
|
109
|
+
const url = new URL(value)
|
|
110
|
+
return url.protocol === 'http:' || url.protocol === 'https:'
|
|
111
|
+
} catch {
|
|
112
|
+
return false
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The proxy address without credentials, for log lines. */
|
|
117
|
+
function displayProxy(value) {
|
|
118
|
+
try {
|
|
119
|
+
const url = new URL(value)
|
|
120
|
+
return `${url.protocol}//${url.host}`
|
|
121
|
+
} catch {
|
|
122
|
+
return 'the configured address'
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Split one allowlist entry into host and optional port, accepting a bracketed
|
|
128
|
+
* IPv6 literal without mistaking its colons for a port separator.
|
|
129
|
+
* @param entry - one already-trimmed entry.
|
|
130
|
+
* @returns host and, when the entry carries one, its port text.
|
|
131
|
+
*/
|
|
132
|
+
function splitEntry(entry) {
|
|
133
|
+
if (entry.startsWith('[')) {
|
|
134
|
+
const close = entry.indexOf(']')
|
|
135
|
+
if (close !== -1) {
|
|
136
|
+
const rest = entry.slice(close + 1)
|
|
137
|
+
return { host: entry.slice(1, close), port: rest.startsWith(':') ? rest.slice(1) : undefined }
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const colon = entry.indexOf(':')
|
|
141
|
+
if (colon !== -1 && entry.indexOf(':', colon + 1) === -1) {
|
|
142
|
+
return { host: entry.slice(0, colon), port: entry.slice(colon + 1) }
|
|
143
|
+
}
|
|
144
|
+
return { host: entry, port: undefined }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Whether a host names this machine, where a proxy cannot meaningfully reach it.
|
|
149
|
+
* @param hostname - a connection's target host, bracketed or not.
|
|
150
|
+
* @returns true for a loopback or unspecified address.
|
|
151
|
+
*/
|
|
152
|
+
function isLoopbackHost(hostname) {
|
|
153
|
+
const host = String(hostname).replace(/^\[|\]$/g, '').replace(/\.$/, '').toLowerCase()
|
|
154
|
+
if (host === 'localhost' || host.endsWith('.localhost')) return true
|
|
155
|
+
if (host === '::1' || host === '::' || host === '0.0.0.0') return true
|
|
156
|
+
if (/^127\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/.test(host)) return true
|
|
157
|
+
const mappedHigh = /^::ffff:([0-9a-f]{1,4}):[0-9a-f]{1,4}$/.exec(host)?.[1]
|
|
158
|
+
return mappedHigh !== undefined && Number.parseInt(mappedHigh, 16) >>> 8 === 127
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Whether one host is listed for proxying.
|
|
163
|
+
*
|
|
164
|
+
* An entry names a host and matches it together with every subdomain under it;
|
|
165
|
+
* a leading `.` or `*.` is accepted, an entry may carry a `:port`, and `*`
|
|
166
|
+
* matches every host. CIDR ranges are not matched, matching the harness's own
|
|
167
|
+
* bypass rules. Loopback is never proxied, even through `*`, so local services
|
|
168
|
+
* cannot be sent to a remote proxy.
|
|
169
|
+
* @param domains - parsed allowlist entries.
|
|
170
|
+
* @param hostname - the connection's target host.
|
|
171
|
+
* @param port - the connection's target port.
|
|
172
|
+
* @returns true when the connection must go through the proxy.
|
|
173
|
+
*/
|
|
174
|
+
function listedForProxy(domains, hostname, port) {
|
|
175
|
+
const host = String(hostname).replace(/^\[|\]$/g, '').replace(/\.$/, '').toLowerCase()
|
|
176
|
+
if (host === '' || isLoopbackHost(host)) return false
|
|
177
|
+
for (const raw of domains) {
|
|
178
|
+
const entry = raw.toLowerCase()
|
|
179
|
+
if (entry === '*') return true
|
|
180
|
+
const split = splitEntry(entry)
|
|
181
|
+
if (split.port !== undefined && split.port !== String(port)) continue
|
|
182
|
+
const candidate = split.host.replace(/^\*?\./, '').replace(/\.$/, '')
|
|
183
|
+
if (candidate === '') continue
|
|
184
|
+
if (host === candidate || host.endsWith(`.${candidate}`)) return true
|
|
185
|
+
}
|
|
186
|
+
return false
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Format a tunnel authority for a CONNECT request line.
|
|
191
|
+
* @param host - target host, possibly an IPv6 literal.
|
|
192
|
+
* @param port - target port.
|
|
193
|
+
* @returns `host:port`, bracketing an IPv6 literal.
|
|
194
|
+
*/
|
|
195
|
+
function authority(host, port) {
|
|
196
|
+
return host.includes(':') && !host.startsWith('[') ? `[${host}]:${port}` : `${host}:${port}`
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Read a CONNECT authority as the client wrote it.
|
|
201
|
+
* @param value - the request's authority text.
|
|
202
|
+
* @returns host and port, or undefined when it cannot be read.
|
|
203
|
+
*/
|
|
204
|
+
function parseAuthority(value) {
|
|
205
|
+
const text = String(value)
|
|
206
|
+
const split = splitEntry(text)
|
|
207
|
+
const host = split.host.replace(/^\[|\]$/g, '')
|
|
208
|
+
if (host === '') return undefined
|
|
209
|
+
const port = split.port === undefined ? 443 : Number(split.port)
|
|
210
|
+
return { host, port: Number.isInteger(port) && port > 0 ? port : 443 }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Start the loopback router that applies the domain allowlist.
|
|
215
|
+
* @param options - the upstream proxy and the domains to send through it.
|
|
216
|
+
* @returns the listening port, an in-place update, and a disposer.
|
|
217
|
+
*/
|
|
218
|
+
function createRouter(options) {
|
|
219
|
+
const state = {
|
|
220
|
+
upstream: options.upstream,
|
|
221
|
+
domains: options.domains,
|
|
222
|
+
fallback: options.fallback === true,
|
|
223
|
+
}
|
|
224
|
+
const sockets = new Set()
|
|
225
|
+
const track = (socket) => {
|
|
226
|
+
sockets.add(socket)
|
|
227
|
+
socket.on('close', () => { sockets.delete(socket) })
|
|
228
|
+
return socket
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Read the current upstream settings.
|
|
233
|
+
* @returns transport choice, host, port, and the Proxy-Authorization header value.
|
|
234
|
+
*/
|
|
235
|
+
const proxyOf = () => {
|
|
236
|
+
const url = new URL(state.upstream)
|
|
237
|
+
const secure = url.protocol === 'https:'
|
|
238
|
+
return {
|
|
239
|
+
secure,
|
|
240
|
+
host: url.hostname,
|
|
241
|
+
port: Number(url.port) || (secure ? 443 : 80),
|
|
242
|
+
auth: url.username === '' && url.password === ''
|
|
243
|
+
? undefined
|
|
244
|
+
: `Basic ${Buffer.from(`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`).toString('base64')}`,
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Open one forwarding request for an absolute-form client request.
|
|
250
|
+
* @param target - the request's URL.
|
|
251
|
+
* @param method - the request method.
|
|
252
|
+
* @param incoming - the client's request headers.
|
|
253
|
+
* @param viaProxy - whether to ask the upstream proxy instead of the origin.
|
|
254
|
+
* @returns the client request object the caller pipes into.
|
|
255
|
+
*/
|
|
256
|
+
const forwardRequest = (target, method, incoming, viaProxy) => {
|
|
257
|
+
const headers = { ...incoming }
|
|
258
|
+
delete headers['proxy-connection']
|
|
259
|
+
if (viaProxy) {
|
|
260
|
+
const proxy = proxyOf()
|
|
261
|
+
if (proxy.auth !== undefined) headers['proxy-authorization'] = proxy.auth
|
|
262
|
+
const transport = proxy.secure ? https : http
|
|
263
|
+
return transport.request({
|
|
264
|
+
host: proxy.host,
|
|
265
|
+
port: proxy.port,
|
|
266
|
+
method,
|
|
267
|
+
path: target.href,
|
|
268
|
+
headers,
|
|
269
|
+
})
|
|
270
|
+
}
|
|
271
|
+
delete headers['proxy-authorization']
|
|
272
|
+
headers.host = target.host
|
|
273
|
+
return http.request({
|
|
274
|
+
host: target.hostname,
|
|
275
|
+
port: Number(target.port) || 80,
|
|
276
|
+
method,
|
|
277
|
+
path: `${target.pathname}${target.search}`,
|
|
278
|
+
headers,
|
|
279
|
+
})
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const server = http.createServer((req, res) => {
|
|
283
|
+
let target
|
|
284
|
+
try {
|
|
285
|
+
target = new URL(req.url ?? '')
|
|
286
|
+
} catch {
|
|
287
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
288
|
+
res.end('net-proxy: absolute-form request URL required')
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
if (target.protocol !== 'http:') {
|
|
292
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
293
|
+
res.end('net-proxy: https requests must use CONNECT')
|
|
294
|
+
return
|
|
295
|
+
}
|
|
296
|
+
const viaProxy = listedForProxy(state.domains, target.hostname, Number(target.port) || 80)
|
|
297
|
+
const fail = () => {
|
|
298
|
+
if (res.writableEnded) return
|
|
299
|
+
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' })
|
|
300
|
+
res.end('net-proxy: request failed')
|
|
301
|
+
}
|
|
302
|
+
const send = (throughProxy) => {
|
|
303
|
+
const request = forwardRequest(target, req.method, req.headers, throughProxy)
|
|
304
|
+
request.on('response', (answer) => {
|
|
305
|
+
if (res.writableEnded) {
|
|
306
|
+
answer.destroy()
|
|
307
|
+
return
|
|
308
|
+
}
|
|
309
|
+
res.writeHead(answer.statusCode ?? 502, answer.headers)
|
|
310
|
+
answer.pipe(res)
|
|
311
|
+
})
|
|
312
|
+
request.on('error', () => {
|
|
313
|
+
const replayable = !throughProxy && state.fallback && !res.writableEnded
|
|
314
|
+
&& (req.method === 'GET' || req.method === 'HEAD')
|
|
315
|
+
if (!replayable) {
|
|
316
|
+
fail()
|
|
317
|
+
return
|
|
318
|
+
}
|
|
319
|
+
const retry = send(true)
|
|
320
|
+
req.pipe(retry)
|
|
321
|
+
})
|
|
322
|
+
return request
|
|
323
|
+
}
|
|
324
|
+
req.pipe(send(viaProxy))
|
|
325
|
+
})
|
|
326
|
+
|
|
327
|
+
server.on('connect', (req, client, head) => {
|
|
328
|
+
client.pause()
|
|
329
|
+
track(client)
|
|
330
|
+
const target = parseAuthority(req.url)
|
|
331
|
+
if (target === undefined) {
|
|
332
|
+
client.end('HTTP/1.1 400 Bad Request\r\n\r\n')
|
|
333
|
+
return
|
|
334
|
+
}
|
|
335
|
+
const throughProxy = () => {
|
|
336
|
+
openProxyTunnel(target).then((remote) => {
|
|
337
|
+
track(remote)
|
|
338
|
+
startRelay(client, remote, head)
|
|
339
|
+
}).catch((error) => { failClient(client, error) })
|
|
340
|
+
}
|
|
341
|
+
if (listedForProxy(state.domains, target.host, target.port)) {
|
|
342
|
+
throughProxy()
|
|
343
|
+
return
|
|
344
|
+
}
|
|
345
|
+
openDirect(target).then((direct) => {
|
|
346
|
+
track(direct)
|
|
347
|
+
startDirectRelay(client, direct, head, target)
|
|
348
|
+
}).catch(() => {
|
|
349
|
+
if (!state.fallback) {
|
|
350
|
+
failClient(client)
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
throughProxy()
|
|
354
|
+
})
|
|
355
|
+
})
|
|
356
|
+
|
|
357
|
+
server.on('clientError', (_error, socket) => {
|
|
358
|
+
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
|
|
359
|
+
})
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Refuse one tunnel.
|
|
363
|
+
* @param client - the client socket.
|
|
364
|
+
* @param error - the proxy's refusal, whose status is relayed when it has one.
|
|
365
|
+
*/
|
|
366
|
+
function failClient(client, error) {
|
|
367
|
+
const status = typeof error?.status === 'number' ? error.status : 502
|
|
368
|
+
if (!client.destroyed) client.end(`HTTP/1.1 ${status} Bad Gateway\r\n\r\n`)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Connect to the target directly, bounded by the fallback timeout.
|
|
373
|
+
* @param target - host and port to reach.
|
|
374
|
+
* @returns the connected socket.
|
|
375
|
+
*/
|
|
376
|
+
function openDirect(target) {
|
|
377
|
+
return new Promise((resolve, reject) => {
|
|
378
|
+
const socket = net.connect(target.port, target.host)
|
|
379
|
+
const timer = setTimeout(() => {
|
|
380
|
+
socket.destroy()
|
|
381
|
+
reject(new Error('direct connection timed out'))
|
|
382
|
+
}, DIRECT_CONNECT_TIMEOUT_MS)
|
|
383
|
+
socket.once('connect', () => {
|
|
384
|
+
clearTimeout(timer)
|
|
385
|
+
resolve(socket)
|
|
386
|
+
})
|
|
387
|
+
socket.once('error', (error) => {
|
|
388
|
+
clearTimeout(timer)
|
|
389
|
+
reject(error)
|
|
390
|
+
})
|
|
391
|
+
})
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Ask the upstream proxy for a tunnel to the target.
|
|
396
|
+
* @param target - host and port to reach.
|
|
397
|
+
* @returns a socket already past the proxy handshake.
|
|
398
|
+
*/
|
|
399
|
+
function openProxyTunnel(target) {
|
|
400
|
+
const proxy = proxyOf()
|
|
401
|
+
return new Promise((resolve, reject) => {
|
|
402
|
+
let settled = false
|
|
403
|
+
const socket = proxy.secure
|
|
404
|
+
? tls.connect({ host: proxy.host, port: proxy.port, servername: proxy.host })
|
|
405
|
+
: net.connect(proxy.port, proxy.host)
|
|
406
|
+
const fail = (error) => {
|
|
407
|
+
if (settled) return
|
|
408
|
+
settled = true
|
|
409
|
+
socket.destroy()
|
|
410
|
+
reject(error)
|
|
411
|
+
}
|
|
412
|
+
socket.once('error', fail)
|
|
413
|
+
socket.once(proxy.secure ? 'secureConnect' : 'connect', () => {
|
|
414
|
+
const lines = [
|
|
415
|
+
`CONNECT ${authority(target.host, target.port)} HTTP/1.1`,
|
|
416
|
+
`Host: ${authority(target.host, target.port)}`,
|
|
417
|
+
]
|
|
418
|
+
if (proxy.auth !== undefined) lines.push(`Proxy-Authorization: ${proxy.auth}`)
|
|
419
|
+
socket.write(`${lines.join('\r\n')}\r\n\r\n`)
|
|
420
|
+
})
|
|
421
|
+
let buffer = Buffer.alloc(0)
|
|
422
|
+
const onData = (chunk) => {
|
|
423
|
+
buffer = Buffer.concat([buffer, chunk])
|
|
424
|
+
const end = buffer.indexOf('\r\n\r\n')
|
|
425
|
+
if (end < 0) {
|
|
426
|
+
if (buffer.length > MAX_RESPONSE_HEAD) fail(new Error('proxy response head is too large'))
|
|
427
|
+
return
|
|
428
|
+
}
|
|
429
|
+
socket.pause()
|
|
430
|
+
socket.off('data', onData)
|
|
431
|
+
const headText = buffer.subarray(0, end).toString('latin1')
|
|
432
|
+
const rest = buffer.subarray(end + 4)
|
|
433
|
+
const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(headText)?.[1] ?? 0)
|
|
434
|
+
if (status !== 200) {
|
|
435
|
+
const error = new Error(`proxy answered ${status}`)
|
|
436
|
+
error.status = status
|
|
437
|
+
fail(error)
|
|
438
|
+
return
|
|
439
|
+
}
|
|
440
|
+
settled = true
|
|
441
|
+
if (rest.length > 0) socket.unshift(rest)
|
|
442
|
+
resolve(socket)
|
|
443
|
+
}
|
|
444
|
+
socket.on('data', onData)
|
|
445
|
+
socket.once('close', () => { if (!settled) fail(new Error('proxy closed the connection')) })
|
|
446
|
+
})
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Hand an established tunnel to the client.
|
|
451
|
+
* @param client - the client socket.
|
|
452
|
+
* @param remote - the tunnel socket.
|
|
453
|
+
* @param head - bytes the client sent after its CONNECT headers.
|
|
454
|
+
*/
|
|
455
|
+
function startRelay(client, remote, head) {
|
|
456
|
+
if (client.destroyed) {
|
|
457
|
+
remote.destroy()
|
|
458
|
+
return
|
|
459
|
+
}
|
|
460
|
+
client.write('HTTP/1.1 200 Connection Established\r\n\r\n')
|
|
461
|
+
if (head.length > 0) remote.write(head)
|
|
462
|
+
remote.pipe(client)
|
|
463
|
+
client.pipe(remote)
|
|
464
|
+
client.resume()
|
|
465
|
+
remote.on('error', () => { client.destroy() })
|
|
466
|
+
client.on('error', () => { remote.destroy() })
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Relay a direct tunnel, switching it to the proxy when the origin never
|
|
471
|
+
* answers and the fallback is enabled.
|
|
472
|
+
*
|
|
473
|
+
* The client's bytes are forwarded immediately while a copy is kept. Until the
|
|
474
|
+
* origin sends its first byte back, the tunnel still carries a handshake, so a
|
|
475
|
+
* failed path can be replaced by the proxy connection and the buffered bytes
|
|
476
|
+
* replayed there; the client-side transport is end to end, so the client never
|
|
477
|
+
* observes the switch.
|
|
478
|
+
* @param client - the client socket.
|
|
479
|
+
* @param direct - the connected direct socket.
|
|
480
|
+
* @param head - bytes the client sent after its CONNECT headers.
|
|
481
|
+
* @param target - the tunnel's target.
|
|
482
|
+
*/
|
|
483
|
+
function startDirectRelay(client, direct, head, target) {
|
|
484
|
+
const pending = head.length > 0 ? [head] : []
|
|
485
|
+
let pendingBytes = head.length
|
|
486
|
+
let serverAnswered = false
|
|
487
|
+
let switched = false
|
|
488
|
+
let finished = false
|
|
489
|
+
let upstream = direct
|
|
490
|
+
|
|
491
|
+
client.write('HTTP/1.1 200 Connection Established\r\n\r\n')
|
|
492
|
+
if (head.length > 0) direct.write(head)
|
|
493
|
+
|
|
494
|
+
const finish = () => {
|
|
495
|
+
if (finished) return
|
|
496
|
+
finished = true
|
|
497
|
+
client.destroy()
|
|
498
|
+
direct.destroy()
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const switchToProxy = () => {
|
|
502
|
+
if (switched || serverAnswered || finished) return
|
|
503
|
+
if (!state.fallback || pendingBytes > MAX_TUNNEL_PENDING) {
|
|
504
|
+
finish()
|
|
505
|
+
return
|
|
506
|
+
}
|
|
507
|
+
switched = true
|
|
508
|
+
const previous = upstream
|
|
509
|
+
previous.removeAllListeners('data')
|
|
510
|
+
previous.removeAllListeners('error')
|
|
511
|
+
previous.removeAllListeners('close')
|
|
512
|
+
previous.on('error', () => {})
|
|
513
|
+
previous.destroy()
|
|
514
|
+
openProxyTunnel(target).then((remote) => {
|
|
515
|
+
if (finished || client.destroyed) {
|
|
516
|
+
remote.destroy()
|
|
517
|
+
return
|
|
518
|
+
}
|
|
519
|
+
track(remote)
|
|
520
|
+
upstream = remote
|
|
521
|
+
remote.on('data', (chunk) => {
|
|
522
|
+
serverAnswered = true
|
|
523
|
+
pending.length = 0
|
|
524
|
+
client.write(chunk)
|
|
525
|
+
})
|
|
526
|
+
remote.on('end', () => { finished = true; client.end() })
|
|
527
|
+
remote.on('error', () => { finished = true; client.destroy() })
|
|
528
|
+
for (const chunk of pending) remote.write(chunk)
|
|
529
|
+
pending.length = 0
|
|
530
|
+
}).catch(() => { finish() })
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
client.on('data', (chunk) => {
|
|
534
|
+
if (!serverAnswered) {
|
|
535
|
+
pending.push(chunk)
|
|
536
|
+
pendingBytes += chunk.length
|
|
537
|
+
if (pendingBytes > MAX_TUNNEL_PENDING) pending.length = 0
|
|
538
|
+
}
|
|
539
|
+
if (upstream.writable) upstream.write(chunk)
|
|
540
|
+
})
|
|
541
|
+
client.on('end', () => { if (upstream.writable) upstream.end() })
|
|
542
|
+
client.on('error', () => { if (upstream.writable) upstream.destroy() })
|
|
543
|
+
|
|
544
|
+
direct.on('data', (chunk) => {
|
|
545
|
+
serverAnswered = true
|
|
546
|
+
pending.length = 0
|
|
547
|
+
client.write(chunk)
|
|
548
|
+
})
|
|
549
|
+
direct.on('end', () => { if (!serverAnswered) switchToProxy() })
|
|
550
|
+
direct.on('error', () => { if (!serverAnswered) switchToProxy() })
|
|
551
|
+
direct.on('close', () => { if (!serverAnswered) switchToProxy() })
|
|
552
|
+
if (direct.destroyed || direct.readableEnded) switchToProxy()
|
|
553
|
+
|
|
554
|
+
client.resume()
|
|
555
|
+
}
|
|
556
|
+
return new Promise((resolve, reject) => {
|
|
557
|
+
server.once('error', reject)
|
|
558
|
+
server.listen(0, '127.0.0.1', () => {
|
|
559
|
+
const address = server.address()
|
|
560
|
+
if (typeof address !== 'object' || address === null) {
|
|
561
|
+
reject(new Error('net-proxy: router did not report a port'))
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
resolve({
|
|
565
|
+
port: address.port,
|
|
566
|
+
update(next) {
|
|
567
|
+
if (typeof next.upstream === 'string' && next.upstream !== '') state.upstream = next.upstream
|
|
568
|
+
if (Array.isArray(next.domains)) state.domains = next.domains
|
|
569
|
+
if (typeof next.fallback === 'boolean') state.fallback = next.fallback
|
|
570
|
+
},
|
|
571
|
+
close: async () => {
|
|
572
|
+
for (const socket of sockets) socket.destroy()
|
|
573
|
+
sockets.clear()
|
|
574
|
+
await new Promise((done) => { server.close(() => { done() }) })
|
|
575
|
+
},
|
|
576
|
+
})
|
|
577
|
+
})
|
|
578
|
+
})
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Present the router as the environment the harness's proxy installer reads.
|
|
583
|
+
* @param port - the router's loopback port.
|
|
584
|
+
* @returns an EnvLookup for both schemes.
|
|
585
|
+
*/
|
|
586
|
+
function routerEnvironment(port) {
|
|
587
|
+
const value = `http://127.0.0.1:${port}`
|
|
588
|
+
return {
|
|
589
|
+
get(name) {
|
|
590
|
+
const key = String(name).toLowerCase()
|
|
591
|
+
if (key === 'http_proxy' || key === 'https_proxy') return { value }
|
|
592
|
+
return undefined
|
|
593
|
+
},
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Keep the process policy in step with the live configuration.
|
|
599
|
+
* @param ctx - owning plugin context.
|
|
600
|
+
* @param config - validated plugin configuration, whose volatile fields are live references.
|
|
601
|
+
*/
|
|
602
|
+
export function apply(ctx, config) {
|
|
603
|
+
let disposed = false
|
|
604
|
+
let generation = 0
|
|
605
|
+
let session
|
|
606
|
+
let tail = Promise.resolve()
|
|
607
|
+
|
|
608
|
+
const read = () => ({
|
|
609
|
+
enabled: config.enabled.get() === true,
|
|
610
|
+
proxyUrl: String(config.proxyUrl.get() ?? '').trim(),
|
|
611
|
+
domains: String(config.domains.get() ?? ''),
|
|
612
|
+
fallback: config.fallback.get() === true,
|
|
613
|
+
})
|
|
614
|
+
|
|
615
|
+
const stop = async (current) => {
|
|
616
|
+
try {
|
|
617
|
+
await current.release()
|
|
618
|
+
} catch (error) {
|
|
619
|
+
ctx.logger.warn('net-proxy: releasing the previous policy failed: %s', error instanceof Error ? error.message : String(error))
|
|
620
|
+
}
|
|
621
|
+
try {
|
|
622
|
+
await current.router.close()
|
|
623
|
+
} catch (error) {
|
|
624
|
+
ctx.logger.warn('net-proxy: closing the previous router failed: %s', error instanceof Error ? error.message : String(error))
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
const sync = async () => {
|
|
629
|
+
if (disposed) return
|
|
630
|
+
const token = ++generation
|
|
631
|
+
const state = read()
|
|
632
|
+
const domains = parseDomains(state.domains)
|
|
633
|
+
const usable = supportedProxyUrl(state.proxyUrl)
|
|
634
|
+
const active = state.enabled && usable && domains.length > 0
|
|
635
|
+
const previous = session
|
|
636
|
+
|
|
637
|
+
if (!active) {
|
|
638
|
+
session = undefined
|
|
639
|
+
if (previous !== undefined) await stop(previous)
|
|
640
|
+
if (state.enabled && !usable) {
|
|
641
|
+
ctx.logger.warn('net-proxy: "Use proxy" is on but no usable proxy server is set; requests connect directly')
|
|
642
|
+
} else if (state.enabled && domains.length === 0) {
|
|
643
|
+
ctx.logger.warn('net-proxy: the proxied-domain list is empty; requests connect directly')
|
|
644
|
+
}
|
|
645
|
+
return
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
if (previous !== undefined) {
|
|
649
|
+
previous.router.update({ upstream: state.proxyUrl, domains, fallback: state.fallback })
|
|
650
|
+
ctx.logger.info('net-proxy: %d listed domain(s) go through %s; direct failures %s', domains.length, displayProxy(state.proxyUrl), state.fallback ? 'retry through the proxy' : 'do not fall back')
|
|
651
|
+
return
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
let router
|
|
655
|
+
try {
|
|
656
|
+
router = await createRouter({ upstream: state.proxyUrl, domains, fallback: state.fallback })
|
|
657
|
+
} catch (error) {
|
|
658
|
+
ctx.logger.error('net-proxy: starting the domain router failed: %s', error instanceof Error ? error.message : String(error))
|
|
659
|
+
return
|
|
660
|
+
}
|
|
661
|
+
if (disposed || token !== generation) {
|
|
662
|
+
await router.close()
|
|
663
|
+
return
|
|
664
|
+
}
|
|
665
|
+
try {
|
|
666
|
+
const release = await httpProxy.installProxyFromEnvironment(routerEnvironment(router.port), (message) => {
|
|
667
|
+
ctx.logger.warn('net-proxy: %s', message)
|
|
668
|
+
})
|
|
669
|
+
if (disposed || token !== generation) {
|
|
670
|
+
await release()
|
|
671
|
+
await router.close()
|
|
672
|
+
return
|
|
673
|
+
}
|
|
674
|
+
session = { release, router }
|
|
675
|
+
ctx.logger.info('net-proxy: %d listed domain(s) go through %s; direct failures %s', domains.length, displayProxy(state.proxyUrl), state.fallback ? 'retry through the proxy' : 'do not fall back')
|
|
676
|
+
} catch (error) {
|
|
677
|
+
await router.close()
|
|
678
|
+
ctx.logger.error('net-proxy: installing the proxy policy failed: %s', error instanceof Error ? error.message : String(error))
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const schedule = () => {
|
|
683
|
+
tail = tail.then(sync, sync)
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
ctx.effect(() => {
|
|
687
|
+
schedule()
|
|
688
|
+
const off = ctx.on('loader/volatile-update', schedule)
|
|
689
|
+
return async () => {
|
|
690
|
+
disposed = true
|
|
691
|
+
generation += 1
|
|
692
|
+
off()
|
|
693
|
+
const previous = session
|
|
694
|
+
session = undefined
|
|
695
|
+
if (previous !== undefined) await stop(previous)
|
|
696
|
+
await tail.catch(() => {})
|
|
697
|
+
}
|
|
698
|
+
}, 'net-proxy: domain allowlist policy')
|
|
699
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Network proxy",
|
|
4
|
+
"description": "Routes only the domains you list through your proxy server; every other host connects directly. Covers the Host's own requests (model calls, web fetch, HTTP MCP) and commands or terminals started afterwards. Set the proxy server and the domain list on this plugin's row page in Plugins (click the row title), or in the Network proxy panel in the left sidebar. Each entry also matches its subdomains; localhost and loopback always connect directly; only http:// and https:// proxies are supported. With “Retry direct failures through the proxy” on, a host outside the list that cannot be reached directly is tried once more through the proxy. If the proxy becomes unreachable, requests to the listed domains fail until you turn off Use proxy or remove them from the list."
|
|
5
|
+
}
|
|
6
|
+
}
|