Compare commits

...
22 changed files with 419 additions and 111 deletions

No files matched your search

+3 -1
View File
@@ -58,7 +58,7 @@ ## 独立文章发布 API
2026-11-02本地将“综合教程”改为“进阶教程”,地址仍 `/advanced`,并统一桌面/手机顶级栏目图标对齐,尚未发布。当前名称、命令和验收见[栏目导航维护](docs/maintenance/NAVIGATION.md)。
2026-11-03本地新增“暂避风头模式”:暂停免费节点发布更新并隐藏机场广告/推荐,保留旧资源和其他文章。命令 `php artisan site:quiet on|off|status`,当前本地关闭、未发布;唯一实现、权限和验收见[暂避风头模式](docs/maintenance/QUIET_MODE.md)。
2026-11-07起“暂避风头模式”只隐藏机场广告和推荐,免费节点照常发布。命令 `php artisan site:quiet on|off|status`,操作、状态文件和回退见[暂避风头模式](docs/maintenance/QUIET_MODE.md)。
## SEO统一合同(2026-10-31)
@@ -73,3 +73,5 @@ ## SEO统一合同(2026-10-31)
2026-11-03用户授权六项待发布改动及关联文章/图片全部上线,并明确开启暂避风头模式:正式cfn已完成Git发布、四篇文章API及四图交付、进阶教程改名和四篇置顶;生产模式开启,本地仍关闭。414项服务器检查和31个下载HEAD通过。此状态替代上文相应“仅本地/未发布”,但不恢复已撤下news;当前Git、回执、权限、验收和回退唯一见[六项发布记录](docs/maintenance/SIX_RELEASE_2026-11-03.md)。已完成服务器侧验收,未做线上页面验收。
2026-11-09公共域名自动选址与站内点击出口按[广告入口自动同步](docs/maintenance/DOMAINHUB_PUBLIC.md)维护;原投放开关保持最终决定权。
+2 -2
View File
@@ -9,7 +9,7 @@
final class QuietMode extends Command
{
protected $signature = 'site:quiet {state=status : on, off, or status}';
protected $description = 'Pause free-node publishing and hide airport promotions without deleting data';
protected $description = 'Hide airport ads and recommendations';
public function handle(): int
{
@@ -36,7 +36,7 @@ public function handle(): int
} finally { if (is_file($temporary)) unlink($temporary); }
\Spatie\ResponseCache\Facades\ResponseCache::clear();
}
$this->info('暂避风头模式:'.(SiteMode::quiet() ? '开启(节点更新暂停,机场广告隐藏)' : '关闭(正常模式)'));
$this->info('暂避风头模式:'.(SiteMode::quiet() ? '开启(机场广告及推荐隐藏,节点照常发布)' : '关闭(正常模式)'));
return self::SUCCESS;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Console\Commands;
use App\Services\{AirportDomains,SiteMode};
use Illuminate\Console\Command;
final class VerifyDomainHub extends Command
{
protected $signature='domainhub:verify';
protected $description='Verify that the application reads the current public domain snapshot';
public function handle(): int
{
$s=AirportDomains::snapshot();
if (! $s || (int)getenv('DOMAINHUB_EXPECT_VERSION') !== ($s['manifest']['version']??null)) return self::FAILURE;
$this->line(json_encode(['version'=>$s['manifest']['version'],'enabled'=>(bool)config('domainhub.enabled'),'quiet'=>SiteMode::quiet(),'banners'=>collect(config('advertising'))->map(fn($p)=>(bool)$p['enabled'])->all(),'recommendations'=>(bool)config('airport_recommendations.enabled')],JSON_THROW_ON_ERROR));
return self::SUCCESS;
}
}
@@ -48,7 +48,6 @@ public function receive(Request $oRequest)
$aOptTag = explode(",", $sOptTag);
$oCategory = Categories::where("sName", $sOptCategoryName)->first();
\App\Services\SiteMode::assertUpdatesAllowed($oCategory?->sSlug);
if (!$oCategory) {
$sMsg = "不存在的文章分类:{$sOptCategoryName}";
@@ -64,7 +63,6 @@ public function receive(Request $oRequest)
];
$oArticle = Articles::where("sSlug", $sSlug)->first();
if ($oArticle) \App\Services\SiteMode::assertUpdatesAllowed($oArticle->oCategory?->sSlug);
if ($oArticle && \Illuminate\Support\Facades\DB::table('editorial_documents')->where('article_id',$oArticle->id)->exists()) {
abort(409, 'This article is managed by the editorial API');
@@ -188,7 +186,6 @@ public function receiveShadowrocketids(Request $oRequest)
public function receiveFreenode(Request $oRequest)
{
\App\Services\SiteMode::assertUpdatesAllowed('freenode');
$sObjName = "nodehub:article_receive_freenodeV2";
$oFlow = Flow::make($sObjName);
@@ -268,7 +265,6 @@ public function receiveFreenode(Request $oRequest)
public function receiveFreenode_laji(Request $oRequest)
{
\App\Services\SiteMode::assertUpdatesAllowed('freenode');
$sObjName = "nodehub:article_receive_freenode";
$oFlow = Flow::make($sObjName);
-1
View File
@@ -109,7 +109,6 @@ public function scopePublicVisible($query)
protected static function booted()
{
static::saving(function ($article) {
\App\Services\SiteMode::guardArticle($article);
// Historical test fixtures and migration tooling may use the pre-SEO schema.
if (!\Illuminate\Support\Facades\Schema::hasColumn('articles', 'sContentUpdatedAt')) return;
if (!$article->exists || $article->isDirty(['sTitle','sTitleSub','sContent','sThumb','iCategoryId','iStatus','bPageThumb'])) {
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Services;
final class AirportDomains
{
public static function snapshot(): ?array
{
$path=config('domainhub.state_path');
if (! $path || ! is_file($path)) return null;
try {$s=json_decode(file_get_contents($path),true,32,JSON_THROW_ON_ERROR);} catch (\Throwable) {return null;}
$m=$s['manifest']??[];
$watermark=json_decode(@file_get_contents($path.'.watermark') ?: '{}',true);
if (($watermark['version']??null)!==($m['version']??null) || ! is_string($s['digest']??null) || ! hash_equals($watermark['digest']??'', $s['digest'])) return null;
if (($m['schema']??null)!=='domainhub.public.v1' || ($m['project']??null)!==config('domainhub.project') || ($m['environment']??null)!==config('domainhub.environment') || ($m['instance']??null)!==config('domainhub.instance')) return null;
if (! is_int($s['checked_at']??null) || $s['checked_at']>time()+120 || time()-$s['checked_at']>config('domainhub.max_age')) return null;
return $s;
}
public static function target(string $provider): ?string
{
if (! array_key_exists($provider,config('airport_recommendations.providers',[]))) return null;
$s=self::snapshot(); $entry=$s['manifest']['providers'][$provider]['selected']??null;
if (! $entry || ($entry['eligible']??false)!==true || ($entry['access']??null)!=='available' || ($entry['reason']??null)!==null) return null;
if (! empty($entry['valid_until']) && strtotime($entry['valid_until'].' UTC')<=time()) return null;
$url=$entry['url']??''; $u=parse_url($url);
if (! filter_var($url,FILTER_VALIDATE_URL) || ($u['scheme']??null)!=='https' || empty($u['host']) || isset($u['user']) || isset($u['pass']) || isset($u['query']) || isset($u['fragment']) || (isset($u['port']) && $u['port']!==443)) return null;
return $url;
}
public static function link(string $provider, string $placement): ?string
{
if (SiteMode::quiet()) return null;
$enabled=$placement==='banner' ? config('advertising.'.$provider.'.enabled',false) : (config('airport_recommendations.enabled',false) && config('airport_recommendations.providers.'.$provider.'.enabled',false));
if (! $enabled) return null;
if (! config('domainhub.enabled')) return $placement==='banner' ? config('advertising.'.$provider.'.url') : config('airport_recommendations.providers.'.$provider.'.url');
return self::target($provider) ? '/go/airport/'.$provider.'/'.$placement : null;
}
public static function redirect(string $provider, string $placement)
{
$headers=['Cache-Control'=>'no-store, private','X-Robots-Tag'=>'noindex, nofollow','Referrer-Policy'=>'no-referrer'];
$target=config('domainhub.enabled') && self::link($provider,$placement) ? self::target($provider) : null;
return $target ? response('',302,[...$headers,'Location'=>$target]) : response('该入口暂不可用,请返回查看其他内容。',410,$headers);
}
}
+7 -5
View File
@@ -11,9 +11,11 @@ final class ArticleRecommendations
public static function providers(): array
{
if (SiteMode::quiet() || ! config('airport_recommendations.enabled')) return [];
$providers = array_filter(config('airport_recommendations.providers', []), fn ($p) =>
($p['enabled'] ?? false) && filter_var($p['url'] ?? '', FILTER_VALIDATE_URL)
&& in_array(parse_url($p['url'], PHP_URL_SCHEME), ['https', 'http'], true));
$providers = [];
foreach (config('airport_recommendations.providers', []) as $key => $provider) {
$url = AirportDomains::link($key, 'recommendation');
if ($url) $providers[$key] = [...$provider, 'url' => $url];
}
uasort($providers, fn ($a, $b) => ($a['order'] ?? 0) <=> ($b['order'] ?? 0));
return $providers;
}
@@ -28,7 +30,7 @@ public static function prepare(Articles $article): array
|| $category?->oParent?->sSlug === 'client';
$quiet = SiteMode::quiet();
$enabled = $scope && self::providers() !== [];
if (! $enabled && ! $quiet) return ['body' => $html, 'enabled' => false, 'inline' => false];
if (! $scope && ! $quiet) return ['body' => $html, 'enabled' => false, 'inline' => false];
$inline = false;
if (in_array($slug, ['freenode', 'shadowrocketids'], true)) {
@@ -49,7 +51,7 @@ public static function prepare(Articles $article): array
}
}
}
if ($quiet) {
if ($quiet || ! $enabled) {
$html = str_replace(self::SLOT, '', $html);
$html = preg_replace('~<p\b[^>]*class=["\'][^"\']*airport-recommendation-jump[^"\']*["\'][^>]*>.*?</p>~si', '', $html);
return ['body' => $html, 'enabled' => false, 'inline' => false];
+1 -26
View File
@@ -2,10 +2,6 @@
namespace App\Services;
use App\Models\Articles;
use App\Models\Categories;
use Illuminate\Http\Exceptions\HttpResponseException;
final class SiteMode
{
public static function quiet(): bool
@@ -13,28 +9,7 @@ public static function quiet(): bool
$path = config('site_mode.state_path');
if (! $path || ! is_file($path)) return (bool) config('site_mode.quiet', false);
$state = json_decode((string) file_get_contents($path), true);
// An unreadable/invalid operational flag must not silently resume publishing.
// An unreadable/invalid operational flag keeps promotions hidden.
return ! is_array($state) || ! is_bool($state['quiet'] ?? null) || $state['quiet'];
}
public static function assertUpdatesAllowed(?string $type): void
{
if ($type !== 'freenode' || ! self::quiet()) return;
throw new HttpResponseException(response()->json([
'isDone' => false, 'status' => 'paused', 'code' => 'FREE_NODE_UPDATES_PAUSED',
'message' => 'Free node updates are temporarily paused; existing publications are retained.',
], 503, ['Retry-After' => '3600']));
}
public static function guardArticle(Articles $article): void
{
if (! self::quiet()) return;
$fields = ['sSlug','iCategoryId','sTitle','sTitleSub','sContent','sThumb',
'iStatus','created_at','sDisplayPublishedAt','sResourceStatus','iResourceCount'];
if ($article->exists && ! $article->isDirty($fields)) return;
$ids = array_filter([$article->iCategoryId, $article->getRawOriginal('iCategoryId')]);
if ($ids && Categories::whereIn('id', $ids)->where('sSlug', 'freenode')->exists()) {
self::assertUpdatesAllowed('freenode');
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
return [
'enabled' => env('DOMAINHUB_PUBLIC_ENABLED', false),
'state_path' => env('DOMAINHUB_PUBLIC_STATE', storage_path('app/private/domainhub-public/state.json')),
'project' => 'fna_v3',
'environment' => env('APP_ENV', 'production') === 'production' ? 'production' : 'local',
'instance' => 'advertising',
'max_age' => 86400,
];
+2
View File
@@ -154,3 +154,5 @@ ## 本任务高度调整正式状态(2026-10-31)
2026-10-31用户再次指定品牌大小写为 `HardNerd`(H/N大写)。内置image_gen只替换字标大小写,保持上一版品牌/标语比例、间距、图标与背景。当前素材 `public/images/ads/hn-ad-compact-HardNerd-20261031.png`(2020×778),提示词 `output/compact-ads-20261031/hn-hardnerd-case-prompt.txt`;本地随机组件引用及alt同步,旧图保留,未发布。
2026-11-03本地新增统一[暂避风头模式](QUIET_MODE.md),可临时隐藏本站机场广告及推荐,单独广告开关和原数据保留。验收后本地恢复关闭,未部署;操作账号、状态优先级和发布范围以该文为准。
2026-11-09公共域名自动选址与站内点击出口按[广告入口自动同步](DOMAINHUB_PUBLIC.md)维护;原投放开关保持最终决定权。
@@ -39,3 +39,5 @@ ## Hardnerd优惠补齐(2026-10-31)
用户确认hardnerd同样使用`clashfreenode.com`享9折。仅更新共享推荐配置的HN coupon/discount及对应渲染断言,所有引用页随配置/响应缓存刷新生效,无需逐篇编辑正文。不创建或修改HN服务端优惠码,不执行下单或优惠核销。Git提交、正式HEAD、恢复点和服务器验收回执见`output/hn-coupon-20261031/`。
2026-11-03本地新增统一[暂避风头模式](QUIET_MODE.md),可临时隐藏本站机场广告及推荐,单独广告开关和原数据保留。验收后本地恢复关闭,未部署;操作账号、状态优先级和发布范围以该文为准。
2026-11-09公共域名自动选址与站内点击出口按[广告入口自动同步](DOMAINHUB_PUBLIC.md)维护;原投放开关保持最终决定权。
+21
View File
@@ -0,0 +1,21 @@
# 广告入口自动同步
2026-11-09用户授权三端对齐及任何聊天的统一入口。权威合同为[DomainHub公共域名](/Users/hellcat/Documents/GemCodes/atom/codex/output/docs/domainhub-public.md)。FNA只消费 fuc/dpl/hn 公共用途,绝不根据名称猜后台、订阅或支付地址。
`AirportDomains`统一供横幅、推荐表、教程末尾和旧推广块使用;无可选项时隐藏该家,全部为空也移除已识别旧推广,正文数据库/订阅载荷不写入。价格、优惠、素材和布局不改。`/go/airport/{fuc|dpl|hn}/{banner|recommendation}`在点击时核对快照、租约、水位、quiet及对应投放开关:可用302/no-store,否则410,不接收任意目标URL。旧页面仍服从最新状态。响应缓存既有配置不启用缓存;新出口no-store/noindex。
`DOMAINHUB_PUBLIC_ENABLED`仅切换地址来源,不打开广告。私有state/config在`storage/app/private/domainhub-public/`,密钥只由同步进程持有。config保存Hub bootstrap、专用调用方、状态路径和`php artisan domainhub:verify`运行回读命令。24小时后无成功同步则不使用;独立watermark不随代码回退。生产每4小时版本补拉,每日上海08:10完整拉取,各自systemd由FNA服务器nginx用户执行。收到撤销先原子应用,运行读取成功才ACK。
FNA是广告无候选Critical/base的唯一汇报方,按每个服务商去重;恢复notification/base。私有`.alerts`保存事件/稳定正文/幂等键/回执/重试,`.runtime`保留模式上下文。quiet或手动关广告不取消域名监测,也不因恢复打开广告。只读异常、签名失败和重试均不输出秘密;uncertain停止另发,需核实。
本地测试:空池、旧推广、过期、quiet、各投放开关、旧页面点击撤销、单调水位。共享consumer测试在ATOM覆盖签名/环境/版本、ACK顺序、重试与去重。发布时先关闭新来源、备份并拉取有效快照/核对解析结果,再开启新来源;不得在无快照时静默退回硬编码地址。回退保留禁选快照和水位;仅回退视图时保留统一解析器。实际Git/定时器/回执状态见下方回执。
## 2026-11-09已发布
生产Git:`8142e5e23e14464f5d9cde49d65d0a5dc70cd4a2`;恢复点VPS-003:`/var/lib/fna-deploy/domainhub-public-20261109/backup`。原版本`a365cde888cb3a722489938c81b287b22a63dd3e`。部署保留生成标签云的线上修改、data.ms和编辑图片;没有覆盖其他任务。生产原quiet=false、三个横幅开关false、推荐表true均逐项核对保持。配置缓存通过单次新PHP进程生成,规避旧StatOrderLikes文件名/类名不一致引起的config:cache第二次启动冲突,没有修改该遗留命令。
DomainHub client3,production/advertising,当前版本34/applied;FUC→fu-nav3.com,DPL→dp-link.net,HN→hardnerd.net。FNA两只timer已active:每4小时版本同步、上海08:10完整拉取。真实三个推荐出口302/no-store和三个关闭横幅出口410/no-store通过;资源入口规范跳转到首页后正文三家均使用站内固定出口。
TeleHub client19仅critical/notification→base;全部服务商有候选,当前无故障告警,不制造测试事故。13项PHP测试90断言及共享消费者6项测试通过;原有弃用提示不属于本次变更。已完成服务器侧验收,未做线上页面验收。当前文档及状态文件是后续维护入口,不把原设计的“待实施”当作现状。
2026-11-09用户进一步指定版本检查改为每4小时;开机90秒检查、每天北京时间08:10完整同步和统一命令变更后立即同步保持。仅从对应Git提交安装同步timer,应用代码版本沿用上述功能版本;备份及源提交回执在同服务器`/var/lib/fna-deploy/domainhub-public-20261109/interval-4h/`。回退只恢复该timer后daemon-reload并重启timer,不重启业务进程。
+9 -31
View File
@@ -1,10 +1,10 @@
# 暂避风头模式
2026-11-03按用户要求新增统一开关:免费节点暂停更新,机场广告暂时下掉。已Git推送并部署正式cfn,按用户明确要求在生产开启;本地仍关闭。当前发布回执、验收和恢复点见[六项发布记录](SIX_RELEASE_2026-11-03.md)。以下本地测试记录保留当时范围。
2026-11-07起,开启暂避风头模式只隐藏机场广告和推荐。免费节点的新发和覆盖更新沿正常接收流程执行,仍按原有规则校验节点结果。2026-11-03旧版行为及原发布记录见[六项发布记录](SIX_RELEASE_2026-11-03.md)。
## 操作
在本站项目目录运行:
在本站项目目录,以 PHP 运行账号(cfn 为 nginx)执行:
```sh
php artisan site:quiet on
@@ -12,36 +12,14 @@ ## 操作
php artisan site:quiet status
```
- on:阻止免费节点新发布和覆盖更新;隐藏机场随机横幅、推荐表格、已知旧福云推广段与自动推荐跳转。
- off:恢复正常接收与原广告配置,各服务商单独开关/链接/价格/优惠码保持原值。
- status:只读查询。没有给公众网页增加操作入口或状态横幅。
- `on` 隐藏机场横幅、推荐表格、可识别的旧福云推广段和推荐跳转。
- `off` 恢复各服务商的原广告与推荐配置。
- `status` 查询当前状态。
初始无运行状态文件时按 `SITE_QUIET_MODE` 配置,默认false。运行命令后以 `storage/app/private/site-mode.json` 内的布尔值为优先,包括false;不必重启PHP或重建配置缓存。CLI与网页使用同一实例目录,不共享其他实例状态。环境变量只作为不存在文件时的缺省值,不覆盖已有运行选择。
初始按 `SITE_QUIET_MODE` 配置(默认关闭)。运行命令后优先读取实例私有的 `storage/app/private/site-mode.json`,开启和关闭均原子保存为 0600 文件,并清理响应缓存。状态文件损坏或不可读时,广告继续隐藏。发布保留实例现有的状态文件及所有者。
状态文件原子替换、0600,私有目录不存在时0700创建,已确认Git忽略。**发布后须以PHP运行账号执行开关命令**,先核实该账号(已有cfn操作常用nginx),不要用root生成网页进程无法读取的0600文件。状态文件损坏/不可读取时保持暂停与隐藏,不能静默恢复;修复同一文件及所有者后运行off或on并分别核对CLI和页面。
## 验收与回退
开启/关闭会清理响应缓存;既有HTML响应缓存合同本已关闭。切换后新请求生效,已打开的旧页面需刷新。开关保存在项目运行目录,发布不能打包覆盖/删除它。
`QuietModeTest` 验证状态切换、广告和推荐隐藏、节点接收进入正常校验,以及开启状态下节点新建和更新成功。
## 范围与实现
- `app/Services/SiteMode.php` 读取开关,暂停返回HTTP503,JSON `isDone=false / status=paused / code=FREE_NODE_UPDATES_PAUSED`,带 `Retry-After: 3600`。不上报发布成功,不消耗正常发布回执;恢复后由正常上游重试/后续发布执行,不自动重放或补造历史文章。
- 两个免费节点接收方法在解析/Flow/配图调用之前阻断;通用接收在目标分类或原文章为freenode时阻断,不能通过换分类绕过。没有改上游任务/服务或服务器调度。
- 文章Eloquent保存事件补充检查:涉及节点正文、标题、图片、分类、发布时间、资源状态等发布字段时拒绝写入;同样保留旧数据。点赞、浏览等指标允许正常保存。直接绕过模型的SQL/人工运维不属于应用发布开关的保护范围。
- 仅暂停freenode,原文章和订阅仍可访问;小火箭ID、教程、资讯、资源列表和站点导航不停止。
- 随机广告组件及保留的三个旧广告组件均检查开关,关闭时不输出广告模板、图片或noscript广告。
- 推荐模块providers为空,隐藏共用推荐并清理匹配的已知旧推广及自动跳转。只处理明确的旧推广结构,不猜测删除普通正文,账号/订阅复制值与正文数据库不变。
- 该模式不删除数据、不撤下已发布资源、不切换现有SEO规则、域名、证书、图片池、上游服务器或其他项目。
## 验收
- 专项 `QuietModeTest`:5项/51断言通过,覆盖命令双向切换、状态持久化/权限、异常状态、专用及通用入口阻断、换分类绕过、模型新建/更新保护、真实点赞字段保存、其他类型放行、广告/旧推广隐藏、复制值及原文保护、恢复。
- 正常回归:QuietMode、ArticleRecommendations、SEO合同及苹果ID解析共32项/331断言通过;之后仅补充旧组件与真实点赞保存断言,再跑专项5项/51断言通过。测试基类隔离运行站点的开关,避免测试误继承本地暂时启用的状态;初轮未隔离的失败已修正。
- 本地IAB开启实测:首页3个复制按钮保留,随机广告0、推荐表格0、旧推广0;教程正文可读,广告0、推荐0、自动推荐跳转0。截图 `output/quiet-mode-20261103/quiet-on.png`。
- 关闭后同一首页恢复随机广告1、推荐模块1,3个订阅按钮保留。CLI回读明确关闭。未进行实际账号登录、上游真实发稿或线上访问。
- PHP语法与本次diff检查通过,未进行生产构建。
## 发布与回退
本批已按用户明确授权完成Git发布,生产开启;后续变更仍按任务授权执行。相关文件包括SiteMode服务、QuietMode命令、配置、接收器入口、模型保存事件、推荐展示服务、四个广告组件、环境模板与测试/维护入口;不能漏发模型或展示服务。默认缺省关闭,不应随代码发布自动切换生产模式。
回退前关闭模式并核对正常状态,再增量撤销本批调用;不得整文件还原覆盖并行SEO、文章渲染或其他修改。运行状态文件须单独保留/按明确运维操作处理,不以Git回退等同模式切换。
回退到 2026-11-03 旧版且模式开启时,节点发布会再次暂停。回退前按当前生产目标核对模式与节点发布行为,使用 Git 恢复点并保留运行状态文件。
@@ -3,8 +3,8 @@
['key' => 'dpl', 'file' => 'dpl-ad-compact-wordmark-20261031.png', 'width' => 2169, 'height' => 725, 'alt' => 'DP-LINK.NET:畅连全球网络。日常访问、远程办公、在线娱乐,查看套餐。'],
['key' => 'hn', 'file' => 'hn-ad-compact-HardNerd-20261031.png', 'width' => 2020, 'height' => 778, 'alt' => 'HardNerd:硬核架构,品质专线,全球网络畅通无阻。'],
['key' => 'fuc', 'file' => 'fuc-ad-compact-five-years-20261031.png', 'width' => 2141, 'height' => 734, 'alt' => '福云:全球网络加速。五年稳定运营。开始使用。'],
])->filter(fn ($ad) => ! \App\Services\SiteMode::quiet() && config('advertising.'.$ad['key'].'.enabled')
&& config('advertising.'.$ad['key'].'.url')
])->map(fn ($ad) => [...$ad, 'url' => \App\Services\AirportDomains::link($ad['key'], 'banner')])->filter(fn ($ad) => ! \App\Services\SiteMode::quiet() && config('advertising.'.$ad['key'].'.enabled')
&& $ad['url']
&& is_file(public_path('images/ads/'.$ad['file'])))->values();
@endphp
@if ($adChoices->isNotEmpty())
@@ -16,7 +16,7 @@
<aside class="random-article-ad" data-random-article-ad aria-label="网络服务广告" hidden>
@foreach ($adChoices as $ad)
<template data-ad-choice="{{ $ad['key'] }}">
<a href="{{ config('advertising.'.$ad['key'].'.url') }}" target="_blank" rel="sponsored noopener noreferrer" aria-label="广告:{{ $ad['alt'] }}(新窗口打开)">
<a href="{{ $ad['url'] }}" target="_blank" rel="sponsored noopener noreferrer" aria-label="广告:{{ $ad['alt'] }}(新窗口打开)">
<span class="random-article-ad__disclosure" aria-hidden="true">广告</span>
<img src="/images/ads/{{ $ad['file'] }}?v={{ filemtime(public_path('images/ads/'.$ad['file'])) }}" alt="{{ $ad['alt'] }}" width="{{ $ad['width'] }}" height="{{ $ad['height'] }}" decoding="async">
</a>
@@ -26,7 +26,7 @@
<noscript>
@php($ad = $adChoices->first())
<aside class="random-article-ad" aria-label="网络服务广告">
<a href="{{ config('advertising.'.$ad['key'].'.url') }}" target="_blank" rel="sponsored noopener noreferrer">
<a href="{{ $ad['url'] }}" target="_blank" rel="sponsored noopener noreferrer">
<span class="random-article-ad__disclosure" aria-hidden="true">广告</span>
<img src="/images/ads/{{ $ad['file'] }}?v={{ filemtime(public_path('images/ads/'.$ad['file'])) }}" alt="{{ $ad['alt'] }}" width="{{ $ad['width'] }}" height="{{ $ad['height'] }}">
</a>
+3
View File
@@ -12,6 +12,9 @@
use App\Http\Controllers\RobotsController;
use App\Http\Controllers\SitemapController;
Route::get('/go/airport/{provider}/{placement}', [\App\Services\AirportDomains::class, 'redirect'])
->where('provider', 'fuc|dpl|hn')->where('placement', 'banner|recommendation');
Route::get('robots.txt', [RobotsController::class, 'index']);
Route::get('sitemap.xml', [SitemapController::class, 'index']);
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace Tests\Feature;
use App\Services\{AirportDomains,ArticleRecommendations};
use App\Models\{Articles,Categories};
use Tests\TestCase;
final class AirportDomainsTest extends TestCase
{
private string $path;
protected function setUp(): void { parent::setUp();$this->path=tempnam(sys_get_temp_dir(),'domainhub-test-');config(['app.key'=>'base64:'.base64_encode(str_repeat('t',32)),'domainhub.enabled'=>true,'domainhub.state_path'=>$this->path,'domainhub.environment'=>'production','site_mode.state_path'=>null,'site_mode.quiet'=>false,'advertising.fuc.enabled'=>true]);$this->snapshot(); }
protected function tearDown(): void { @unlink($this->path);@unlink($this->path.'.watermark');parent::tearDown(); }
private function snapshot(?array $selected=['url'=>'https://fu-nav3.com/','eligible'=>true,'access'=>'available','reason'=>null],int $age=0): void
{
file_put_contents($this->path,json_encode(['digest'=>str_repeat('a',64),'checked_at'=>time()-$age,'manifest'=>['schema'=>'domainhub.public.v1','project'=>'fna_v3','environment'=>'production','instance'=>'advertising','version'=>8,'providers'=>['fuc'=>['selected'=>$selected],'hn'=>['selected'=>null],'dpl'=>['selected'=>null]]]]));
file_put_contents($this->path.'.watermark',json_encode(['version'=>8,'digest'=>str_repeat('a',64)]));
}
public function test_single_resolver_and_click_revocation_without_render_or_remote_requests(): void
{
$this->assertSame('/go/airport/fuc/recommendation',ArticleRecommendations::providers()['fuc']['url']);
$this->assertSame('/go/airport/fuc/banner',AirportDomains::link('fuc','banner'));
$this->get('/go/airport/fuc/recommendation')->assertStatus(302)->assertHeader('Location','https://fu-nav3.com/')->assertHeader('X-Robots-Tag','noindex, nofollow');
$this->snapshot(null);
$this->assertSame([],ArticleRecommendations::providers());
$this->get('/go/airport/fuc/recommendation')->assertStatus(410)->assertHeader('Cache-Control','no-store, private');
}
public function test_expiry_quiet_and_independent_switches(): void
{
config(['advertising.fuc.enabled'=>false]);$this->assertNull(AirportDomains::link('fuc','banner'));
$this->assertNotNull(AirportDomains::link('fuc','recommendation'));
config(['site_mode.quiet'=>true]);$this->get('/go/airport/fuc/recommendation')->assertStatus(410);
config(['site_mode.quiet'=>false]);$this->snapshot(age:86401);$this->assertNull(AirportDomains::target('fuc'));
file_put_contents($this->path,'broken');$this->assertNull(AirportDomains::target('fuc'));
}
public function test_empty_pool_strips_legacy_promo_without_touching_subscription_payload(): void
{
$this->snapshot(null);$category=new Categories();$category->setRawAttributes(['sSlug'=>'freenode']);$category->setRelation('oParent',null);
$tail='<h2>免费资源</h2><pre>vmess://keep-exact</pre>';
$a=new Articles();$a->setRelation('oCategory',$category);$html='<h2>机场推荐 - 福云:</h2><p><a href="https://fuuu.cloud">机场官网:福云</a></p>'.$tail;$a->setRawAttributes(['sContent'=>$html]);
$r=ArticleRecommendations::prepare($a);$this->assertFalse($r['enabled']);$this->assertSame($tail,$r['body']);$this->assertSame($html,$a->sContent);
}
}
+17 -37
View File
@@ -8,7 +8,7 @@
use App\Services\ArticleRecommendations;
use App\Services\SiteMode;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Exceptions\HttpResponseException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
@@ -51,16 +51,6 @@ protected function tearDown(): void
parent::tearDown();
}
private function paused(callable $action): void
{
try { $action(); $this->fail('Expected paused response.'); }
catch (HttpResponseException $e) {
$this->assertSame(503, $e->getResponse()->getStatusCode());
$this->assertSame('3600', $e->getResponse()->headers->get('Retry-After'));
$this->assertSame('FREE_NODE_UPDATES_PAUSED', json_decode($e->getResponse()->getContent(), true)['code']);
}
}
public function test_command_switch_is_persistent_reversible_and_private(): void
{
$this->assertFalse(SiteMode::quiet());
@@ -75,7 +65,7 @@ public function test_command_switch_is_persistent_reversible_and_private(): void
$this->assertFalse(SiteMode::quiet());
}
public function test_invalid_state_stays_paused_and_environment_fallback_works(): void
public function test_invalid_state_keeps_ads_hidden_and_environment_fallback_works(): void
{
config(['site_mode.quiet'=>true]); $this->assertTrue(SiteMode::quiet());
config(['site_mode.quiet'=>false]);
@@ -83,38 +73,28 @@ public function test_invalid_state_stays_paused_and_environment_fallback_works()
file_put_contents($this->state, '{"quiet":"false"}'); $this->assertTrue(SiteMode::quiet());
}
public function test_receivers_pause_before_images_flows_and_any_database_write(): void
public function test_free_node_receiver_runs_normal_validation_with_ads_hidden(): void
{
config(['site_mode.quiet'=>true]);
$controller = new ArticlesController();
$this->paused(fn () => $controller->receiveFreenode(new Request()));
$this->paused(fn () => $controller->receiveFreenode_laji(new Request()));
$this->paused(fn () => $controller->receive(new Request(['_raw'=>[
'id'=>8, 'opt'=>json_encode(['sCategoryName'=>'免费节点']),
]])));
// Moving an existing node article to another category must not bypass the pause.
$this->paused(fn () => $controller->receive(new Request(['_raw'=>[
'id'=>7, 'opt'=>json_encode(['sCategoryName'=>'新手教程']),
]])));
$this->assertSame(1, DB::table('articles')->count());
$this->assertSame('original', DB::table('articles')->where('id',7)->value('sContent'));
Http::assertNothingSent();
$this->expectException(HttpException::class);
$this->expectExceptionMessage('Resource update has no usable result');
(new ArticlesController())->receiveFreenode(new Request(['article'=>[
'title'=>'Free nodes', 'title_sub'=>'', 'content'=>'A resource update',
'tags'=>[], 'check_status'=>'failed',
]]));
}
public function test_model_rejects_publication_changes_but_allows_metrics_and_other_types(): void
public function test_free_node_model_can_publish_and_update_with_ads_hidden(): void
{
config(['site_mode.quiet'=>true]);
$existing = Articles::find(7); $existing->sContent = 'replacement';
$this->paused(fn () => $existing->save());
$this->assertSame('original', DB::table('articles')->where('id',7)->value('sContent'));
$existing = Articles::find(7);
$existing->sContent = 'replacement';
$existing->save();
$new = new Articles(['iCategoryId'=>1,'sSlug'=>'fn-new','sContent'=>'new']);
$this->paused(fn () => $new->save());
$metrics = Articles::find(7); $metrics->iLikeCount = 10; $metrics->save();
$this->assertSame(10, DB::table('articles')->where('id',7)->value('iLikeCount'));
foreach ([2,3] as $id) SiteMode::guardArticle(new Articles(['iCategoryId'=>$id,'sContent'=>'unchanged scope']));
SiteMode::assertUpdatesAllowed('shadowrocketids');
$this->assertSame(1, DB::table('articles')->count());
config(['site_mode.quiet'=>false]); SiteMode::assertUpdatesAllowed('freenode');
$new->save();
$this->assertSame('replacement', Articles::find(7)->sContent);
$this->assertSame('new', Articles::where('sSlug', 'fn-new')->firstOrFail()->sContent);
}
public function test_promotions_disappear_without_mutating_original_body_or_copy_payload(): void
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Signed public-domain consumer. Run only on the owning project's server.
Canonical source: ATOM integrations/domainhub/public_client.py; copies are versioned.
"""
import argparse
import fcntl
import hashlib
import hmac
import json
import os
import re
import subprocess
import tempfile
import time
import uuid
from pathlib import Path
from urllib.parse import urlsplit
from urllib.request import Request, HTTPRedirectHandler, build_opener
from urllib.error import HTTPError
MAX_AGE = 86400
TERMINAL = {'sent', 'failed', 'uncertain', 'cancelled', 'rejected'}
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *_a, **_k): return None
def read(path, default=None):
try: return json.loads(Path(path).read_text())
except (OSError, ValueError): return default
def atomic(path, data):
path=Path(path); path.parent.mkdir(parents=True, exist_ok=True)
fd,name=tempfile.mkstemp(prefix='.'+path.name, dir=path.parent)
try:
with os.fdopen(fd,'w') as out:
os.fchmod(out.fileno(),0o640)
json.dump(data,out,ensure_ascii=False,separators=(',',':'))
out.flush(); os.fsync(out.fileno())
os.replace(name,path)
directory=os.open(path.parent,os.O_RDONLY)
try: os.fsync(directory)
finally: os.close(directory)
finally:
if os.path.exists(name): os.unlink(name)
def request(url, key, data=None, extra=None):
headers={'Authorization':'Bearer '+key,'Accept':'application/json',**(extra or {})}
if data is not None: headers['Content-Type']='application/json'
req=Request(url,data=json.dumps(data,ensure_ascii=False,separators=(',',':')).encode() if data is not None else None,headers=headers)
with build_opener(NoRedirect()).open(req,timeout=12) as response:
body=response.read(1048577)
if len(body)>1048576: raise ValueError('response_too_large')
return response.headers,body
def signed(config, path, transport=request, now=None):
headers,body=transport(config['hub_url'].rstrip('/')+'/api/v1/domainhub/public/'+path,config['key'])
stamp=headers.get('X-DomainHub-Timestamp',''); signature=headers.get('X-DomainHub-Signature','')
now=time.time() if now is None else now
if not stamp.isdigit() or abs(now-int(stamp))>120: raise ValueError('invalid_timestamp')
expected=hmac.new(config['key'].encode(),stamp.encode()+b'.'+body,hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected,signature): raise ValueError('invalid_signature')
data=json.loads(body)
if any(data.get(k)!=config[k] for k in ['project','environment','instance']): raise ValueError('wrong_scope')
if type(data.get('version')) is not int or data['version']<1: raise ValueError('invalid_version')
return data,body,headers
def validate_manifest(manifest, config):
if manifest.get('schema')!='domainhub.public.v1' or not isinstance(manifest.get('providers'),dict): raise ValueError('invalid_schema')
if set(manifest['providers'])!=set(config['providers']): raise ValueError('wrong_providers')
for provider in manifest['providers'].values():
entries=provider.get('entries')
if not isinstance(entries,list): raise ValueError('invalid_entries')
codes=set()
for entry in entries:
u=urlsplit(entry.get('url',''))
if u.scheme!='https' or not u.hostname or u.username or u.password or u.query or u.fragment or u.port not in (None,443) or any(c.isspace() for c in entry['url']): raise ValueError('invalid_public_url')
if entry.get('role') not in {'primary','navigation','direct_access'} or type(entry.get('eligible')) is not bool or entry.get('code') in codes: raise ValueError('invalid_entry')
codes.add(entry['code'])
if entry['eligible'] and (entry.get('access')!='available' or entry.get('reason') is not None): raise ValueError('invalid_eligibility')
selected=provider.get('selected')
if selected is not None and (selected not in entries or not selected['eligible']): raise ValueError('invalid_selection')
def current(state, now=None):
now=time.time() if now is None else now
return isinstance(state,dict) and 0<=now-state.get('checked_at',0)<=MAX_AGE
def available(state, provider, now=None):
if not current(state,now): return None
selected=state['manifest']['providers'].get(provider,{}).get('selected')
if not selected or not selected.get('eligible') or selected.get('access')!='available': return None
until=selected.get('valid_until')
if until:
from datetime import datetime, timezone
stamp=datetime.fromisoformat(until).replace(tzinfo=timezone.utc).timestamp()
if stamp <= (time.time() if now is None else now): return None
return selected
def runtime_check(config, version):
result=subprocess.run(config['validate_command'],env={**os.environ,'DOMAINHUB_EXPECT_VERSION':str(version)},capture_output=True,timeout=20)
if result.returncode: raise ValueError('runtime_verification_failed')
return json.loads(result.stdout or b'{}')
def sync(config, force=False, transport=request, verify=runtime_check, now=None):
now=int(time.time() if now is None else now)
path=Path(config['state_path']); state=read(path,{})
watermark=read(str(path)+'.watermark',{'version':0,'digest':''})
meta,_,_=signed(config,'version',transport,now)
if meta.get('schema')!='domainhub.public-version.v1' or not re.fullmatch('[a-f0-9]{64}',meta.get('digest','')): raise ValueError('invalid_version_response')
if meta['version']<watermark['version'] or (meta['version']==watermark['version'] and watermark['digest']!=meta['digest']): raise ValueError('rollback_or_conflict')
changed=state.get('digest')!=meta['digest'] or state.get('manifest',{}).get('version')!=meta['version']
if changed or force:
manifest,body,headers=signed(config,'snapshot',transport,now)
digest=hashlib.sha256(body).hexdigest()
if manifest['version']<meta['version'] or manifest['version']<watermark['version']: raise ValueError('stale_snapshot')
if manifest['version']==meta['version'] and digest!=meta['digest']: raise ValueError('snapshot_digest_mismatch')
validate_manifest(manifest,config)
if manifest['version']==watermark['version'] and digest!=watermark['digest']: raise ValueError('same_version_conflict')
state={'manifest':manifest,'digest':digest,'delivery':int(headers['X-DomainHub-Delivery']),'checked_at':now}
else:
validate_manifest(state['manifest'],config)
state={**state,'checked_at':now,'delivery':meta['delivery']}
atomic(str(path)+'.watermark',{'version':state['manifest']['version'],'digest':state['digest']})
atomic(path,state)
# ACK only after the consuming application's resolver reads the active file.
if config.get('catalog_path'):
provider=state['manifest']['providers'][config['catalog_provider']]
records=[]
candidates=sorted([e for e in provider['entries'] if e['eligible'] and e['role']!='navigation'], key=lambda e:(0 if e['role']=='direct_access' else 1,-e['priority'], -__import__('datetime').datetime.fromisoformat(e['activated_at']).timestamp(),e['code']))
preferred=candidates[0]['code'] if candidates else None
for e in provider['entries']:
item={'domain':e['hostname'],'role':'direct' if e['role']=='direct_access' else e['role'],'domainhub':e['code'],'eligible':e['eligible'],'recommended':e['code']==preferred}
if e['access']!='available': item['access']=e['access']
records.append(item)
atomic(config['catalog_path'],{'source':'domainhub.public.v1','version':state['manifest']['version'],'domains':records})
context=verify(config,state['manifest']['version'])
atomic(str(path)+'.runtime',context)
_,body=transport(config['hub_url'].rstrip('/')+'/api/v1/domainhub/public/deliveries/'+str(state['delivery'])+'/ack',config['key'],{'version':state['manifest']['version'],'digest':state['digest'],'status':'applied'})
if json.loads(body).get('status')!='applied': raise ValueError('invalid_ack')
return {'version':state['manifest']['version'],'changed':changed,'status':'applied'}
def incidents(config, state, journal, now):
active=journal.setdefault('active',{}); outbox=journal.setdefault('outbox',[])
context=read(config['state_path']+'.runtime',{})
for code in config['providers']:
selection=available(state,code,now)
if selection is None and code not in active:
incident=str(uuid.uuid4()); active[code]=incident
provider=(state or {}).get('manifest',{}).get('providers',{}).get(code,{})
reasons=';'.join(e['hostname']+': '+str(e.get('reason') or '不可用') for e in provider.get('entries',[]))
if not current(state,now): reasons='快照缺失或超过24小时未成功同步。'+reasons
text=f"【{config['label']} - {code}无可用广告域名】\n该服务商已暂停自动引流。\n原因:{reasons}\n版本:{(state or {}).get('manifest',{}).get('version','无')}\n投放状态:{json.dumps(context,ensure_ascii=False)}\n请补充可用入口或核实后明确恢复域名。"
outbox.append({'key':'domainhub.'+incident+'.critical','bot':'critical','text':text,'status':'pending','receipt':None,'retry_at':0,'attempts':0})
elif selection is not None and code in active:
incident=active.pop(code)
outbox.append({'key':'domainhub.'+incident+'.recovery','bot':'notification','text':f"【{config['label']} - {code}广告域名恢复】\n当前选用:{selection['url']}\n版本:{state['manifest']['version']}\n仍遵守原投放开关和暂避风头模式。",'status':'pending','receipt':None,'retry_at':0,'attempts':0})
def alerts(config, now=None, transport=request):
if not config.get('alerts_enabled'): return
now=int(time.time() if now is None else now); path=config['state_path']+'.alerts'
journal=read(path,{'active':{},'outbox':[]})
incidents(config,read(config['state_path']),journal,now)
atomic(path,journal)
for message in [m for m in journal['outbox'] if m['status'] not in TERMINAL and m['retry_at']<=now][:5]:
message['attempts']+=1; delay=min(21600,900*(2**min(message['attempts']-1,5)))
try:
endpoint=config['telehub_url'].rstrip('/')+'/api/v1/messages'
if message['receipt']: _,body=transport(endpoint+'/'+message['receipt'],config['telehub_key'])
else: _,body=transport(endpoint,config['telehub_key'],{'bot':message['bot'],'target':'base','text':message['text']},{'Idempotency-Key':message['key']})
receipt=json.loads(body)['data']
if (not re.fullmatch('[a-f0-9-]{36}',receipt.get('id','')) or receipt.get('status') not in TERMINAL|{'queued','sending'} or receipt.get('bot_code')!=message['bot'] or receipt.get('target_code')!='base' or (message['receipt'] and message['receipt']!=receipt['id'])): raise ValueError('invalid_receipt')
message.update(receipt=receipt['id'],status=receipt['status'],error=None)
except HTTPError as exc:
message['error']='http_'+str(exc.code)
if exc.code==429: delay=max(delay,int(exc.headers.get('Retry-After','0')) if exc.headers.get('Retry-After','0').isdigit() else 0)
elif 400<=exc.code<500: message['status']='rejected'
except (OSError,ValueError,KeyError,TimeoutError): message['error']='transport_or_receipt'
message['retry_at']=now+delay; atomic(path,journal)
def main():
parser=argparse.ArgumentParser();parser.add_argument('--config',required=True);parser.add_argument('--full',action='store_true');args=parser.parse_args()
config=read(args.config)
if not config or config.get('environment')!='production' or not re.fullmatch('dhc_[a-f0-9]{64}',config.get('key','')): raise SystemExit('invalid_private_configuration')
if urlsplit(config['hub_url']).scheme!='https': raise SystemExit('invalid_hub_url')
path=Path(config['state_path']); path.parent.mkdir(parents=True,exist_ok=True)
with open(str(path)+'.lock','a') as lock:
try: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError: return
try: print(json.dumps(sync(config,args.full)))
except Exception as exc: print(json.dumps({'status':'sync_failed','error':type(exc).__name__}))
alerts(config)
if __name__=='__main__': main()
@@ -0,0 +1,16 @@
[Unit]
Description=FNA daily full public domain reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=nginx
Group=nginx
UMask=0027
ExecStart=/usr/bin/python3 /www/wwwroot/clashfreenode-new.com/tools/domainhub/public_client.py --config /www/wwwroot/clashfreenode-new.com/storage/app/private/domainhub-public/config.json --full
TimeoutStartSec=240
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=/www/wwwroot/clashfreenode-new.com/storage /www/wwwroot/clashfreenode-new.com/bootstrap/cache
ProtectHome=true
PrivateTmp=true
@@ -0,0 +1,7 @@
[Unit]
Description=FNA daily complete domain snapshot at 08:10 Shanghai
[Timer]
OnCalendar=*-*-* 08:10:00 Asia/Shanghai
Persistent=true
[Install]
WantedBy=timers.target
@@ -0,0 +1,16 @@
[Unit]
Description=FNA signed public domain reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=nginx
Group=nginx
UMask=0027
ExecStart=/usr/bin/python3 /www/wwwroot/clashfreenode-new.com/tools/domainhub/public_client.py --config /www/wwwroot/clashfreenode-new.com/storage/app/private/domainhub-public/config.json
TimeoutStartSec=240
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=/www/wwwroot/clashfreenode-new.com/storage /www/wwwroot/clashfreenode-new.com/bootstrap/cache
ProtectHome=true
PrivateTmp=true
@@ -0,0 +1,8 @@
[Unit]
Description=FNA public domain changes every four hours
[Timer]
OnBootSec=90
OnUnitActiveSec=4h
Persistent=true
[Install]
WantedBy=timers.target