@goodandready/dsh-messenger-gateway 0.4.15 → 0.4.17

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/lib/proxy.js ADDED
@@ -0,0 +1,669 @@
1
+ // Outbound proxy support for Telegram Bot API calls (HTTP/HTTPS CONNECT and SOCKS5).
2
+ //
3
+ // Telegram is blocked in some networks, so the gateway needs to reach
4
+ // api.telegram.org through a proxy. This module is dependency-free: it tunnels a
5
+ // raw TCP socket to the target through the configured proxy and then lets the
6
+ // regular node:https stack (with normal certificate verification) talk over it
7
+ // via a minimal custom agent.
8
+ //
9
+ // Supported proxy URLs:
10
+ // http://[user:pass@]host:port
11
+ // https://[user:pass@]host:port
12
+ // socks5://[user:pass@]host:port (socks5h:// and socks:// are aliases)
13
+ //
14
+ // Configuration precedence (first non-empty wins): plugin setting -> environment
15
+ // (DSH_MESSENGER_TELEGRAM_PROXY, TELEGRAM_PROXY, HTTPS_PROXY, ALL_PROXY, HTTP_PROXY).
16
+ // Setting the value to off/none/direct disables the setting and the environment.
17
+
18
+ import http from 'node:http'
19
+ import https from 'node:https'
20
+ import net from 'node:net'
21
+ import tls from 'node:tls'
22
+
23
+ const ENV_KEYS = [
24
+ 'DSH_MESSENGER_TELEGRAM_PROXY',
25
+ 'TELEGRAM_PROXY',
26
+ 'HTTPS_PROXY',
27
+ 'https_proxy',
28
+ 'ALL_PROXY',
29
+ 'all_proxy',
30
+ 'HTTP_PROXY',
31
+ 'http_proxy',
32
+ ]
33
+
34
+ const DISABLED_VALUES = new Set(['off', 'none', 'no', 'direct', 'false', '0', '-'])
35
+
36
+ const PROXY_KINDS = {
37
+ 'http:': { kind: 'http', protocol: 'http', defaultPort: 80 },
38
+ 'https:': { kind: 'https', protocol: 'https', defaultPort: 443 },
39
+ 'socks:': { kind: 'socks5', protocol: 'socks5', defaultPort: 1080 },
40
+ 'socks5:': { kind: 'socks5', protocol: 'socks5', defaultPort: 1080 },
41
+ 'socks5h:': { kind: 'socks5', protocol: 'socks5', defaultPort: 1080 },
42
+ }
43
+
44
+ function decodePart(value) {
45
+ if (!value) return ''
46
+ try {
47
+ return decodeURIComponent(value)
48
+ } catch {
49
+ return value
50
+ }
51
+ }
52
+
53
+ function bareHost(hostname) {
54
+ return String(hostname || '').replace(/^\[|\]$/g, '')
55
+ }
56
+
57
+ /** Parse a proxy URL into a spec object; returns null when no proxy is configured. */
58
+ export function parseProxySpec(raw) {
59
+ const value = String(raw ?? '').trim()
60
+ if (!value) return null
61
+ if (DISABLED_VALUES.has(value.toLowerCase())) return null
62
+ const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? value : `http://${value}`
63
+ let url
64
+ try {
65
+ url = new URL(candidate)
66
+ } catch {
67
+ throw new Error(`invalid proxy URL: ${value}`)
68
+ }
69
+ const entry = PROXY_KINDS[url.protocol.toLowerCase()]
70
+ if (!entry) {
71
+ throw new Error(`unsupported proxy protocol "${url.protocol}" (use http://, https:// or socks5://)`)
72
+ }
73
+ const host = bareHost(url.hostname)
74
+ if (!host) throw new Error(`invalid proxy URL: ${value}`)
75
+ const spec = {
76
+ kind: entry.kind,
77
+ protocol: entry.protocol,
78
+ host,
79
+ port: Number(url.port) || entry.defaultPort,
80
+ username: decodePart(url.username),
81
+ password: decodePart(url.password),
82
+ raw: value,
83
+ }
84
+ spec.label = maskProxyUrl(spec)
85
+ return spec
86
+ }
87
+
88
+ /** Credential-safe proxy label for logs and the settings UI. */
89
+ export function maskProxyUrl(specOrUrl) {
90
+ const spec = typeof specOrUrl === 'string' ? parseProxySpec(specOrUrl) : specOrUrl
91
+ if (!spec) return ''
92
+ const auth = (spec.username || spec.password) ? `${encodeURIComponent(spec.username)}:***@` : ''
93
+ return `${spec.protocol}://${auth}${spec.host}:${spec.port}`
94
+ }
95
+
96
+ /**
97
+ * Resolve the effective proxy URL: explicit plugin setting first, environment
98
+ * second. Returns '' when no proxy should be used.
99
+ */
100
+ export function resolveProxySetting(configured, env = process.env) {
101
+ const explicit = String(configured ?? '').trim()
102
+ if (explicit) {
103
+ if (DISABLED_VALUES.has(explicit.toLowerCase())) return ''
104
+ return explicit
105
+ }
106
+ for (const key of ENV_KEYS) {
107
+ const value = String(env?.[key] ?? '').trim()
108
+ if (!value) continue
109
+ if (DISABLED_VALUES.has(value.toLowerCase())) return ''
110
+ return value
111
+ }
112
+ return ''
113
+ }
114
+
115
+ /** True when no_proxy/NO_PROXY says the host must be reached directly. */
116
+ export function shouldBypassProxy(host, env = process.env) {
117
+ const rules = String((env?.no_proxy || env?.NO_PROXY) ?? '').trim()
118
+ if (!rules) return false
119
+ const target = String(host || '').toLowerCase()
120
+ for (const rawRule of rules.split(',')) {
121
+ const rule = rawRule.trim().toLowerCase()
122
+ if (!rule) continue
123
+ if (rule === '*') return true
124
+ const bare = rule.startsWith('.') ? rule.slice(1) : rule
125
+ if (target === bare || target.endsWith(`.${bare}`)) return true
126
+ }
127
+ return false
128
+ }
129
+
130
+ function basicAuthHeader(spec) {
131
+ if (!spec.username && !spec.password) return undefined
132
+ return `Basic ${Buffer.from(`${spec.username}:${spec.password}`).toString('base64')}`
133
+ }
134
+
135
+ function isAborted(signal) {
136
+ return Boolean(signal?.aborted)
137
+ }
138
+
139
+ function abortReason(signal, fallback = 'proxy request aborted') {
140
+ const reason = signal?.reason
141
+ if (reason instanceof Error) return reason
142
+ if (reason !== undefined) return new Error(String(reason))
143
+ return new Error(fallback)
144
+ }
145
+
146
+ /** Tunnel to host:port through an http(s) proxy using the CONNECT method. */
147
+ function connectViaHttpProxy(spec, host, port, { signal, timeoutMs }) {
148
+ return new Promise((resolve, reject) => {
149
+ const mod = spec.kind === 'https' ? https : http
150
+ const headers = { host: `${host}:${port}` }
151
+ const auth = basicAuthHeader(spec)
152
+ if (auth) headers['proxy-authorization'] = auth
153
+ const options = {
154
+ host: spec.host,
155
+ port: spec.port,
156
+ method: 'CONNECT',
157
+ path: `${host}:${port}`,
158
+ headers,
159
+ agent: false,
160
+ }
161
+ if (spec.kind === 'https') options.servername = spec.host
162
+
163
+ let settled = false
164
+ const req = mod.request(options)
165
+ const cleanup = () => {
166
+ if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
167
+ }
168
+ const fail = (err) => {
169
+ if (settled) return
170
+ settled = true
171
+ cleanup()
172
+ reject(err)
173
+ }
174
+ const onAbort = () => {
175
+ req.destroy(abortReason(signal))
176
+ fail(abortReason(signal))
177
+ }
178
+ req.setTimeout(Math.max(1000, Number(timeoutMs) || 20000), () => {
179
+ req.destroy(new Error(`proxy CONNECT timeout after ${timeoutMs}ms`))
180
+ })
181
+ req.on('error', (err) => fail(err))
182
+ req.on('response', (res) => {
183
+ res.resume()
184
+ fail(new Error(`proxy CONNECT rejected (HTTP ${res.statusCode}${res.statusCode === 407 ? ' proxy authentication required' : ''})`))
185
+ })
186
+ req.on('connect', (res, socket, head) => {
187
+ if (settled) {
188
+ socket.destroy()
189
+ return
190
+ }
191
+ if (res.statusCode !== 200) {
192
+ socket.destroy()
193
+ fail(new Error(`proxy CONNECT rejected (HTTP ${res.statusCode}${res.statusCode === 407 ? ' proxy authentication required' : ''})`))
194
+ return
195
+ }
196
+ settled = true
197
+ cleanup()
198
+ socket.setNoDelay(true)
199
+ if (head && head.length) socket.unshift(head)
200
+ resolve(socket)
201
+ })
202
+ if (signal) {
203
+ if (isAborted(signal)) {
204
+ onAbort()
205
+ return
206
+ }
207
+ signal.addEventListener('abort', onAbort, { once: true })
208
+ }
209
+ req.end()
210
+ })
211
+ }
212
+
213
+ /** Small exact-length reader used for the SOCKS5 handshake. */
214
+ class SocketReader {
215
+ constructor(socket) {
216
+ this.socket = socket
217
+ this.buffer = Buffer.alloc(0)
218
+ this.error = null
219
+ this.closed = false
220
+ this.waiters = []
221
+ this.onData = (chunk) => {
222
+ this.buffer = Buffer.concat([this.buffer, chunk])
223
+ this.wake()
224
+ }
225
+ this.onError = (err) => {
226
+ this.error = err
227
+ this.wake()
228
+ }
229
+ this.onClose = () => {
230
+ this.closed = true
231
+ this.wake()
232
+ }
233
+ socket.on('data', this.onData)
234
+ socket.on('error', this.onError)
235
+ socket.on('close', this.onClose)
236
+ }
237
+
238
+ wake() {
239
+ const waiters = this.waiters
240
+ this.waiters = []
241
+ for (const resolve of waiters) resolve()
242
+ }
243
+
244
+ async read(size) {
245
+ while (this.buffer.length < size) {
246
+ if (this.error) throw this.error
247
+ if (this.closed) throw new Error('proxy closed the connection during SOCKS5 handshake')
248
+ await new Promise((resolve) => this.waiters.push(resolve))
249
+ }
250
+ const out = this.buffer.subarray(0, size)
251
+ this.buffer = this.buffer.subarray(size)
252
+ return out
253
+ }
254
+
255
+ detach() {
256
+ this.socket.removeListener('data', this.onData)
257
+ this.socket.removeListener('error', this.onError)
258
+ this.socket.removeListener('close', this.onClose)
259
+ const rest = this.buffer
260
+ this.buffer = Buffer.alloc(0)
261
+ return rest
262
+ }
263
+ }
264
+
265
+ function socksErrorMessage(code) {
266
+ const map = {
267
+ 0x01: 'general SOCKS server failure',
268
+ 0x02: 'connection not allowed by ruleset',
269
+ 0x03: 'network unreachable',
270
+ 0x04: 'host unreachable',
271
+ 0x05: 'connection refused',
272
+ 0x06: 'TTL expired',
273
+ 0x07: 'command not supported',
274
+ 0x08: 'address type not supported',
275
+ }
276
+ return map[code] || `error 0x${Number(code).toString(16)}`
277
+ }
278
+
279
+ function encodeSocksTarget(host, port) {
280
+ const portBuf = Buffer.alloc(2)
281
+ portBuf.writeUInt16BE(port, 0)
282
+ if (net.isIPv4(host)) {
283
+ return Buffer.concat([Buffer.from([0x01]), Buffer.from(host.split('.').map(Number)), portBuf])
284
+ }
285
+ if (net.isIPv6(host)) {
286
+ return Buffer.concat([Buffer.from([0x04]), expandIpv6(host), portBuf])
287
+ }
288
+ const name = Buffer.from(host, 'utf8')
289
+ if (name.length > 255) throw new Error(`SOCKS5 target host too long: ${host}`)
290
+ return Buffer.concat([Buffer.from([0x03, name.length]), name, portBuf])
291
+ }
292
+
293
+ function expandIpv6(host) {
294
+ const [head, tail] = host.split('::')
295
+ const headParts = head ? head.split(':').filter(Boolean) : []
296
+ const tailParts = tail !== undefined && tail ? tail.split(':').filter(Boolean) : []
297
+ const missing = 8 - headParts.length - tailParts.length
298
+ const parts = [...headParts, ...Array(Math.max(0, missing)).fill('0'), ...tailParts]
299
+ const buf = Buffer.alloc(16)
300
+ parts.slice(0, 8).forEach((part, index) => buf.writeUInt16BE(parseInt(part || '0', 16) || 0, index * 2))
301
+ return buf
302
+ }
303
+
304
+ function writeAll(socket, buffer) {
305
+ return new Promise((resolve, reject) => {
306
+ const onError = (err) => {
307
+ socket.removeListener('error', onError)
308
+ reject(err)
309
+ }
310
+ socket.once('error', onError)
311
+ socket.write(buffer, () => {
312
+ socket.removeListener('error', onError)
313
+ resolve()
314
+ })
315
+ })
316
+ }
317
+
318
+ /** Tunnel to host:port through a SOCKS5 proxy (remote DNS resolution). */
319
+ async function connectViaSocks5(spec, host, port, { signal, timeoutMs }) {
320
+ const socket = net.connect({ host: spec.host, port: spec.port })
321
+ socket.setNoDelay(true)
322
+ const reader = new SocketReader(socket)
323
+ const cleanup = () => {
324
+ if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
325
+ }
326
+ const onAbort = () => {
327
+ socket.destroy(abortReason(signal))
328
+ }
329
+ const timer = setTimeout(
330
+ () => socket.destroy(new Error(`SOCKS5 handshake timeout after ${timeoutMs}ms`)),
331
+ Math.max(1000, Number(timeoutMs) || 20000),
332
+ )
333
+ if (signal) {
334
+ if (isAborted(signal)) onAbort()
335
+ else signal.addEventListener('abort', onAbort, { once: true })
336
+ }
337
+ try {
338
+ await new Promise((resolve, reject) => {
339
+ socket.once('connect', resolve)
340
+ socket.once('error', reject)
341
+ })
342
+ const useAuth = Boolean(spec.username || spec.password)
343
+ await writeAll(socket, useAuth ? Buffer.from([0x05, 0x02, 0x00, 0x02]) : Buffer.from([0x05, 0x01, 0x00]))
344
+ const greeting = await reader.read(2)
345
+ if (greeting[0] !== 0x05) throw new Error(`SOCKS5 proxy reply has unsupported version 0x${greeting[0].toString(16)}`)
346
+ if (greeting[1] === 0xff) throw new Error('SOCKS5 proxy refused all authentication methods')
347
+ if (greeting[1] === 0x02) {
348
+ if (!useAuth) throw new Error('SOCKS5 proxy requires username/password authentication')
349
+ const user = Buffer.from(spec.username, 'utf8')
350
+ const pass = Buffer.from(spec.password, 'utf8')
351
+ await writeAll(socket, Buffer.concat([Buffer.from([0x01, user.length]), user, Buffer.from([pass.length]), pass]))
352
+ const authReply = await reader.read(2)
353
+ if (authReply[1] !== 0x00) throw new Error('SOCKS5 proxy rejected the supplied username/password')
354
+ } else if (greeting[1] !== 0x00) {
355
+ throw new Error(`SOCKS5 proxy selected unsupported authentication method 0x${greeting[1].toString(16)}`)
356
+ }
357
+ await writeAll(socket, Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), encodeSocksTarget(host, port)]))
358
+ const replyHead = await reader.read(4)
359
+ if (replyHead[0] !== 0x05) throw new Error('SOCKS5 proxy returned a malformed reply')
360
+ if (replyHead[1] !== 0x00) {
361
+ throw new Error(`SOCKS5 proxy could not connect to ${host}:${port} (${socksErrorMessage(replyHead[1])})`)
362
+ }
363
+ const atyp = replyHead[3]
364
+ const addrLength = atyp === 0x01 ? 4 : atyp === 0x04 ? 16 : (await reader.read(1))[0]
365
+ await reader.read(addrLength + 2)
366
+ const leftover = reader.detach()
367
+ if (leftover.length) socket.unshift(leftover)
368
+ return socket
369
+ } catch (err) {
370
+ reader.detach()
371
+ socket.destroy()
372
+ throw err
373
+ } finally {
374
+ clearTimeout(timer)
375
+ cleanup()
376
+ }
377
+ }
378
+
379
+ async function openTunnel(spec, host, port, options) {
380
+ return spec.kind === 'socks5'
381
+ ? connectViaSocks5(spec, host, port, options)
382
+ : connectViaHttpProxy(spec, host, port, options)
383
+ }
384
+
385
+ function wrapTls(socket, servername, { signal } = {}) {
386
+ return new Promise((resolve, reject) => {
387
+ const cleanup = () => {
388
+ if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
389
+ }
390
+ const onAbort = () => {
391
+ socket.destroy(abortReason(signal))
392
+ reject(abortReason(signal))
393
+ }
394
+ const tlsSocket = tls.connect({ socket, servername, ALPNProtocols: ['http/1.1'], minVersion: 'TLSv1.2' }, () => {
395
+ cleanup()
396
+ resolve(tlsSocket)
397
+ })
398
+ tlsSocket.once('error', (err) => {
399
+ cleanup()
400
+ reject(err)
401
+ })
402
+ if (signal) {
403
+ if (isAborted(signal)) {
404
+ onAbort()
405
+ return
406
+ }
407
+ signal.addEventListener('abort', onAbort, { once: true })
408
+ }
409
+ })
410
+ }
411
+
412
+ /**
413
+ * Minimal http.Agent-compatible object: every request gets a fresh tunnel, so
414
+ * there is no socket pool to maintain. Node calls addRequest() and receives the
415
+ * connected socket back through req.onSocket().
416
+ */
417
+ class ProxyTunnelAgent {
418
+ constructor({ spec, timeoutMs, logger }) {
419
+ this.spec = spec
420
+ this.timeoutMs = timeoutMs
421
+ this.logger = logger
422
+ this.protocol = 'https:'
423
+ this.defaultPort = 443
424
+ this.keepAlive = false
425
+ }
426
+
427
+ getName() {
428
+ return `dsh-telegram-proxy:${this.spec.label}`
429
+ }
430
+
431
+ keepSocketAlive() {
432
+ return false
433
+ }
434
+
435
+ reuseSocket(socket) {
436
+ try { socket?.destroy() } catch { /* ignore */ }
437
+ }
438
+
439
+ destroy() {
440
+ /* nothing pooled */
441
+ }
442
+
443
+ addRequest(req, options = {}) {
444
+ const targetHost = options.host || options.hostname
445
+ const targetPort = Number(options.port) || (options.protocol === 'https:' ? 443 : 80)
446
+ const signal = options.__dshAbortSignal
447
+ const servername = options.servername || targetHost
448
+ openTunnel(this.spec, targetHost, targetPort, { signal, timeoutMs: this.timeoutMs })
449
+ .then(async (raw) => {
450
+ try {
451
+ if (signal?.aborted) throw abortReason(signal)
452
+ return options.protocol === 'https:' ? await wrapTls(raw, servername, { signal }) : raw
453
+ } catch (err) {
454
+ raw.destroy()
455
+ throw err
456
+ }
457
+ })
458
+ .then((socket) => {
459
+ if (req.destroyed) {
460
+ socket.destroy()
461
+ return
462
+ }
463
+ req.onSocket(socket)
464
+ })
465
+ .catch((err) => {
466
+ this.logger?.debug?.(`telegram proxy tunnel failed (${this.spec.label}): ${err?.message || err}`)
467
+ failRequest(req, err)
468
+ })
469
+ }
470
+ }
471
+
472
+ // A ClientRequest that never received a socket does not surface destroy(err):
473
+ // Node only emits 'error' once the request owns a socket. Report the failure
474
+ // explicitly so the awaiting fetch() rejects instead of hanging.
475
+ function failRequest(req, err) {
476
+ try { req.destroy() } catch { /* ignore */ }
477
+ try { req.emit('error', err) } catch { /* ignore */ }
478
+ }
479
+
480
+ function headersToObject(headers) {
481
+ if (!headers) return {}
482
+ if (typeof headers.forEach === 'function' && typeof headers.get === 'function') {
483
+ const out = {}
484
+ headers.forEach((value, key) => { out[key] = value })
485
+ return out
486
+ }
487
+ if (Array.isArray(headers)) return Object.fromEntries(headers)
488
+ return { ...headers }
489
+ }
490
+
491
+ async function serializeBody(body) {
492
+ if (body === undefined || body === null) return { buffer: null, contentType: undefined }
493
+ if (typeof body === 'string') return { buffer: Buffer.from(body, 'utf8'), contentType: undefined }
494
+ if (Buffer.isBuffer(body)) return { buffer: body, contentType: undefined }
495
+ if (body instanceof Uint8Array) return { buffer: Buffer.from(body), contentType: undefined }
496
+ if (body instanceof ArrayBuffer) return { buffer: Buffer.from(body), contentType: undefined }
497
+ if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
498
+ return { buffer: Buffer.from(body.toString(), 'utf8'), contentType: 'application/x-www-form-urlencoded;charset=UTF-8' }
499
+ }
500
+ if (typeof FormData !== 'undefined' && typeof Request !== 'undefined' && body instanceof FormData) {
501
+ // Let the platform multipart encoder build the body, then read it back.
502
+ const prepared = new Request('http://dsh-messenger-gateway.invalid/', { method: 'POST', body })
503
+ const buffer = Buffer.from(await prepared.arrayBuffer())
504
+ return { buffer, contentType: prepared.headers.get('content-type') || undefined }
505
+ }
506
+ return { buffer: Buffer.from(String(body), 'utf8'), contentType: undefined }
507
+ }
508
+
509
+ function makeResponse(res, buffer, url) {
510
+ const headers = res.headers || {}
511
+ return {
512
+ ok: Number(res.statusCode) >= 200 && Number(res.statusCode) < 300,
513
+ status: Number(res.statusCode),
514
+ statusText: String(res.statusMessage || ''),
515
+ url,
516
+ headers: {
517
+ get: (name) => {
518
+ const value = headers[String(name).toLowerCase()]
519
+ return value === undefined ? null : String(value)
520
+ },
521
+ has: (name) => headers[String(name).toLowerCase()] !== undefined,
522
+ forEach: (cb) => {
523
+ for (const [key, value] of Object.entries(headers)) cb(String(value), key)
524
+ },
525
+ entries: () => Object.entries(headers)[Symbol.iterator](),
526
+ },
527
+ async text() { return buffer.toString('utf8') },
528
+ async json() { return JSON.parse(buffer.toString('utf8')) },
529
+ async arrayBuffer() {
530
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
531
+ },
532
+ async blob() { return new Blob([buffer]) },
533
+ }
534
+ }
535
+
536
+ function requestOverTunnel({ spec, url, method, headers, body, signal, timeoutMs, logger }) {
537
+ return new Promise((resolve, reject) => {
538
+ const mod = url.protocol === 'https:' ? https : http
539
+ const onAbort = () => {
540
+ const reason = abortReason(signal)
541
+ failRequest(req, reason)
542
+ reject(reason)
543
+ }
544
+ let req
545
+ serializeBody(body).then((payload) => {
546
+ const outgoing = { ...headers }
547
+ delete outgoing['content-length']
548
+ delete outgoing['Content-Length']
549
+ if (payload.contentType && !outgoing['content-type'] && !outgoing['Content-Type']) {
550
+ outgoing['content-type'] = payload.contentType
551
+ }
552
+ if (!outgoing.host && !outgoing.Host) outgoing.host = url.host
553
+ if (signal?.aborted) {
554
+ reject(abortReason(signal))
555
+ return
556
+ }
557
+ const agent = new ProxyTunnelAgent({ spec, timeoutMs, logger })
558
+ req = mod.request({
559
+ protocol: url.protocol,
560
+ host: url.hostname,
561
+ hostname: url.hostname,
562
+ port: Number(url.port) || (url.protocol === 'https:' ? 443 : 80),
563
+ path: `${url.pathname}${url.search}`,
564
+ method: String(method || 'GET').toUpperCase(),
565
+ headers: outgoing,
566
+ servername: url.hostname,
567
+ agent,
568
+ __dshAbortSignal: signal,
569
+ }, (res) => {
570
+ const chunks = []
571
+ res.on('data', (chunk) => chunks.push(chunk))
572
+ res.on('end', () => {
573
+ if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
574
+ resolve(makeResponse(res, Buffer.concat(chunks), url.href))
575
+ })
576
+ res.on('error', (err) => {
577
+ if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
578
+ reject(err)
579
+ })
580
+ })
581
+ req.on('error', (err) => {
582
+ if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
583
+ reject(err)
584
+ })
585
+ if (signal) signal.addEventListener('abort', onAbort, { once: true })
586
+ req.end(payload.buffer ?? undefined)
587
+ }, reject)
588
+ })
589
+ }
590
+
591
+ /** Canonical proxy URL (compat with the upstream `normalizeProxyUrl`). */
592
+ export function normalizeProxyUrl(raw) {
593
+ const spec = parseProxySpec(raw)
594
+ if (!spec) return ''
595
+ const auth = (spec.username || spec.password)
596
+ ? `${encodeURIComponent(spec.username)}:${encodeURIComponent(spec.password)}@`
597
+ : ''
598
+ return `${spec.protocol}://${auth}${spec.host}:${spec.port}`
599
+ }
600
+
601
+ /** Custom Telegram Bot API root (upstream name for the api base URL). */
602
+ export function normalizeApiRoot(rawUrl) {
603
+ const trimmed = String(rawUrl || '').trim()
604
+ if (!trimmed) return 'https://api.telegram.org'
605
+ let parsed
606
+ try {
607
+ parsed = new URL(trimmed)
608
+ } catch (err) {
609
+ throw new Error(`Invalid apiRoot URL "${trimmed}": ${err.message}`)
610
+ }
611
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
612
+ throw new Error(`Unsupported apiRoot protocol "${parsed.protocol}". Must be http: or https:`)
613
+ }
614
+ return trimmed.replace(/\/+$/, '')
615
+ }
616
+
617
+ /**
618
+ * Build a fetch()-compatible function that routes every request through the
619
+ * proxy. Returns null when no proxy is configured (callers keep global fetch).
620
+ * Throws on malformed proxy URLs so the failure is visible in the plugin log.
621
+ */
622
+ export function createProxiedFetch(configuredProxy, options = {}) {
623
+ const env = options.env || process.env
624
+ const resolved = resolveProxySetting(configuredProxy, env)
625
+ if (!resolved) return null
626
+ const spec = parseProxySpec(resolved)
627
+ if (!spec) return null
628
+ const timeoutMs = Number(options.timeoutMs) || 20_000
629
+ const logger = options.logger
630
+ const proxied = async (input, init = {}) => {
631
+ const href = typeof input === 'string' ? input : (input instanceof URL ? input.href : input?.url)
632
+ const url = new URL(href)
633
+ if (shouldBypassProxy(url.hostname, env)) return fetch(input, init)
634
+ return requestOverTunnel({
635
+ spec,
636
+ url,
637
+ method: init.method || 'GET',
638
+ headers: headersToObject(init.headers),
639
+ body: init.body,
640
+ signal: init.signal,
641
+ timeoutMs,
642
+ logger,
643
+ })
644
+ }
645
+ proxied.proxy = spec
646
+ proxied.label = spec.label
647
+ proxied.raw = resolved
648
+ return proxied
649
+ }
650
+
651
+ /** Human readable proxy state for logs and the settings UI diagnostics. */
652
+ export function describeProxy(configuredProxy, env = process.env) {
653
+ const explicit = String(configuredProxy ?? '').trim()
654
+ try {
655
+ const resolved = resolveProxySetting(configuredProxy, env)
656
+ if (!resolved) return { configured: explicit, source: explicit ? 'settings' : 'env', active: false, label: '' }
657
+ const spec = parseProxySpec(resolved)
658
+ if (!spec) return { configured: explicit, active: false, label: '' }
659
+ return {
660
+ configured: explicit,
661
+ source: explicit ? 'settings' : 'env',
662
+ active: true,
663
+ label: spec.label,
664
+ kind: spec.kind,
665
+ }
666
+ } catch (err) {
667
+ return { configured: explicit, active: false, error: err.message, label: '' }
668
+ }
669
+ }