67 lines
3.0 KiB
PHP
67 lines
3.0 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace app\service\group;
|
|
|
|
use app\service\Settings;
|
|
|
|
/** 客服仅接受部署配置登记的固定回调;未配置时不注册客户端。 */
|
|
final class KefuClient
|
|
{
|
|
public const ID = 'kefu';
|
|
|
|
public static function entry(): string
|
|
{
|
|
$base = Settings::get('IAM_KEFU_BASE_URL');
|
|
if ($base === '' || preg_match('/[\x00-\x20\x7f\\\\]/', $base)) { return ''; }
|
|
$parts = parse_url($base);
|
|
if (!$parts || !in_array($parts['scheme'] ?? '', ['http', 'https'], true) || empty($parts['host'])
|
|
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])
|
|
|| !filter_var($base, FILTER_VALIDATE_URL)
|
|
|| !preg_match('~^(?:|/(?:[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*/?)?)$~D', $parts['path'] ?? '')) { return ''; }
|
|
if ($parts['scheme'] === 'http' && !self::isHttpOriginAllowed($base)) { return ''; }
|
|
return rtrim($base, '/') . '/auth/group-login';
|
|
}
|
|
|
|
/** HTTP stays loopback-only unless the deployment lists this exact origin. */
|
|
public static function isHttpOriginAllowed(string $url): bool
|
|
{
|
|
$origin = self::httpOrigin($url);
|
|
if ($origin === '') { return false; }
|
|
$host = strtolower((string) parse_url($url, PHP_URL_HOST));
|
|
return in_array($host, ['localhost', '127.0.0.1', '[::1]', '::1'], true)
|
|
|| self::isExplicitHttpOriginAllowed($url);
|
|
}
|
|
|
|
public static function isExplicitHttpOriginAllowed(string $url): bool
|
|
{
|
|
$origin = self::httpOrigin($url);
|
|
$configured = Settings::get('IAM_KEFU_ALLOWED_HTTP_ORIGINS');
|
|
if ($origin === '' || $configured === '' || preg_match('/[\x00-\x1f\x7f]/', $configured)) { return false; }
|
|
$origins = [];
|
|
foreach (explode(',', $configured) as $candidate) {
|
|
$candidate = trim($candidate, ' ');
|
|
// Entries are origins, never URL prefixes, paths, wildcards or credentials.
|
|
if (!preg_match('~^http://(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::[1-9][0-9]{0,4})?$~iD', $candidate)
|
|
|| ($allowed = self::httpOrigin($candidate)) === '') { return false; }
|
|
$origins[] = $allowed;
|
|
}
|
|
return in_array($origin, $origins, true);
|
|
}
|
|
|
|
private static function httpOrigin(string $url): string
|
|
{
|
|
$parts = parse_url($url);
|
|
if (!$parts || ($parts['scheme'] ?? '') !== 'http' || empty($parts['host'])
|
|
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])
|
|
|| preg_match('/[\x00-\x20\x7f\\\\%]/', $url) || !filter_var($url, FILTER_VALIDATE_URL)
|
|
|| (isset($parts['port']) && $parts['port'] < 1)) { return ''; }
|
|
return 'http://' . strtolower($parts['host']) . ':' . ($parts['port'] ?? 80);
|
|
}
|
|
|
|
public static function companyCode(): string
|
|
{
|
|
$code = Settings::get('IAM_KEFU_COMPANY_CODE');
|
|
return preg_match('/^[a-z][a-z0-9-]{1,31}$/D', $code) ? $code : '';
|
|
}
|
|
}
|