修复国家设置,允许不设置任何国家,不做判断

This commit is contained in:
root
2026-06-20 04:09:37 +08:00
parent 6b3b99b0f1
commit 24ff3f9657
11 changed files with 188 additions and 23 deletions
+39 -4
View File
@@ -1,6 +1,7 @@
<?php
require_once __DIR__ . '/cong.php';
require_once __DIR__ . '/admin/bootstrap.php';
require_once __DIR__ . '/lib/Cloak/CountryAllowlist.php';
require_once __DIR__ . '/admin/ConfigWriter.php';
require_once __DIR__ . '/lib/Cloak/DomainRepository.php';
require_once __DIR__ . '/lib/CloakAdSourceGuard.php';
@@ -83,7 +84,9 @@ if (!empty($_REQUEST["action"]) && $_REQUEST["action"] == "setuvi") {
if (!empty($_REQUEST["action"]) && $_REQUEST["action"] == "submit") {
$check_name = trim($_REQUEST["check_name"]);
$methods = trim($_REQUEST["methods"]);
$country = trim($_REQUEST["country"]);
$country_on = in_array(strtoupper(trim($_REQUEST['country_on'] ?? '')), ['ON']) ? 'ON' : 'OFF';
$country_raw = $country_on === 'ON' ? (string) ($_REQUEST['country'] ?? '') : '';
$country = $country_on === 'ON' ? CountryAllowlist::formatForConfig($country_raw) : '';
$blacklist_group_id = (int)($_REQUEST["blacklist_group_id"] ?? 0);
$whitelist_group_id = (int)($_REQUEST["whitelist_group_id"] ?? 0);
try {
@@ -148,6 +151,11 @@ if (!empty($_REQUEST["action"]) && $_REQUEST["action"] == "submit") {
exit();
}
if ($country_on === 'ON' && $country === '') {
echo "<script>alert('已开启国家条件,请填写允许的国家代码(如 US,GB,CA)。');history.back();</script>";
exit();
}
if (!empty($methods)) {
ConfigWriter::save($check_name, [
'methods' => $methods,
@@ -889,9 +897,26 @@ $_d = function($name, $default) { return defined($name) ? constant($name) : $def
</td>
</tr>
<tr>
<td class="form-label-cell">指定国家访问真实页(逗号分隔国家代码)</td>
<td class="form-val-cell"><input type="text" name="country" class="form-control form-control-sm" value="<?php echo SHOW_SITE_COUNTRY; ?>" placeholder="如:US,GB,CA(请用英文逗号)" style="max-width:300px;"></td>
</tr>
<td class="form-label-cell">
国家条件<br>
<small class="text-muted">开启后仅允许填写的国家访问真实页;关闭则不做国家拦截。</small>
</td>
<td class="form-val-cell">
<?php
$countryCodesVal = defined('SHOW_SITE_COUNTRY')
? CountryAllowlist::formatForConfig((string) SHOW_SITE_COUNTRY)
: '';
$countryOnVal = $countryCodesVal !== '' ? 'ON' : 'OFF';
echo onoff_radio('country_on', $countryOnVal, '开启', '关闭');
?>
</td>
</tr>
<tr id="countryCodesRow"<?php echo $countryOnVal === 'ON' ? '' : ' style="display:none;"'; ?>>
<td class="form-label-cell">允许的国家代码(多个使用英文逗号隔开)</td>
<td class="form-val-cell">
<input type="text" name="country" class="form-control form-control-sm" value="<?php echo htmlspecialchars($countryCodesVal); ?>" placeholder="如:US,GB,CA(小写会自动转大写;支持中英文逗号、分号)" style="max-width:360px;">
</td>
</tr>
<tr>
<td class="form-label-cell">广告策略 ID</td>
<td class="form-val-cell"><input type="text" name="costm_ip_score" class="form-control form-control-sm" value="<?php echo COSTM_IP_SCORE; ?>" style="max-width:360px;"></td>
@@ -1210,6 +1235,16 @@ $_d = function($name, $default) { return defined($name) ? constant($name) : $def
$(target).slideToggle(180);
});
function syncCountryCodesRow() {
var on = $('input[name="country_on"]:checked').val() === 'ON';
$('#countryCodesRow').toggle(on);
if (!on) {
$('input[name="country"]').val('');
}
}
$(document).on('change', 'input[name="country_on"]', syncCountryCodesRow);
syncCountryCodesRow();
// 动态添加链接
var linkIdx = 1;
$(document).on('click', '#addNewLinkBtn', function() {
+1 -1
View File
@@ -55,7 +55,7 @@ if (!function_exists('cloak_dbg_record')) {
//-----------------------------------------------ip check bof-----------------------------------------------
$v_info = new visitorInfo();
$v_info->get_visitor_Info(COSTM_IP_SCORE, CHECK_KEY, SHOW_SITE_COUNTRY);
$v_info->get_visitor_Info(COSTM_IP_SCORE, CHECK_KEY, CountryAllowlist::resolvedConfig());
$reason = '';
+56 -5
View File
@@ -6,18 +6,56 @@ require_once __DIR__ . '/CountryCodeNormalizer.php';
class CountryAllowlist
{
/**
* SHOW_SITE_COUNTRY 是否已配置(非空允许列表 = 开启国家条件)
*
* @param string|null $config 默认读取 SHOW_SITE_COUNTRY
*/
public static function isEnabled($config = null)
{
if ($config === null) {
$config = defined('SHOW_SITE_COUNTRY') ? SHOW_SITE_COUNTRY : '';
}
return self::parse($config) !== [];
}
/**
* 保存前规范化用户输入:兼容中文逗号/分号、顿号、全角空格及多余空白。
*
* @param string $config
*/
public static function normalizeInput($config)
{
$config = trim((string) $config);
if ($config === '') {
return '';
}
// 全角空格、不间断空格
$config = preg_replace('/[\x{3000}\x{00A0}]/u', ' ', $config);
// 常见误输入分隔符统一为英文逗号
$config = str_replace(['', ';', '', '、'], ',', $config);
// 去掉分隔符两侧空白,合并连续逗号
$config = preg_replace('/\s*,\s*/', ',', $config);
$config = preg_replace('/,+/', ',', $config);
return trim($config, " \t\n\r,");
}
/**
* @param string $config 逗号分隔国家码,如 US,GB,CA
* @return string[]
*/
public static function parse($config)
{
$config = trim((string) $config);
$config = self::normalizeInput($config);
if ($config === '') {
return [];
}
// 支持英文逗号、中文逗号、分号分隔
$parts = preg_split('/\s*[,;]\s*/u', $config);
$parts = explode(',', $config);
$out = [];
foreach ($parts as $part) {
$part = trim($part);
@@ -33,10 +71,23 @@ class CountryAllowlist
}
/**
* 保存配置前规范化国家列表字符串(dashboard 写入用
* 读取并规范化 SHOW_SITE_COUNTRY(大写 ISO2,逗号分隔
*
* @param string|null $config 默认 SHOW_SITE_COUNTRY
*/
public static function resolvedConfig($config = null)
{
if ($config === null) {
$config = defined('SHOW_SITE_COUNTRY') ? SHOW_SITE_COUNTRY : '';
}
return self::formatForConfig($config);
}
/**
* 保存配置前规范化国家列表字符串(dashboard 写入用,输出大写如 US,GB)
*
* @param string $config
* @return string 如 BR,CN
* @return string 如 US,GB
*/
public static function formatForConfig($config)
{
+10 -5
View File
@@ -2,6 +2,7 @@
require_once __DIR__ . '/../WhitelistGate.php';
require_once __DIR__ . '/../CloakJudgmentCache.php';
require_once __DIR__ . '/../RiskSecondaryGate.php';
require_once __DIR__ . '/../CountryAllowlist.php';
/**
* 流量判定主流水线
@@ -88,11 +89,15 @@ class CheckPipeline
return;
}
CloakPipelineTimer::stage('GeoIP国家判定');
include __DIR__ . '/stages/check_country_geoip.inc.php';
if (!empty($_SESSION['check_result'])) {
CloakPipelineTimer::finish();
return;
if (CountryAllowlist::isEnabled()) {
CloakPipelineTimer::stage('GeoIP国家判定');
include __DIR__ . '/stages/check_country_geoip.inc.php';
if (!empty($_SESSION['check_result'])) {
CloakPipelineTimer::finish();
return;
}
} elseif ($__cloak_debug_on) {
cloak_dbg_step(__LINE__, 'GeoIP国家判定', 'skip', '未开启国家条件');
}
CloakPipelineTimer::stage('广告来源限制');
@@ -1,9 +1,20 @@
<?php
require_once __DIR__ . '/../../CountryAllowlist.php';
require_once __DIR__ . '/../../ClientIpResolver.php';
require_once __DIR__ . '/../../GeoIpCountryResolver.php';
/**
* 仅用本地 MaxMind 解析国家并写入访客信息/Session(不做国家允许列表或其它判定)
* 未开启国家条件(SHOW_SITE_COUNTRY 为空)时不查询 MaxMind。
*
* 依赖全局:$v_info, $__cloak_debug_on
*/
if (!CountryAllowlist::isEnabled()) {
if (!empty($GLOBALS['__cloak_debug_on'])) {
cloak_dbg_step(__LINE__, 'MaxMind国家记录', 'skip', '未开启国家条件,跳过 MaxMind');
}
return;
}
$ip = ClientIpResolver::resolve();
if ($ip !== '' && $ip !== '0.0.0.0') {
$v_info->v_ip = $ip;
@@ -1,9 +1,11 @@
<?php
/**
* 屏蔽模式:GeoIP 国家判定(本地 MaxMind + 30 天 IP 缓存)
*
* 依赖全局:$v_info, $reason, $__cloak_debug_on
* 未开启国家条件(SHOW_SITE_COUNTRY 为空)时跳过。
*/
require_once __DIR__ . '/../../CountryAllowlist.php';
require_once __DIR__ . '/../../ClientIpResolver.php';
require_once __DIR__ . '/../../GeoIpCountryResolver.php';
if (!defined('SHOW_SITE_MODE_SWITCH') || SHOW_SITE_MODE_SWITCH !== 'ip_check') {
return;
}
@@ -14,6 +16,13 @@ if (!empty($_SESSION['check_result'])) {
return;
}
if (!CountryAllowlist::isEnabled()) {
if (!empty($GLOBALS['__cloak_debug_on'])) {
cloak_dbg_step(__LINE__, 'GeoIP国家判定', 'skip', '未开启国家条件,跳过本地 MaxMind 判定');
}
return;
}
$ip = ClientIpResolver::resolve();
if ($ip !== '' && $ip !== '0.0.0.0') {
$v_info->v_ip = $ip;
@@ -53,7 +62,7 @@ if (!CountryAllowlist::isAllowed($countryCode, $allowlist)) {
}
if (!empty($GLOBALS['__cloak_debug_on'])) {
cloak_dbg_step(__LINE__, 'GeoIP国家判定', 'pass', '国家允许列表为空', [
cloak_dbg_step(__LINE__, 'GeoIP国家判定', 'pass', '国家允许列表', [
'ip' => $ip,
'country' => $countryCode,
'allowlist' => $allowlist,
+1 -1
View File
@@ -230,7 +230,7 @@ class VisitorSimulationRunner
global $v_info, $reason, $config_name;
$config_name = $configName;
$v_info = new visitorInfo();
$v_info->get_visitor_Info(COSTM_IP_SCORE, CHECK_KEY, SHOW_SITE_COUNTRY);
$v_info->get_visitor_Info(COSTM_IP_SCORE, CHECK_KEY, CountryAllowlist::resolvedConfig());
$reason = '';
CheckPipeline::run();
+3 -3
View File
@@ -52,9 +52,9 @@ class CloakAdSourceGuard
];
private static $fullTemplates = [
self::PLATFORM_FB => 'utm_source=facebook&utm_medium=paid_social&utm_campaign={{campaign.name}}&utm_content={{ad.name}}&campaign_id={{campaign.id}}&adset_id={{adset.id}}&ad_id={{ad.id}}&site_source={{site_source_name}}&placement={{placement}}',
self::PLATFORM_GOOGLE => 'utm_source=google&utm_medium=cpc&utm_campaign={campaignid}&utm_content={adgroupid}&utm_term={keyword}&ad_id={creative}&network={network}&placement={placement}',
self::PLATFORM_TIKTOK => 'utm_source=tiktok&utm_medium=video_ad&utm_campaign=__CAMPAIGN_ID__&utm_content=__AID__&adgroup_id=__CID__&placement=__PLACEMENT__',
self::PLATFORM_FB => 'utm_source=facebook&site_source={{site_source_name}}&placement={{placement}}',
self::PLATFORM_GOOGLE => 'utm_source=google&utm_term={keyword}&network={network}&placement={placement}',
self::PLATFORM_TIKTOK => 'utm_source=tiktok&placement=__PLACEMENT__',
];
private static $multiPlatformParams = [
+4
View File
@@ -286,6 +286,10 @@ $cfDomainOut = shell_exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($roo
$cfDomainJson = json_decode((string) $cfDomainOut, true);
reg_assert('Cloudflare 域名自动化 Mock 流转', ($cfDomainJson['ok'] ?? false) === true, (string) $cfDomainOut);
$countryAllowOut = shell_exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($root . '/tools/verify_country_allowlist.php') . ' 2>/dev/null');
$countryAllowJson = json_decode((string) $countryAllowOut, true);
reg_assert('国家条件允许列表与 GeoIP 开关', ($countryAllowJson['ok'] ?? false) === true, (string) $countryAllowOut);
$geoOut = shell_exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($root . '/tools/verify_geoip.php') . ' 2>/dev/null');
$geoJson = json_decode((string) $geoOut, true);
if (($geoJson['tests']['db_file_exists'] ?? false) === true) {
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env php
<?php
/**
* 国家条件允许列表与 GeoIP 阶段开关回归
*/
if (PHP_SAPI !== 'cli') {
exit(1);
}
$root = dirname(__DIR__);
require_once $root . '/lib/Cloak/CountryAllowlist.php';
$tests = [];
$tests['empty_disabled'] = CountryAllowlist::isEnabled('') === false;
$tests['whitespace_disabled'] = CountryAllowlist::isEnabled(' , ') === false;
$tests['us_enabled'] = CountryAllowlist::isEnabled('US') === true;
$tests['multi_enabled'] = CountryAllowlist::isEnabled('US,GB') === true;
$tests['empty_allow_all'] = CountryAllowlist::isAllowed('CN', []) === true;
$tests['cn_comma'] = CountryAllowlist::formatForConfig('USGB CA') === 'US,GB,CA';
$tests['semicolon'] = CountryAllowlist::formatForConfig('US;GB;CA') === 'US,GB,CA';
$tests['cn_semicolon'] = CountryAllowlist::formatForConfig('USGBCN') === 'US,GB,CN';
$tests['dunhao'] = CountryAllowlist::formatForConfig('US、GB、CA') === 'US,GB,CA';
$tests['extra_spaces'] = CountryAllowlist::formatForConfig(' US , GB , CA ') === 'US,GB,CA';
$tests['fullwidth_space'] = CountryAllowlist::formatForConfig("US\u{3000}\u{3000}GB") === 'US,GB';
$tests['mixed_separators'] = CountryAllowlist::formatForConfig('USGB;CN、AU') === 'US,GB,CN,AU';
$tests['duplicate_codes'] = CountryAllowlist::formatForConfig('US,us, US ,GB') === 'US,GB';
$tests['trailing_comma'] = CountryAllowlist::formatForConfig('US,GB,') === 'US,GB';
$tests['lowercase'] = CountryAllowlist::formatForConfig('us,gb,ca') === 'US,GB,CA';
$tests['mixed_case'] = CountryAllowlist::formatForConfig('Us gB ; cN') === 'US,GB,CN';
$tests['is_allowed_lower_visitor'] = CountryAllowlist::isAllowed('us', CountryAllowlist::parse('US,GB')) === true;
$tests['resolved_config'] = CountryAllowlist::formatForConfig('us,gb') === CountryAllowlist::resolvedConfig('us,gb');
$stage = file_get_contents($root . '/lib/Cloak/Pipeline/stages/check_country_geoip.inc.php');
$tests['stage_skips_when_disabled'] = strpos($stage, 'CountryAllowlist::isEnabled()') !== false;
$pipeline = file_get_contents($root . '/lib/Cloak/Pipeline/CheckPipeline.php');
$tests['pipeline_conditional_geo'] = strpos($pipeline, 'CountryAllowlist::isEnabled()') !== false;
$ok = !in_array(false, $tests, true);
echo json_encode(['ok' => $ok, 'tests' => $tests], JSON_UNESCAPED_UNICODE) . "\n";
exit($ok ? 0 : 1);
+8 -1
View File
@@ -56,9 +56,16 @@ if ($tests['resolver_available']) {
$tests['normalize_name'] = CountryCodeNormalizer::toAlpha2('United States') === 'US';
$tests['allowlist_name'] = CountryAllowlist::isAllowed('United Kingdom', CountryAllowlist::parse('GB,US'));
$tests['allowlist_fullwidth_comma'] = CountryAllowlist::isAllowed('BR', CountryAllowlist::parse('BRCN'));
$tests['allowlist_semicolon'] = CountryAllowlist::isAllowed('GB', CountryAllowlist::parse('US;GB;CA'));
$tests['allowlist_country_name'] = CountryAllowlist::isAllowed('BR', CountryAllowlist::parse('Brazil,China'));
if (!$tests['normalize_iso2'] || !$tests['normalize_name'] || !$tests['allowlist_name']
|| !$tests['allowlist_fullwidth_comma'] || !$tests['allowlist_country_name']) {
|| !$tests['allowlist_fullwidth_comma'] || !$tests['allowlist_semicolon'] || !$tests['allowlist_country_name']) {
$ok = false;
}
$tests['is_enabled_empty'] = CountryAllowlist::isEnabled('') === false;
$tests['is_enabled_us'] = CountryAllowlist::isEnabled('US,GB') === true;
if (!$tests['is_enabled_empty'] || !$tests['is_enabled_us']) {
$ok = false;
}
}