Files
php-ai-sdk/src/Proxy.php
T
rsgrinko 305a7d0151 Прокси: AI_PROXY, HTTP/SOCKS, работа через прокси в http_request
- новый класс Proxy: разбор адреса (http/https/socks4/4a/5/5h),
  авторизация, исключения NO_PROXY; AI_PROXY=none — принудительно напрямую;
- HttpTransport, AiClient, HttpRequestTool, Config и .env.example знают
  о прокси; если AI_PROXY пуст, cURL по-прежнему читает окружение;
- через прокси http_request не требует локального DNS (UrlGuard::pin
  с resolve: false), локальные и приватные адреса по-прежнему запрещены;
- тесты: разбор адреса, NO_PROXY, сквозной запрос через мини-прокси,
  Proxy-Authorization, обход прокси и принудительно напрямую;
- docs: README, reference, tools, providers, examples; пример 24-proxy.php.
2026-11-25 17:13:02 +00:00

309 lines
11 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace Rsgrinko\AiSdk;
/**
* Прокси для HTTP-запросов SDK: к модели и из инструментов.
*
* Адрес понимает и со схемой, и без неё; схема задаёт тип прокси:
*
* proxy.local:3128 HTTP-прокси (схема по умолчанию)
* http://proxy.local:3128 то же явно
* socks5h://127.0.0.1:1080 SOCKS5, имя резолвит прокси
* socks5://127.0.0.1:1080 SOCKS5, имя резолвит клиент
* user:pass@proxy.local:3128 с авторизацией (креды можно декодировать
* из URL, лишние символы — %XX)
*
* Порт обязателен: у прокси нет общепринятого порта по умолчанию, и молча
* ходить «куда-то» хуже, чем получить понятную ошибку.
*
* Три состояния:
* null — ничего не задано: cURL сам возьмёт http_proxy/HTTPS_PROXY/
* ALL_PROXY/NO_PROXY из окружения (как раньше);
* direct() — «none»/«direct» в AI_PROXY: ходить напрямую, переменные
* окружения игнорировать;
* объект Proxy — явный прокси. Тогда окружение не читается, а NO_PROXY из
* AI_NO_PROXY отключает прокси для перечисленных хостов.
*/
final class Proxy
{
/** Значения AI_PROXY, означающие «без прокси, даже если окружение против». */
private const DIRECT_WORDS = ['none', 'direct', 'off', 'no'];
/** Схема => тип прокси для cURL. */
private const TYPES = [
'http' => CURLPROXY_HTTP,
'https' => CURLPROXY_HTTPS,
'socks4' => CURLPROXY_SOCKS4,
'socks4a' => CURLPROXY_SOCKS4A,
'socks5' => CURLPROXY_SOCKS5,
'socks5h' => CURLPROXY_SOCKS5_HOSTNAME,
];
/**
* @param string $host адрес без схемы и креденшелов
* @param list<string> $noProxy хосты, которые прокси не трогает
*/
private function __construct(
private readonly string $host,
private readonly int $port,
private readonly int $type,
private readonly string $user = '',
private readonly string $password = '',
private readonly array $noProxy = [],
private readonly bool $direct = false,
) {
}
/**
* Ходить напрямую, не глядя на http_proxy/HTTPS_PROXY. Так AI_PROXY=none
* спасает от прокси в окружении, которое мешает локальной модели.
*/
public static function direct(): self
{
return new self('', 0, CURLPROXY_HTTP, direct: true);
}
/**
* Прокси из окружения: AI_PROXY и связанные с ним переменные.
* null — переменная не задана, поведение cURL по умолчанию.
*
* @throws \InvalidArgumentException если адрес некорректен
*/
public static function fromEnv(): ?self
{
return self::fromString(
(string) Env::get('AI_PROXY', ''),
(string) Env::get('AI_PROXY_USER', ''),
(string) Env::get('AI_PROXY_PASS', ''),
(string) Env::get('AI_NO_PROXY', ''),
);
}
/**
* Прокси из настроек клиента (Config::ENV: proxy, proxy_user, proxy_pass,
* no_proxy). Пустое значение — null, как у fromEnv().
*
* @throws \InvalidArgumentException если адрес некорректен
*/
public static function fromConfig(Config $config): ?self
{
return self::fromString(
$config->string('proxy', ''),
$config->string('proxy_user', ''),
$config->string('proxy_pass', ''),
$config->string('no_proxy', ''),
);
}
/**
* Собрать прокси из строки. Пустая строка — null (не задан),
* none/direct/off/no — direct().
*
* @throws \InvalidArgumentException если адрес некорректен
*/
public static function fromString(
string $address,
string $user = '',
string $password = '',
string $noProxy = '',
): ?self {
$address = trim($address);
if ($address === '') {
return null;
}
if (in_array(strtolower($address), self::DIRECT_WORDS, true)) {
return self::direct();
}
if (!str_contains($address, '://')) {
$address = 'http://' . $address;
}
$parts = parse_url($address);
if ($parts === false || !isset($parts['scheme'], $parts['host'])) {
throw new \InvalidArgumentException(
'Некорректный адрес прокси: "' . $address . '". Пример: http://proxy.local:3128'
);
}
$scheme = strtolower($parts['scheme']);
if (!isset(self::TYPES[$scheme])) {
throw new \InvalidArgumentException(
'Неизвестный тип прокси: ' . $scheme
. '. Поддерживаются: ' . implode(', ', array_keys(self::TYPES)) . '.'
);
}
$path = (string) ($parts['path'] ?? '');
if ($path !== '' && $path !== '/') {
throw new \InvalidArgumentException(
'В адресе прокси не должно быть пути: "' . $address . '". Нужны только хост и порт.'
);
}
if (isset($parts['query']) || isset($parts['fragment'])) {
throw new \InvalidArgumentException(
'В адресе прокси не должно быть параметров: "' . $address . '". Нужны только хост и порт.'
);
}
if (!isset($parts['port'])) {
throw new \InvalidArgumentException(
'В адресе прокси не указан порт: "' . $address . '". Пример: http://proxy.local:3128'
);
}
return new self(
host: (string) $parts['host'],
port: (int) $parts['port'],
type: self::TYPES[$scheme],
// Явные настройки важнее креденшелов из URL.
user: $user !== '' ? $user : rawurldecode((string) ($parts['user'] ?? '')),
password: $password !== '' ? $password : rawurldecode((string) ($parts['pass'] ?? '')),
noProxy: self::parseNoProxy($noProxy),
);
}
/**
* @return list<string>
*/
private static function parseNoProxy(string $list): array
{
$entries = array_map('trim', explode(',', $list));
return array_values(array_filter($entries, static fn (string $entry): bool => $entry !== ''));
}
/**
* Идёт ли запрос на этот URL через прокси.
*/
public function appliesTo(string $url): bool
{
if ($this->direct) {
return false;
}
if ($this->noProxy === []) {
return true;
}
$parts = parse_url($url);
$host = strtolower(trim((string) ($parts['host'] ?? ''), '[]'));
if ($host === '') {
return true;
}
$scheme = strtolower((string) ($parts['scheme'] ?? 'http'));
$port = (int) ($parts['port'] ?? ($scheme === 'https' ? 443 : 80));
foreach ($this->noProxy as $entry) {
if (self::matchesNoProxy($host, $port, $entry)) {
return false;
}
}
return true;
}
/**
* Запись NO_PROXY: `*` — всё, `example.com` — сам хост и поддомены,
* `.example.com` и `*.example.com` — то же, `example.com:8080` — только
* этот порт.
*/
private static function matchesNoProxy(string $host, int $port, string $entry): bool
{
$entry = strtolower(trim($entry));
if ($entry === '') {
return false;
}
if ($entry === '*') {
return true;
}
$entryPort = null;
if (preg_match('/^(\[[^\]]+\]|[^:]+):(\d+)$/', $entry, $match) === 1) {
$entry = $match[1];
$entryPort = (int) $match[2];
}
if ($entryPort !== null && $entryPort !== $port) {
return false;
}
$entry = trim(ltrim($entry, '.'), '[]');
if (str_starts_with($entry, '*.')) {
$entry = substr($entry, 2);
}
if ($entry === '') {
return false;
}
return $host === $entry || str_ends_with($host, '.' . $entry);
}
public function isDirect(): bool
{
return $this->direct;
}
/**
* Параметры cURL для этого запроса. Целевой хост из NO_PROXY получает
* CURLOPT_PROXY = '' — соединение напрямую, без прокси из окружения.
*
* @return array<int, mixed>
*/
public function curlOptions(string $url): array
{
if (!$this->appliesTo($url)) {
// Пустая строка отключает и прокси из окружения: решение явное.
return [CURLOPT_PROXY => ''];
}
$options = [
CURLOPT_PROXY => $this->host,
CURLOPT_PROXYPORT => $this->port,
CURLOPT_PROXYTYPE => $this->type,
];
if ($this->user !== '' || $this->password !== '') {
$options[CURLOPT_PROXYUSERPWD] = $this->user . ':' . $this->password;
}
// Пустой список — тоже важно: иначе NO_PROXY из окружения мог бы
// молча отменить явно заданный прокси.
$options[CURLOPT_NOPROXY] = implode(',', $this->noProxy);
return $options;
}
/**
* Человеческое описание для логов и примеров. Пароль не показывается.
*/
public function describe(): string
{
if ($this->direct) {
return 'напрямую (прокси из окружения игнорируется)';
}
$scheme = array_search($this->type, self::TYPES, true);
$auth = $this->user === '' ? '' : $this->user . ':***@';
return ($scheme === false ? 'http' : (string) $scheme) . '://' . $auth . $this->host . ':' . $this->port
. ($this->noProxy === [] ? '' : ' (кроме ' . implode(', ', $this->noProxy) . ')');
}
}