@itphx/synth-shared 0.10.1 → 0.12.3
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/dist/config/defaults.js +172 -3
- package/dist/config/env-overrides.d.ts +33 -1
- package/dist/config/env-overrides.js +191 -5
- package/dist/config/execution.d.ts +66 -0
- package/dist/config/execution.js +146 -0
- package/dist/config/index.d.ts +4 -0
- package/dist/config/index.js +4 -0
- package/dist/config/loader.js +19 -0
- package/dist/config/proxy.d.ts +415 -0
- package/dist/config/proxy.js +1567 -0
- package/dist/config/resolve.d.ts +67 -0
- package/dist/config/resolve.js +187 -1
- package/dist/config/tls-runtime.d.ts +78 -0
- package/dist/config/tls-runtime.js +356 -0
- package/dist/config/tls.d.ts +215 -0
- package/dist/config/tls.js +394 -0
- package/dist/config/types.d.ts +1571 -2835
- package/dist/config/types.js +717 -58
- package/dist/i18n/index.d.ts +1 -1
- package/dist/i18n/index.js +279 -0
- package/dist/index.d.ts +24 -3
- package/dist/index.js +25 -2
- package/dist/model-metadata.d.ts +10 -0
- package/dist/protocols/index.d.ts +0 -1
- package/dist/schemas/index.d.ts +1014 -2231
- package/dist/schemas/index.js +222 -14
- package/dist/types/analytics.d.ts +113 -0
- package/dist/types/analytics.js +61 -0
- package/dist/types/authority.d.ts +464 -0
- package/dist/types/authority.js +445 -0
- package/dist/types/background.d.ts +96 -0
- package/dist/types/background.js +24 -0
- package/dist/types/bus-events.d.ts +23 -1
- package/dist/types/catalog.d.ts +349 -0
- package/dist/types/catalog.js +393 -0
- package/dist/types/decision.d.ts +28 -337
- package/dist/types/egress.d.ts +114 -0
- package/dist/types/egress.js +68 -0
- package/dist/types/events.d.ts +54 -2
- package/dist/types/external-credentials.d.ts +352 -0
- package/dist/types/external-credentials.js +200 -0
- package/dist/types/fs.d.ts +11 -0
- package/dist/types/fs.js +11 -0
- package/dist/types/hooks.d.ts +50 -9
- package/dist/types/index.d.ts +23 -0
- package/dist/types/index.js +55 -0
- package/dist/types/llm-filters.d.ts +150 -0
- package/dist/types/llm-filters.js +54 -0
- package/dist/types/maintenance.d.ts +39 -0
- package/dist/types/maintenance.js +11 -0
- package/dist/types/mcp.d.ts +101 -5
- package/dist/types/mcp.js +127 -5
- package/dist/types/message.d.ts +45 -1
- package/dist/types/pack.d.ts +1102 -0
- package/dist/types/pack.js +1003 -0
- package/dist/types/permission.d.ts +31 -15
- package/dist/types/permission.js +1 -1
- package/dist/types/pipeline-engine.d.ts +453 -0
- package/dist/types/pipeline-engine.js +440 -0
- package/dist/types/pipeline.d.ts +275 -0
- package/dist/types/pipeline.js +212 -0
- package/dist/types/plugin-audit.d.ts +110 -0
- package/dist/types/plugin-audit.js +185 -0
- package/dist/types/plugin-hybrid.d.ts +85 -0
- package/dist/types/plugin-hybrid.js +68 -0
- package/dist/types/plugin-lock.d.ts +95 -0
- package/dist/types/plugin-lock.js +1 -0
- package/dist/types/plugin-protocol.d.ts +221 -0
- package/dist/types/plugin-protocol.js +322 -0
- package/dist/types/plugin-runtime.d.ts +25 -0
- package/dist/types/plugin-runtime.js +11 -0
- package/dist/types/plugin-scan.d.ts +159 -0
- package/dist/types/plugin-scan.js +166 -0
- package/dist/types/plugin-tools.d.ts +51 -0
- package/dist/types/plugin-tools.js +72 -0
- package/dist/types/project.d.ts +14 -0
- package/dist/types/prompt-blocks.d.ts +102 -0
- package/dist/types/prompt-blocks.js +24 -0
- package/dist/types/prompt.d.ts +47 -4
- package/dist/types/provider.d.ts +11 -0
- package/dist/types/question.d.ts +153 -0
- package/dist/types/question.js +65 -0
- package/dist/types/schedules.d.ts +26 -3
- package/dist/types/semver.d.ts +48 -0
- package/dist/types/semver.js +218 -0
- package/dist/types/service-keys.d.ts +41 -3
- package/dist/types/service-keys.js +44 -2
- package/dist/types/session.d.ts +54 -1
- package/dist/types/steering.d.ts +74 -0
- package/dist/types/steering.js +75 -0
- package/dist/types/tools.d.ts +125 -5
- package/dist/types/tools.js +75 -0
- package/dist/types/trust.d.ts +31 -0
- package/dist/types/trust.js +27 -0
- package/dist/types/webhooks.d.ts +1 -1
- package/dist/types/worktree.d.ts +170 -0
- package/dist/types/worktree.js +101 -0
- package/dist/utils/index.d.ts +46 -1
- package/dist/utils/index.js +145 -12
- package/dist/utils/reasoning.d.ts +16 -0
- package/dist/utils/reasoning.js +37 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,1567 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ADR-099 (этап D1): HTTP/HTTPS-прокси в едином egress-слое.
|
|
3
|
+
*
|
|
4
|
+
* Здесь только **чтение и валидация** конфигурации прокси (секция `proxy`,
|
|
5
|
+
* ADR-023): приоритет `SYNTH_PROXY_*` > `config.proxy` > стандартные
|
|
6
|
+
* `HTTP_PROXY`/`HTTPS_PROXY`/`ALL_PROXY`/`NO_PROXY` (если `fromEnv`) > defaults.
|
|
7
|
+
* Построение undici-dispatcher'а и применение к исходящим запросам — в core
|
|
8
|
+
* (`packages/core/src/security/proxy-dispatcher.ts`).
|
|
9
|
+
*
|
|
10
|
+
* Fail-closed: битый URL, неподдерживаемая схема (SOCKS5 — этап D2) и
|
|
11
|
+
* userinfo-аутентификация (Basic/NTLM — этап D2) → ошибка на старте, как
|
|
12
|
+
* `security.tls.caFile` → не-PEM. Пароли не логируются и не отдаются наружу
|
|
13
|
+
* (`redactProxyUrl`).
|
|
14
|
+
*/
|
|
15
|
+
import { readFileSync } from 'node:fs';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { BlockList, isIP } from 'node:net';
|
|
18
|
+
import { PROXY_PROFILE_NAME_RE, proxyConfigSchema } from './types.js';
|
|
19
|
+
import { matchTlsHostPattern } from './tls.js';
|
|
20
|
+
/** Env-имена секции `proxy` (ADR-023). */
|
|
21
|
+
export const PROXY_ENV = {
|
|
22
|
+
enabled: 'SYNTH_PROXY_ENABLED',
|
|
23
|
+
url: 'SYNTH_PROXY_URL',
|
|
24
|
+
httpProxy: 'SYNTH_PROXY_HTTP_PROXY',
|
|
25
|
+
httpsProxy: 'SYNTH_PROXY_HTTPS_PROXY',
|
|
26
|
+
allProxy: 'SYNTH_PROXY_ALL_PROXY',
|
|
27
|
+
noProxy: 'SYNTH_PROXY_NO_PROXY',
|
|
28
|
+
fallbackDirect: 'SYNTH_PROXY_FALLBACK_DIRECT',
|
|
29
|
+
connectTimeoutMs: 'SYNTH_PROXY_CONNECT_TIMEOUT_MS',
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Пароль Basic-аутентификации прокси: **только** env или файл
|
|
33
|
+
* `{dataDir}/secrets/proxy-password` (в config.yaml не хранится — инвариант 13).
|
|
34
|
+
*/
|
|
35
|
+
export const PROXY_PASSWORD_ENV = 'SYNTH_PROXY_PASSWORD';
|
|
36
|
+
/** Env-имена секции `proxy.tls` (TLS/mTLS к прокси, ADR-023). */
|
|
37
|
+
export const PROXY_TLS_ENV = {
|
|
38
|
+
caFile: 'SYNTH_PROXY_TLS_CA_FILE',
|
|
39
|
+
caPem: 'SYNTH_PROXY_TLS_CA_PEM',
|
|
40
|
+
certFile: 'SYNTH_PROXY_TLS_CERT_FILE',
|
|
41
|
+
keyFile: 'SYNTH_PROXY_TLS_KEY_FILE',
|
|
42
|
+
rejectUnauthorized: 'SYNTH_PROXY_TLS_REJECT_UNAUTHORIZED',
|
|
43
|
+
};
|
|
44
|
+
/** Поля URL прокси (для per-field кредов). */
|
|
45
|
+
export const PROXY_URL_FIELDS = ['url', 'httpProxy', 'httpsProxy', 'allProxy'];
|
|
46
|
+
/** Стандартные env-имена прокси (учитываются только при `fromEnv`). */
|
|
47
|
+
export const STANDARD_PROXY_ENV = {
|
|
48
|
+
httpProxy: ['HTTP_PROXY', 'http_proxy'],
|
|
49
|
+
httpsProxy: ['HTTPS_PROXY', 'https_proxy'],
|
|
50
|
+
allProxy: ['ALL_PROXY', 'all_proxy'],
|
|
51
|
+
noProxy: ['NO_PROXY', 'no_proxy'],
|
|
52
|
+
};
|
|
53
|
+
/** Ошибка конфигурации прокси (fail-closed, код для API/логов). */
|
|
54
|
+
export class ProxyConfigError extends Error {
|
|
55
|
+
code = 'EGRESS_PROXY_CONFIG_INVALID';
|
|
56
|
+
constructor(message) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = 'ProxyConfigError';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** `true` — SOCKS5-прокси (D2b). */
|
|
62
|
+
export function isSocksProxyProtocol(protocol) {
|
|
63
|
+
return protocol === 'socks5:' || protocol === 'socks5h:';
|
|
64
|
+
}
|
|
65
|
+
/** Пустая (не заданная) конфигурация — прокси выключен (поведение не меняется). */
|
|
66
|
+
export function emptyResolvedProxyConfig() {
|
|
67
|
+
return {
|
|
68
|
+
enabled: false,
|
|
69
|
+
source: 'none',
|
|
70
|
+
mode: 'all',
|
|
71
|
+
profiles: {},
|
|
72
|
+
rules: [],
|
|
73
|
+
noProxy: [],
|
|
74
|
+
fromEnv: true,
|
|
75
|
+
fallbackDirect: false,
|
|
76
|
+
connectTimeoutMs: 10_000,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Разбирает URL прокси: `http`, `https`, `socks5`, `socks5h` (D2b).
|
|
81
|
+
* Userinfo (`user:pass@host`) разрешён: креды извлекаются отдельно (для SOCKS5 —
|
|
82
|
+
* RFC 1929 user/pass), `href` всегда без userinfo (безопасен для логов/статуса).
|
|
83
|
+
* `password` без `username` — ошибка; отсутствие пароля при наличии username
|
|
84
|
+
* решает резолвер (env/файл).
|
|
85
|
+
*
|
|
86
|
+
* `socks5h://` — hostname цели резолвит прокси; `socks5://` — клиент (поведение
|
|
87
|
+
* зависит от клиента, undici передаёт hostname в SOCKS CONNECT).
|
|
88
|
+
*/
|
|
89
|
+
export function parseProxyUrl(raw) {
|
|
90
|
+
const value = raw.trim();
|
|
91
|
+
if (!value)
|
|
92
|
+
throw new ProxyConfigError('proxy: пустой URL');
|
|
93
|
+
let url;
|
|
94
|
+
try {
|
|
95
|
+
url = new URL(value);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new ProxyConfigError(`proxy: некорректный URL "${redactProxyUrl(value)}"`);
|
|
99
|
+
}
|
|
100
|
+
if (url.protocol === 'socks:') {
|
|
101
|
+
throw new ProxyConfigError('proxy: схема "socks:" не поддерживается — используйте socks5:// или socks5h://');
|
|
102
|
+
}
|
|
103
|
+
if (url.protocol !== 'http:' &&
|
|
104
|
+
url.protocol !== 'https:' &&
|
|
105
|
+
url.protocol !== 'socks5:' &&
|
|
106
|
+
url.protocol !== 'socks5h:') {
|
|
107
|
+
throw new ProxyConfigError(`proxy: схема "${url.protocol.replace(/:$/, '')}" не поддерживается (только http/https/socks5/socks5h)`);
|
|
108
|
+
}
|
|
109
|
+
if (!url.hostname) {
|
|
110
|
+
throw new ProxyConfigError(`proxy: не удалось выделить хост из "${redactProxyUrl(value)}"`);
|
|
111
|
+
}
|
|
112
|
+
const protocol = url.protocol;
|
|
113
|
+
const defaultPort = protocol === 'https:' ? 443 : isSocksProxyProtocol(protocol) ? 1080 : 80;
|
|
114
|
+
const port = url.port ? Number(url.port) : defaultPort;
|
|
115
|
+
const decoded = decodeUserinfo(url, value);
|
|
116
|
+
if (decoded.password !== undefined && decoded.username === undefined) {
|
|
117
|
+
throw new ProxyConfigError('proxy: пароль в URL задан без имени пользователя');
|
|
118
|
+
}
|
|
119
|
+
const parsed = {
|
|
120
|
+
href: `${protocol}//${url.host}`,
|
|
121
|
+
protocol,
|
|
122
|
+
hostname: url.hostname,
|
|
123
|
+
port,
|
|
124
|
+
};
|
|
125
|
+
if (decoded.username !== undefined)
|
|
126
|
+
parsed.username = decoded.username;
|
|
127
|
+
if (decoded.password !== undefined)
|
|
128
|
+
parsed.password = decoded.password;
|
|
129
|
+
return parsed;
|
|
130
|
+
}
|
|
131
|
+
/** Декодирует userinfo; битый percent-encoding → fail-closed без эха секрета. */
|
|
132
|
+
function decodeUserinfo(url, raw) {
|
|
133
|
+
if (!url.username && !url.password)
|
|
134
|
+
return {};
|
|
135
|
+
try {
|
|
136
|
+
return {
|
|
137
|
+
...(url.username ? { username: decodeURIComponent(url.username) } : {}),
|
|
138
|
+
...(url.password ? { password: decodeURIComponent(url.password) } : {}),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
throw new ProxyConfigError(`proxy: некорректный userinfo в URL "${redactProxyUrl(raw)}"`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Безопасное представление URL прокси для логов/API: без userinfo, path/query/hash.
|
|
147
|
+
* Невалидный URL → пустая строка (не эхоим потенциальный секрет).
|
|
148
|
+
*/
|
|
149
|
+
export function redactProxyUrl(raw) {
|
|
150
|
+
if (raw === undefined || raw === '')
|
|
151
|
+
return '';
|
|
152
|
+
try {
|
|
153
|
+
const url = new URL(raw);
|
|
154
|
+
url.username = '';
|
|
155
|
+
url.password = '';
|
|
156
|
+
url.search = '';
|
|
157
|
+
url.hash = '';
|
|
158
|
+
// `URL.origin` для не-special схем (socks5) равен "null" — собираем вручную.
|
|
159
|
+
return `${url.protocol}//${url.host}`;
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return '';
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Матчер `noProxy` (без regex): `host`, `.suffix`, `*.suffix`, `host:port`,
|
|
167
|
+
* IPv4/IPv6-литерал, CIDR, `*` (всё напрямую).
|
|
168
|
+
*
|
|
169
|
+
* - `example.com` — точное совпадение;
|
|
170
|
+
* - `.example.com` — сам домен и поддомены;
|
|
171
|
+
* - `*.example.com` — только поддомены;
|
|
172
|
+
* - `example.com:8443` — точный host+port;
|
|
173
|
+
* - `10.0.0.0/8` — только IP-литералы хоста (DNS не выполняется);
|
|
174
|
+
* - `*` — прокси не используется ни для одного хоста.
|
|
175
|
+
*/
|
|
176
|
+
export class NoProxyMatcher {
|
|
177
|
+
_all;
|
|
178
|
+
_hosts = new Set();
|
|
179
|
+
_suffixes = [];
|
|
180
|
+
_wildcards = [];
|
|
181
|
+
_hostPorts = new Set();
|
|
182
|
+
_ips = new Set();
|
|
183
|
+
_cidrs = new BlockList();
|
|
184
|
+
_hasCidr;
|
|
185
|
+
constructor(entries) {
|
|
186
|
+
let all = false;
|
|
187
|
+
let hasCidr = false;
|
|
188
|
+
for (const raw of entries ?? []) {
|
|
189
|
+
if (typeof raw !== 'string')
|
|
190
|
+
continue;
|
|
191
|
+
const entry = raw.trim().toLowerCase().replace(/\.$/, '');
|
|
192
|
+
if (!entry)
|
|
193
|
+
continue;
|
|
194
|
+
if (entry === '*') {
|
|
195
|
+
all = true;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (entry.includes('/')) {
|
|
199
|
+
const slash = entry.lastIndexOf('/');
|
|
200
|
+
const net = entry.slice(0, slash).trim();
|
|
201
|
+
const prefix = Number(entry.slice(slash + 1).trim());
|
|
202
|
+
const version = isIP(net);
|
|
203
|
+
if (version === 0 || !Number.isInteger(prefix))
|
|
204
|
+
continue;
|
|
205
|
+
if (prefix < 0 || prefix > (version === 4 ? 32 : 128))
|
|
206
|
+
continue;
|
|
207
|
+
try {
|
|
208
|
+
this._cidrs.addSubnet(net, prefix, version === 4 ? 'ipv4' : 'ipv6');
|
|
209
|
+
hasCidr = true;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
// Невалидный CIDR — запись игнорируется (fail-soft: остальные правила работают).
|
|
213
|
+
}
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
// IPv6 в скобках: `[::1]` либо `[::1]:8080`.
|
|
217
|
+
const bracket = /^\[([^\]]+)\](?::(\d+))?$/.exec(entry);
|
|
218
|
+
if (bracket) {
|
|
219
|
+
const host = bracket[1];
|
|
220
|
+
if (bracket[2])
|
|
221
|
+
this._hostPorts.add(`${host}|${bracket[2]}`);
|
|
222
|
+
else
|
|
223
|
+
this._ips.add(host);
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (entry.startsWith('*.')) {
|
|
227
|
+
const suffix = entry.slice(2);
|
|
228
|
+
if (suffix)
|
|
229
|
+
this._wildcards.push(suffix);
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
if (entry.startsWith('.')) {
|
|
233
|
+
const suffix = entry.slice(1);
|
|
234
|
+
if (suffix)
|
|
235
|
+
this._suffixes.push(suffix);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
if (isIP(entry) !== 0) {
|
|
239
|
+
this._ips.add(entry);
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
// `host:port` (не IPv6: там двоеточий больше одного).
|
|
243
|
+
const colon = entry.lastIndexOf(':');
|
|
244
|
+
if (colon > 0 && !entry.slice(0, colon).includes(':') && /^\d+$/.test(entry.slice(colon + 1))) {
|
|
245
|
+
this._hostPorts.add(`${entry.slice(0, colon)}|${entry.slice(colon + 1)}`);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
this._hosts.add(entry);
|
|
249
|
+
}
|
|
250
|
+
this._all = all;
|
|
251
|
+
this._hasCidr = hasCidr;
|
|
252
|
+
}
|
|
253
|
+
/** `true` — хост исключён из прокси (идём напрямую). */
|
|
254
|
+
matches(rawHost, port) {
|
|
255
|
+
const host = normalizeHost(rawHost);
|
|
256
|
+
if (!host)
|
|
257
|
+
return false;
|
|
258
|
+
if (this._all)
|
|
259
|
+
return true;
|
|
260
|
+
if (this._hosts.has(host) || this._ips.has(host))
|
|
261
|
+
return true;
|
|
262
|
+
if (this._suffixes.some((suffix) => host === suffix || host.endsWith(`.${suffix}`)))
|
|
263
|
+
return true;
|
|
264
|
+
// `*.suffix` — только поддомены; семантика шаблона общая с ADR-099-матчером.
|
|
265
|
+
if (this._wildcards.some((suffix) => matchTlsHostPattern(`*.${suffix}`, host)))
|
|
266
|
+
return true;
|
|
267
|
+
if (port !== undefined && port !== '') {
|
|
268
|
+
if (this._hostPorts.has(`${host}|${String(port)}`))
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
if (this._hasCidr) {
|
|
272
|
+
const version = isIP(host);
|
|
273
|
+
if (version !== 0) {
|
|
274
|
+
try {
|
|
275
|
+
if (this._cidrs.check(host, version === 4 ? 'ipv4' : 'ipv6'))
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
// некорректный литерал — не матчим
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/** Нормализует hostname (нижний регистр, без завершающей точки/скобок IPv6). */
|
|
287
|
+
function normalizeHost(rawHost) {
|
|
288
|
+
let host = rawHost.trim().toLowerCase().replace(/\.$/, '');
|
|
289
|
+
if (host.startsWith('[') && host.endsWith(']'))
|
|
290
|
+
host = host.slice(1, -1);
|
|
291
|
+
return host;
|
|
292
|
+
}
|
|
293
|
+
/** Валидное DNS-имя (метки `[a-z0-9_-]`, без пустых меток, длина ≤ 253). */
|
|
294
|
+
function isValidHostname(host) {
|
|
295
|
+
if (host === '' || host.length > 253)
|
|
296
|
+
return false;
|
|
297
|
+
return host
|
|
298
|
+
.split('.')
|
|
299
|
+
.every((label) => /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?$/.test(label));
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Валидирует host-паттерны правил прокси (`proxy.rules[].hosts`).
|
|
303
|
+
* Возвращает нормализованные значения (trim/lower-case/без завершающей точки).
|
|
304
|
+
*
|
|
305
|
+
* Допустимо: exact (`api.example.com`), `.suffix` (apex+sub), `*.suffix` (sub),
|
|
306
|
+
* `host:port`, IPv4/IPv6-литерал (в т.ч. `[::1]:8080`), CIDR (только по IP-литералу
|
|
307
|
+
* цели — DNS не выполняется), `*`.
|
|
308
|
+
*
|
|
309
|
+
* **Fail-closed**: невалидный паттерн — `ProxyConfigError` (а не тихий игнор),
|
|
310
|
+
* иначе опечатка в правиле молча меняет маршрут (прокси ↔ direct).
|
|
311
|
+
*/
|
|
312
|
+
export function validateProxyHostPatterns(entries, context = 'proxy.rules') {
|
|
313
|
+
if (!Array.isArray(entries) || entries.length === 0) {
|
|
314
|
+
throw new ProxyConfigError(`${context}.hosts: нужен хотя бы один паттерн`);
|
|
315
|
+
}
|
|
316
|
+
return entries.map((raw, index) => {
|
|
317
|
+
const where = `${context}.hosts[${index}]`;
|
|
318
|
+
if (typeof raw !== 'string') {
|
|
319
|
+
throw new ProxyConfigError(`${where}: паттерн должен быть строкой`);
|
|
320
|
+
}
|
|
321
|
+
// Завершающая точка нормализуется, но `*.` — невалидный wildcard, а не `*`.
|
|
322
|
+
const rawValue = raw.trim().toLowerCase();
|
|
323
|
+
const value = rawValue !== '*' && !rawValue.endsWith('*.') ? rawValue.replace(/\.$/, '') : rawValue;
|
|
324
|
+
if (value === '') {
|
|
325
|
+
throw new ProxyConfigError(`${where}: пустой паттерн`);
|
|
326
|
+
}
|
|
327
|
+
if (/\s/.test(value)) {
|
|
328
|
+
throw new ProxyConfigError(`${where}: пробелы в паттерне "${raw}" недопустимы`);
|
|
329
|
+
}
|
|
330
|
+
if (value === '*')
|
|
331
|
+
return value;
|
|
332
|
+
if (value.includes('/')) {
|
|
333
|
+
const slash = value.lastIndexOf('/');
|
|
334
|
+
const net = value.slice(0, slash);
|
|
335
|
+
const prefixRaw = value.slice(slash + 1);
|
|
336
|
+
const family = isIP(net);
|
|
337
|
+
if (family === 0) {
|
|
338
|
+
throw new ProxyConfigError(`${where}: CIDR "${raw}" — сеть должна быть IP-литералом (DNS/CIDR по имени не поддерживается)`);
|
|
339
|
+
}
|
|
340
|
+
if (!/^\d{1,3}$/.test(prefixRaw)) {
|
|
341
|
+
throw new ProxyConfigError(`${where}: CIDR "${raw}" — невалидная длина префикса`);
|
|
342
|
+
}
|
|
343
|
+
const prefix = Number(prefixRaw);
|
|
344
|
+
const max = family === 4 ? 32 : 128;
|
|
345
|
+
if (prefix > max) {
|
|
346
|
+
throw new ProxyConfigError(`${where}: CIDR "${raw}" — префикс должен быть 0..${max} для IPv${family}`);
|
|
347
|
+
}
|
|
348
|
+
return value;
|
|
349
|
+
}
|
|
350
|
+
if (value.includes('*')) {
|
|
351
|
+
if (!value.startsWith('*.') || value.slice(2) === '') {
|
|
352
|
+
throw new ProxyConfigError(`${where}: невалидный wildcard "${raw}" (допустимо только "*.suffix")`);
|
|
353
|
+
}
|
|
354
|
+
const suffix = value.slice(2);
|
|
355
|
+
if (suffix.includes('*') || isIP(suffix) !== 0 || !isValidHostname(suffix)) {
|
|
356
|
+
throw new ProxyConfigError(`${where}: невалидный wildcard-суффикс "${raw}"`);
|
|
357
|
+
}
|
|
358
|
+
return value;
|
|
359
|
+
}
|
|
360
|
+
// IPv6 в скобках: `[::1]` либо `[::1]:8080`.
|
|
361
|
+
const bracket = /^\[([^\]]+)\](?::(\d+))?$/.exec(value);
|
|
362
|
+
if (bracket) {
|
|
363
|
+
const host = bracket[1];
|
|
364
|
+
if (isIP(host) !== 6) {
|
|
365
|
+
throw new ProxyConfigError(`${where}: "${raw}" — в скобках ожидается IPv6-литерал`);
|
|
366
|
+
}
|
|
367
|
+
if (bracket[2] !== undefined)
|
|
368
|
+
assertPort(bracket[2], where, raw);
|
|
369
|
+
return value;
|
|
370
|
+
}
|
|
371
|
+
if (isIP(value) !== 0)
|
|
372
|
+
return value;
|
|
373
|
+
if (value.startsWith('.')) {
|
|
374
|
+
const suffix = value.slice(1);
|
|
375
|
+
if (suffix === '' || isIP(suffix) !== 0 || !isValidHostname(suffix)) {
|
|
376
|
+
throw new ProxyConfigError(`${where}: невалидный суффикс "${raw}"`);
|
|
377
|
+
}
|
|
378
|
+
return value;
|
|
379
|
+
}
|
|
380
|
+
// `host:port` (IPv6-литералы уже обработаны выше — там двоеточий больше).
|
|
381
|
+
const colon = value.lastIndexOf(':');
|
|
382
|
+
if (colon > 0 && !value.slice(0, colon).includes(':')) {
|
|
383
|
+
const host = value.slice(0, colon);
|
|
384
|
+
const port = value.slice(colon + 1);
|
|
385
|
+
if (!/^\d+$/.test(port)) {
|
|
386
|
+
throw new ProxyConfigError(`${where}: невалидный порт в "${raw}"`);
|
|
387
|
+
}
|
|
388
|
+
assertPort(port, where, raw);
|
|
389
|
+
if (!isValidHostname(host)) {
|
|
390
|
+
throw new ProxyConfigError(`${where}: невалидный хост в "${raw}"`);
|
|
391
|
+
}
|
|
392
|
+
return value;
|
|
393
|
+
}
|
|
394
|
+
if (!isValidHostname(value)) {
|
|
395
|
+
throw new ProxyConfigError(`${where}: невалидный паттерн "${raw}"`);
|
|
396
|
+
}
|
|
397
|
+
return value;
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
/** Проверка диапазона порта паттерна (1..65535). */
|
|
401
|
+
function assertPort(rawPort, where, rawPattern) {
|
|
402
|
+
const port = Number(rawPort);
|
|
403
|
+
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
|
|
404
|
+
throw new ProxyConfigError(`${where}: порт в "${rawPattern}" должен быть 1..65535`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
/** Непустое значение env (пустая строка — «не задано», как прочие env-резолверы). */
|
|
408
|
+
function envValue(env, key) {
|
|
409
|
+
const value = env[key];
|
|
410
|
+
return value !== undefined && value !== '' ? value : undefined;
|
|
411
|
+
}
|
|
412
|
+
/** Парсит boolean env; невалидно → warn + `undefined` (фоллбэк на config). */
|
|
413
|
+
function envBoolean(raw, name) {
|
|
414
|
+
if (raw === undefined || raw === '')
|
|
415
|
+
return undefined;
|
|
416
|
+
const v = raw.toLowerCase();
|
|
417
|
+
if (v === 'true' || v === '1')
|
|
418
|
+
return true;
|
|
419
|
+
if (v === 'false' || v === '0')
|
|
420
|
+
return false;
|
|
421
|
+
console.warn(`[config] невалидное значение ${name}="${raw}" (ожидается true/1/false/0) — игнорируется`);
|
|
422
|
+
return undefined;
|
|
423
|
+
}
|
|
424
|
+
/** Парсит положительное целое env; невалидно → warn + `undefined`. */
|
|
425
|
+
function envPositiveInt(raw, name) {
|
|
426
|
+
if (raw === undefined || raw === '')
|
|
427
|
+
return undefined;
|
|
428
|
+
const n = Number(raw);
|
|
429
|
+
if (Number.isInteger(n) && n > 0)
|
|
430
|
+
return n;
|
|
431
|
+
console.warn(`[config] невалидное значение ${name}="${raw}" (ожидается положительное целое) — игнорируется`);
|
|
432
|
+
return undefined;
|
|
433
|
+
}
|
|
434
|
+
/** Разбивает список no_proxy из env (через запятую/пробелы — стандарт). */
|
|
435
|
+
function splitEnvList(raw) {
|
|
436
|
+
if (raw === undefined || raw.trim() === '')
|
|
437
|
+
return [];
|
|
438
|
+
return raw
|
|
439
|
+
.split(/[,\s]+/)
|
|
440
|
+
.map((item) => item.trim())
|
|
441
|
+
.filter(Boolean);
|
|
442
|
+
}
|
|
443
|
+
/** Env-имя пароля профиля: `default` — legacy `SYNTH_PROXY_PASSWORD`. */
|
|
444
|
+
export function proxyProfilePasswordEnv(name) {
|
|
445
|
+
if (name === 'default')
|
|
446
|
+
return PROXY_PASSWORD_ENV;
|
|
447
|
+
return `SYNTH_PROXY_${name.toUpperCase().replace(/-/g, '_')}_PASSWORD`;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Путь файла пароля профиля: `default` — legacy `{dataDir}/secrets/proxy-password`,
|
|
451
|
+
* прочие — `{dataDir}/secrets/proxy/<profile>.password`.
|
|
452
|
+
*/
|
|
453
|
+
export function proxyProfilePasswordPath(dataDir, name) {
|
|
454
|
+
if (name === 'default')
|
|
455
|
+
return join(dataDir, 'secrets', 'proxy-password');
|
|
456
|
+
return join(dataDir, 'secrets', 'proxy', `${name}.password`);
|
|
457
|
+
}
|
|
458
|
+
/** Читает пароль из env/файла профиля (лениво: только если реально нужен). */
|
|
459
|
+
function makeProfilePasswordResolver(env, dataDir, name) {
|
|
460
|
+
let cached = null;
|
|
461
|
+
return () => {
|
|
462
|
+
if (cached !== null)
|
|
463
|
+
return cached;
|
|
464
|
+
const fromEnv = envValue(env, proxyProfilePasswordEnv(name));
|
|
465
|
+
if (fromEnv !== undefined) {
|
|
466
|
+
cached = fromEnv;
|
|
467
|
+
return cached;
|
|
468
|
+
}
|
|
469
|
+
cached = dataDir ? readProxyPasswordFile(proxyProfilePasswordPath(dataDir, name)) : undefined;
|
|
470
|
+
return cached;
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
/** Читает файл пароля по точному пути; ENOENT → `undefined` (пароля нет). */
|
|
474
|
+
export function readProxyPasswordFile(path) {
|
|
475
|
+
let raw;
|
|
476
|
+
try {
|
|
477
|
+
raw = readFileSync(path, 'utf-8');
|
|
478
|
+
}
|
|
479
|
+
catch (err) {
|
|
480
|
+
if (err.code === 'ENOENT')
|
|
481
|
+
return undefined;
|
|
482
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
483
|
+
throw new ProxyConfigError(`proxy: не удалось прочитать пароль из "${path}": ${reason}`);
|
|
484
|
+
}
|
|
485
|
+
const value = raw.trim();
|
|
486
|
+
return value === '' ? undefined : value;
|
|
487
|
+
}
|
|
488
|
+
/** PEM-маркер блока. */
|
|
489
|
+
const PEM_BLOCK_RE = /-----BEGIN [A-Z0-9 ]+-----/;
|
|
490
|
+
/** Читает PEM-файл прокси-TLS; нет/не читается/не PEM → fail-closed. */
|
|
491
|
+
function readProxyPemFile(path, field, marker, scope = 'proxy.tls') {
|
|
492
|
+
let content;
|
|
493
|
+
try {
|
|
494
|
+
content = readFileSync(path, 'utf-8');
|
|
495
|
+
}
|
|
496
|
+
catch (err) {
|
|
497
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
498
|
+
throw new ProxyConfigError(`[config] ${scope}.${field}: не удалось прочитать файл "${path}": ${reason}`);
|
|
499
|
+
}
|
|
500
|
+
if (!marker.test(content)) {
|
|
501
|
+
throw new ProxyConfigError(`[config] ${scope}.${field}: файл "${path}" не содержит PEM ` +
|
|
502
|
+
`(ожидается блок "-----BEGIN ${field === 'keyFile' ? 'PRIVATE KEY' : 'CERTIFICATE'}-----")`);
|
|
503
|
+
}
|
|
504
|
+
return content;
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* TLS профиля прокси: **только** config/UI (без env `SYNTH_PROXY_TLS_*`).
|
|
508
|
+
* Правила те же, что у `proxy.tls`: `caFile`↔`caPem`, `certFile`+`keyFile` парой,
|
|
509
|
+
* нечитаемый/не-PEM файл — fail-closed.
|
|
510
|
+
*/
|
|
511
|
+
function resolveProfileTls(tls, name) {
|
|
512
|
+
const cfg = (tls ?? {});
|
|
513
|
+
const scope = `proxy.profiles.${name}.tls`;
|
|
514
|
+
const nonEmpty = (value) => value !== undefined && value !== '' ? value : undefined;
|
|
515
|
+
const caFile = nonEmpty(cfg.caFile);
|
|
516
|
+
const caPem = nonEmpty(cfg.caPem);
|
|
517
|
+
if (caFile !== undefined && caPem !== undefined) {
|
|
518
|
+
throw new ProxyConfigError(`[config] ${scope}: 'caFile' и 'caPem' взаимоисключащи — задайте ровно один источник CA`);
|
|
519
|
+
}
|
|
520
|
+
const certFile = nonEmpty(cfg.certFile);
|
|
521
|
+
const keyFile = nonEmpty(cfg.keyFile);
|
|
522
|
+
if ((certFile === undefined) !== (keyFile === undefined)) {
|
|
523
|
+
throw new ProxyConfigError(`[config] ${scope}: mTLS к прокси требует и certFile, и keyFile (задайте оба либо ни одного)`);
|
|
524
|
+
}
|
|
525
|
+
const configured = caFile !== undefined ||
|
|
526
|
+
caPem !== undefined ||
|
|
527
|
+
certFile !== undefined ||
|
|
528
|
+
keyFile !== undefined ||
|
|
529
|
+
cfg.rejectUnauthorized === false;
|
|
530
|
+
const resolved = { rejectUnauthorized: cfg.rejectUnauthorized ?? true };
|
|
531
|
+
if (caFile !== undefined) {
|
|
532
|
+
resolved.ca = readProxyPemFile(caFile, 'caFile', /-----BEGIN CERTIFICATE-----/, scope);
|
|
533
|
+
}
|
|
534
|
+
else if (caPem !== undefined) {
|
|
535
|
+
if (!PEM_BLOCK_RE.test(caPem)) {
|
|
536
|
+
throw new ProxyConfigError(`[config] ${scope}.caPem: значение не содержит PEM-сертификат ` +
|
|
537
|
+
'(ожидается блок "-----BEGIN CERTIFICATE-----")');
|
|
538
|
+
}
|
|
539
|
+
resolved.ca = caPem;
|
|
540
|
+
}
|
|
541
|
+
if (certFile !== undefined && keyFile !== undefined) {
|
|
542
|
+
resolved.cert = readProxyPemFile(certFile, 'certFile', /-----BEGIN CERTIFICATE-----/, scope);
|
|
543
|
+
resolved.key = readProxyPemFile(keyFile, 'keyFile', /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/, scope);
|
|
544
|
+
}
|
|
545
|
+
const meta = { hasCaPem: caPem !== undefined };
|
|
546
|
+
if (caFile !== undefined)
|
|
547
|
+
meta.caFile = caFile;
|
|
548
|
+
if (certFile !== undefined)
|
|
549
|
+
meta.certFile = certFile;
|
|
550
|
+
if (keyFile !== undefined)
|
|
551
|
+
meta.keyFile = keyFile;
|
|
552
|
+
return { resolved, meta, configured };
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Эффективный TLS/mTLS к **самому прокси** (`proxy.tls`, ADR-023).
|
|
556
|
+
* Схема — как `security.tls`: env `SYNTH_PROXY_TLS_*` > config.yaml > defaults;
|
|
557
|
+
* `caFile` ↔ `caPem` взаимоисключающие; `certFile`/`keyFile` — только вместе;
|
|
558
|
+
* нечитаемый/не-PEM файл → fail-closed.
|
|
559
|
+
*/
|
|
560
|
+
export function resolveProxyTls(config, env = process.env) {
|
|
561
|
+
const cfg = (config?.proxy?.tls ?? {});
|
|
562
|
+
const pick = (envKey, cfgValue) => {
|
|
563
|
+
const envValueRaw = envValue(env, envKey);
|
|
564
|
+
if (envValueRaw !== undefined)
|
|
565
|
+
return envValueRaw;
|
|
566
|
+
return cfgValue !== undefined && cfgValue !== '' ? cfgValue : undefined;
|
|
567
|
+
};
|
|
568
|
+
const caFile = pick(PROXY_TLS_ENV.caFile, cfg.caFile);
|
|
569
|
+
const caPem = pick(PROXY_TLS_ENV.caPem, cfg.caPem);
|
|
570
|
+
if (caFile !== undefined && caPem !== undefined) {
|
|
571
|
+
throw new ProxyConfigError(`[config] proxy.tls: 'caFile' и 'caPem' взаимоисключащи — задайте ровно один ` +
|
|
572
|
+
`источник CA (${PROXY_TLS_ENV.caFile} ИЛИ ${PROXY_TLS_ENV.caPem})`);
|
|
573
|
+
}
|
|
574
|
+
const certFile = pick(PROXY_TLS_ENV.certFile, cfg.certFile);
|
|
575
|
+
const keyFile = pick(PROXY_TLS_ENV.keyFile, cfg.keyFile);
|
|
576
|
+
if ((certFile === undefined) !== (keyFile === undefined)) {
|
|
577
|
+
throw new ProxyConfigError('[config] proxy.tls: mTLS к прокси требует и certFile, и keyFile (задайте оба либо ни одного)');
|
|
578
|
+
}
|
|
579
|
+
const rejectUnauthorized = envBoolean(envValue(env, PROXY_TLS_ENV.rejectUnauthorized), PROXY_TLS_ENV.rejectUnauthorized) ??
|
|
580
|
+
cfg.rejectUnauthorized ??
|
|
581
|
+
true;
|
|
582
|
+
const result = { rejectUnauthorized };
|
|
583
|
+
if (caFile !== undefined) {
|
|
584
|
+
const content = readProxyPemFile(caFile, 'caFile', /-----BEGIN CERTIFICATE-----/);
|
|
585
|
+
result.ca = content;
|
|
586
|
+
}
|
|
587
|
+
else if (caPem !== undefined) {
|
|
588
|
+
if (!PEM_BLOCK_RE.test(caPem)) {
|
|
589
|
+
throw new ProxyConfigError('[config] proxy.tls.caPem: значение не содержит PEM-сертификат ' +
|
|
590
|
+
'(ожидается блок "-----BEGIN CERTIFICATE-----")');
|
|
591
|
+
}
|
|
592
|
+
result.ca = caPem;
|
|
593
|
+
}
|
|
594
|
+
if (certFile !== undefined && keyFile !== undefined) {
|
|
595
|
+
result.cert = readProxyPemFile(certFile, 'certFile', /-----BEGIN CERTIFICATE-----/);
|
|
596
|
+
result.key = readProxyPemFile(keyFile, 'keyFile', /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/);
|
|
597
|
+
}
|
|
598
|
+
return result;
|
|
599
|
+
}
|
|
600
|
+
/** Протокол URL без исключения (для проверок конфигурации). */
|
|
601
|
+
function safeProtocol(raw) {
|
|
602
|
+
try {
|
|
603
|
+
return new URL(raw).protocol;
|
|
604
|
+
}
|
|
605
|
+
catch {
|
|
606
|
+
return '';
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
/** Явно ли сконфигурирован TLS к прокси (config или env) — для проверки socks5. */
|
|
610
|
+
function isProxyTlsConfigured(cfg, env) {
|
|
611
|
+
const fromCfg = Object.values(cfg.tls ?? {}).some((value) => value !== undefined && value !== '');
|
|
612
|
+
if (fromCfg)
|
|
613
|
+
return true;
|
|
614
|
+
return Object.values(PROXY_TLS_ENV).some((key) => envValue(env, key) !== undefined);
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Метаданные TLS к прокси для статуса/UI: пути файлов и флаг `caPem`.
|
|
618
|
+
* Приоритет env `SYNTH_PROXY_TLS_*` > эффективный config/runtime. Содержимое
|
|
619
|
+
* PEM/ключа **не** возвращается.
|
|
620
|
+
*/
|
|
621
|
+
export function resolveProxyTlsMeta(config, env = process.env) {
|
|
622
|
+
const cfg = (config?.proxy?.tls ?? {});
|
|
623
|
+
const pick = (envKey, cfgValue) => {
|
|
624
|
+
const fromEnv = envValue(env, envKey);
|
|
625
|
+
if (fromEnv !== undefined)
|
|
626
|
+
return fromEnv;
|
|
627
|
+
return cfgValue !== undefined && cfgValue !== '' ? cfgValue : undefined;
|
|
628
|
+
};
|
|
629
|
+
const caFile = pick(PROXY_TLS_ENV.caFile, cfg.caFile);
|
|
630
|
+
const caPem = pick(PROXY_TLS_ENV.caPem, cfg.caPem);
|
|
631
|
+
const certFile = pick(PROXY_TLS_ENV.certFile, cfg.certFile);
|
|
632
|
+
const keyFile = pick(PROXY_TLS_ENV.keyFile, cfg.keyFile);
|
|
633
|
+
const meta = { hasCaPem: caPem !== undefined };
|
|
634
|
+
if (caFile !== undefined)
|
|
635
|
+
meta.caFile = caFile;
|
|
636
|
+
if (certFile !== undefined)
|
|
637
|
+
meta.certFile = certFile;
|
|
638
|
+
if (keyFile !== undefined)
|
|
639
|
+
meta.keyFile = keyFile;
|
|
640
|
+
return meta;
|
|
641
|
+
}
|
|
642
|
+
/** Публичная redacted-форма TLS-метаданных (никогда не содержит PEM/ключей). */
|
|
643
|
+
function redactedTlsMeta(meta) {
|
|
644
|
+
if (!meta)
|
|
645
|
+
return undefined;
|
|
646
|
+
const result = { hasCaPem: meta.hasCaPem === true };
|
|
647
|
+
if (meta.caFile !== undefined)
|
|
648
|
+
result.caFile = meta.caFile;
|
|
649
|
+
if (meta.certFile !== undefined)
|
|
650
|
+
result.certFile = meta.certFile;
|
|
651
|
+
if (meta.keyFile !== undefined)
|
|
652
|
+
result.keyFile = meta.keyFile;
|
|
653
|
+
return result;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Поле-уровневое слияние `config.yaml proxy` и runtime-override (UI).
|
|
657
|
+
* Runtime приоритетнее; пустая строка трактуется как «не задано» (как в config).
|
|
658
|
+
* Вложенные `auth`/`tls` мёржатся по полям.
|
|
659
|
+
*
|
|
660
|
+
* Источник конфигурации всегда один (иначе `resolveProxyConfig` бросает «два
|
|
661
|
+
* источника»): `profiles` и legacy top-level (`url`/`httpProxy`/`httpsProxy`/
|
|
662
|
+
* `allProxy`/`auth`/`tls`) не смешиваются между base и runtime.
|
|
663
|
+
* - runtime с **непустыми** `profiles` — режим профилей: `profiles` из runtime,
|
|
664
|
+
* legacy top-level base игнорируется (свои top-level runtime-объекта остаются —
|
|
665
|
+
* их отклонит валидация);
|
|
666
|
+
* - runtime без `profiles`, но с legacy top-level — переключение на legacy:
|
|
667
|
+
* `profiles` base не берутся, `rules`/`defaultProfile`/`mode` base тоже (они
|
|
668
|
+
* относятся к исчезнувшей профильной конфигурации: правила и `defaultProfile`
|
|
669
|
+
* ссылаются на профили, а `mode: selected` остаётся без правил); свои значения
|
|
670
|
+
* runtime сохраняются;
|
|
671
|
+
* - runtime только с `rules`/`mode`/`defaultProfile` — `profiles` base сохраняются.
|
|
672
|
+
*/
|
|
673
|
+
export function mergeProxyConfig(base, runtime) {
|
|
674
|
+
const b = (base ?? {});
|
|
675
|
+
const r = (runtime ?? {});
|
|
676
|
+
// Режим профилей/legacy определяется по runtime: base при смене режима не подмешивается.
|
|
677
|
+
const runtimeProfileMode = hasNonEmptyProfiles(r);
|
|
678
|
+
const runtimeLegacyMode = hasLegacyTopLevel(r);
|
|
679
|
+
// Переключение с профилей на legacy (runtime без profiles, но с top-level URL/auth/tls):
|
|
680
|
+
// структурная конфигурация base (`profiles`/`rules`/`defaultProfile`/`mode`) не
|
|
681
|
+
// переносится — иначе остаются ссылки на исчезнувшие профили или `mode: selected`
|
|
682
|
+
// без правил. Свои значения runtime сохраняются.
|
|
683
|
+
const switchToLegacy = runtimeLegacyMode && hasNonEmptyProfiles(b);
|
|
684
|
+
const pickString = (key) => {
|
|
685
|
+
const value = r[key];
|
|
686
|
+
if (value !== undefined && value !== '')
|
|
687
|
+
return value;
|
|
688
|
+
if (runtimeProfileMode)
|
|
689
|
+
return undefined;
|
|
690
|
+
const fallback = b[key];
|
|
691
|
+
return fallback !== undefined && fallback !== '' ? fallback : undefined;
|
|
692
|
+
};
|
|
693
|
+
const merged = {};
|
|
694
|
+
if (r.enabled !== undefined)
|
|
695
|
+
merged.enabled = r.enabled;
|
|
696
|
+
else if (b.enabled !== undefined)
|
|
697
|
+
merged.enabled = b.enabled;
|
|
698
|
+
if (r.mode !== undefined)
|
|
699
|
+
merged.mode = r.mode;
|
|
700
|
+
else if (!switchToLegacy && b.mode !== undefined)
|
|
701
|
+
merged.mode = b.mode;
|
|
702
|
+
const runtimeDefault = r.defaultProfile !== undefined && r.defaultProfile !== '' ? r.defaultProfile : undefined;
|
|
703
|
+
const configDefault = !switchToLegacy && b.defaultProfile !== undefined && b.defaultProfile !== ''
|
|
704
|
+
? b.defaultProfile
|
|
705
|
+
: undefined;
|
|
706
|
+
const defaultProfile = runtimeDefault ?? configDefault;
|
|
707
|
+
if (defaultProfile !== undefined)
|
|
708
|
+
merged.defaultProfile = defaultProfile;
|
|
709
|
+
// `profiles`/`rules` — не поле-уровневое слияние: runtime заменяет config целиком.
|
|
710
|
+
const profiles = runtimeProfileMode
|
|
711
|
+
? r.profiles
|
|
712
|
+
: switchToLegacy
|
|
713
|
+
? undefined
|
|
714
|
+
: r.profiles !== undefined
|
|
715
|
+
? r.profiles
|
|
716
|
+
: b.profiles;
|
|
717
|
+
if (profiles !== undefined)
|
|
718
|
+
merged.profiles = profiles;
|
|
719
|
+
const rules = r.rules !== undefined ? r.rules : switchToLegacy ? undefined : b.rules;
|
|
720
|
+
if (rules !== undefined)
|
|
721
|
+
merged.rules = rules;
|
|
722
|
+
const url = pickString('url');
|
|
723
|
+
if (url !== undefined)
|
|
724
|
+
merged.url = url;
|
|
725
|
+
const httpProxy = pickString('httpProxy');
|
|
726
|
+
if (httpProxy !== undefined)
|
|
727
|
+
merged.httpProxy = httpProxy;
|
|
728
|
+
const httpsProxy = pickString('httpsProxy');
|
|
729
|
+
if (httpsProxy !== undefined)
|
|
730
|
+
merged.httpsProxy = httpsProxy;
|
|
731
|
+
const allProxy = pickString('allProxy');
|
|
732
|
+
if (allProxy !== undefined)
|
|
733
|
+
merged.allProxy = allProxy;
|
|
734
|
+
const auth = runtimeProfileMode ? r.auth : (r.auth ?? b.auth);
|
|
735
|
+
if (auth !== undefined)
|
|
736
|
+
merged.auth = auth;
|
|
737
|
+
if (runtimeProfileMode) {
|
|
738
|
+
if (r.tls !== undefined)
|
|
739
|
+
merged.tls = r.tls;
|
|
740
|
+
}
|
|
741
|
+
else if (r.tls !== undefined || b.tls !== undefined) {
|
|
742
|
+
merged.tls = { ...(b.tls ?? {}), ...(r.tls ?? {}) };
|
|
743
|
+
}
|
|
744
|
+
if (r.noProxy !== undefined)
|
|
745
|
+
merged.noProxy = r.noProxy;
|
|
746
|
+
else if (b.noProxy !== undefined)
|
|
747
|
+
merged.noProxy = b.noProxy;
|
|
748
|
+
if (r.fromEnv !== undefined)
|
|
749
|
+
merged.fromEnv = r.fromEnv;
|
|
750
|
+
else if (b.fromEnv !== undefined)
|
|
751
|
+
merged.fromEnv = b.fromEnv;
|
|
752
|
+
if (r.fallbackDirect !== undefined)
|
|
753
|
+
merged.fallbackDirect = r.fallbackDirect;
|
|
754
|
+
else if (b.fallbackDirect !== undefined)
|
|
755
|
+
merged.fallbackDirect = b.fallbackDirect;
|
|
756
|
+
if (r.connectTimeoutMs !== undefined)
|
|
757
|
+
merged.connectTimeoutMs = r.connectTimeoutMs;
|
|
758
|
+
else if (b.connectTimeoutMs !== undefined)
|
|
759
|
+
merged.connectTimeoutMs = b.connectTimeoutMs;
|
|
760
|
+
return merged;
|
|
761
|
+
}
|
|
762
|
+
/** `true` — `profiles` заданы и непусты (режим профилей). */
|
|
763
|
+
function hasNonEmptyProfiles(cfg) {
|
|
764
|
+
const profiles = cfg?.profiles;
|
|
765
|
+
return profiles !== undefined && Object.keys(profiles).length > 0;
|
|
766
|
+
}
|
|
767
|
+
/** `true` — задан хотя бы один непустой legacy top-level (`url`/`auth`/`tls`). */
|
|
768
|
+
function hasLegacyTopLevel(cfg) {
|
|
769
|
+
if (cfg === undefined)
|
|
770
|
+
return false;
|
|
771
|
+
if (PROXY_URL_FIELDS.some((field) => {
|
|
772
|
+
const value = cfg[field];
|
|
773
|
+
return typeof value === 'string' && value !== '';
|
|
774
|
+
})) {
|
|
775
|
+
return true;
|
|
776
|
+
}
|
|
777
|
+
if (cfg.auth !== undefined)
|
|
778
|
+
return true;
|
|
779
|
+
return (cfg.tls !== undefined &&
|
|
780
|
+
Object.values(cfg.tls).some((value) => value !== undefined && value !== ''));
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Сливает env, runtime и config.yaml для секции `proxy` (ADR-023).
|
|
784
|
+
*
|
|
785
|
+
* Приоритет: явные `SYNTH_PROXY_*` > runtime (`settings.json`, UI) > `config.proxy`
|
|
786
|
+
* > стандартные env (при `fromEnv`) > defaults. Стандартные `HTTP_PROXY`/… не
|
|
787
|
+
* применяются, если runtime/config явно задали `enabled: false`.
|
|
788
|
+
*
|
|
789
|
+
* `options.dataDir` нужен только для файла пароля
|
|
790
|
+
* `{dataDir}/secrets/proxy-password` (инвариант 13).
|
|
791
|
+
*/
|
|
792
|
+
export function resolveProxyConfig(config, env = process.env, options = {}) {
|
|
793
|
+
const cfg = mergeProxyConfig(config?.proxy, options.runtime);
|
|
794
|
+
const fromEnv = cfg.fromEnv ?? true;
|
|
795
|
+
const empty = emptyResolvedProxyConfig();
|
|
796
|
+
const explicitEnv = envBoolean(envValue(env, PROXY_ENV.enabled), PROXY_ENV.enabled);
|
|
797
|
+
const explicit = explicitEnv ?? cfg.enabled;
|
|
798
|
+
const mode = cfg.mode ?? 'all';
|
|
799
|
+
if (mode !== 'all' && mode !== 'selected') {
|
|
800
|
+
throw new ProxyConfigError(`proxy.mode "${String(mode)}" не поддерживается (all|selected)`);
|
|
801
|
+
}
|
|
802
|
+
const rawProfiles = cfg.profiles;
|
|
803
|
+
const hasProfiles = rawProfiles !== undefined && Object.keys(rawProfiles).length > 0;
|
|
804
|
+
const rawRules = Array.isArray(cfg.rules) ? cfg.rules : [];
|
|
805
|
+
const structured = hasProfiles || rawRules.length > 0;
|
|
806
|
+
const runtimeProfiles = options.runtime?.profiles;
|
|
807
|
+
// Профили и legacy top-level URL/auth/tls — два источника конфигурации: запрещено.
|
|
808
|
+
if (hasProfiles) {
|
|
809
|
+
const topLevelUrl = PROXY_URL_FIELDS.map((field) => cfg[field]).find((value) => value !== undefined && value !== '');
|
|
810
|
+
if (topLevelUrl !== undefined) {
|
|
811
|
+
throw new ProxyConfigError('proxy: при заданных proxy.profiles top-level url/httpProxy/httpsProxy/allProxy запрещены ' +
|
|
812
|
+
'(перенесите URL в профиль — иначе два источника конфигурации)');
|
|
813
|
+
}
|
|
814
|
+
const envUrl = [PROXY_ENV.url, PROXY_ENV.httpProxy, PROXY_ENV.httpsProxy, PROXY_ENV.allProxy]
|
|
815
|
+
.map((key) => envValue(env, key))
|
|
816
|
+
.find((value) => value !== undefined);
|
|
817
|
+
if (envUrl !== undefined) {
|
|
818
|
+
throw new ProxyConfigError('proxy: при заданных proxy.profiles env SYNTH_PROXY_URL/HTTP_PROXY/HTTPS_PROXY/ALL_PROXY ' +
|
|
819
|
+
'запрещены (URL задаётся только в профилях)');
|
|
820
|
+
}
|
|
821
|
+
if (hasLegacyAuth(cfg.auth)) {
|
|
822
|
+
throw new ProxyConfigError('proxy: при заданных proxy.profiles top-level proxy.auth запрещён — auth задаётся в профиле');
|
|
823
|
+
}
|
|
824
|
+
if (hasConfiguredTls(cfg.tls)) {
|
|
825
|
+
throw new ProxyConfigError('proxy: при заданных proxy.profiles top-level proxy.tls запрещён — tls задаётся в профиле ' +
|
|
826
|
+
'(env SYNTH_PROXY_TLS_* для профилей не применяется)');
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
// Стандартные env — только для legacy-default; профили/правила из env не читаются.
|
|
830
|
+
const allowStandardEnv = fromEnv && explicit !== false && !hasProfiles;
|
|
831
|
+
const runtimeCfg = (options.runtime ?? {});
|
|
832
|
+
const originOf = (field) => runtimeCfg[field] !== undefined && runtimeCfg[field] !== '' ? 'runtime' : 'config';
|
|
833
|
+
const pick = (envKey, field, standard) => {
|
|
834
|
+
const take = (raw, origin) => {
|
|
835
|
+
const parsed = parseProxyUrl(raw);
|
|
836
|
+
const picked = { value: parsed.href, origin };
|
|
837
|
+
if (parsed.username !== undefined)
|
|
838
|
+
picked.username = parsed.username;
|
|
839
|
+
if (parsed.password !== undefined)
|
|
840
|
+
picked.password = parsed.password;
|
|
841
|
+
return picked;
|
|
842
|
+
};
|
|
843
|
+
const synth = envValue(env, envKey);
|
|
844
|
+
if (synth !== undefined)
|
|
845
|
+
return take(synth, 'env');
|
|
846
|
+
const cfgValue = cfg[field];
|
|
847
|
+
if (cfgValue !== undefined && cfgValue !== '')
|
|
848
|
+
return take(cfgValue, originOf(field));
|
|
849
|
+
if (allowStandardEnv) {
|
|
850
|
+
for (const key of standard) {
|
|
851
|
+
const raw = envValue(env, key);
|
|
852
|
+
if (raw !== undefined)
|
|
853
|
+
return take(raw, 'env');
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
return {};
|
|
857
|
+
};
|
|
858
|
+
const url = pick(PROXY_ENV.url, 'url', []);
|
|
859
|
+
const httpProxy = pick(PROXY_ENV.httpProxy, 'httpProxy', STANDARD_PROXY_ENV.httpProxy);
|
|
860
|
+
const httpsProxy = pick(PROXY_ENV.httpsProxy, 'httpsProxy', STANDARD_PROXY_ENV.httpsProxy);
|
|
861
|
+
const allProxy = pick(PROXY_ENV.allProxy, 'allProxy', STANDARD_PROXY_ENV.allProxy);
|
|
862
|
+
// noProxy: SYNTH_PROXY_NO_PROXY > config.noProxy (непустой) > NO_PROXY (при fromEnv).
|
|
863
|
+
let noProxy = [];
|
|
864
|
+
const envNoProxy = envValue(env, PROXY_ENV.noProxy);
|
|
865
|
+
if (envNoProxy !== undefined) {
|
|
866
|
+
noProxy = splitEnvList(envNoProxy);
|
|
867
|
+
}
|
|
868
|
+
else if (Array.isArray(cfg.noProxy) && cfg.noProxy.length > 0) {
|
|
869
|
+
noProxy = cfg.noProxy.map((item) => String(item).trim()).filter(Boolean);
|
|
870
|
+
}
|
|
871
|
+
else if (fromEnv) {
|
|
872
|
+
for (const key of STANDARD_PROXY_ENV.noProxy) {
|
|
873
|
+
const raw = envValue(env, key);
|
|
874
|
+
if (raw !== undefined) {
|
|
875
|
+
noProxy = splitEnvList(raw);
|
|
876
|
+
break;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
const fields = [
|
|
881
|
+
['url', url],
|
|
882
|
+
['httpProxy', httpProxy],
|
|
883
|
+
['httpsProxy', httpsProxy],
|
|
884
|
+
['allProxy', allProxy],
|
|
885
|
+
];
|
|
886
|
+
const picked = fields.map(([, value]) => value);
|
|
887
|
+
const legacyUrls = picked
|
|
888
|
+
.map((p) => p.value)
|
|
889
|
+
.filter((value) => value !== undefined);
|
|
890
|
+
const hasLegacyUrl = legacyUrls.length > 0;
|
|
891
|
+
// D2b: SOCKS5 — только TCP-туннель; TLS к прокси (`proxy.tls`) неприменим.
|
|
892
|
+
const anySocks = legacyUrls.some((value) => isSocksProxyProtocol(safeProtocol(value)));
|
|
893
|
+
if (!hasProfiles && anySocks && isProxyTlsConfigured(cfg, env)) {
|
|
894
|
+
throw new ProxyConfigError('proxy.tls несовместим с socks5:// (TLS применяется только к http(s)-прокси); ' +
|
|
895
|
+
'уберите proxy.tls или используйте http(s)-прокси');
|
|
896
|
+
}
|
|
897
|
+
const hasProfileUrl = hasProfiles &&
|
|
898
|
+
Object.values(rawProfiles).some((profile) => PROXY_URL_FIELDS.some((field) => {
|
|
899
|
+
const value = profile?.[field];
|
|
900
|
+
return typeof value === 'string' && value !== '';
|
|
901
|
+
}));
|
|
902
|
+
const hasAnyUrl = hasProfiles ? hasProfileUrl : hasLegacyUrl;
|
|
903
|
+
const enabled = explicit ?? (hasAnyUrl || rawRules.length > 0);
|
|
904
|
+
if (enabled && !hasAnyUrl && !structured) {
|
|
905
|
+
// Legacy-поведение (без profiles/rules): fail-closed без URL.
|
|
906
|
+
throw new ProxyConfigError('proxy.enabled=true, но не задан URL прокси — укажите proxy.url/httpProxy/httpsProxy/allProxy ' +
|
|
907
|
+
`либо ${PROXY_ENV.url} (fail-closed: тихого direct-режима нет)`);
|
|
908
|
+
}
|
|
909
|
+
const envFallback = envBoolean(envValue(env, PROXY_ENV.fallbackDirect), PROXY_ENV.fallbackDirect);
|
|
910
|
+
const fallbackDirect = envFallback ?? cfg.fallbackDirect ?? empty.fallbackDirect;
|
|
911
|
+
const connectTimeoutMs = envPositiveInt(envValue(env, PROXY_ENV.connectTimeoutMs), PROXY_ENV.connectTimeoutMs) ??
|
|
912
|
+
cfg.connectTimeoutMs ??
|
|
913
|
+
empty.connectTimeoutMs;
|
|
914
|
+
const origins = picked
|
|
915
|
+
.map((p) => p.origin)
|
|
916
|
+
.filter((origin) => origin !== undefined);
|
|
917
|
+
const profiles = hasProfiles
|
|
918
|
+
? resolveNamedProfiles(rawProfiles, {
|
|
919
|
+
env,
|
|
920
|
+
dataDir: options.dataDir,
|
|
921
|
+
enabled,
|
|
922
|
+
runtimeProfiles,
|
|
923
|
+
})
|
|
924
|
+
: {};
|
|
925
|
+
// Legacy synthetic default: top-level URL/auth/tls (+ env/стандартные env).
|
|
926
|
+
// В режиме профилей top-level TLS/env к профилям не применяются.
|
|
927
|
+
const legacyTls = resolveProxyTls({ proxy: hasProfiles ? {} : cfg }, hasProfiles ? {} : env);
|
|
928
|
+
const legacyTlsMeta = resolveProxyTlsMeta({ proxy: hasProfiles ? {} : cfg }, hasProfiles ? {} : env);
|
|
929
|
+
const auth = hasProfiles ? undefined : validateProxyAuth(cfg.auth);
|
|
930
|
+
const credentials = {};
|
|
931
|
+
if (!hasProfiles && enabled) {
|
|
932
|
+
const password = makeProfilePasswordResolver(env, options.dataDir, 'default');
|
|
933
|
+
for (const [field, value] of fields) {
|
|
934
|
+
if (value.value === undefined)
|
|
935
|
+
continue;
|
|
936
|
+
const username = value.username ?? auth?.username;
|
|
937
|
+
if (username === undefined || username === '')
|
|
938
|
+
continue;
|
|
939
|
+
const pwd = value.password ?? password();
|
|
940
|
+
if (pwd === undefined) {
|
|
941
|
+
throw new ProxyConfigError(`proxy: для пользователя "${username}" не задан пароль — укажите ${PROXY_PASSWORD_ENV} ` +
|
|
942
|
+
'или файл {dataDir}/secrets/proxy-password (в config.yaml пароль не хранится)');
|
|
943
|
+
}
|
|
944
|
+
credentials[field] = { username, password: pwd };
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
const firstCredentials = Object.values(credentials).find((value) => value !== undefined);
|
|
948
|
+
const authUsername = firstCredentials?.username ??
|
|
949
|
+
auth?.username ??
|
|
950
|
+
picked.map((p) => p.username).find((value) => value !== undefined);
|
|
951
|
+
if (!hasProfiles && hasLegacyUrl) {
|
|
952
|
+
const profile = {
|
|
953
|
+
name: 'default',
|
|
954
|
+
source: origins.includes('env')
|
|
955
|
+
? 'env'
|
|
956
|
+
: origins.includes('runtime')
|
|
957
|
+
? 'runtime'
|
|
958
|
+
: 'config',
|
|
959
|
+
legacy: true,
|
|
960
|
+
tls: legacyTls,
|
|
961
|
+
};
|
|
962
|
+
if (url.value !== undefined)
|
|
963
|
+
profile.url = url.value;
|
|
964
|
+
if (httpProxy.value !== undefined)
|
|
965
|
+
profile.httpProxy = httpProxy.value;
|
|
966
|
+
if (httpsProxy.value !== undefined)
|
|
967
|
+
profile.httpsProxy = httpsProxy.value;
|
|
968
|
+
if (allProxy.value !== undefined)
|
|
969
|
+
profile.allProxy = allProxy.value;
|
|
970
|
+
if (Object.keys(credentials).length > 0)
|
|
971
|
+
profile.credentials = credentials;
|
|
972
|
+
if (authUsername !== undefined && authUsername !== '') {
|
|
973
|
+
profile.auth = { type: 'basic', username: authUsername };
|
|
974
|
+
}
|
|
975
|
+
if (legacyTlsMeta.caFile !== undefined ||
|
|
976
|
+
legacyTlsMeta.certFile !== undefined ||
|
|
977
|
+
legacyTlsMeta.keyFile !== undefined ||
|
|
978
|
+
legacyTlsMeta.hasCaPem ||
|
|
979
|
+
legacyTls.rejectUnauthorized === false) {
|
|
980
|
+
profile.tlsMeta = legacyTlsMeta;
|
|
981
|
+
}
|
|
982
|
+
profiles.default = profile;
|
|
983
|
+
}
|
|
984
|
+
const hasLegacyTlsMeta = legacyTlsMeta.caFile !== undefined ||
|
|
985
|
+
legacyTlsMeta.certFile !== undefined ||
|
|
986
|
+
legacyTlsMeta.keyFile !== undefined ||
|
|
987
|
+
legacyTlsMeta.hasCaPem ||
|
|
988
|
+
legacyTls.rejectUnauthorized === false;
|
|
989
|
+
let defaultProfile;
|
|
990
|
+
if (cfg.defaultProfile !== undefined) {
|
|
991
|
+
if (profiles[cfg.defaultProfile] === undefined) {
|
|
992
|
+
throw new ProxyConfigError(`proxy.defaultProfile: профиль "${cfg.defaultProfile}" не найден ` +
|
|
993
|
+
`(есть: ${Object.keys(profiles).join(', ') || '—'})`);
|
|
994
|
+
}
|
|
995
|
+
defaultProfile = cfg.defaultProfile;
|
|
996
|
+
}
|
|
997
|
+
else if (profiles.default !== undefined) {
|
|
998
|
+
defaultProfile = 'default';
|
|
999
|
+
}
|
|
1000
|
+
else if (mode === 'all' && structured) {
|
|
1001
|
+
throw new ProxyConfigError('proxy.defaultProfile: mode=all требует default-профиль (задайте profiles.default ' +
|
|
1002
|
+
'или proxy.defaultProfile)');
|
|
1003
|
+
}
|
|
1004
|
+
if (mode === 'selected' && rawRules.length === 0) {
|
|
1005
|
+
throw new ProxyConfigError('proxy.rules: mode=selected требует хотя бы одно правило (иначе весь трафик — direct)');
|
|
1006
|
+
}
|
|
1007
|
+
const rules = resolveProxyRules(rawRules, profiles, defaultProfile);
|
|
1008
|
+
const source = !enabled
|
|
1009
|
+
? 'none'
|
|
1010
|
+
: hasProfiles
|
|
1011
|
+
? runtimeProfiles !== undefined
|
|
1012
|
+
? 'runtime'
|
|
1013
|
+
: 'config'
|
|
1014
|
+
: origins.includes('env')
|
|
1015
|
+
? 'env'
|
|
1016
|
+
: origins.includes('runtime')
|
|
1017
|
+
? 'runtime'
|
|
1018
|
+
: origins.includes('config')
|
|
1019
|
+
? 'config'
|
|
1020
|
+
: 'none';
|
|
1021
|
+
const resolved = {
|
|
1022
|
+
enabled,
|
|
1023
|
+
source,
|
|
1024
|
+
mode,
|
|
1025
|
+
profiles,
|
|
1026
|
+
rules,
|
|
1027
|
+
noProxy,
|
|
1028
|
+
fromEnv,
|
|
1029
|
+
fallbackDirect,
|
|
1030
|
+
connectTimeoutMs,
|
|
1031
|
+
};
|
|
1032
|
+
// TLS/mTLS к прокси: legacy-поле — только без профилей (профили несут свой tls).
|
|
1033
|
+
if (!hasProfiles)
|
|
1034
|
+
resolved.tls = legacyTls;
|
|
1035
|
+
if (defaultProfile !== undefined)
|
|
1036
|
+
resolved.defaultProfile = defaultProfile;
|
|
1037
|
+
if (authUsername !== undefined && authUsername !== '') {
|
|
1038
|
+
resolved.auth = { type: 'basic', username: authUsername };
|
|
1039
|
+
}
|
|
1040
|
+
if (hasLegacyTlsMeta)
|
|
1041
|
+
resolved.tlsMeta = legacyTlsMeta;
|
|
1042
|
+
// Legacy-поля заполняются только без `profiles` (в режиме профилей источник — profiles).
|
|
1043
|
+
if (!hasProfiles) {
|
|
1044
|
+
if (url.value !== undefined)
|
|
1045
|
+
resolved.url = url.value;
|
|
1046
|
+
if (httpProxy.value !== undefined)
|
|
1047
|
+
resolved.httpProxy = httpProxy.value;
|
|
1048
|
+
if (httpsProxy.value !== undefined)
|
|
1049
|
+
resolved.httpsProxy = httpsProxy.value;
|
|
1050
|
+
if (allProxy.value !== undefined)
|
|
1051
|
+
resolved.allProxy = allProxy.value;
|
|
1052
|
+
if (Object.keys(credentials).length > 0)
|
|
1053
|
+
resolved.credentials = credentials;
|
|
1054
|
+
}
|
|
1055
|
+
return resolved;
|
|
1056
|
+
}
|
|
1057
|
+
/** `true` — top-level `proxy.auth` задан (в режиме профилей запрещён). */
|
|
1058
|
+
function hasLegacyAuth(auth) {
|
|
1059
|
+
return auth !== undefined;
|
|
1060
|
+
}
|
|
1061
|
+
/** `true` — top-level `proxy.tls` задан (в режиме профилей запрещён). */
|
|
1062
|
+
function hasConfiguredTls(tls) {
|
|
1063
|
+
return tls !== undefined;
|
|
1064
|
+
}
|
|
1065
|
+
/** Резолвит именованные профили (валидация URL/auth/паролей/TLS). */
|
|
1066
|
+
function resolveNamedProfiles(raw, ctx) {
|
|
1067
|
+
const result = {};
|
|
1068
|
+
for (const [name, rawProfile] of Object.entries(raw)) {
|
|
1069
|
+
if (!PROXY_PROFILE_NAME_RE.test(name)) {
|
|
1070
|
+
throw new ProxyConfigError(`proxy.profiles: имя "${name}" невалидно (ожидается ^[a-z][a-z0-9_-]{0,31}$)`);
|
|
1071
|
+
}
|
|
1072
|
+
const scope = `proxy.profiles.${name}`;
|
|
1073
|
+
const profile = rawProfile ?? {};
|
|
1074
|
+
const values = new Map();
|
|
1075
|
+
for (const field of PROXY_URL_FIELDS) {
|
|
1076
|
+
const rawUrl = profile[field];
|
|
1077
|
+
if (rawUrl === undefined || rawUrl === '')
|
|
1078
|
+
continue;
|
|
1079
|
+
values.set(field, parseProxyUrl(rawUrl));
|
|
1080
|
+
}
|
|
1081
|
+
if (values.size === 0) {
|
|
1082
|
+
throw new ProxyConfigError(`${scope}: не задан URL — укажите url или httpProxy/httpsProxy/allProxy`);
|
|
1083
|
+
}
|
|
1084
|
+
const auth = validateProxyAuth(profile.auth, `${scope}.auth`);
|
|
1085
|
+
const anySocks = [...values.values()].some((parsed) => isSocksProxyProtocol(parsed.protocol));
|
|
1086
|
+
const tlsInfo = resolveProfileTls(profile.tls, name);
|
|
1087
|
+
if (anySocks && tlsInfo.configured) {
|
|
1088
|
+
throw new ProxyConfigError(`${scope}: tls несовместим с socks5:// (TLS применяется только к http(s)-прокси)`);
|
|
1089
|
+
}
|
|
1090
|
+
const credentials = {};
|
|
1091
|
+
if (ctx.enabled) {
|
|
1092
|
+
const password = makeProfilePasswordResolver(ctx.env, ctx.dataDir, name);
|
|
1093
|
+
for (const [field, parsed] of values) {
|
|
1094
|
+
const username = parsed.username ?? auth?.username;
|
|
1095
|
+
if (username === undefined || username === '')
|
|
1096
|
+
continue;
|
|
1097
|
+
const pwd = parsed.password ?? password();
|
|
1098
|
+
if (pwd === undefined) {
|
|
1099
|
+
throw new ProxyConfigError(`${scope}: для пользователя "${username}" не задан пароль — укажите ` +
|
|
1100
|
+
`${proxyProfilePasswordEnv(name)} или файл ` +
|
|
1101
|
+
`{dataDir}/secrets/proxy/${name}.password (в config.yaml пароль не хранится)`);
|
|
1102
|
+
}
|
|
1103
|
+
credentials[field] = { username, password: pwd };
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
const resolved = {
|
|
1107
|
+
name,
|
|
1108
|
+
source: ctx.runtimeProfiles !== undefined && ctx.runtimeProfiles[name] !== undefined
|
|
1109
|
+
? 'runtime'
|
|
1110
|
+
: 'config',
|
|
1111
|
+
legacy: false,
|
|
1112
|
+
};
|
|
1113
|
+
if (profile.label !== undefined && profile.label !== '')
|
|
1114
|
+
resolved.label = profile.label;
|
|
1115
|
+
if (values.has('url'))
|
|
1116
|
+
resolved.url = values.get('url').href;
|
|
1117
|
+
if (values.has('httpProxy'))
|
|
1118
|
+
resolved.httpProxy = values.get('httpProxy').href;
|
|
1119
|
+
if (values.has('httpsProxy'))
|
|
1120
|
+
resolved.httpsProxy = values.get('httpsProxy').href;
|
|
1121
|
+
if (values.has('allProxy'))
|
|
1122
|
+
resolved.allProxy = values.get('allProxy').href;
|
|
1123
|
+
if (Object.keys(credentials).length > 0)
|
|
1124
|
+
resolved.credentials = credentials;
|
|
1125
|
+
const firstCredentials = Object.values(credentials).find((value) => value !== undefined);
|
|
1126
|
+
const authUsername = firstCredentials?.username ??
|
|
1127
|
+
auth?.username ??
|
|
1128
|
+
[...values.values()].map((parsed) => parsed.username).find((value) => value !== undefined);
|
|
1129
|
+
if (authUsername !== undefined && authUsername !== '') {
|
|
1130
|
+
resolved.auth = { type: 'basic', username: authUsername };
|
|
1131
|
+
}
|
|
1132
|
+
if (tlsInfo.configured) {
|
|
1133
|
+
resolved.tls = tlsInfo.resolved;
|
|
1134
|
+
resolved.tlsMeta = tlsInfo.meta;
|
|
1135
|
+
}
|
|
1136
|
+
result[name] = resolved;
|
|
1137
|
+
}
|
|
1138
|
+
return result;
|
|
1139
|
+
}
|
|
1140
|
+
/** Резолвит правила маршрутизации: id, хосты, ссылки на профили. */
|
|
1141
|
+
function resolveProxyRules(rawRules, profiles, defaultProfile) {
|
|
1142
|
+
const seen = new Set();
|
|
1143
|
+
return rawRules.map((raw, index) => {
|
|
1144
|
+
const scope = `proxy.rules[${index}]`;
|
|
1145
|
+
const id = raw.id !== undefined && raw.id !== '' ? raw.id : `rule-${index + 1}`;
|
|
1146
|
+
if (seen.has(id)) {
|
|
1147
|
+
throw new ProxyConfigError(`${scope}: id "${id}" повторяется (id правил уникальны)`);
|
|
1148
|
+
}
|
|
1149
|
+
seen.add(id);
|
|
1150
|
+
const hosts = validateProxyHostPatterns(raw.hosts, scope);
|
|
1151
|
+
if (raw.action !== 'proxy' && raw.action !== 'direct') {
|
|
1152
|
+
throw new ProxyConfigError(`${scope}.action: ожидается proxy|direct`);
|
|
1153
|
+
}
|
|
1154
|
+
if (raw.action === 'direct' && raw.profile !== undefined) {
|
|
1155
|
+
throw new ProxyConfigError(`${scope}: action=direct несовместим с profile (уберите profile или выберите action=proxy)`);
|
|
1156
|
+
}
|
|
1157
|
+
const rule = { id, hosts, action: raw.action };
|
|
1158
|
+
if (raw.label !== undefined && raw.label !== '')
|
|
1159
|
+
rule.label = raw.label;
|
|
1160
|
+
if (raw.action === 'proxy') {
|
|
1161
|
+
const profileName = raw.profile ?? defaultProfile;
|
|
1162
|
+
if (profileName === undefined) {
|
|
1163
|
+
throw new ProxyConfigError(`${scope}: action=proxy без profile требует defaultProfile ` +
|
|
1164
|
+
'(задайте profile в правиле или proxy.defaultProfile)');
|
|
1165
|
+
}
|
|
1166
|
+
if (profiles[profileName] === undefined) {
|
|
1167
|
+
throw new ProxyConfigError(`${scope}: профиль "${profileName}" не найден (есть: ${Object.keys(profiles).join(', ') || '—'})`);
|
|
1168
|
+
}
|
|
1169
|
+
rule.profile = profileName;
|
|
1170
|
+
}
|
|
1171
|
+
return rule;
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Валидация входной секции `proxy` для сохранения runtime-override через API.
|
|
1176
|
+
*
|
|
1177
|
+
* Схема (`proxyConfigSchema`) + полный резолв (URL/схемы, `noProxy`, только
|
|
1178
|
+
* `auth.type=basic`, `tls` caFile↔caPem, cert+key, пароль из env/файла).
|
|
1179
|
+
* Дополнительно **запрещает пароль в userinfo URL** и **пароль в теле запроса**
|
|
1180
|
+
* (`auth.password`) — в `settings.json`/PG секреты не хранятся (инвариант 13),
|
|
1181
|
+
* пароль задаётся отдельным endpoint'ом.
|
|
1182
|
+
* `SYNTH_PROXY_*`/стандартные env намеренно игнорируются, чтобы валидировать
|
|
1183
|
+
* именно сохраняемый объект (пароль из `SYNTH_PROXY_PASSWORD`/файла остаётся).
|
|
1184
|
+
*/
|
|
1185
|
+
export function validateProxyConfig(input, env = process.env, options = {}) {
|
|
1186
|
+
const parsed = proxyConfigSchema.safeParse(input);
|
|
1187
|
+
if (!parsed.success) {
|
|
1188
|
+
const issue = parsed.error.issues[0];
|
|
1189
|
+
const path = issue?.path.join('.') || 'proxy';
|
|
1190
|
+
throw new ProxyConfigError(`proxy.${path}: ${issue?.message ?? 'невалидная структура'}`);
|
|
1191
|
+
}
|
|
1192
|
+
const config = parsed.data;
|
|
1193
|
+
/**
|
|
1194
|
+
* Пароль в теле запроса (инвариант 13): пароль прокси задаётся только env или
|
|
1195
|
+
* файлом в `{dataDir}/secrets/`. Поле `auth.password` НЕ входит в контракт
|
|
1196
|
+
* `proxy.auth` (`proxyAuthConfigSchema`), поэтому Zod его молча вырезает — клиент
|
|
1197
|
+
* получил бы «200 OK» и решил, что пароль применён. Поэтому проверяем **сырой**
|
|
1198
|
+
* вход и отвечаем явной ошибкой (fail-closed), а не полагаемся на вырезание.
|
|
1199
|
+
*/
|
|
1200
|
+
const assertNoAuthPassword = (raw, scope, passwordHint) => {
|
|
1201
|
+
if (!raw || typeof raw !== 'object')
|
|
1202
|
+
return;
|
|
1203
|
+
const auth = raw.auth;
|
|
1204
|
+
if (!auth || typeof auth !== 'object')
|
|
1205
|
+
return;
|
|
1206
|
+
const value = auth.password;
|
|
1207
|
+
if (value === undefined || value === null || value === '')
|
|
1208
|
+
return;
|
|
1209
|
+
throw new ProxyConfigError(`${scope}: пароль не хранится в настройках (инвариант 13) — задайте его через ` +
|
|
1210
|
+
`${passwordHint} (в теле запроса пароль не принимается)`);
|
|
1211
|
+
};
|
|
1212
|
+
assertNoAuthPassword(input, 'proxy.auth', `${PROXY_PASSWORD_ENV} или {dataDir}/secrets/proxy-password`);
|
|
1213
|
+
const rawProfiles = input?.profiles;
|
|
1214
|
+
if (rawProfiles && typeof rawProfiles === 'object' && !Array.isArray(rawProfiles)) {
|
|
1215
|
+
for (const [name, profile] of Object.entries(rawProfiles)) {
|
|
1216
|
+
const passwordHint = name === 'default'
|
|
1217
|
+
? `${PROXY_PASSWORD_ENV} или {dataDir}/secrets/proxy-password`
|
|
1218
|
+
: `${proxyProfilePasswordEnv(name)} или {dataDir}/secrets/proxy/${name}.password`;
|
|
1219
|
+
assertNoAuthPassword(profile, `proxy.profiles.${name}.auth`, passwordHint);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
/** Пароль в userinfo URL — в сохраняемом объекте запрещён (инвариант 13). */
|
|
1223
|
+
const assertNoUrlPassword = (raw, scope, passwordEnv) => {
|
|
1224
|
+
if (raw === undefined || raw === '')
|
|
1225
|
+
return;
|
|
1226
|
+
const url = parseProxyUrl(raw);
|
|
1227
|
+
if (url.password === undefined)
|
|
1228
|
+
return;
|
|
1229
|
+
throw new ProxyConfigError(`${scope}: пароль в URL не хранится (инвариант 13) — задайте username и пароль ` +
|
|
1230
|
+
`через ${passwordEnv} или файл в {dataDir}/secrets (в config.yaml пароль не хранится)`);
|
|
1231
|
+
};
|
|
1232
|
+
for (const field of PROXY_URL_FIELDS) {
|
|
1233
|
+
assertNoUrlPassword(config[field], `proxy.${field}`, 'secrets/proxy-password или SYNTH_PROXY_PASSWORD');
|
|
1234
|
+
}
|
|
1235
|
+
for (const [name, profile] of Object.entries(config.profiles ?? {})) {
|
|
1236
|
+
const passwordHint = name === 'default'
|
|
1237
|
+
? `${PROXY_PASSWORD_ENV} или {dataDir}/secrets/proxy-password`
|
|
1238
|
+
: `${proxyProfilePasswordEnv(name)} или {dataDir}/secrets/proxy/${name}.password`;
|
|
1239
|
+
for (const field of PROXY_URL_FIELDS) {
|
|
1240
|
+
assertNoUrlPassword(profile[field], `proxy.profiles.${name}.${field}`, passwordHint);
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
const validationEnv = { ...env };
|
|
1244
|
+
for (const key of [
|
|
1245
|
+
...Object.values(PROXY_ENV),
|
|
1246
|
+
...Object.values(PROXY_TLS_ENV),
|
|
1247
|
+
...STANDARD_PROXY_ENV.httpProxy,
|
|
1248
|
+
...STANDARD_PROXY_ENV.httpsProxy,
|
|
1249
|
+
...STANDARD_PROXY_ENV.allProxy,
|
|
1250
|
+
...STANDARD_PROXY_ENV.noProxy,
|
|
1251
|
+
]) {
|
|
1252
|
+
delete validationEnv[key];
|
|
1253
|
+
}
|
|
1254
|
+
resolveProxyConfig({ proxy: config }, validationEnv, options);
|
|
1255
|
+
return config;
|
|
1256
|
+
}
|
|
1257
|
+
/** Валидация `proxy.auth`: D2a — только `basic`; NTLM/Negotiate — D3/D4. */
|
|
1258
|
+
function validateProxyAuth(auth, scope = 'proxy.auth') {
|
|
1259
|
+
if (auth === undefined)
|
|
1260
|
+
return undefined;
|
|
1261
|
+
if (auth.type !== 'basic') {
|
|
1262
|
+
throw new ProxyConfigError(`${scope}.type "${auth.type}" не поддерживается (NTLM/Negotiate — этапы D3/D4); ` +
|
|
1263
|
+
"доступен только 'basic'");
|
|
1264
|
+
}
|
|
1265
|
+
if (!auth.username) {
|
|
1266
|
+
throw new ProxyConfigError(`${scope}.username обязателен для type=basic (либо задайте userinfo в URL прокси)`);
|
|
1267
|
+
}
|
|
1268
|
+
return auth;
|
|
1269
|
+
}
|
|
1270
|
+
/** Разбирает origin (URL-строка/`URL`); невалидный/не-HTTP(S) → `undefined`. */
|
|
1271
|
+
function parseProxyTarget(origin) {
|
|
1272
|
+
let parsed;
|
|
1273
|
+
try {
|
|
1274
|
+
parsed = typeof origin === 'string' ? new URL(origin) : origin;
|
|
1275
|
+
}
|
|
1276
|
+
catch {
|
|
1277
|
+
return undefined;
|
|
1278
|
+
}
|
|
1279
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
1280
|
+
return undefined;
|
|
1281
|
+
const port = parsed.port !== '' ? Number(parsed.port) : parsed.protocol === 'https:' ? 443 : 80;
|
|
1282
|
+
return { protocol: parsed.protocol, hostname: parsed.hostname, port };
|
|
1283
|
+
}
|
|
1284
|
+
/** Кэш матчеров (noProxy/правила не меняются в пределах resolved-конфига). */
|
|
1285
|
+
const matcherCache = new WeakMap();
|
|
1286
|
+
function cachedMatcher(key, entries) {
|
|
1287
|
+
let matcher = matcherCache.get(key);
|
|
1288
|
+
if (matcher === undefined) {
|
|
1289
|
+
matcher = new NoProxyMatcher(entries);
|
|
1290
|
+
matcherCache.set(key, matcher);
|
|
1291
|
+
}
|
|
1292
|
+
return matcher;
|
|
1293
|
+
}
|
|
1294
|
+
/** Поле URL профиля по схеме цели. */
|
|
1295
|
+
function schemeFieldFor(protocol) {
|
|
1296
|
+
return protocol === 'https:' ? 'httpsProxy' : 'httpProxy';
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* URL профиля для схемы цели: `http(s)Proxy` → `allProxy` → `url`; креды —
|
|
1300
|
+
* по выбранному полю. Используется и маршрутом, и `defaultProxyEntry`.
|
|
1301
|
+
*/
|
|
1302
|
+
function profileEntryFor(profile, field) {
|
|
1303
|
+
const order = [field, 'allProxy', 'url'];
|
|
1304
|
+
for (const candidate of order) {
|
|
1305
|
+
const value = profile[candidate];
|
|
1306
|
+
if (value === undefined)
|
|
1307
|
+
continue;
|
|
1308
|
+
const entry = {
|
|
1309
|
+
url: value,
|
|
1310
|
+
field: candidate,
|
|
1311
|
+
};
|
|
1312
|
+
const credentials = profile.credentials?.[candidate];
|
|
1313
|
+
if (credentials)
|
|
1314
|
+
entry.credentials = credentials;
|
|
1315
|
+
return entry;
|
|
1316
|
+
}
|
|
1317
|
+
return undefined;
|
|
1318
|
+
}
|
|
1319
|
+
/** Legacy-профиль из flat-полей (для вручную собранных `ResolvedProxyConfig`). */
|
|
1320
|
+
function legacyProfileOf(config) {
|
|
1321
|
+
if (config.url === undefined &&
|
|
1322
|
+
config.httpProxy === undefined &&
|
|
1323
|
+
config.httpsProxy === undefined &&
|
|
1324
|
+
config.allProxy === undefined) {
|
|
1325
|
+
return undefined;
|
|
1326
|
+
}
|
|
1327
|
+
const profile = {
|
|
1328
|
+
name: 'default',
|
|
1329
|
+
source: config.source === 'none' ? 'config' : config.source,
|
|
1330
|
+
legacy: true,
|
|
1331
|
+
};
|
|
1332
|
+
if (config.url !== undefined)
|
|
1333
|
+
profile.url = config.url;
|
|
1334
|
+
if (config.httpProxy !== undefined)
|
|
1335
|
+
profile.httpProxy = config.httpProxy;
|
|
1336
|
+
if (config.httpsProxy !== undefined)
|
|
1337
|
+
profile.httpsProxy = config.httpsProxy;
|
|
1338
|
+
if (config.allProxy !== undefined)
|
|
1339
|
+
profile.allProxy = config.allProxy;
|
|
1340
|
+
if (config.credentials !== undefined)
|
|
1341
|
+
profile.credentials = config.credentials;
|
|
1342
|
+
if (config.auth !== undefined)
|
|
1343
|
+
profile.auth = config.auth;
|
|
1344
|
+
if (config.tls !== undefined)
|
|
1345
|
+
profile.tls = config.tls;
|
|
1346
|
+
if (config.tlsMeta !== undefined)
|
|
1347
|
+
profile.tlsMeta = config.tlsMeta;
|
|
1348
|
+
return profile;
|
|
1349
|
+
}
|
|
1350
|
+
/** Профиль по имени: из `profiles`, для `default` — фоллбэк на flat-поля. */
|
|
1351
|
+
function profileByName(config, name) {
|
|
1352
|
+
if (name === undefined)
|
|
1353
|
+
return undefined;
|
|
1354
|
+
const profile = config.profiles?.[name];
|
|
1355
|
+
// Legacy-профиль выводится из flat-полей: они остаются авторитетными
|
|
1356
|
+
// (совместимость с кодом/тестами, патчащими `url`/`httpProxy`/… напрямую).
|
|
1357
|
+
if (profile?.legacy) {
|
|
1358
|
+
const legacy = legacyProfileOf(config);
|
|
1359
|
+
if (legacy !== undefined)
|
|
1360
|
+
return legacy;
|
|
1361
|
+
}
|
|
1362
|
+
if (profile !== undefined)
|
|
1363
|
+
return profile;
|
|
1364
|
+
if (name === 'default')
|
|
1365
|
+
return legacyProfileOf(config);
|
|
1366
|
+
return undefined;
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Единая точка маршрутизации прокси для target-origin (ADR-099).
|
|
1370
|
+
*
|
|
1371
|
+
* Порядок: `enabled:false` → всё direct; `noProxy` **всегда выигрывает**;
|
|
1372
|
+
* правила (первое совпадение); затем default (`mode: all`) либо `no-match`
|
|
1373
|
+
* (`mode: selected`). `action: proxy` берёт `rule.profile ?? defaultProfile`.
|
|
1374
|
+
* CIDR матчится только по IP-литералу цели (DNS не выполняется).
|
|
1375
|
+
*/
|
|
1376
|
+
export function resolveProxyRoute(config, origin) {
|
|
1377
|
+
if (!config?.enabled)
|
|
1378
|
+
return { action: 'direct', reason: 'disabled' };
|
|
1379
|
+
const target = parseProxyTarget(origin);
|
|
1380
|
+
if (target === undefined)
|
|
1381
|
+
return { action: 'direct', reason: 'no-match' };
|
|
1382
|
+
const noProxyEntries = config.noProxy ?? [];
|
|
1383
|
+
const noProxy = cachedMatcher(noProxyEntries, noProxyEntries);
|
|
1384
|
+
if (noProxy.matches(target.hostname, target.port)) {
|
|
1385
|
+
return { action: 'direct', reason: 'no-proxy' };
|
|
1386
|
+
}
|
|
1387
|
+
const field = schemeFieldFor(target.protocol);
|
|
1388
|
+
for (const rule of config.rules ?? []) {
|
|
1389
|
+
const matcher = cachedMatcher(rule, rule.hosts);
|
|
1390
|
+
if (!matcher.matches(target.hostname, target.port))
|
|
1391
|
+
continue;
|
|
1392
|
+
if (rule.action === 'direct') {
|
|
1393
|
+
return { action: 'direct', reason: 'rule', rule };
|
|
1394
|
+
}
|
|
1395
|
+
const profileName = rule.profile ?? config.defaultProfile ?? 'default';
|
|
1396
|
+
const profile = profileByName(config, profileName);
|
|
1397
|
+
if (profile === undefined) {
|
|
1398
|
+
return { action: 'direct', reason: 'no-default', rule };
|
|
1399
|
+
}
|
|
1400
|
+
const entry = profileEntryFor(profile, field);
|
|
1401
|
+
if (entry === undefined) {
|
|
1402
|
+
return { action: 'direct', reason: 'no-default', rule };
|
|
1403
|
+
}
|
|
1404
|
+
const route = {
|
|
1405
|
+
action: 'proxy',
|
|
1406
|
+
reason: 'rule',
|
|
1407
|
+
rule,
|
|
1408
|
+
profile: profileName,
|
|
1409
|
+
proxyUrl: entry.url,
|
|
1410
|
+
};
|
|
1411
|
+
if (entry.credentials !== undefined)
|
|
1412
|
+
route.credentials = entry.credentials;
|
|
1413
|
+
return route;
|
|
1414
|
+
}
|
|
1415
|
+
const mode = config.mode ?? 'all';
|
|
1416
|
+
if (mode === 'selected')
|
|
1417
|
+
return { action: 'direct', reason: 'no-match' };
|
|
1418
|
+
return resolveDefaultProxyRoute(config, field);
|
|
1419
|
+
}
|
|
1420
|
+
/** Default-ветка маршрута (без правил/noProxy) — общая с `defaultProxyEntry`. */
|
|
1421
|
+
function resolveDefaultProxyRoute(config, field) {
|
|
1422
|
+
const defaultName = config.defaultProfile ?? 'default';
|
|
1423
|
+
const defaultProfile = profileByName(config, defaultName);
|
|
1424
|
+
if (defaultProfile === undefined)
|
|
1425
|
+
return { action: 'direct', reason: 'no-default' };
|
|
1426
|
+
const entry = profileEntryFor(defaultProfile, field);
|
|
1427
|
+
if (entry === undefined)
|
|
1428
|
+
return { action: 'direct', reason: 'no-default' };
|
|
1429
|
+
const route = {
|
|
1430
|
+
action: 'proxy',
|
|
1431
|
+
reason: 'default',
|
|
1432
|
+
profile: defaultName,
|
|
1433
|
+
proxyUrl: entry.url,
|
|
1434
|
+
};
|
|
1435
|
+
if (entry.credentials !== undefined)
|
|
1436
|
+
route.credentials = entry.credentials;
|
|
1437
|
+
return route;
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Эффективный прокси для target-origin: `{url, credentials?}` или `undefined`.
|
|
1441
|
+
* Полностью выводится из `resolveProxyRoute` (профили/правила/noProxy).
|
|
1442
|
+
*/
|
|
1443
|
+
export function proxyEntryFor(config, origin) {
|
|
1444
|
+
const route = resolveProxyRoute(config, origin);
|
|
1445
|
+
if (route.action !== 'proxy' || route.proxyUrl === undefined)
|
|
1446
|
+
return undefined;
|
|
1447
|
+
return route.credentials !== undefined
|
|
1448
|
+
? { url: route.proxyUrl, credentials: route.credentials }
|
|
1449
|
+
: { url: route.proxyUrl };
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Прокси по умолчанию (для диагностики/`/settings/proxy/check`): профиль
|
|
1453
|
+
* `defaultProfile` без учёта правил; порядок полей `https → all → url → http`
|
|
1454
|
+
* (как legacy-поведение). `undefined` — default-профиля/URL нет.
|
|
1455
|
+
*/
|
|
1456
|
+
export function defaultProxyEntry(config) {
|
|
1457
|
+
if (!config.enabled)
|
|
1458
|
+
return undefined;
|
|
1459
|
+
// Порядок legacy: https → all → url → http (http — фоллбэк для http-only прокси).
|
|
1460
|
+
let route = resolveDefaultProxyRoute(config, 'httpsProxy');
|
|
1461
|
+
if (route.action !== 'proxy')
|
|
1462
|
+
route = resolveDefaultProxyRoute(config, 'httpProxy');
|
|
1463
|
+
if (route.action !== 'proxy' || route.proxyUrl === undefined)
|
|
1464
|
+
return undefined;
|
|
1465
|
+
return route.credentials !== undefined
|
|
1466
|
+
? { url: route.proxyUrl, credentials: route.credentials }
|
|
1467
|
+
: { url: route.proxyUrl };
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* URL прокси для target-origin (по маршруту: профили/правила/noProxy).
|
|
1471
|
+
* `undefined` — для этой цели прокси нет (direct).
|
|
1472
|
+
*/
|
|
1473
|
+
export function proxyUrlFor(config, origin) {
|
|
1474
|
+
return resolveProxyRoute(config, origin).proxyUrl;
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* Нужно ли направлять URL через прокси (маршрут `action: proxy`).
|
|
1478
|
+
* DNS/CIDR-сверка не выполняется (только host/port цели).
|
|
1479
|
+
*/
|
|
1480
|
+
export function shouldProxyUrl(config, rawUrl) {
|
|
1481
|
+
const route = resolveProxyRoute(config, rawUrl);
|
|
1482
|
+
return route.action === 'proxy' && route.proxyUrl !== undefined;
|
|
1483
|
+
}
|
|
1484
|
+
/** Redacted-профиль для статуса: без userinfo/паролей/PEM. */
|
|
1485
|
+
function redactedProfileStatus(profile) {
|
|
1486
|
+
const result = {
|
|
1487
|
+
name: profile.name,
|
|
1488
|
+
legacy: profile.legacy,
|
|
1489
|
+
source: profile.source,
|
|
1490
|
+
};
|
|
1491
|
+
if (profile.label !== undefined && profile.label !== '')
|
|
1492
|
+
result.label = profile.label;
|
|
1493
|
+
const url = redactProxyUrl(profile.url);
|
|
1494
|
+
if (url)
|
|
1495
|
+
result.url = url;
|
|
1496
|
+
const httpProxy = redactProxyUrl(profile.httpProxy);
|
|
1497
|
+
if (httpProxy)
|
|
1498
|
+
result.httpProxy = httpProxy;
|
|
1499
|
+
const httpsProxy = redactProxyUrl(profile.httpsProxy);
|
|
1500
|
+
if (httpsProxy)
|
|
1501
|
+
result.httpsProxy = httpsProxy;
|
|
1502
|
+
const allProxy = redactProxyUrl(profile.allProxy);
|
|
1503
|
+
if (allProxy)
|
|
1504
|
+
result.allProxy = allProxy;
|
|
1505
|
+
if (profile.auth && profile.auth.username !== '') {
|
|
1506
|
+
result.auth = { type: 'basic', username: profile.auth.username };
|
|
1507
|
+
}
|
|
1508
|
+
const meta = redactedTlsMeta(profile.tlsMeta);
|
|
1509
|
+
if (meta) {
|
|
1510
|
+
result.tls = { ...meta, rejectUnauthorized: profile.tls?.rejectUnauthorized ?? true };
|
|
1511
|
+
}
|
|
1512
|
+
return result;
|
|
1513
|
+
}
|
|
1514
|
+
/** Read-only статус прокси (без userinfo/секретов/PEM). */
|
|
1515
|
+
export function proxyStatus(config) {
|
|
1516
|
+
const resolved = config ?? emptyResolvedProxyConfig();
|
|
1517
|
+
const profiles = {};
|
|
1518
|
+
for (const [name, profile] of Object.entries(resolved.profiles ?? {})) {
|
|
1519
|
+
profiles[name] = redactedProfileStatus(profile);
|
|
1520
|
+
}
|
|
1521
|
+
const rules = (resolved.rules ?? []).map((rule) => {
|
|
1522
|
+
const item = {
|
|
1523
|
+
id: rule.id,
|
|
1524
|
+
hosts: [...rule.hosts],
|
|
1525
|
+
action: rule.action,
|
|
1526
|
+
};
|
|
1527
|
+
if (rule.label !== undefined && rule.label !== '')
|
|
1528
|
+
item.label = rule.label;
|
|
1529
|
+
if (rule.profile !== undefined)
|
|
1530
|
+
item.profile = rule.profile;
|
|
1531
|
+
return item;
|
|
1532
|
+
});
|
|
1533
|
+
const status = {
|
|
1534
|
+
enabled: resolved.enabled,
|
|
1535
|
+
source: resolved.source,
|
|
1536
|
+
mode: resolved.mode ?? 'all',
|
|
1537
|
+
profiles,
|
|
1538
|
+
rules,
|
|
1539
|
+
noProxy: [...resolved.noProxy],
|
|
1540
|
+
fromEnv: resolved.fromEnv,
|
|
1541
|
+
fallbackDirect: resolved.fallbackDirect,
|
|
1542
|
+
connectTimeoutMs: resolved.connectTimeoutMs,
|
|
1543
|
+
restartRequired: true,
|
|
1544
|
+
};
|
|
1545
|
+
if (resolved.defaultProfile !== undefined)
|
|
1546
|
+
status.defaultProfile = resolved.defaultProfile;
|
|
1547
|
+
const url = redactProxyUrl(resolved.url);
|
|
1548
|
+
if (url)
|
|
1549
|
+
status.url = url;
|
|
1550
|
+
const httpProxy = redactProxyUrl(resolved.httpProxy);
|
|
1551
|
+
if (httpProxy)
|
|
1552
|
+
status.httpProxy = httpProxy;
|
|
1553
|
+
const httpsProxy = redactProxyUrl(resolved.httpsProxy);
|
|
1554
|
+
if (httpsProxy)
|
|
1555
|
+
status.httpsProxy = httpsProxy;
|
|
1556
|
+
const allProxy = redactProxyUrl(resolved.allProxy);
|
|
1557
|
+
if (allProxy)
|
|
1558
|
+
status.allProxy = allProxy;
|
|
1559
|
+
if (resolved.auth && resolved.auth.username !== '') {
|
|
1560
|
+
status.auth = { type: 'basic', username: resolved.auth.username };
|
|
1561
|
+
}
|
|
1562
|
+
const tlsMeta = redactedTlsMeta(resolved.tlsMeta);
|
|
1563
|
+
if (tlsMeta) {
|
|
1564
|
+
status.tls = { ...tlsMeta, rejectUnauthorized: resolved.tls?.rejectUnauthorized ?? true };
|
|
1565
|
+
}
|
|
1566
|
+
return status;
|
|
1567
|
+
}
|