Compare commits

..
Author SHA1 Message Date
Codex c65a137070 Publish tutorial on Clash routing modes and proxy groups 2026-10-31 15:01:29 +08:00
Codex 77f9b09c58 Record tutorial sitemap deployment and server verification 2026-10-31 14:30:41 +08:00
Codex b0d61806dc Record tutorial sitemap deployment and server verification 2026-10-31 14:29:50 +08:00
Codex 252e0c38cb Include tutorial landing pages in sitemap and verify notification receipts 2026-10-31 14:27:59 +08:00
Codex ace6d74a18 Record successful production IndexNow submission 2026-10-31 14:22:14 +08:00
Codex 5748124383 Notify IndexNow after editorial publication with durable retry 2026-10-31 14:18:14 +08:00
Codex d981a2aa4f Record editorial release verification and schedule policy 2026-10-31 14:11:05 +08:00
Codex 3a62bccbcd Keep unrelated local maintenance notes out of publishing deployment 2026-10-31 14:06:35 +08:00
Codex 7039990ddc Add resumable editorial publishing through SSH jump host 2026-10-31 14:06:07 +08:00
Codex 4fb57e494d Record restored original images and independent lifecycle contract 2026-10-31 13:29:39 +08:00
Codex 21bb77c176 Preserve independent FNA image copies after source withdrawal 2026-10-31 13:27:38 +08:00
Codex 26cb1ed724 Record Hardnerd advertisement copy update 2026-10-30 19:35:03 +08:00
Codex 48a97f2820 Update Hardnerd advertisement copy 2026-10-30 19:32:58 +08:00
Codex 3e10db81a4 Document Hardnerd ad production release and recovery 2026-10-30 19:04:36 +08:00
Codex f0a0f34d8b Publish Hardnerd image advertisement in article content 2026-10-30 19:01:48 +08:00
Codex a5c5540b97 Bound delivery backlog processing and document verified production behavior 2026-10-30 16:21:36 +08:00
Codex be17c0c8ee Cache only approved delivery assets without reconciling existing article mappings 2026-10-30 16:15:56 +08:00
Codex f72192063d Synchronize approved illustration deliveries and acknowledge verified static copies 2026-10-30 16:07:22 +08:00
Codex c663829c6d Document verified static illustration deployment and recovery 2026-10-30 12:28:03 +08:00
Codex ce27dbdd1e Return same-site illustration URLs in serialized articles 2026-10-30 12:25:24 +08:00
Codex 9d2cd9a895 Preserve concurrent article mappings during static sync 2026-10-30 12:03:17 +08:00
Codex 25e0f87d97 Cache successful static images without caching missing-file errors 2026-10-30 11:57:35 +08:00
Codex b892a4150a Serve article illustrations as deduplicated local static files 2026-10-30 11:51:22 +08:00
73 changed files with 2775 additions and 41 deletions

No files matched your search

+3
View File
@@ -63,3 +63,6 @@ AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
# Approved illustration delivery (independent per environment)
ILLUSTRATION_DELIVERY_ENABLED=false
+1
View File
@@ -23,3 +23,4 @@ Thumbs.db
!/_env/*
./vite.config.js
/node_modules
/public/images/illustrations
+15
View File
@@ -0,0 +1,15 @@
# FNA_V3维护入口
## FNA 静态配图副本
2026-10-30起Resource保留原稿、图池和固定分配,FNA保存按内容去重的公开展示副本,由本站Nginx直接提供。同步、创建时校验、撤回、缓存与部署验收唯一正文见[静态配图副本](docs/maintenance/LOCAL_ILLUSTRATIONS.md)。用户访问图片不调用Resource、不执行PHP修复。
## AI 文章写作(必读)
文章写作和发布先读docs/content/WRITING.md及docs/maintenance/EDITORIAL_API.md。项目身份和访问边界先读GemDocs AI版项目总览、维护协议及10-项目/fna_v3.md。
插画完成后按[自动交付](docs/maintenance/ILLUSTRATION_DELIVERY.md)提交批准批次;不要再手工上传发布/编辑图池或把保存草稿当作上线完成。
周期文章按[固定发布封装](docs/maintenance/EDITORIAL_RELEASE.md)执行:本机SSH必须经白色机到正式业务服务器,使用服务器进程内API,不临时开放公网接口。每周三篇、每天15:00检查、错过窗口回补及文章随机展示时间见[周期写作](docs/maintenance/WEEKLY_TUTORIALS.md);这一流程替代周期写作中的手动开关API步骤,不扩大其他实例或全站改版权限。
教程SEO、编辑API的IndexNow结果与重试、栏目sitemap的唯一维护说明见[教程SEO通知](docs/maintenance/EDITORIAL_INDEXNOW.md)。`sitemap: done`不代表搜索引擎已收到通知或已收录。
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Console\Commands;
use App\Services\Editorial\ReleaseRunner;
use Illuminate\Console\Command;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
final class EditorialRelease extends Command
{
protected $signature = 'editorial:release';
protected $description = 'Run a resumable editorial API operation from JSON on stdin, on this application server';
public function handle(): int
{
try {
abort_unless(PHP_SAPI === 'cli', 403);
if (! app()->environment('testing')) {
abort_unless(app()->environment('production')
&& realpath(base_path()) === '/www/wwwroot/clashfreenode-new.com'
&& rtrim(config('editorial.base_url'), '/') === 'https://clashfreenode.com'
&& function_exists('posix_geteuid') && posix_getpwuid(posix_geteuid())['name'] === 'nginx', 403, 'Server binding mismatch');
}
$raw = stream_get_contents(STDIN, 48 * 1024 * 1024 + 1);
abort_unless(strlen($raw) <= 48 * 1024 * 1024, 413);
$input = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
abort_unless(is_array($input), 422);
$result = app(ReleaseRunner::class)->run($input);
$this->line(json_encode(['ok' => true, 'data' => $result], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
return ($result['phase'] ?? '') === 'published_pending' ? 2 : 0;
} catch (\Throwable $e) {
$status = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;
$this->line(json_encode(['ok' => false, 'status' => $status, 'error' => 'Release operation failed; use the same release_id to inspect or resume. No credential details are exposed.']));
return 1;
}
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Console\Commands;
use App\Services\Editorial\PublicationEffects;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class RetryEditorialIndexNow extends Command
{
protected $signature = 'editorial:indexnow-retry';
protected $description = 'Retry due editorial IndexNow notifications without republishing content';
public function handle(): int
{
if (! app()->environment(['production', 'testing']) || ! config('editorial.indexnow_enabled', app()->environment('production'))) {
$this->line('IndexNow retry disabled in this environment.');
return self::SUCCESS;
}
$ids = DB::table('editorial_publications')->where('effects->indexnow->status', 'pending')
->where(function ($q) {
$q->whereNull('effects->indexnow->next_attempt_at')
->orWhere('effects->indexnow->next_attempt_at', '<=', now()->timestamp);
})->orderBy('updated_at')->limit(10)->pluck('id');
$pending = 0;
foreach ($ids as $id) {
try {
$receipt = app(PublicationEffects::class)->synchronize($id);
$pending += ($receipt['effects']['indexnow']['status'] ?? '') === 'pending' ? 1 : 0;
} catch (\Throwable) {
$pending++;
}
}
$this->line(json_encode(['processed' => count($ids), 'pending' => $pending]));
return $pending ? self::FAILURE : self::SUCCESS;
}
}
@@ -0,0 +1,100 @@
<?php
namespace App\Console\Commands;
use App\Services\IllustrationPool;
use App\Services\LocalIllustrations;
use Illuminate\Console\Command;
final class SyncIllustrationDeliveries extends Command
{
protected $signature = 'illustrations:sync-deliveries';
protected $description = 'Synchronize pending illustration deliveries and acknowledge verified static copies';
public function handle(): int
{
if (! config('illustrations.delivery_enabled') || ! IllustrationPool::enabled() || ! LocalIllustrations::enabled()) {
$this->error('Illustration delivery is disabled');
return self::FAILURE;
}
$dir = dirname(config('illustrations.local_manifest'));
if (! is_dir($dir)) {
mkdir($dir, 0700, true);
}
$lock = fopen($dir.'/delivery.lock', 'c');
if (! $lock) {
return self::FAILURE;
}
if (! flock($lock, LOCK_EX | LOCK_NB)) {
fclose($lock);
return self::SUCCESS;
}
try {
$pending = array_slice(IllustrationPool::pendingDeliveries(), 0, 3); // Bound metadata calls below the consumer rate limit.
if (! $pending) {
$this->line('No pending illustration deliveries');
return self::SUCCESS;
}
$snapshots = [];
$images = [];
foreach ($pending as $batch) {
foreach ($batch['assets'] ?? [] as $asset) {
$pool = $asset['pool'] ?? '';
if (! in_array($pool, config('illustrations.categories'), true)) {
throw new \RuntimeException('invalid_pool');
}
if (! isset($snapshots[$pool])) {
$snapshots[$pool] = IllustrationPool::sourceSnapshot($pool);
}
$match = null;
foreach ($snapshots[$pool]['items'] as $image) {
if (($image['asset_id'] ?? '') === ($asset['asset_id'] ?? null)) {
$match = $image;
}
}
if (! $match) {
throw new \RuntimeException('delivery_asset_unavailable');
}
$images[$asset['asset_id']] = $match;
}
}
app(LocalIllustrations::class)->cacheDeliveryAssets(array_values($images));
$bytes = file_get_contents(config('illustrations.local_manifest'));
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
foreach ($pending as $batch) {
if (($batch['state'] ?? '') !== 'awaiting_sync' || empty($batch['assets'])) {
throw new \RuntimeException('invalid_delivery');
}
foreach ($batch['assets'] as $asset) {
$local = $manifest['assets'][$asset['asset_id']] ?? null;
$sha = $asset['sha256'] ?? '';
if (! preg_match('/\A[a-f0-9]{64}\z/D', $sha) || ! $local || ($local['sha256'] ?? '') !== $sha || ($local['mime'] ?? '') !== 'image/webp') {
throw new \RuntimeException('missing_copy');
}
$path = rtrim(config('illustrations.local_directory'), '/').'/'.$sha.'.webp';
if (! is_file($path) || is_link($path) || hash_file('sha256', $path) !== $sha) {
throw new \RuntimeException('invalid_copy');
}
}
$ack = IllustrationPool::acknowledgeDelivery($batch['id'], ['fingerprint' => $batch['fingerprint'], 'manifest_sha256' => hash('sha256', $bytes)]);
if (($ack['state'] ?? '') !== 'completed') {
throw new \RuntimeException('ack_failed');
}
$this->line('Completed illustration delivery '.$batch['id']);
}
return self::SUCCESS;
} catch (\Throwable) {
$this->error('Illustration delivery sync incomplete; will retry without a completion ACK.');
return self::FAILURE;
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
}
@@ -0,0 +1,53 @@
<?php
namespace App\Console\Commands;
use App\Models\Articles;
use App\Services\IllustrationPool;
use App\Services\LocalIllustrations;
use Illuminate\Console\Command;
use Spatie\ResponseCache\Facades\ResponseCache;
final class SyncLocalIllustrations extends Command
{
protected $signature = 'illustrations:sync-local {--assign-missing : Create missing Resource assignments for existing public articles}';
protected $description = 'Copy approved Resource images into deduplicated local static files and atomically reconcile article mappings';
public function handle(LocalIllustrations $local): int
{
if (! IllustrationPool::enabled()) {
$this->error('Resource binding is not enabled for this environment');
return self::FAILURE;
}
try {
$baseline = $local->selectionBaseline();
$snapshots = [];
$expected = [];
foreach (config('illustrations.categories') as $category => $pool) {
$keys = Articles::where('iCategoryId', $category)->where('iStatus', 1)->orderBy('created_at')->orderBy('id')->pluck('sSlug')->all();
IllustrationPool::forget($pool);
$snapshot = IllustrationPool::sourceSnapshot($pool);
$missing = array_values(array_diff($keys, array_keys($snapshot['selections']), array_keys($snapshot['unavailable'] ?? [])));
if ($missing && ! $this->option('assign-missing')) throw new \RuntimeException('Missing article assignments; rerun with --assign-missing using a write-scoped consumer');
foreach (array_chunk($missing, 200) as $chunk) IllustrationPool::assignSource($pool, $chunk);
if ($missing) $snapshot = IllustrationPool::sourceSnapshot($pool);
$snapshots[$pool] = $snapshot;
$expected[$pool] = $keys;
}
$result = $local->synchronize($snapshots, $baseline);
foreach ($expected as $pool => $keys) {
foreach ($keys as $key) {
if (! $local->thumbnail($pool, $key)) $result['pending'][$pool.':'.$key] ??= 'local_copy_unavailable';
}
}
ResponseCache::clear();
\Illuminate\Support\Facades\Cache::forget('article_order_likes');
$this->line(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
return $result['pending'] ? self::FAILURE : self::SUCCESS;
} catch (\Throwable) {
// Never print request/credential exceptions or leave partial manifest writes.
$this->error('Local illustration sync failed; existing manifest retained if publication did not complete. Retry after checking Resource and filesystem access.');
return self::FAILURE;
}
}
}
@@ -32,6 +32,7 @@ public function source(int $article)
return response()->json(['article_id' => $a->id, 'title' => $a->sTitle, 'summary' => $a->sTitleSub,
'slug' => $a->sSlug, 'body_html' => $a->sContent, 'category_slug' => $category->sSlug,
'tag_ids' => DB::table('article_tag')->where('iArticleId', $a->id)->pluck('iTagId'),
'created_at' => $a->created_at, 'display_published_at' => $a->sDisplayPublishedAt,
'cover' => $a->sThumb, 'show_cover' => (bool) $a->bPageThumb,
'like_growth' => ['seven_day_remaining' => (int) $a->i7like, 'yearly' => (int) $a->i365like,
'one_year_target' => (int) $a->iYearLikeTarget, 'one_year_added' => (int) $a->iYearLikeAdded,
@@ -140,7 +141,7 @@ public function preview(string $draft, string $key, Publisher $p)
}
$a = new Articles;
$a->forceFill(['id' => 0, 'sTitle' => $item['title'], 'sTitleSub' => $item['summary'], 'sSlug' => $item['slug'], 'sContent' => $html,
'created_at' => now(), 'iLikeCount' => 0, 'bPageThumb' => $item['show_cover'] ?? false, 'sThumb' => $cover]);
'created_at' => now(), 'sDisplayPublishedAt' => now()->subSeconds($item['display_offset_seconds'] ?? 0), 'iLikeCount' => 0, 'bPageThumb' => $item['show_cover'] ?? false, 'sThumb' => $cover]);
$category = Categories::where('sSlug', $item['category_slug'])->with('oParent')->firstOrFail();
$a->setRelation('oCategory', $category);
$a->setRelation('oTags', collect());
+17 -13
View File
@@ -3,29 +3,33 @@
namespace App\Http\Controllers;
use App\Models\Articles;
use App\Models\Categories;
use Illuminate\Http\Response;
class SitemapController extends Controller
{
public function index(): Response
{
// 连表查询分类:按 aOpt['noindexday'] 动态过滤过期文章
// Use the same expiry rule as article metadata, including on SQLite in isolated tests.
$cArticles = Articles::where('iStatus', 1)
->whereHas('oCategory', function ($q) {
$q->where(function ($query) {
// 1. 没有配置 noindexday,或者 noindexday = 0 的文章,一直保留
$query->whereNull('aOpt')
->orWhereRaw("JSON_UNQUOTE(JSON_EXTRACT(aOpt, '$.noindexday')) IS NULL")
->orWhereRaw("JSON_UNQUOTE(JSON_EXTRACT(aOpt, '$.noindexday')) = '0'")
// 2. 配置了天数的,只取 N 天内创建的新文章
->orWhereRaw("articles.created_at >= NOW() - INTERVAL CAST(JSON_UNQUOTE(JSON_EXTRACT(aOpt, '$.noindexday')) AS UNSIGNED) DAY");
});
})
->where('created_at', '<=', now())
->whereHas('oCategory', fn ($q) => $q->where('iStatus', 1))
->with('oCategory')
->orderBy('created_at', 'desc')
->get();
->get()->reject(fn ($article) => $article->bIsSeoExpired());
$visible = fn ($q) => $q->where('iStatus', 1)->where('created_at', '<=', now());
$cCategories = Categories::whereIn('sSlug', ['client', 'advanced'])
->where('iParentId', 0)->where('iStatus', 1)
->where(function ($q) use ($visible) {
$q->whereHas('aArticles', $visible)->orWhereHas('aChildren', function ($children) use ($visible) {
$children->where('iStatus', 1)->whereHas('aArticles', $visible);
});
})->orderBy('sSlug')->get();
$sXmlContent = view('sitemap', [
'cArticles' => $cArticles
'cArticles' => $cArticles,
'cCategories' => $cCategories,
])->render();
return response($sXmlContent, 200)->header('Content-Type', 'text/xml');
@@ -15,7 +15,9 @@ public function handle(Request $request, Closure $next)
abort_unless(($db['database'] ?? '') === 'fna_v3' && in_array($db['host'] ?? '', ['localhost', '127.0.0.1']) && empty($db['url']), 503, 'Local editorial database binding mismatch');
}
$path = config('editorial.credential_file');
$credential = is_file($path) ? json_decode(file_get_contents($path), true) : null;
$process = PHP_SAPI === 'cli' ? config('editorial.process_credential') : null;
$credential = $process ?? (is_file($path) ? json_decode(file_get_contents($path), true) : null);
abort_if($process && (! is_int($process['expires_at'] ?? null) || $process['expires_at'] <= time()), 401, 'Process session expired');
abort_unless(is_array($credential)
&& ($credential['environment'] ?? null) === app()->environment()
&& ($credential['project'] ?? null) === 'fna-v3'
+11 -1
View File
@@ -20,6 +20,16 @@ public function getSThumbAttribute($value)
return \App\Services\IllustrationPool::thumbnail($this->attributes, $value);
}
public function attributesToArray(): array
{
$attributes = parent::attributesToArray();
// Laravel's snake-case mutator discovery misses the legacy camelCase column.
if (array_key_exists('sThumb', $attributes)) {
$attributes['sThumb'] = $this->getAttribute('sThumb');
}
return $attributes;
}
protected $appends = ['s_created_at_diff'];
use Searchable;
@@ -28,7 +38,7 @@ protected function sCreatedAtDiff(): Attribute
{
return Attribute::get(function () {
// 1. 别直接用 $this->created_at,防止它还没被实例化成 Carbon 对象
$oDate = \Carbon\Carbon::parse($this->created_at);
$oDate = \Carbon\Carbon::parse($this->attributes['sDisplayPublishedAt'] ?? $this->created_at);
$oNow = \Carbon\Carbon::now();
// 2. 计算小时差(强制转整数)
+1 -1
View File
@@ -12,7 +12,7 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
$this->app->scoped(\App\Services\LocalIllustrations::class);
}
/**
@@ -0,0 +1,97 @@
<?php
namespace App\Services\Editorial;
use App\Models\Articles;
use Illuminate\Support\Facades\Http;
/** Durable notification state lives in the publication receipt, alongside cache/search effects. */
final class IndexNowNotification
{
public function initial(array $articles): array
{
if (! $this->enabled()) {
return ['status' => 'skipped', 'reason' => 'disabled-environment'];
}
if (! collect($articles)->contains(fn ($a) => $a['content_changed'] ?? false)) {
return ['status' => 'skipped', 'reason' => 'no-content-change'];
}
return ['status' => 'pending', 'attempts' => 0];
}
public function synchronize(array $state, array $published): array
{
if (($state['status'] ?? '') !== 'pending' || ! $this->enabled()
|| ($state['next_attempt_at'] ?? 0) > now()->timestamp) {
return $state;
}
$base = rtrim((string) config('editorial.base_url'), '/');
$host = parse_url($base, PHP_URL_HOST);
// No per-article target, redirect, or credentials in URLs. Never probe public pages from local.
if (! $host || ! preg_match('~\Ahttps://[a-z0-9.-]+\z~i', $base)
|| $base !== rtrim((string) config('app.url'), '/')
|| $host !== config('app.site_code')) {
return $this->pending($state, 'site-binding-mismatch');
}
$key = config('key.indexnow');
if (! is_string($key) || ! preg_match('/\A[a-zA-Z0-9-]{8,128}\z/', $key)) {
return $this->pending($state, 'key-missing-or-invalid');
}
$urls = [];
foreach ($published as $item) {
if (! ($item['content_changed'] ?? false)) {
continue;
}
$article = Articles::with('oCategory')->find($item['article_id']);
if (! $article || (int) $article->iStatus !== 1 || ! $article->oCategory
|| (int) $article->oCategory->iStatus !== 1 || $article->created_at->isFuture()
|| $article->bIsSeoExpired()) {
continue;
}
$url = $base.'/a/'.$article->sSlug.'.html';
if ($url === $item['url'] && preg_match('/\A[a-z0-9_-]+\z/', $article->sSlug)) {
$urls[] = $url;
}
}
$urls = array_values(array_unique($urls));
if (! $urls) {
return array_replace($state, ['status' => 'skipped', 'reason' => 'no-current-indexable-url']);
}
try {
$response = Http::connectTimeout(5)->timeout(15)->withoutRedirecting()->acceptJson()
->post('https://api.indexnow.org/indexnow', [
'host' => $host, 'key' => $key, 'keyLocation' => $base.'/'.$key.'.txt', 'urlList' => $urls,
]);
$code = $response->status();
if (in_array($code, [200, 202], true)) {
return ['status' => 'done', 'attempts' => ($state['attempts'] ?? 0) + 1,
'http_status' => $code, 'urls' => $urls, 'submitted_at' => now()->toIso8601String(),
'result' => $code === 202 ? 'received-key-validation-pending' : 'received'];
}
return $this->pending($state, 'http-error', $code);
} catch (\Throwable) {
// Response bodies and exception messages may contain the key. Persist only safe diagnostics.
return $this->pending($state, 'transport-error');
}
}
private function enabled(): bool
{
return app()->environment(['production', 'testing'])
&& (bool) config('editorial.indexnow_enabled', app()->environment('production'));
}
private function pending(array $state, string $reason, ?int $code = null): array
{
$attempts = ($state['attempts'] ?? 0) + 1;
return ['status' => 'pending', 'attempts' => $attempts, 'reason' => $reason, 'http_status' => $code,
'last_attempt_at' => now()->toIso8601String(),
'next_attempt_at' => now()->timestamp + min(86400, 300 * 2 ** min(9, $attempts - 1))];
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Services\Editorial;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
/** Calls the existing HTTP routes on the application server, without opening its public API. */
final class ProcessApi
{
private array $credential;
public function __construct()
{
abort_unless(PHP_SAPI === 'cli', 403);
$this->credential = ['schema' => 'gemdocs.credential.v1', 'project' => 'fna-v3',
'environment' => app()->environment(), 'base_url' => config('editorial.base_url'),
'expires_at' => time() + 600, 'fields' => ['api_key' => 'fna_ed_'.bin2hex(random_bytes(32))]];
}
public function call(string $method, string $path, array $data = [], ?UploadedFile $image = null): array
{
abort_unless(in_array($method, ['GET', 'POST']) && preg_match('~\A[a-zA-Z0-9_/-]+\z~', $path), 422);
$response = $this->dispatch($method, '/api/editorial/v1/'.$path, $data, $image);
$body = json_decode($response->getContent(), true);
abort_unless($response->isSuccessful(), $response->getStatusCode(), 'Editorial API rejected operation; inspect state before retry');
abort_unless(is_array($body), 502, 'Unexpected API response');
return $body;
}
public function preview(string $url): string
{
$base = rtrim(config('editorial.base_url'), '/');
abort_unless(str_starts_with($url, $base.'/api/editorial/v1/preview/'), 422, 'Preview origin mismatch');
$response = $this->dispatch('GET', substr($url, strlen($base)));
abort_unless($response->isSuccessful() && str_contains($response->headers->get('Content-Type', ''), 'text/html')
&& str_contains($response->headers->get('X-Robots-Tag', ''), 'noindex'), 502, 'Preview render failed');
return $response->getContent();
}
private function dispatch(string $method, string $path, array $data = [], ?UploadedFile $image = null)
{
abort_unless(time() < $this->credential['expires_at'], 401, 'Process session expired');
$before = ['editorial.enabled' => config('editorial.enabled'),
'editorial.process_credential' => config('editorial.process_credential')];
$originalRequest = app('request');
config(['editorial.enabled' => true, 'editorial.process_credential' => $this->credential]);
try {
$server = ['HTTP_ACCEPT' => 'application/json', 'HTTP_AUTHORIZATION' => 'Bearer '.$this->credential['fields']['api_key'],
'CONTENT_TYPE' => 'application/json', 'REMOTE_ADDR' => '127.0.0.1'];
$request = Request::create(rtrim(config('editorial.base_url'), '/').$path, $method, [], [],
$image ? ['image' => $image] : [], $server, $image ? null : json_encode($data));
$kernel = app(Kernel::class);
$response = $kernel->handle($request);
$kernel->terminate($request, $response);
return $response;
} finally {
config($before);
app()->instance('request', $originalRequest);
}
}
}
@@ -36,6 +36,12 @@ public function synchronize(string $id): array
}
// Sitemap is generated from current DB rows, no external submission is performed.
$effects['sitemap'] = ['status' => ($effects['cache']['status'] ?? '') === 'done' ? 'done' : 'pending', 'method' => 'database-driven'];
// Legacy receipts were not queued for notification; never backfill them implicitly.
$notification = $effects['indexnow'] ?? ['status' => 'skipped', 'reason' => 'legacy-publication'];
if (($effects['cache']['status'] ?? '') === 'done') {
$notification = app(IndexNowNotification::class)->synchronize($notification, $receipt['articles']);
}
$effects['indexnow'] = $notification;
DB::table('editorial_publications')->where('id', $id)->update(['effects' => json_encode($effects), 'updated_at' => now()]);
});
+11 -4
View File
@@ -23,6 +23,7 @@ public function draft(array $input): array
'articles.*.tag_ids' => 'sometimes|array|max:20', 'articles.*.tag_ids.*' => 'integer|min:1',
'articles.*.cover' => 'sometimes|nullable|string|max:255',
'articles.*.show_cover' => 'sometimes|boolean',
'articles.*.display_time_randomize' => 'sometimes|boolean',
'articles.*.adopt_article_id' => 'sometimes|integer|min:1',
'articles.*.like_settings' => 'sometimes|array:seven_day,yearly,one_year',
'articles.*.like_settings.seven_day' => 'sometimes|integer|min:0|max:1000000',
@@ -64,6 +65,7 @@ public function draft(array $input): array
abort_if($doc->article_id && ! $article, 409, 'Managed article was removed');
if ($article) {
abort_if(array_key_exists('like_settings', $row), 422, 'Like settings are only accepted for new articles');
abort_if(array_key_exists('display_time_randomize', $row), 422, 'Display time settings are only accepted for new articles');
abort_unless($article->sSlug === $row['slug'], 409, 'Stable article URL cannot change');
$sourceCategory = DB::table('categories')->where('id', $article->iCategoryId)->value('sSlug');
abort_if(in_array($sourceCategory, ['freenode', 'shadowrocketids']), 422, 'Resource articles cannot be adopted by the editorial API');
@@ -84,7 +86,8 @@ public function draft(array $input): array
'base_article_hash' => $article ? $this->articleHash($article) : null,
];
if (! $article) {
// Freeze the random defaults once per draft, so a retry/publication cannot redraw them.
// Freeze display offset and like defaults once; retries cannot redraw them.
$item['display_offset_seconds'] = ($row['display_time_randomize'] ?? true) ? random_int(0, 21600) : 0;
$item['like_settings'] = [
'seven_day' => $row['like_settings']['seven_day'] ?? random_int(5, 35),
'yearly' => $row['like_settings']['yearly'] ?? 50,
@@ -114,7 +117,7 @@ public function getDraft(string $id): array
return ['draft_id' => $id, 'hash' => $d->payload_hash, 'status' => $d->status, 'publication_id' => $d->publication_id,
'articles' => array_map(fn ($i) => ['content_key' => $i['content_key'], 'revision' => $i['revision'], 'title' => $i['title'],
'path' => '/a/'.$i['slug'].'.html', 'like_settings' => $i['like_settings'] ?? null,
'path' => '/a/'.$i['slug'].'.html', 'display_offset_seconds' => $i['display_offset_seconds'] ?? 0, 'like_settings' => $i['like_settings'] ?? null,
'preview_url' => $base.URL::temporarySignedRoute('editorial.preview', now()->addMinutes(config('editorial.preview_minutes')), ['draft' => $id, 'key' => $i['content_key']], absolute: false)], $items)];
}
@@ -189,7 +192,8 @@ public function publish(string $id, array $input): array
'i7like' => $likes['seven_day'], 'i365like' => $likes['yearly'],
'iYearLikeTarget' => $likes['one_year'], 'iYearLikeAdded' => 0,
'sYearLikeStartedAt' => $likes['one_year'] > 0 ? now() : null,
'iIsTop' => 0, 'created_at' => now()]);
'iIsTop' => 0, 'created_at' => now(),
'sDisplayPublishedAt' => now()->subSeconds($item['display_offset_seconds'] ?? 0)]);
}
$oldTags = $this->tags($articleId);
DB::table('article_tag')->where('iArticleId', $articleId)->delete();
@@ -202,10 +206,13 @@ public function publish(string $id, array $input): array
DB::table('editorial_documents')->where('content_key', $item['content_key'])->update(['article_id' => $articleId, 'published_revision' => $item['revision'], 'updated_at' => now()]);
DB::table('editorial_versions')->insert(['content_key' => $item['content_key'], 'revision' => $item['revision'], 'snapshot' => json_encode($item, JSON_UNESCAPED_UNICODE), 'created_at' => now()]);
$published[] = ['content_key' => $item['content_key'], 'article_id' => $articleId, 'revision' => $item['revision'],
'content_changed' => $item['base_article_hash'] !== $this->articleHash(DB::table('articles')->where('id', $articleId)->first()),
'url' => rtrim(config('editorial.base_url'), '/').'/a/'.$item['slug'].'.html'];
}
DB::table('editorial_publications')->insert(['id' => $data['request_id'], 'draft_id' => $id, 'payload_hash' => $opHash,
'receipt' => json_encode(['publication_id' => $data['request_id'], 'status' => 'published', 'articles' => $published], JSON_UNESCAPED_UNICODE), 'created_at' => now(), 'updated_at' => now()]);
'receipt' => json_encode(['publication_id' => $data['request_id'], 'status' => 'published', 'articles' => $published], JSON_UNESCAPED_UNICODE),
'effects' => json_encode(['indexnow' => app(IndexNowNotification::class)->initial($published)]),
'created_at' => now(), 'updated_at' => now()]);
DB::table('editorial_drafts')->where('id', $id)->update(['status' => 'published', 'publication_id' => $data['request_id'], 'updated_at' => now()]);
return $data['request_id'];
+205
View File
@@ -0,0 +1,205 @@
<?php
namespace App\Services\Editorial;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
final class ReleaseRunner
{
public function __construct(private ProcessApi $api) {}
public function run(array $input): array
{
$op = $input['operation'] ?? '';
abort_unless(in_array($op, ['catalog', 'source', 'prepare', 'review', 'publish', 'status']), 422, 'Unknown operation');
if ($op === 'catalog') {
return $this->api->call('GET', 'catalog');
}
if ($op === 'source') {
abort_unless(is_int($input['article_id'] ?? null) && $input['article_id'] > 0, 422);
return $this->api->call('GET', 'source-articles/'.$input['article_id']);
}
$id = $input['release_id'] ?? '';
abort_unless(is_string($id) && Str::isUuid($id), 422, 'release_id must be a UUID');
$root = config('editorial.release_directory', storage_path('app/private/editorial-releases'));
if (! is_dir($root)) {
mkdir($root, 0700, true);
}
$lock = fopen($root.'/runner.lock', 'c');
abort_unless($lock && flock($lock, LOCK_EX | LOCK_NB), 409, 'Another release operation is running');
try {
$file = $root.'/'.$id.'.json';
$state = is_file($file) ? json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR) : null;
if ($op === 'prepare') {
$bundle = ['articles' => $input['articles'] ?? [], 'assets' => $input['assets'] ?? []];
$bundleHash = app(Publisher::class)->hash($bundle);
abort_if($state && $state['bundle_hash'] !== $bundleHash, 409, 'Release ID reused with changed bundle');
if (! $state) {
$state = ['release_id' => $id, 'bundle_hash' => $bundleHash, 'draft_id' => $id,
'publication_request_id' => (string) Str::uuid(), 'phase' => 'preparing'];
$this->save($file, $state); // Persist IDs before any API mutation.
}
$articles = $this->assets($bundle);
$draft = $this->api->call('POST', 'drafts', ['request_id' => $id, 'articles' => $articles]);
$state['draft'] = $draft;
if ($state['phase'] === 'preparing') {
$state['phase'] = 'prepared';
}
$this->save($file, $state);
return $state;
}
abort_unless($state, 404, 'Release not found; retry prepare using the original bundle');
if ($op === 'status') {
return $this->receipt($file, $state);
}
$draft = $this->api->call('GET', 'drafts/'.$state['draft_id']);
if ($op === 'review') {
$previews = [];
foreach ($draft['articles'] as $article) {
$previews[$article['content_key']] = $this->api->preview($article['preview_url']);
}
$state['review'] = ['hash' => $draft['hash'], 'digest' => app(Publisher::class)->hash($previews), 'rendered_at' => gmdate('c')];
$state['phase'] = $draft['status'] === 'published' ? 'published' : 'reviewed';
$this->save($file, $state);
return $state + ['previews' => $previews];
}
abort_unless(isset($state['review'])
&& hash_equals($state['review']['hash'], $input['expected_hash'] ?? '')
&& hash_equals($state['review']['digest'], $input['review_digest'] ?? '')
&& hash_equals($draft['hash'], $state['review']['hash']), 409, 'Review the frozen draft before publishing');
// Query first even after a lost response or interrupted local state update.
$state = $this->receipt($file, $state);
if (! isset($state['receipt'])) {
$state['phase'] = 'publishing';
$this->save($file, $state);
$state['receipt'] = $this->api->call('POST', 'drafts/'.$state['draft_id'].'/publish',
['request_id' => $state['publication_request_id'], 'expected_hash' => $state['review']['hash']]);
$this->save($file, $state);
}
$receiptId = $state['receipt']['publication_id'];
$state['receipt'] = $this->api->call('POST', 'publications/'.$receiptId.'/synchronize');
return $this->verify($file, $state);
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
private function receipt(string $file, array $state): array
{
try {
$state['receipt'] = $this->api->call('GET', 'publications/'.$state['publication_request_id']);
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
if ($e->getStatusCode() !== 404) {
throw $e;
}
// Another publisher may have completed this same draft with its own UUID.
$draft = $this->api->call('GET', 'drafts/'.$state['draft_id']);
if ($draft['publication_id']) {
$state['receipt'] = $this->api->call('GET', 'publications/'.$draft['publication_id']);
} else {
return $state;
}
}
return $this->verify($file, $state);
}
private function verify(string $file, array $state): array
{
$timestamp = \Illuminate\Support\Facades\DB::table('editorial_publications')->where('id', $state['receipt']['publication_id'])->value('created_at');
$state['published_at'] = \Carbon\CarbonImmutable::parse($timestamp, config('app.timezone'))->toIso8601String();
$readback = [];
foreach ($state['receipt']['articles'] as $article) {
$source = $this->api->call('GET', 'source-articles/'.$article['article_id']);
$version = $this->api->call('GET', 'articles/'.$article['content_key'].'/versions/'.$article['revision'])['content'];
$imagesValid = true;
$resolve = function (string $html) use (&$imagesValid) {
return preg_replace_callback('/asset:([a-f0-9]{64})/', function ($m) use (&$imagesValid) {
$extension = \Illuminate\Support\Facades\DB::table('editorial_assets')->where('sha256', $m[1])->value('extension');
$url = '/images/editorial/'.$m[1].'.'.$extension;
$path = public_path(ltrim($url, '/'));
$imagesValid = $imagesValid && is_file($path) && hash_file('sha256', $path) === $m[1];
return $url;
}, $html);
};
$expectedHtml = $resolve($version['html']);
$expectedCover = $version['cover'] ? $resolve($version['cover']) : $version['cover'];
$matches = $source['body_html'] === $expectedHtml && $source['title'] === $version['title']
&& $source['summary'] === $version['summary'] && $source['slug'] === $version['slug']
&& $source['category_slug'] === $version['category_slug'] && $source['cover'] === $expectedCover
&& $source['show_cover'] === $version['show_cover'] && $imagesValid;
$readback[] = ['content_key' => $article['content_key'], 'article_id' => $article['article_id'],
'revision_matches' => (int) $source['management']['published_revision'] === (int) $article['revision'],
'content_matches' => $matches,
'body_sha256' => hash('sha256', $source['body_html']), 'like_growth' => $source['like_growth']];
}
$state['readback'] = $readback;
$done = collect($state['receipt']['effects'])->every(fn ($e, $name) => ($e['status'] ?? '') === 'done'
|| ($name === 'indexnow' && ($e['status'] ?? '') === 'skipped'));
$state['phase'] = $done && collect($readback)->every(fn ($r) => $r['revision_matches'] && $r['content_matches']) ? 'complete' : 'published_pending';
$this->save($file, $state);
return $state;
}
private function assets(array $bundle): array
{
abort_unless(is_array($bundle['assets']) && count($bundle['assets']) <= 10, 422);
$replacements = [];
foreach ($bundle['assets'] as $asset) {
abort_unless(preg_match('/\A[a-z0-9_-]{1,80}\z/', $asset['name'] ?? '') && ! isset($replacements['file:'.$asset['name']]), 422, 'Invalid or duplicate asset name');
$bytes = base64_decode($asset['base64'] ?? '', true);
abort_unless($bytes !== false && strlen($bytes) <= 8 * 1024 * 1024, 422, 'Invalid asset');
$temp = tempnam(sys_get_temp_dir(), 'editorial-upload-');
try {
file_put_contents($temp, $bytes);
chmod($temp, 0600);
$result = $this->api->call('POST', 'assets', [], new UploadedFile($temp, $asset['name'], null, null, true));
$replacements['file:'.$asset['name']] = $result['reference'];
} finally {
@unlink($temp);
}
}
$articles = $bundle['articles'];
abort_unless(is_array($articles) && count($articles) >= 1 && count($articles) <= 10, 422);
foreach ($articles as &$article) {
foreach (['body', 'cover'] as $field) {
if (isset($article[$field])) {
$article[$field] = preg_replace_callback('/file:([a-z0-9_-]+)/', function ($m) use ($replacements) {
abort_unless(isset($replacements[$m[0]]), 422, 'Missing bundled asset');
return $replacements[$m[0]];
}, $article[$field]);
}
}
}
return $articles;
}
private function save(string $file, array $state): void
{
$temp = $file.'.'.bin2hex(random_bytes(8));
try {
$handle = fopen($temp, 'x');
chmod($temp, 0600);
$bytes = json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
if (fwrite($handle, $bytes) !== strlen($bytes) || ! fflush($handle) || ! fsync($handle)) {
throw new \RuntimeException('Release state write failed');
}
fclose($handle);
if (! rename($temp, $file)) {
throw new \RuntimeException('Release state replacement failed');
}
} finally {
@unlink($temp);
}
}
}
+51 -12
View File
@@ -41,21 +41,22 @@ private static function request(string $method, string $path, array $body = []):
}
}
public static function pendingDeliveries(): array
{
return self::request('GET', 'illustration-deliveries');
}
public static function acknowledgeDelivery(string $id, array $receipt): array
{
if (! preg_match('/\A[a-f0-9-]{36}\z/D', $id)) throw new \RuntimeException('Invalid delivery');
return self::request('POST', 'illustration-deliveries/'.$id.'/ack', $receipt);
}
public static function snapshot(string $pool): array
{
return Cache::store('file')->remember('illustrations.v2.'.$pool, 60, function () use ($pool) {
try {
$data = self::request('GET', 'pools/'.$pool);
$seen = [];
while (!empty($data['next'])) {
$after = $data['next'];
if (isset($seen[$after])) throw new \RuntimeException('Resource pagination did not advance');
$seen[$after] = true;
$page = self::request('GET', 'pools/'.$pool.'?after='.rawurlencode($after));
$data['selections'] = array_replace($data['selections'], $page['selections']);
$data['unavailable'] = array_replace($data['unavailable'] ?? [], $page['unavailable'] ?? []);
$data['next'] = $page['next'];
}
$data = self::sourceSnapshot($pool);
Cache::store('file')->forever('illustrations.v2.last-good.'.$pool, $data);
return $data;
} catch (\Throwable $e) {
@@ -71,7 +72,41 @@ public static function forget(string $pool): void
Cache::store('file')->forget('illustrations.v2.'.$pool);
}
public static function sourceSnapshot(string $pool): array
{
$data = self::request('GET', 'pools/'.$pool);
$seen = [];
while (! empty($data['next'])) {
$after = $data['next'];
if (isset($seen[$after])) throw new \RuntimeException('Resource pagination did not advance');
$seen[$after] = true;
$page = self::request('GET', 'pools/'.$pool.'?after='.rawurlencode($after));
$data['selections'] = array_replace($data['selections'], $page['selections']);
$data['unavailable'] = array_replace($data['unavailable'] ?? [], $page['unavailable'] ?? []);
$data['next'] = $page['next'];
}
return $data;
}
public static function assign(string $pool, array $keys): array
{
$selections = self::assignSource($pool, $keys);
if (LocalIllustrations::enabled()) {
foreach ($selections as $key => &$image) {
$image['url'] = url(app(LocalIllustrations::class)->storeSelection($pool, $key, $image));
}
unset($image);
}
return $selections;
}
public static function assetMetadata(string $id): array
{
if (! preg_match('/\A[a-f0-9-]{36}\z/D', $id)) throw new \RuntimeException('Invalid illustration asset');
return self::request('GET', 'assets/'.$id);
}
public static function assignSource(string $pool, array $keys): array
{
$data = self::request('POST', 'pools/'.$pool.'/selections', ['keys' => $keys]);
self::forget($pool);
@@ -85,9 +120,13 @@ public static function forArticle(string $pool, string $slug): string
public static function thumbnail(array $article, ?string $original): ?string
{
if (!self::enabled()) return $original;
$pool = config('illustrations.categories.'.($article['iCategoryId'] ?? ''));
if (!$pool || empty($article['sSlug'])) return $original;
if (LocalIllustrations::enabled()) {
$url = app(LocalIllustrations::class)->thumbnail($pool, $article['sSlug']);
return $url ? url($url) : null;
}
if (!self::enabled()) return $original;
try {
$snapshot = self::snapshot($pool);
$reason = $snapshot['unavailable'][$article['sSlug']] ?? null;
+198
View File
@@ -0,0 +1,198 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
/** Public, content-addressed display copies. Network and hash work only runs on writes/sync. */
final class LocalIllustrations
{
private ?array $manifest = null;
public static function enabled(): bool
{
return (bool) config('illustrations.local_enabled');
}
private function read(): array
{
if ($this->manifest !== null) return $this->manifest;
$path = config('illustrations.local_manifest');
try {
$value = is_file($path) && ! is_link($path) ? json_decode(file_get_contents($path), true, 512, JSON_THROW_ON_ERROR) : [];
return $this->manifest = ($value['version'] ?? null) === 1 ? $value : ['version' => 1, 'assets' => [], 'selections' => []];
} catch (\Throwable) {
// Public requests never fetch Resource, hash files or repair a missing manifest.
return $this->manifest = ['version' => 1, 'assets' => [], 'selections' => []];
}
}
public function thumbnail(string $pool, string $slug): ?string
{
$state = $this->read();
$id = $state['selections'][$pool][$slug] ?? null;
$url = $id ? ($state['assets'][$id]['url'] ?? null) : null;
return is_string($url) && preg_match('~\A'.preg_quote(config('illustrations.local_url_prefix'), '~').'/[a-f0-9]{64}\.(?:webp|png|jpg|gif)\z~D', $url) ? $url : null;
}
private function locked(callable $callback): mixed
{
$dir = dirname(config('illustrations.local_manifest'));
if (! is_dir($dir) && ! mkdir($dir, 0700, true) && ! is_dir($dir)) throw new \RuntimeException('Local illustration state directory unavailable');
if (is_link($dir)) throw new \RuntimeException('Local illustration state must not be a symlink');
$lock = fopen($dir.'/state.lock', 'c');
if (! $lock || ! flock($lock, LOCK_EX)) throw new \RuntimeException('Local illustration lock unavailable');
try {
$this->manifest = null;
return $callback();
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
private function save(array $state): void
{
$state['version'] = 1;
$state['updated_at'] = gmdate('c');
$path = config('illustrations.local_manifest');
$tmp = tempnam(dirname($path), '.manifest-');
try {
chmod($tmp, 0600);
$bytes = json_encode($state, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
if (file_put_contents($tmp, $bytes) !== strlen($bytes) || ! rename($tmp, $path)) throw new \RuntimeException('Local illustration manifest update failed');
$this->manifest = $state;
} finally {
if (is_file($tmp)) unlink($tmp);
}
}
private function copy(array $image, array $assets): array
{
$id = $image['asset_id'] ?? '';
$source = $image['url'] ?? '';
$base = rtrim(config('illustrations.base_url'), '/');
if (! preg_match('/\A[a-f0-9-]{36}\z/D', $id) || ! preg_match('~\A'.preg_quote($base, '~').'/media/[a-f0-9-]{36}\z~D', $source)) throw new \RuntimeException('Unregistered illustration source');
$meta = $assets[$id] ?? IllustrationPool::assetMetadata($id);
$sha = $meta['sha256'] ?? '';
$mime = $meta['mime'] ?? '';
$ext = ['image/webp' => 'webp', 'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif'][$mime] ?? null;
$size = (int) ($meta['bytes'] ?? 0);
if (! $ext || ! preg_match('/\A[a-f0-9]{64}\z/D', $sha) || $size < 1 || $size > 20971520) throw new \RuntimeException('Invalid illustration metadata');
$dir = config('illustrations.local_directory');
if (is_link($dir) || (! is_dir($dir) && ! mkdir($dir, 0755, true) && ! is_dir($dir))) throw new \RuntimeException('Local illustration directory unavailable');
$path = $dir.'/'.$sha.'.'.$ext;
if (is_link($path)) throw new \RuntimeException('Local illustration file must not be a symlink');
if (! is_file($path) || filesize($path) !== $size || ! hash_equals($sha, hash_file('sha256', $path))) {
$tmp = tempnam(dirname(config('illustrations.local_manifest')), '.image-');
$out = null;
$stream = null;
try {
$response = Http::withOptions(['proxy' => '', 'allow_redirects' => false, 'stream' => true])->withUserAgent('FNA-V3/LocalIllustrations')->connectTimeout(3)->timeout(30)->get($source);
if (! $response->successful()) throw new \RuntimeException('Illustration download failed');
$stream = $response->toPsrResponse()->getBody();
$out = fopen($tmp, 'wb');
$bytes = 0;
$hash = hash_init('sha256');
while (! $stream->eof()) {
$chunk = $stream->read(65536);
$bytes += strlen($chunk);
if ($bytes > 20971520 || fwrite($out, $chunk) !== strlen($chunk)) throw new \RuntimeException('Invalid illustration download size');
hash_update($hash, $chunk);
}
fclose($out);$out = null;
$info = @getimagesize($tmp);
if ($bytes !== $size || ! hash_equals($sha, hash_final($hash)) || ! $info || ($info['mime'] ?? '') !== $mime || $info[0] * $info[1] > 10000000) throw new \RuntimeException('Illustration download integrity failed');
chmod($tmp, 0644);
if (! rename($tmp, $path)) throw new \RuntimeException('Local illustration publication failed');
} finally {
if (is_resource($out)) fclose($out);
if ($stream) $stream->close();
if (is_file($tmp)) unlink($tmp);
}
}
return ['asset_id' => $id, 'sha256' => $sha, 'mime' => $mime, 'bytes' => $size,
'url' => config('illustrations.local_url_prefix').'/'.$sha.'.'.$ext, 'source_url' => $source];
}
/** Delivery intake copies only approved batch assets; it does not reconcile existing articles. */
public function cacheDeliveryAssets(array $images): void
{
$this->locked(function () use ($images) {
$state = $this->read();
foreach ($images as $image) {
$state['assets'][$image['asset_id']] = $this->copy($image, $state['assets']);
}
$this->save($state);
});
}
public function storeSelection(string $pool, string $slug, array $image): string
{
return $this->locked(function () use ($pool, $slug, $image) {
$state = $this->read();
$asset = $this->copy($image, $state['assets']);
$state['assets'][$image['asset_id']] = $asset;
$state['selections'][$pool][$slug] = $image['asset_id'];
$this->save($state);
return $asset['url'];
});
}
/** One atomic manifest switch after all downloadable files pass verification. */
public function selectionBaseline(): array
{
$this->manifest = null;
return $this->read()['selections'];
}
public function synchronize(array $snapshots, ?array $baseline = null): array
{
$baseline ??= $this->selectionBaseline();
return $this->locked(function () use ($snapshots, $baseline) {
$state = $this->read();
$pending = [];
foreach ($snapshots as $pool => $snapshot) {
$available = [];
foreach (array_merge($snapshot['items'], array_values($snapshot['selections'])) as $image) {
$id = $image['asset_id'];
if (isset($available[$id])) continue;
$state['assets'][$id] = $this->copy($image, $state['assets']);
$available[$id] = true;
}
// Published FNA copies are independent of the source lifecycle.
// A deleted source reference must not silently remove a local assignment.
$selections = $state['selections'][$pool] ?? [];
foreach ($snapshot['selections'] as $slug => $image) $selections[$slug] = $image['asset_id'];
foreach ($snapshot['unavailable'] ?? [] as $slug => $reason) {
$id = $state['selections'][$pool][$slug] ?? null;
$old = $id ? ($state['assets'][$id] ?? null) : null;
$local = $old ? config('illustrations.local_directory').'/'.basename($old['url']) : null;
// Source deletion, disabling or withdrawal never revokes an FNA copy.
if ($local && is_file($local) && ! is_link($local) && hash_equals($old['sha256'], hash_file('sha256', $local))) {
$selections[$slug] = $id;
} else {
// Report missing/corrupt local bytes without destroying recovery metadata.
$selections[$slug] = $id;
$pending[$pool.':'.$slug] = $reason;
}
}
// Receivers may publish new mappings while the remote snapshot is in flight.
// Never replace a local change made after this sync's baseline was captured.
$current = $state['selections'][$pool] ?? [];
$before = $baseline[$pool] ?? [];
foreach (array_unique(array_merge(array_keys($before), array_keys($current))) as $slug) {
$exists = array_key_exists($slug, $current);
if ($exists !== array_key_exists($slug, $before) || ($current[$slug] ?? null) !== ($before[$slug] ?? null)) {
if ($exists) $selections[$slug] = $current[$slug];
else unset($selections[$slug]);
unset($pending[$pool.':'.$slug]);
}
}
$state['selections'][$pool] = $selections;
}
$this->save($state);
return ['assets' => count($state['assets']), 'selections' => array_map('count', $state['selections']), 'pending' => $pending];
});
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
return [
'hn' => [
'enabled' => env('HN_AD_ENABLED', true),
'url' => env('HN_AD_URL', 'https://hardnerd.net/'),
],
];
+1
View File
@@ -7,4 +7,5 @@
'preview_minutes' => 30,
'max_batch' => 10,
'search_index' => env('EDITORIAL_SEARCH_INDEX', env('APP_ENV') === 'local' ? 'fna_v3_articles' : null),
'indexnow_enabled' => env('EDITORIAL_INDEXNOW_ENABLED', env('APP_ENV') === 'production'),
];
+5
View File
@@ -1,8 +1,13 @@
<?php
return [
'delivery_enabled' => (bool) env('ILLUSTRATION_DELIVERY_ENABLED', false),
'enabled' => (bool) env('RESOURCE_V2_ILLUSTRATIONS_ENABLED', env('LOCAL_ILLUSTRATIONS_ENABLED', env('APP_ENV') === 'local')),
'base_url' => env('RESOURCE_V2_URL', 'http://resource.loc:8612'),
'credential_file' => env('RESOURCE_V2_CREDENTIAL_FILE'),
'local_enabled' => (bool) env('LOCAL_ILLUSTRATIONS_MIRROR_ENABLED', false),
'local_directory' => public_path('images/illustrations'),
'local_manifest' => storage_path('app/private/illustrations/manifest.json'),
'local_url_prefix' => '/images/illustrations',
'categories' => [1 => 'freenode', 9 => 'shadowrocketids'],
];
@@ -0,0 +1,18 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('articles', fn (Blueprint $table) => $table->timestamp('sDisplayPublishedAt')->nullable());
}
public function down(): void
{
Schema::table('articles', fn (Blueprint $table) => $table->dropColumn('sDisplayPublishedAt'));
}
};
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=Process approved illustration deliveries (fna)
After=network-online.target
[Service]
Type=oneshot
User=nginx
Group=nginx
WorkingDirectory=/www/wwwroot/clashfreenode-new.com
ExecStart=/usr/bin/php -d memory_limit=512M artisan illustrations:sync-deliveries --no-interaction
TimeoutStartSec=300
UMask=0022
NoNewPrivileges=true
PrivateTmp=true
+8
View File
@@ -0,0 +1,8 @@
[Unit]
Description=Poll approved illustration deliveries (fna)
[Timer]
OnBootSec=60
OnUnitInactiveSec=60
Persistent=true
[Install]
WantedBy=timers.target
+13
View File
@@ -4,6 +4,8 @@ # AI 写作与文章关联索引
发布已采用本站[独立文章 API](../maintenance/EDITORIAL_API.md),不经过ATOM。AI保留项目正文源,通过API保存冻结草稿、取得签名预览、发布确认的hash并核对回执;本索引仍由写作AI同任务维护,API不会自动改写它。
2026-10-31用户另行授权综合教程每周随机三篇的周期写作与发布,Codex任务已建立,自2026-11-02当周开始。随机计划、额度、幂等台账与执行状态唯一见[周期写作](../maintenance/WEEKLY_TUTORIALS.md);这一授权不扩大为全站重写或其他实例发布。
本文是写作流程、文章用途及文章关系的唯一维护入口。文章正文保存在各自源文件,数据库是页面实际读取的内容;栏目实现、渲染与备份方法见[教程维护](../maintenance/TUTORIALS.md),SEO项目状态见[SEO清单](../maintenance/SEO_PLAN.md)。不要在这些文档中再复制一份持续更新的文章关系表。
## 1 写作前先确定读者要完成的任务
@@ -25,6 +27,10 @@ ## 1 写作前先确定读者要完成的任务
自然、准确地表达;必要时用真实操作图、流程图、配置示例。软件版本、下载入口与兼容要求使用当次核对的官方来源;来源核验、页面检查和设备实测分别记录,未做实测不写“实测”。
### 周期文章的展示时间(2026-10-31)
用户要求每天北京时间15:00检查周期计划,新文章展示日期从实际发布时间随机向前偏移0~21600秒(含端点)。API在新文草稿中冻结`display_offset_seconds`,首次发布计算独立的`sDisplayPublishedAt`;列表和详情沿原有日期显示样式使用该字段,未设置时使用真实创建时间。实际`created_at`、发布回执及点赞起点不改;重试、旧文编辑和回退不重抽、不改旧文展示时间。`display_time_randomize`只允许新建时设置,默认true,显式false为零偏移。不要把随机时间或内部执行过程写进公开正文。
### AI 新文章的点赞参数(2026-10-29)
后续AI通过本站独立文章API**新建文章**时使用以下默认设置,由API在保存草稿时为每篇独立取值并冻结;相同请求重试、查询预览及发布不重新抽取。重写、接管、回退已有文章不重置原参数、点赞数或已完成进度,不自动给现有文章批量补额度。
@@ -59,6 +65,9 @@ ## 2 当前文章登记
| cfw-mac-legacy | 210 / Mac | Clash Verge Rev 使用教程:Mac 安装、订阅与系统代理 | `/a/m173.html` | [verge-mac.md](tutorials/verge-mac.md);本地API版本2 | Mac操作入口;#install DMG安装,#import 订阅,系统代理与退出排错;无设备联网实测 |
| cfw-linux-legacy | 211 / Linux | Clash Verge Rev 使用教程:Linux 安装、订阅与代理设置 | `/a/m174.html` | [verge-linux.md](tutorials/verge-linux.md);本地API版本5 | Linux桌面入门;#install 包格式与架构,#import 订阅,#terminal 单条curl代理验证;不适用于无桌面的服务器 |
| system-proxy-vs-tun | 365 / 综合教程 | 系统代理和 TUN 有什么区别?接管范围、使用选择与排错 | `/a/system-proxy-vs-tun.html` | [system-proxy-tun.md](tutorials/system-proxy-tun.md);本地API版本1 | 桌面代理接管与出口选择;`#choose` 场景选择、`#switch` 切换检查、`#troubleshoot` 排错;三张流程图 |
| clash-routing-modes | 366 / 综合教程 | Clash 规则、全局和直连怎么选?代理组与分流排错教程 | `/a/clash-rule-global-direct.html` | [clash-routing-modes.md](tutorials/clash-routing-modes.md);2026-10-31本地ID366/版本1,正式ID382/版本1已发布 | 模式选择与代理组分流;`#groups` 组内选择、`#custom` 添加规则、`#verify` 验证新连接 |
2026-10-31新教程正式ID382/版本1、本地ID366/版本1已发表;系统代理/TUN正文补入口后两环境均为API版本2(正式ID376、本地ID365)。正式发布时间14:58:28北京时间,IndexNow由VPS-003提交返回200,服务器HTTP与图哈希/锚点验收通过。唯一状态与恢复记录见[规则模式教程发布记录](../maintenance/ROUTING_MODES_2026-10-31.md)。
这里只登记长期编辑内容及值得复用的稳定资源说明,不逐条收录日更节点或账号文章。稳定入口为 `/freenode`(公开免费节点)、`/client`(入门)、`/advanced`(综合教程);平台入口和名称修改另按项目路由核对,不从名称自行拼接。
@@ -99,6 +108,10 @@ ## 3 已有文章关系
| system-proxy-vs-tun | cfw-mac-legacy `#enable` | 切换前完成 Mac 基本连接 | 已在本地正文实现 |
| system-proxy-vs-tun | cfw-linux-legacy `#connect` / `#terminal` | Linux 基础连接及单条命令显式代理 | 已在本地正文实现 |
| system-proxy-vs-tun | mihomo-dns `#dns-2` | 继续检查 DNS 接管、加密和出口 | 已在本地正文实现 |
| system-proxy-vs-tun | clash-routing-modes `#groups` | 已接管但走错出口时检查规则和代理组;放在场景选择之前 | 2026-10-31本地与正式已发布 |
| clash-routing-modes | verge-windows-start `#enable` / cfw-mac-legacy `#enable` | 尚未完成基本连接时返回对应平台操作 | 2026-10-31本地与正式已发布 |
| clash-routing-modes | system-proxy-vs-tun `#routing` / `#troubleshoot` | 解释接管和分流的区别,以及看不到连接时排错 | 2026-10-31本地与正式已发布 |
| clash-routing-modes | mihomo-dns `#dns-2` | 出口正确但域名解析仍异常时继续查DNS | 2026-10-31本地与正式已发布 |
两篇Android教程通过订阅格式段落互链;Mac下载指南与操作教程互链,Linux从下载指南和真实Linux栏目获得入口,iOS沿用真实iOS栏目入口。系统代理与TUN专题由Windows和DNS正文提供入口,并指向三平台的基础操作及DNS专题。目录、标签、导航和热门榜不算正文关联;正文内链及锚点已经本地HTTP验证。
@@ -0,0 +1,9 @@
# 规则、全局与直连配图
原生 SVG 为可编辑源,PNG 为文章 API 上传用图;未使用外部截图。封面沿用 system-proxy-tun-cover.svg 的现有样式;正文两图分别表达路由模式与代理组选择路径。
- `cover.svg` / `cover.png`:960×540。
- `modes.svg` / `modes.png`:1000×670。
- `groups.svg` / `groups.png`:1000×610。
正文源:../../clash-routing-modes.md。技术图使用本机 Chrome 在禁网页面渲染,正式展示副本通过文章资产 API 发布。制作/发布记录见 ../../../../maintenance/ROUTING_MODES_2026-10-31.md。
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 960 540"><rect width="960" height="540" fill="#eaf2f7"/><rect x="55" y="62" width="6" height="412" fill="#347c99"/><g font-family="Arial, PingFang SC, Microsoft YaHei, sans-serif"><text x="97" y="130" font-size="24" fill="#47748a" letter-spacing="3">代理设置 · 综合教程</text><text x="97" y="265" font-size="51" fill="#18394d" font-weight="700">规则、全局与直连</text><text x="100" y="327" font-size="30" fill="#547084">分流模式 · 代理组 · 连接验证</text><path d="M100 403H725" stroke="#92b6c9" stroke-width="3"/><circle cx="100" cy="403" r="9" fill="#347c99"/><circle cx="410" cy="403" r="9" fill="#347c99"/><circle cx="725" cy="403" r="9" fill="#347c99"/></g></svg>

After

Width:  |  Height:  |  Size: 775 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="610" viewBox="0 0 1000 610"><rect width="1000" height="610" rx="20" fill="#f0f5f7"/><g font-family="PingFang SC, Microsoft YaHei, sans-serif"><text x="45" y="64" font-size="34" fill="#264658" font-weight="600">同一条影音规则,两种不同的组内选择</text><text x="45" y="115" font-size="29" fill="#264658" font-weight="600">情况一:影音组直接选择节点甲</text><rect x="45" y="145" width="275" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="69" y="204" font-size="30" fill="#264658" font-weight="600">影音规则</text><text x="326" y="204" font-size="29" fill="#264658" font-weight="400">→</text><rect x="363" y="145" width="275" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="387" y="204" font-size="30" fill="#264658" font-weight="600">影音组</text><text x="644" y="204" font-size="29" fill="#264658" font-weight="400">→</text><rect x="681" y="145" width="275" height="95" rx="14" fill="#e3edf3" stroke="#bed0d9"/><text x="705" y="204" font-size="30" fill="#264658" font-weight="600">节点甲</text><text x="45" y="285" font-size="26" fill="#5d7380" font-weight="400">调整“节点选择”不会改变上面这条选择路径。</text><text x="45" y="345" font-size="29" fill="#264658" font-weight="600">情况二:影音组选择另一个代理组</text><rect x="45" y="375" width="195" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="69" y="434" font-size="30" fill="#264658" font-weight="600">影音规则</text><text x="246" y="434" font-size="29" fill="#264658" font-weight="400">→</text><rect x="283" y="375" width="195" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="307" y="434" font-size="30" fill="#264658" font-weight="600">影音组</text><text x="484" y="434" font-size="29" fill="#264658" font-weight="400">→</text><rect x="521" y="375" width="195" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="545" y="434" font-size="30" fill="#264658" font-weight="600">节点选择</text><text x="722" y="434" font-size="29" fill="#264658" font-weight="400">→</text><rect x="759" y="375" width="195" height="95" rx="14" fill="#e3edf3" stroke="#bed0d9"/><text x="783" y="434" font-size="30" fill="#264658" font-weight="600">节点乙</text><text x="45" y="515" font-size="26" fill="#5d7380" font-weight="400">此时调整“节点选择”,才会影响影音连接的后续出口。</text><text x="45" y="571" font-size="26" fill="#5d7380" font-weight="400">示意组名:请以自己的配置与新连接详情为准。</text></g></svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="670" viewBox="0 0 1000 670"><rect width="1000" height="670" rx="20" fill="#f0f5f7"/><g font-family="PingFang SC, Microsoft YaHei, sans-serif"><text x="45" y="64" font-size="34" fill="#264658" font-weight="600">模式决定:已进入客户端的连接怎样出去</text><rect x="45" y="105" width="910" height="86" rx="14" fill="#fff" stroke="#bed0d9"/><text x="75" y="159" font-size="32" fill="#264658" font-weight="600">请求已进入 Mihomo</text><rect x="45" y="245" width="154" height="100" rx="14" fill="#e1ece8" stroke="#bed0d9"/><text x="87" y="306" font-size="32" fill="#264658" font-weight="600">规则</text><text x="214" y="306" font-size="32" fill="#264658" font-weight="400">→</text><rect x="265" y="245" width="330" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="290" y="305" font-size="29" fill="#264658" font-weight="400">匹配当前规则</text><text x="612" y="306" font-size="32" fill="#264658" font-weight="400">→</text><rect x="665" y="245" width="290" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="685" y="305" font-size="26" fill="#264658" font-weight="400">代理组 / 直连 / 拒绝</text><rect x="45" y="375" width="154" height="100" rx="14" fill="#e1eaf3" stroke="#bed0d9"/><text x="87" y="436" font-size="32" fill="#264658" font-weight="600">全局</text><text x="214" y="436" font-size="32" fill="#264658" font-weight="400">→</text><rect x="265" y="375" width="330" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="290" y="435" font-size="29" fill="#264658" font-weight="400">使用 GLOBAL 当前选择</text><text x="612" y="436" font-size="32" fill="#264658" font-weight="400">→</text><rect x="665" y="375" width="290" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="685" y="435" font-size="26" fill="#264658" font-weight="400">选中的节点或策略</text><rect x="45" y="505" width="154" height="100" rx="14" fill="#efe9df" stroke="#bed0d9"/><text x="87" y="566" font-size="32" fill="#264658" font-weight="600">直连</text><text x="214" y="566" font-size="32" fill="#264658" font-weight="400">→</text><rect x="265" y="505" width="330" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="290" y="565" font-size="29" fill="#264658" font-weight="400">使用本地网络</text><text x="612" y="566" font-size="32" fill="#264658" font-weight="400">→</text><rect x="665" y="505" width="290" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="685" y="565" font-size="26" fill="#264658" font-weight="400">直接连接目标</text><text x="45" y="645" font-size="26" fill="#5d7380" font-weight="400">未进入客户端的连接,不会仅因切换模式而被接管。</text></g></svg>

After

Width:  |  Height:  |  Size: 2.7 KiB

@@ -0,0 +1 @@
<link rel="stylesheet" href="/css/tutorials.css"><div class="tutorial-body"><p>同一个网站,规则模式打不开,切成全局却正常;明明选了新节点,连接记录里还是另一个名字。遇到这类问题,先看这条连接实际走了哪条规则、哪个代理组,再决定要改什么。</p><p>本文以 Clash Verge Rev 和 Mihomo 为例,讲清规则、全局、直连三个模式,并完成一次“只让指定网站走指定出口”的配置。还没有完成导入和首次连接,可以先看 <a href="/a/clash-verge-rev-windows.html#enable">Windows 入门教程</a>;Mac 用户可以从<a href="/a/m173.html#enable">对应操作步骤</a>开始。</p><nav class="guide-toc" aria-label="文章目录"><strong>阅读路线</strong><a href="#modes">三个模式怎么选</a><a href="#groups">为什么换节点没效果</a><a href="#order">规则先后顺序</a><a href="#custom">添加一条网站规则</a><a href="#verify">从连接记录验证</a><a href="#troubleshoot">按现象排查</a></nav><h2 id="modes">01 三个模式,改变的是出口选择</h2><p>先确定前提:请求已经进入了客户端。系统代理、应用自身代理设置和 TUN 负责把流量送进来,下面三个模式负责决定进去以后怎样处理。未被接管的应用,不会因为切到全局就自动经过客户端;接管方式见<a href="/a/system-proxy-vs-tun.html#routing">系统代理与 TUN 的区别</a>。</p><div class="table-wrap"><table><thead><tr><th>模式</th><th>进入客户端后的普通业务连接</th><th>适合什么时候用</th></tr></thead><tbody><tr><td>规则(Rule)</td><td>按当前配置匹配规则,选择直连、代理组或其他策略</td><td>日常分流:不同网站使用不同出口</td></tr><tr><td>全局(Global)</td><td>使用 GLOBAL 组当前选择的节点或策略</td><td>临时对比:判断问题是否与分流结果有关</td></tr><tr><td>直连(Direct)</td><td>由本地网络直接连接目标</td><td>临时检查本地网络,或不需要代理出口时</td></tr></tbody></table></div><p>这三个模式是路由选择,不是速度档位。全局也要检查 GLOBAL 组究竟选了什么:如果选的是 DIRECT,结果仍然是直连;如果选的是另一个代理组,还要继续看那个组的选择。<a href="https://wiki.metacubex.one/config/general/">Mihomo 运行模式说明</a></p><p>直连模式也不等于退出客户端:系统代理、TUN 等入口可能仍开启。要停用接管,需要处理对应开关,不能只把模式改成“直连”。<a href="https://www.clashverge.dev/guide/term.html">Clash Verge Rev 名词解释</a></p><figure class="guide-figure"><img src="/images/editorial/98a43bdd771dd4c6c5ec6b87bb5f0ebf679fa2b228dddbb764adecf50b0374e9.png" alt="请求进入客户端后,规则模式按规则分流,全局模式使用 GLOBAL 选择,直连模式使用本地网络" width="1000" height="670"><figcaption>图 1:模式作用于已进入客户端的连接;切模式不会补上接管范围的缺口。</figcaption></figure><h2 id="groups">02 换了节点没效果,可能换错了组</h2><p>代理页里有“节点选择”“流媒体”“自动选择”等分组时,不要把它们当成一排作用相同的开关。规则通常先指向一个组,组再选节点,也可能继续选另一个组。</p><p>例如,一份配置把视频网站分给“影音”,普通网页交给“节点选择”。你在“节点选择”里换成节点乙,但“影音”仍直接选着节点甲,视频连接就可能继续走甲。只有“影音”选择了“节点选择”这个组,它才会沿着这条选择关系继续向下找出口。</p><figure class="guide-figure"><img src="/images/editorial/417b203a4af30200b6ed3b37d0b0e823a9b47db49e2d743b1110b35329cc5de8.png" alt="规则命中影音组后,该组直接选择节点甲时不经过节点选择组;选择节点选择组时才跟随其中的节点乙" width="1000" height="610"><figcaption>图 2:两种配置的差别在于“影音”组的选择。组名只是配置中的名称,实际关系要查看当前选择。</figcaption></figure><p>手动选择组(<code>select</code>)由你决定使用哪个选项;如果它选择的是自动选择组(<code>url-test</code>),后者仍会按自己的测速配置选择节点。想固定到具体节点,就检查整条选择路径,而不是只看最外层的组名。<a href="https://wiki.metacubex.one/config/proxy-groups/select/">手动选择组</a>与<a href="https://wiki.metacubex.one/config/proxy-groups/url-test/">自动选择组</a></p><p>实际排查时,可以在连接详情里找策略、代理链或类似字段。不同界面展示顺序可能不同,重点是认出“命中了哪个组”和“最终使用哪个节点”。</p><h2 id="order">03 先看顺序,再看规则写得对不对</h2><p>Mihomo 的路由规则从上往下匹配。通常前面命中的规则就决定Line truncated
@@ -0,0 +1,98 @@
同一个网站,规则模式打不开,切成全局却正常;明明选了新节点,连接记录里还是另一个名字。遇到这类问题,先看这条连接实际走了哪条规则、哪个代理组,再决定要改什么。
本文以 Clash Verge Rev 和 Mihomo 为例,讲清规则、全局、直连三个模式,并完成一次“只让指定网站走指定出口”的配置。还没有完成导入和首次连接,可以先看 [Windows 入门教程](/a/clash-verge-rev-windows.html#enable);Mac 用户可以从[对应操作步骤](/a/m173.html#enable)开始。
<nav class="guide-toc" aria-label="文章目录"><strong>阅读路线</strong><a href="#modes">三个模式怎么选</a><a href="#groups">为什么换节点没效果</a><a href="#order">规则先后顺序</a><a href="#custom">添加一条网站规则</a><a href="#verify">从连接记录验证</a><a href="#troubleshoot">按现象排查</a></nav>
<h2 id="modes">01 三个模式,改变的是出口选择</h2>
先确定前提:请求已经进入了客户端。系统代理、应用自身代理设置和 TUN 负责把流量送进来,下面三个模式负责决定进去以后怎样处理。未被接管的应用,不会因为切到全局就自动经过客户端;接管方式见[系统代理与 TUN 的区别](/a/system-proxy-vs-tun.html#routing)。
<div class="table-wrap">
| 模式 | 进入客户端后的普通业务连接 | 适合什么时候用 |
| --- | --- | --- |
| 规则(Rule) | 按当前配置匹配规则,选择直连、代理组或其他策略 | 日常分流:不同网站使用不同出口 |
| 全局(Global) | 使用 GLOBAL 组当前选择的节点或策略 | 临时对比:判断问题是否与分流结果有关 |
| 直连(Direct) | 由本地网络直接连接目标 | 临时检查本地网络,或不需要代理出口时 |
</div>
这三个模式是路由选择,不是速度档位。全局也要检查 GLOBAL 组究竟选了什么:如果选的是 DIRECT,结果仍然是直连;如果选的是另一个代理组,还要继续看那个组的选择。[Mihomo 运行模式说明](https://wiki.metacubex.one/config/general/)
直连模式也不等于退出客户端:系统代理、TUN 等入口可能仍开启。要停用接管,需要处理对应开关,不能只把模式改成“直连”。[Clash Verge Rev 名词解释](https://www.clashverge.dev/guide/term.html)
<figure class="guide-figure"><img src="/images/editorial/98a43bdd771dd4c6c5ec6b87bb5f0ebf679fa2b228dddbb764adecf50b0374e9.png" alt="请求进入客户端后,规则模式按规则分流,全局模式使用 GLOBAL 选择,直连模式使用本地网络" width="1000" height="670"><figcaption>图 1:模式作用于已进入客户端的连接;切模式不会补上接管范围的缺口。</figcaption></figure>
<h2 id="groups">02 换了节点没效果,可能换错了组</h2>
代理页里有“节点选择”“流媒体”“自动选择”等分组时,不要把它们当成一排作用相同的开关。规则通常先指向一个组,组再选节点,也可能继续选另一个组。
例如,一份配置把视频网站分给“影音”,普通网页交给“节点选择”。你在“节点选择”里换成节点乙,但“影音”仍直接选着节点甲,视频连接就可能继续走甲。只有“影音”选择了“节点选择”这个组,它才会沿着这条选择关系继续向下找出口。
<figure class="guide-figure"><img src="/images/editorial/417b203a4af30200b6ed3b37d0b0e823a9b47db49e2d743b1110b35329cc5de8.png" alt="规则命中影音组后,该组直接选择节点甲时不经过节点选择组;选择节点选择组时才跟随其中的节点乙" width="1000" height="610"><figcaption>图 2:两种配置的差别在于“影音”组的选择。组名只是配置中的名称,实际关系要查看当前选择。</figcaption></figure>
手动选择组(`select`)由你决定使用哪个选项;如果它选择的是自动选择组(`url-test`),后者仍会按自己的测速配置选择节点。想固定到具体节点,就检查整条选择路径,而不是只看最外层的组名。[手动选择组](https://wiki.metacubex.one/config/proxy-groups/select/)与[自动选择组](https://wiki.metacubex.one/config/proxy-groups/url-test/)
实际排查时,可以在连接详情里找策略、代理链或类似字段。不同界面展示顺序可能不同,重点是认出“命中了哪个组”和“最终使用哪个节点”。
<h2 id="order">03 先看顺序,再看规则写得对不对</h2>
Mihomo 的路由规则从上往下匹配。通常前面命中的规则就决定了后续策略,因此“更精确”不会自动获得更高优先级;精确规则如果排在已经覆盖它的规则之后,仍可能用不上。涉及 UDP 等条件时,还要注意目标策略是否具备相应支持。[路由规则与优先级](https://wiki.metacubex.one/config/rules/)
下面是用来理解顺序的片段,不是可以替换整个订阅的完整配置。`example.com` 是示例域名,“节点选择”必须换成你配置中真实存在的组名:
```yaml
rules:
- DOMAIN,video.example.com,节点选择
- DOMAIN-SUFFIX,example.com,DIRECT
- MATCH,节点选择
```
在这个例子里,访问 `video.example.com` 先命中第一条,交给“节点选择”;访问 `docs.example.com` 则命中第二条,使用直连。如果把前两条交换,`video.example.com` 也会先被域名后缀规则接住。
`DOMAIN` 对应完整域名;`DOMAIN-SUFFIX` 对应该域名及其子域名。末尾的 `MATCH` 用于接住前面没有匹配到的连接。不要为了让某个网站使用节点,就在前面塞一条覆盖所有连接的 MATCH:那会让后面的分流规则失去机会。
<h2 id="custom">04 在 Verge Rev 里给一个网站添加规则</h2>
先选一个你确实需要调整的网站。例如,某个域名在当前网络下直连不通,而你已有能访问它的节点。只改这一项,验证后再扩展范围。
1. 在“订阅”页面找到**正在使用的配置**,右键选择“编辑规则”。这里维护的是该订阅的自定义规则,可以保留在后续订阅更新中。
2. 新增规则,类型先选 `DOMAIN`,内容填写连接记录里的完整主机名,例如 `video.example.com`。不要填 `https://`、路径或整个网页地址。
3. 代理策略选择当前配置中实际存在的代理组;需要直连时选 DIRECT,需要使用节点时选相应的组,并确认组内选择。
4. 需要覆盖订阅中已有的分流结果时,放入**前置规则**,同时检查前面是否还有会先命中的自定义项。不要把它追加在已兜底的 MATCH 后面。
5. 保存并确认没有配置错误,保持规则模式,然后让目标应用重新发起连接。
界面入口与前置/后置规则的含义可参考 [Verge Rev 自定义规则](https://www.clashverge.dev/guide/rules.html)。这与直接改下载下来的订阅正文不同;后者可能被下一次更新覆盖。
一个网页可能同时访问登录、图片、视频和接口等多个域名。添加主站域名后页面只恢复了一部分,先查看失败连接,再补真正需要的域名。不要因为一个资源加载失败,就直接扩大成整类域名、全部应用或全部流量。
<h2 id="verify">05 改完以后,检查一条新连接</h2>
验证时保持订阅、模式和接管方式稳定,只调整刚才那条规则或对应组的选择。打开“连接”页面,清除筛选,重新访问目标内容,找到刚建立的连接,逐项检查:
- **目标是否相同:** 看实际域名或 IP,而不是只认浏览器标签页上的网站名。
- **规则是否符合预期:** 有没有命中新加的规则,还是先被另一条规则或规则集处理。
- **策略是否正确:** 命中的组是否是你刚才修改的组,组内有没有继续指向其他组或 DIRECT。
- **应用是否恢复:** 出口符合预期以后,再验证原先失败的操作,例如播放、登录或下载。
已有长连接不适合作为换规则、换节点后的唯一观察对象。可优先重连目标应用,或只关闭相关连接后重新测试;直接清空所有连接会影响其他正在使用的程序。
如果仍无法区分,可以做一次有控制的对比:记录当前设置,在全局模式中选择**同一个明确的节点**,重新建立目标连接。全局可用、规则模式不可用,提示你继续查分流和代理组;它并不能单独证明某一条规则错误,因为模式变化也可能影响其他配置行为。对比后切回规则模式,修正具体目标。
<h2 id="troubleshoot">06 几种常见现象,对应查哪里</h2>
<div class="table-wrap">
| 现象 | 下一步检查 |
| --- | --- |
| 换了节点,目标连接仍走旧节点 | 是否改错代理组、组里还有嵌套选择,以及观察的是否为旧连接 |
| 明明加了代理规则,却显示 DIRECT | 当前模式、规则顺序、实际域名,以及命中组是否选了 DIRECT |
| 全局能用,规则不能用 | 对比同一目标的新连接,确认规则模式的最终出口是否与全局相同 |
| 网页文字出现了,图片或视频失败 | 找失败资源的域名与连接,逐项判断,不只给主站加规则 |
| 完全找不到应用的连接记录 | 清除筛选、查看日志,再检查应用代理或 TUN 接管;规则还没到发挥作用的阶段 |
| 订阅更新后又不对了 | 是否改了会被覆盖的订阅正文、当前配置是否切换、原代理组是否还存在 |
</div>
如果连接已经走了预期节点,但仍出现域名解析异常,继续检查 [DNS 接管、加密和出口](/a/mihomo-dns-leak.html#dns-2)。如果客户端根本看不到目标流量,则回到[系统代理与 TUN 的排查步骤](/a/system-proxy-vs-tun.html#troubleshoot)。先根据连接记录确定问题发生在哪一步,再动对应设置,通常比不断切换三个模式更有效。
+1 -1
View File
@@ -1 +1 @@
<link rel="stylesheet" href="/css/tutorials.css"><div class="tutorial-body"><p>浏览器能打开网页,终端却一直超时;已经切到“全局”,游戏还是连不上;打开 TUN 后能用了,又担心所有网站都被送到国外。遇到这些情况,先分清两件事:<strong>流量有没有进入代理客户端,以及进入以后走哪个出口。</strong></p><p>系统代理和 TUN 主要解决第一件事,规则、全局和直连模式主要解决第二件事。本文以 Clash Verge Rev 和 Mihomo 桌面客户端为例,说明它们的区别、适用场景和检查方法。</p><nav class="guide-toc" aria-label="文章目录"><strong>阅读路线</strong><a href="#system-proxy">系统代理接管什么</a><a href="#tun">TUN 改变了什么</a><a href="#routing">为什么全局不等于全部</a><a href="#choose">应该用哪一种</a><a href="#switch">怎样切换和检查</a><a href="#troubleshoot">按现象排错</a><a href="#dns">DNS 还要单独看</a></nav><h2 id="system-proxy">01 系统代理:让应用按设置转交请求</h2><p>打开 Clash Verge Rev 的“系统代理”,客户端会修改操作系统的代理设置,把代理地址指向本机正在监听的端口。愿意读取并遵循这项设置的应用,就会把相应请求交给客户端处理。浏览器通常可以通过这种方式使用代理。<a href="https://www.clashverge.dev/guide/quickstart.html">官方快速入门</a></p><p>这里的关键是“应用遵循设置”。有的软件读取系统设置,有的软件使用自己的代理配置,还有的软件直接建立连接。同一台电脑上,浏览器正常、另一个应用不走代理,并不矛盾。</p><figure class="guide-diagram"><div class="diagram-label">图 1 · 系统代理依赖应用配合</div><div class="guide-flow"><div><b>应用读取设置</b><small>使用系统指定的代理</small></div><span aria-hidden="true">→</span><div><b>本机代理端口</b><small>请求进入 Mihomo</small></div><span aria-hidden="true">→</span><div><b>匹配出口</b><small>直连或代理节点</small></div></div><div class="guide-branch">不遵循系统代理的应用:仍按自己的网络设置连接,不会仅因这个开关而进入 Mihomo。</div><figcaption>这也解释了为什么“浏览器能用”不能代表电脑上每个应用都已经走代理。</figcaption></figure><p>如果应用提供 HTTP 或 SOCKS 代理选项,可以单独指向客户端的本机端口。地址通常是 <code>127.0.0.1</code>,端口应查看客户端当前设置,不要照抄别人的数字;HTTP、SOCKS 和混合端口也要对应正确。</p><p>终端工具同样需要看各自支持什么。以 Linux 上的 curl 为例,可以先用<a href="/a/m174.html#terminal">单条命令指定代理的方法</a>检查,不必为了一个工具马上接管整台电脑。</p><h2 id="tun">02 TUN:通过虚拟网卡接收流量</h2><p>TUN 会创建虚拟网络接口,并通过路由把符合接管条件的 IP 流量交给内核。应用不必先学会使用 HTTP 或 SOCKS 代理,因此它常用于系统代理无法覆盖的程序。Mihomo 可以处理通过 TUN 进入的 TCP、UDP 流量,但最终能否完成连接,还取决于配置、节点和目标服务。<a href="https://www.clashverge.dev/guide/term.html">官方名词解释</a></p><figure class="guide-diagram"><div class="diagram-label">图 2 · TUN 在网络路由这一层接管</div><div class="guide-flow"><div><b>应用发起连接</b><small>无需读取系统代理</small></div><span aria-hidden="true">→</span><div><b>系统路由 → TUN</b><small>进入虚拟网卡</small></div><span aria-hidden="true">→</span><div><b>Mihomo 处理</b><small>再决定实际出口</small></div></div><div class="guide-branch">被排除的地址、接口或其他未进入 TUN 的连接,仍可能走原来的网络路径。</div><figcaption>TUN 扩大了接管范围,但开关亮着不等于每一条连接都已被接管。</figcaption></figure><p>TUN 也有接管范围。自动路由、排除网段、IPv6 设置及其他 VPN 的路由,都可能影响实际路径。例如,把某个局域网网段排除在 TUN 之外,就是让它绕过这层接管;这与连接进入 Mihomo 后命中 <code>DIRECT</code> 规则不同。<a href="https://wiki.metacubex.one/config/inbound/tun/">Mihomo TUN 配置</a>、<a href="https://www.clashverge.dev/guide/bypass.html">代理绕过说明</a></p><p>日常使用图形客户端时,优先使用它提供的 TUN 设置。建立网卡和修改路由需要相应权限;Clash Verge Rev 的服务模式可让具有权限的后台服务启动内核,不代表必须一直以管理员身份运行整个界面。<a href="https://www.clashverge.dev/guide/term.html">服务模式说明</a></p><h2 id="routing">03 “全局”和 TUN 不是同一个维度</h2><p>把“规则”改成“全局”,改变的是进入内核后的出口选择。一个完全没有进入客Line truncated
<link rel="stylesheet" href="/css/tutorials.css"><div class="tutorial-body"><p>浏览器能打开网页,终端却一直超时;已经切到“全局”,游戏还是连不上;打开 TUN 后能用了,又担心所有网站都被送到国外。遇到这些情况,先分清两件事:<strong>流量有没有进入代理客户端,以及进入以后走哪个出口。</strong></p><p>系统代理和 TUN 主要解决第一件事,规则、全局和直连模式主要解决第二件事。本文以 Clash Verge Rev 和 Mihomo 桌面客户端为例,说明它们的区别、适用场景和检查方法。</p><nav class="guide-toc" aria-label="文章目录"><strong>阅读路线</strong><a href="#system-proxy">系统代理接管什么</a><a href="#tun">TUN 改变了什么</a><a href="#routing">为什么全局不等于全部</a><a href="#choose">应该用哪一种</a><a href="#switch">怎样切换和检查</a><a href="#troubleshoot">按现象排错</a><a href="#dns">DNS 还要单独看</a></nav><h2 id="system-proxy">01 系统代理:让应用按设置转交请求</h2><p>打开 Clash Verge Rev 的“系统代理”,客户端会修改操作系统的代理设置,把代理地址指向本机正在监听的端口。愿意读取并遵循这项设置的应用,就会把相应请求交给客户端处理。浏览器通常可以通过这种方式使用代理。<a href="https://www.clashverge.dev/guide/quickstart.html">官方快速入门</a></p><p>这里的关键是“应用遵循设置”。有的软件读取系统设置,有的软件使用自己的代理配置,还有的软件直接建立连接。同一台电脑上,浏览器正常、另一个应用不走代理,并不矛盾。</p><figure class="guide-diagram"><div class="diagram-label">图 1 · 系统代理依赖应用配合</div><div class="guide-flow"><div><b>应用读取设置</b><small>使用系统指定的代理</small></div><span aria-hidden="true">→</span><div><b>本机代理端口</b><small>请求进入 Mihomo</small></div><span aria-hidden="true">→</span><div><b>匹配出口</b><small>直连或代理节点</small></div></div><div class="guide-branch">不遵循系统代理的应用:仍按自己的网络设置连接,不会仅因这个开关而进入 Mihomo。</div><figcaption>这也解释了为什么“浏览器能用”不能代表电脑上每个应用都已经走代理。</figcaption></figure><p>如果应用提供 HTTP 或 SOCKS 代理选项,可以单独指向客户端的本机端口。地址通常是 <code>127.0.0.1</code>,端口应查看客户端当前设置,不要照抄别人的数字;HTTP、SOCKS 和混合端口也要对应正确。</p><p>终端工具同样需要看各自支持什么。以 Linux 上的 curl 为例,可以先用<a href="/a/m174.html#terminal">单条命令指定代理的方法</a>检查,不必为了一个工具马上接管整台电脑。</p><h2 id="tun">02 TUN:通过虚拟网卡接收流量</h2><p>TUN 会创建虚拟网络接口,并通过路由把符合接管条件的 IP 流量交给内核。应用不必先学会使用 HTTP 或 SOCKS 代理,因此它常用于系统代理无法覆盖的程序。Mihomo 可以处理通过 TUN 进入的 TCP、UDP 流量,但最终能否完成连接,还取决于配置、节点和目标服务。<a href="https://www.clashverge.dev/guide/term.html">官方名词解释</a></p><figure class="guide-diagram"><div class="diagram-label">图 2 · TUN 在网络路由这一层接管</div><div class="guide-flow"><div><b>应用发起连接</b><small>无需读取系统代理</small></div><span aria-hidden="true">→</span><div><b>系统路由 → TUN</b><small>进入虚拟网卡</small></div><span aria-hidden="true">→</span><div><b>Mihomo 处理</b><small>再决定实际出口</small></div></div><div class="guide-branch">被排除的地址、接口或其他未进入 TUN 的连接,仍可能走原来的网络路径。</div><figcaption>TUN 扩大了接管范围,但开关亮着不等于每一条连接都已被接管。</figcaption></figure><p>TUN 也有接管范围。自动路由、排除网段、IPv6 设置及其他 VPN 的路由,都可能影响实际路径。例如,把某个局域网网段排除在 TUN 之外,就是让它绕过这层接管;这与连接进入 Mihomo 后命中 <code>DIRECT</code> 规则不同。<a href="https://wiki.metacubex.one/config/inbound/tun/">Mihomo TUN 配置</a>、<a href="https://www.clashverge.dev/guide/bypass.html">代理绕过说明</a></p><p>日常使用图形客户端时,优先使用它提供的 TUN 设置。建立网卡和修改路由需要相应权限;Clash Verge Rev 的服务模式可让具有权限的后台服务启动内核,不代表必须一直以管理员身份运行整个界面。<a href="https://www.clashverge.dev/guide/term.html">服务模式说明</a></p><h2 id="routing">03 “全局”和 TUN 不是同一个维度</h2><p>把“规则”改成“全局”,改变的是进入内核后的出口选择。一个完全没有进入客Line truncated
@@ -43,6 +43,8 @@
一个具体例子:浏览器和下载工具访问同一域名,浏览器连接记录里显示了节点,下载工具却没有记录。此时应优先检查下载工具的代理设置或接管方式;反复切换全局,通常没有解决前面的缺口。
如果流量已经进入客户端,却仍走错节点,可以继续看[规则模式、代理组与实际出口的检查方法](/a/clash-rule-global-direct.html#groups),分清应该改哪一个组。
<h2 id="choose">04 按应用需求选择,不必一开始全部打开</h2>
| 你要完成的事 | 可以先这样做 |
@@ -0,0 +1,10 @@
# Inside the site's HTTPS server block; files are verified before publication.
# Hash URLs can be cached; retirement must replace article mappings and clear caches.
location ^~ /images/illustrations/ {
if ($uri !~ "^/images/illustrations/[a-f0-9]{64}\.(webp|png|jpg|gif)$") { return 404; }
try_files $uri =404;
etag on;
add_header Cache-Control "public, max-age=31536000, immutable";
add_header X-Content-Type-Options nosniff always;
add_header X-Illustration-Delivery static always;
}
+5 -3
View File
@@ -1,5 +1,7 @@
# FNA_V3 独立文章 API
2026-10-31新增[经白色机的固定发布封装](EDITORIAL_RELEASE.md):周期写作使用本机SSH经白色机到业务服务器,由`editorial:release`进程调用本页原API路由。公网编辑API保持关闭,进程权限不落盘;无需逐次修改生产.env或启用公网密钥。以下HTTP契约继续有效,服务器命令复用同一套验证、事务和回执。
状态:2026-10-27本地实施并联调;2026-10-29已随独立test预览提交、推送和部署,10篇教程真实API迁移通过后,test编辑接口已关闭且临时密钥移除。正式站现已切换,正式10篇教程亦通过同一API迁移;生产临时密钥用后删除,编辑接口默认关闭,后续明确写作/发布任务再按绑定环境启用并完成后关闭。test执行和回执沿[发布记录](RELEASE_PREFLIGHT_2026-10-28.md#当前门槛先test预览确认后再切正式2026-10-29),日常本地调用不受影响。用户明确采用本站独立接收 API,不经过 ATOM;不新增 ATOM 依赖。入口为 `http://fna-v3.loc/api/editorial/v1`,生产地址尚未指定。
## 职责与数据
@@ -8,7 +10,7 @@ ## 职责与数据
项目正文源保留可编辑稿;`editorial_drafts`保存收到并渲染后的冻结版本,发布读取该快照,不临时重新读取文件。`articles`为公开显示数据,草稿不写入它。`editorial_documents`按稳定`content_key`绑定本站文章;`editorial_versions`保留已发布版本和首次接管旧文的基线版本0;`editorial_publications`保存独立发布回执及后续处理状态。图片元信息在`editorial_assets`。
新API不调用旧接收器,不发送旧Telegram通知、IndexNow提交或ATOM请求。旧资源接收接口继续沿用原流程,不在本次改造范围;普通编辑API拒绝免费节点与小火箭ID两个自动资源栏目。旧接口/人工直接编辑同一文章会造成草稿基线变化,新API发布时返回409,不能静默覆盖并行修改。
新API不调用旧接收器,不发送旧Telegram通知或ATOM请求。2026-10-31起编辑文章新增/实质修改后具有独立IndexNow回执与失败重试,见[教程SEO通知](EDITORIAL_INDEXNOW.md);本地和测试不真实外发。旧资源接收接口继续沿用原流程,不在本次改造范围;普通编辑API拒绝免费节点与小火箭ID两个自动资源栏目。旧接口/人工直接编辑同一文章会造成草稿基线变化,新API发布时返回409,不能静默覆盖并行修改。
## 凭据与环境
@@ -114,9 +116,9 @@ ### 3 发布确认过的版本
- `status: published`:本次内容已写入本站公开文章表;这是所调用环境的状态,本地成功不代表生产成功。
- `articles`:各文章的`content_key`、`article_id`、`revision`和URL。
- `effects.cache/search/sitemap`:各后续处理的独立结果。搜索暂时失败不撤销已提交正文,返回`pending`,不能重发正文来弥补搜索失败。
- `effects.cache/search/sitemap/indexnow`:各后续处理的独立结果。搜索暂时失败不撤销已提交正文,返回`pending`,不能重发正文来弥补搜索失败。
后续处理为刷新本站响应缓存与热门数据缓存、同步本站搜索,以及使用数据库驱动的sitemap。缓存未刷新时sitemap也标记pending。不调用搜索引擎主动提交。
后续处理为刷新本站响应缓存与热门数据缓存、同步本站搜索,以及使用数据库驱动的sitemap。缓存未刷新时sitemap也标记pending。IndexNow以独立`effects.indexnow`记录,不与sitemap结果混用,见[教程SEO通知](EDITORIAL_INDEXNOW.md)。
### 4 查询、重试与回退
+33
View File
@@ -0,0 +1,33 @@
# 编辑文章 IndexNow
用户2026-10-31要求接入教程发布后的自动推送。新增或实际内容改变的编辑文章在发布事务写入IndexNow待处理状态,缓存刷新完成后提交当前有效URL。目标为IndexNow官方API,复用本站既有key及根目录验证文件,不生成/轮换密钥,不改旧资源接收器。
- `config/editorial.php` 的 `indexnow_enabled`:默认仅production开启,可用`EDITORIAL_INDEXNOW_ENABLED=false`关闭。local不会发出通知,测试使用Http fake。
- `PublicationEffects`保存`effects.indexnow`,包括状态、次数、HTTP状态和下一次重试时间;不保存key、响应正文或异常消息。只有200/202记done;202表示收到并待验证key。提交被接收不等于搜索引擎已经抓取或收录,见[官方协议](https://www.indexnow.org/documentation)。
- `editorial:indexnow-retry`挂接原Laravel调度,每5分钟检查一次,单次最多10个到期回执,防重叠;退避从5分钟递增,最大24小时。定时任务运行在FNA业务服务器,以原nginx身份执行,白色机仅SSH跳板。
- 已done的通知不重复调用;同一发布UUID重放不重发文章。网络结果未知或提交后进程崩溃可能重复通知同一URL,按至少一次投递处理,不能承诺第三方只收到一次。每次重试都重新确认文章仍公开、栏目启用且可索引。
- 内容未变、已撤下、不再允许索引时跳过;旧版本中没有IndexNow状态的历史发布回执不自动补推。暂时禁用不会丢弃已pending状态。
- 仅推送同一站点的规范文章地址;app.url、editorial.base_url、app.site_code必须一致,不跟随重定向,不从文章输入指定外部推送目标。
## 2026-10-31已部署与验证
功能提交`574812438338755b160453c4a574557365903506`已Git推送并部署正式cfn,独立分支`codex/editorial-indexnow-publish-20261031`,基线`d981a2aa4fa21abe4512ddd287a2f51f87b11197`。同名旧候选分支另有包含sitemap改动的并行提交415b5f8,保留未覆盖;本任务只部署IndexNow范围,没有捆绑其他SEO工作。
专项4项测试/52断言通过:新增/更新通知、同UUID去重、无变化跳过、429退避后202成功、旧回执不补推、禁用环境/域名错配拒发、撤下后停止重试。本地相关业务回归合计36项/344断言通过;其中共享工作区的sitemap测试未作为本次部署范围。
正式站现有188篇文章的核心内容与日期、所有旧编辑发布回执保持;生成标签模板哈希和data.ms并行目录保留。新重试命令以nginx实际运行,空队列返回processed=0/pending=0,已登记每5分钟调度;未为演练制造失败队列,也未宣称已观察到一笔真实失败的自动恢复。公网编辑API仍关闭,首页HTTP200。
2026-10-31 14:20:55北京时间,通过本机SSH→白色机→业务服务器,由新组件对现有`/a/system-proxy-vs-tun.html`执行一次真实通知验收,HTTP200,密钥文件HTTP200且内容匹配;未改正文、未重新发布、未改旧回执、未批量补推。只证明通知被接收,不代表已收录。已完成服务器侧验收,未做线上页面验收。精确证据见[回执](EDITORIAL_INDEXNOW_2026-10-31.json)。
私有恢复点:VPS-003 `/root/backups/cfn-indexnow-20261031/`,包含Git bundle、原HEAD/工作区状态、标签模板、文章核心字段与旧回执快照、真实提交事件和部署记录。回滚可检出基线,保留已有effects状态和内容;单独停推可设`EDITORIAL_INDEXNOW_ENABLED=false`,不要删除pending回执。普通发布继续通过[白色机发布封装](EDITORIAL_RELEASE.md)。
## 两个教程栏目sitemap已部署(2026-10-31)
基于并行IndexNow正式文档提交`ace6d74a18988697340ebcd15e2b79a4dee0e697`,只发布本批7个栏目/测试/文档文件,功能提交`252e0c38cb85d0c1331063b1019a2bb13c27ac8a`已推送`codex/tutorial-sitemap-20261031`并检出正式cfn。保留57481243的通知实现,不重复部署旧候选415b5f8,也不覆盖其并行验收记录。
本地34项/310断言通过。正式sitemap从25项变27项,精确增加`/client`与`/advanced`,旧集合无移除;首页、两栏目和system-proxy-vs-tun详情HTTP200,两栏目index/follow及自引用canonical通过。188篇正文核心、既有发布回执、生成标签模板哈希及data.ms并行目录保持。重试命令以nginx执行返回processed=0/pending=0,原项目调度存在,密钥文件HTTP200且内容匹配。
切换时曾因2秒PHP OPcache检查窗口出现新模板与旧控制器混用,验收脚本立即回滚。最终通过Unix FastCGI socket仅失效本批文件缓存,临时私有脚本用后删除;未重启共享PHP-FPM、未改其配置。原两次候选回滚后,接续并行IndexNow新基线完成本次限定发布。
本批未再次发送真实通知、不补交历史文章;上一节的真实HTTP200验收继续有效。已完成服务器侧验收,未做线上页面验收。脱敏验收见[栏目回执](TUTORIAL_SITEMAP_2026-10-31.json)。恢复点:VPS-003 `/root/backups/cfn-tutorial-sitemap-20261031/`,包含原HEAD/status、Git bundle、模板、前后运行摘要和opcode失效回执。仅回滚本批时检回ace6d74a并定点失效PHP缓存,保留新通知实现、内容及回执。
@@ -0,0 +1,56 @@
{
"base": "d981a2aa4fa21abe4512ddd287a2f51f87b11197",
"commit": "574812438338755b160453c4a574557365903506",
"branch": "codex/editorial-indexnow-publish-20261031",
"files": [
"app/Console/Commands/RetryEditorialIndexNow.php",
"app/Services/Editorial/IndexNowNotification.php",
"app/Services/Editorial/PublicationEffects.php",
"app/Services/Editorial/Publisher.php",
"app/Services/Editorial/ReleaseRunner.php",
"config/editorial.php",
"docs/maintenance/EDITORIAL_API.md",
"docs/maintenance/EDITORIAL_INDEXNOW.md",
"docs/maintenance/EDITORIAL_RELEASE.md",
"routes/console.php",
"tests/Feature/EditorialApiTest.php"
],
"checks": {
"enabled": true,
"public_api_enabled": false,
"key_valid": true,
"retry_scheduled": true,
"retry_command": {
"processed": 0,
"pending": 0
},
"existing_articles_and_receipts_unchanged": true,
"tags_preserved": true,
"homepage_http": 200
},
"backup_directory": "/root/backups/cfn-indexnow-20261031",
"status": "M resources/views/components/generated-tags-cloud.blade.php\n?? data.ms/",
"live_verification": {
"ok": true,
"key_file_http_matches": true,
"notification": {
"status": "done",
"attempts": 1,
"http_status": 200,
"urls": [
"https://clashfreenode.com/a/system-proxy-vs-tun.html"
],
"submitted_at": "2026-10-31T06:20:55+00:00",
"result": "received"
},
"verification_only": true,
"article_modified": false
},
"tests": {
"indexnow_tests": 4,
"indexnow_assertions": 52,
"local_regression_tests": 36,
"local_regression_assertions": 344
},
"parallel_branch_preserved": "codex/editorial-indexnow-20261031 (415b5f8ab57432ff238b6d83b83d1bee75c95c7b); sitemap changes not deployed in this task"
}
+51
View File
@@ -0,0 +1,51 @@
# 经白色机的固定文章发布流程
## 设计
维护脚本:`tools/editorial/release.py`(本机传输)、`tools/editorial/ssh_askpass.py`(只向OpenSSH认证组件提供登记密码)、`editorial:release`(业务服务器命令)。现有文章API负责资产、草稿、版本、链接校验、原子发布、回执和搜索缓存同步,契约见[EDITORIAL_API.md](EDITORIAL_API.md)。本封装不另写文章SQL,不经ATOM。
固定路线:本机SSH→VPS-001白色机→VPS-003 `/www/wwwroot/clashfreenode-new.com`。SSH强制ProxyCommand、既有主机密钥核验,禁用配置文件和已有连接复用,不接受自定义目标/命令,也没有直连回退。白色机仅转发SSH,不保存稿件、凭据或运行定时器。
远端固定以nginx运行`php artisan editorial:release`,命令校验production环境、真实项目路径和base_url。JSON由stdin传递。服务器内通过Laravel HTTP Kernel调用原有API路由,经过原认证、校验和控制器;无需本机或公网HTTP。运行身份使用现有服务器权限,不改SSH策略或管理员凭据。
进程内临时API认证值只保存在内存,寿命10分钟,每次内部请求后恢复原配置,结束/断开杀进程即消失;不写.env或公用credential.json,不重载配置、不启用公网编辑入口。签名预览也在同一命令内渲染,公网API关闭时这些预览URL不可从外部打开。旧API的手动操作契约仍保留,周期发布改用本封装。
## 调用
本机在项目目录执行,输出文件包含私有预览,权限600,不提交Git:
```sh
python3 tools/editorial/release.py catalog --input /私有目录/empty.json --output /私有目录/catalog.json
python3 tools/editorial/release.py source --input /私有目录/source.json --output /私有目录/source-result.json
python3 tools/editorial/release.py prepare --input /私有目录/bundle.json --output /私有目录/prepared.json
python3 tools/editorial/release.py review --input /私有目录/id.json --output /私有目录/review.json
python3 tools/editorial/release.py publish --input /私有目录/publish.json --output /私有目录/published.json
python3 tools/editorial/release.py status --input /私有目录/id.json --output /私有目录/status.json
```
- empty.json为`{}`;source.json为`{"article_id":真实整数ID}`。catalog/source只读,不创建release。
- bundle.json含`release_id`(UUID)、`articles`(原API字段)及可选`assets`。每个asset为`{"name":"diagram","base64":"实际PNG/JPEG/WebP/GIF字节的base64"}`,正文/封面用`file:diagram`占位;程序上传后替换为asset引用。单图≤8MiB、最多10图、总输入≤48MiB;不接收SVG,既有本站SVG可以按真实路径引用。新画的技术SVG可在本地渲染为PNG后通过资产API上传,无需为了配图部署程序。
- id.json仅`{"release_id":"原UUID"}`。服务器先保存稳定草稿ID/发布UUID,再调用API;相同bundle重复prepare不新建版本或重新抽取参数,相同release_id改正文拒绝409。改稿应显式创建新release并使用当前版本。
- review.json的`data.previews`含原模板渲染的HTML,`data.review`含hash和digest。先阅读及检查冻结版本;程序渲染通过不等于人类/浏览器视觉验收。正式HTML内含线上资源链接,禁止直接在本机浏览器打开加载;视觉检查在本地对应稿件完成。必须线上页面验收时仍按项目访问批准规则到Windows,不以取预览为由越界。
- publish.json为`{"release_id":"原UUID","expected_hash":"review中hash","review_digest":"review中digest"}`,不得盲填或以另一份稿件替换。程序先查回执;已发表则只重试后处理,草稿版本冲突返回失败。
- status会从API重新查询并核对公开正文,不只读本地台账。`phase=complete`要求内容/版本/上传图哈希和缓存/搜索/sitemap/IndexNow状态通过(无需通知的IndexNow skipped视为完成),且IndexNow通知为done或明确skipped;`published_pending`代表正文已提交但后续仍待处理,退出码2,不能据此另发正文。返回`published_at`来自服务器真实发布事务时间。
本机工具只输出结果文件路径及状态,不回显SSH认证、正文或预览。SSH断开、超时或非JSON输出都保存未知/失败状态,不自动重放写入;用原release_id查status。不存在草稿时沿原bundle恢复prepare。
## 状态与恢复
服务器台账`storage/app/private/editorial-releases/UUID.json`,权限600;原子替换并fsync,文件锁防并发,系统会在进程退出时释放锁。保存IDs先于写入API。台账记录prepared/reviewed/publishing/complete或published_pending;唯一发表事实仍以API事务回执为准。服务器台账损坏/丢失时须从原请求UUID和API回执恢复,不能另起ID重发。
回读校验包括真实版本、标题、摘要、slug、栏目、封面、正文哈希及内容寻址图文件SHA;点赞参数随结果返回供确认。文章完整HTTP页面及外部链接状态按任务另外验证,不能把内部Kernel渲染说成外部网络/浏览器验收。没有真实新稿时不向正式站发布演练文章。
上线前仅执行`2026_10_31_150000_add_article_display_timestamp.php`迁移(新增可空`sDisplayPublishedAt`);旧文显示回退原时间。新文草稿冻结0~21600秒偏移,首次发布计算展示时间;保留created_at、实际回执、点赞起点,旧文改稿不改展示日期。回滚程序保留新增可空列和历史发布记录,不删业务数据。
验证与当前部署状态见[2026-10-31发布记录](EDITORIAL_RELEASE_2026-10-31.md)。周期调度和额度唯一见[WEEKLY_TUTORIALS.md](WEEKLY_TUTORIALS.md)。
IndexNow的结果、环境开关及服务器延时重试见[教程SEO通知](EDITORIAL_INDEXNOW.md)。通知pending只重试后处理,不再次发表正文。
2026-10-31编辑发布已接入[IndexNow通知与重试](EDITORIAL_INDEXNOW.md),复用发布回执effects;通知pending不表示正文未发布,禁止为通知重发正文。
## 图片发布目录
2026-10-31首篇真实上传配图时发现正式 `public/images/editorial` 缺失。用户明确批准创建该专用目录并设为nginx所有、0755;已实施并完成真实文章发布。上级public/images权限未改变。以后部署预检该目录存在且执行身份nginx可写,禁止临时以root执行文章发布来绕过。回执见[首篇周期教程](ROUTING_MODES_2026-10-31.md)。
@@ -0,0 +1,66 @@
{
"base": "4fb57e494de1796d314698c6317eb58bc1acbed1",
"commit": "3a62bccbcdb2da0630e8c192b5b758c264624514",
"branch": "codex/editorial-release-20261031",
"files": [
"AGENTS.md",
"app/Console/Commands/EditorialRelease.php",
"app/Http/Controllers/Api/Editorial/EditorialController.php",
"app/Http/Middleware/EditorialAuthentication.php",
"app/Models/Articles.php",
"app/Services/Editorial/ProcessApi.php",
"app/Services/Editorial/Publisher.php",
"app/Services/Editorial/ReleaseRunner.php",
"database/migrations/2026_10_31_150000_add_article_display_timestamp.php",
"docs/content/WRITING.md",
"docs/maintenance/EDITORIAL_API.md",
"docs/maintenance/EDITORIAL_RELEASE.md",
"docs/maintenance/EDITORIAL_RELEASE_2026-10-31.md",
"docs/maintenance/WEEKLY_TUTORIALS.md",
"tests/Feature/EditorialApiTest.php",
"tests/Feature/EditorialReleaseTest.php",
"tools/editorial/release.py",
"tools/editorial/ssh_askpass.py",
"tools/editorial/test_weekly.py",
"tools/editorial/weekly.py"
],
"backup_directory": "/root/backups/cfn-editorial-release-20261031",
"backup": {
"articles": 188,
"tables": 23,
"backup_sha256": "b1ccc19cdc5e43a85ad85cf9b656ef2da97cbb07b23d49283078004e85d292ac"
},
"checks": {
"environment": "production",
"editorial_base": "https://clashfreenode.com",
"public_api_enabled": false,
"credential_file_exists": false,
"articles": 188,
"article_core_preserved": true,
"display_values": 0,
"process_api_catalog": true,
"editorial_articles": 10,
"tags_preserved": true,
"http": {
"/": 200,
"/advanced": 200,
"/a/system-proxy-vs-tun.html": 200,
"/api/editorial/v1/catalog": 503
},
"local_wrapper_through_white_host": true
},
"head": "3a62bccbcdb2da0630e8c192b5b758c264624514",
"status": "M resources/views/components/generated-tags-cloud.blade.php\n?? data.ms/",
"tested_new_production_publication": false,
"tests": {
"php_tests": 30,
"php_assertions": 268,
"python_tests": 5
},
"automation": {
"id": "fna",
"check": "15:00 Asia/Shanghai daily",
"weekly_target": 3,
"starts_on": "2026-11-02"
}
}
@@ -0,0 +1,22 @@
# 文章发布封装实施记录(2026-10-31)
已通过Git提交、推送并部署正式cfn。功能HEAD `3a62bccbcdb2da0630e8c192b5b758c264624514`,基线 `4fb57e494de1796d314698c6317eb58bc1acbed1`,分支 `codex/editorial-release-20261031`。后续仅记录文档的提交不改变此功能版本。
范围:固定本机SSH→白色机VPS-001→业务服务器VPS-003,服务器进程内调用原有文章API,恢复台账/发布回读,新文独立展示时间,以及本机每周三篇、每日15:00检查的计划工具。没有部署白色机写作任务,没有修改SSH/网络/原定时器,没有恢复test。
## 验证
- 隔离SQLite业务测试30项、268断言通过,覆盖原API、点赞、发布封装:冻结草稿、图片上传和SHA、真实模板渲染、未review拒发、并行版本冲突、锁互斥、过期权限拒绝、失败后配置恢复、已提交但响应丢失后按原UUID恢复、搜索pending只重试同步、正文回读检测外部改动。新文随机展示偏移冻结、0~21600秒范围、真实创建/年度点赞时间不改、旧文修改保留展示日期均通过。
- Python5项测试通过:三篇随机不同日期/每日15:00、漏跑回补、同日不连发、未决任务恢复和真实时间计数、跨周不积累未开始欠稿、固定白色机转发及主机核验。
- 本地指定可空字段迁移已完成;第一次沙箱连接MySQL被拒,按授权提升后执行成功。
- 正式站188篇文章的ID、slug、标题、正文、封面、栏目、创建/更新日期逐项保持;新增展示字段均为空,旧文显示不变。既有生成标签模板哈希和`data.ms/`并行目录保留。
- 真实业务服务器命令以nginx读取10篇编辑文章目录通过;本机新release.py经固定白色机链路调用同一目录也通过,未访问本机线上HTTP。
- 服务器侧HTTP:首页、/advanced、系统代理/TUN文章200;公网编辑目录503(保持关闭),公用编辑密钥文件不存在。进程内认证没有写入.env或凭据文件。
部署首次迁移因Git检出采用私有备份umask导致新代码文件不可被nginx读取,已自动回退;随后仅修正本次代码文件及路径的正常读取权限,沿原恢复点重试成功,私有配置/备份权限未放宽。未重置数据库或数据。
## 回滚与边界
私有恢复点位于VPS-003 `/root/backups/cfn-editorial-release-20261031/`:Git bundle、原HEAD/工作区状态、标签模板原件、23表一致性数据库备份、文章核心字段快照、提交及验收回执。正常代码回退检出上述基线并清响应缓存,保留新增可空列与既有文章/发布历史;不执行drop列或整库覆盖。暂停周期任务使用automation_update ID `fna`。
调度已更新为每周三篇、北京时间每天15:00,自2026-11-02当周开始;首轮自动写作未执行。为避免污染正式内容,本次没有在生产发布演练文章;端到端写入/恢复在隔离测试验证,生产验证为真实SSH、命令、API目录和服务器HTTP。已完成服务器侧验收,未做线上页面验收。精确回执见[JSON](EDITORIAL_RELEASE_2026-10-31.json)。
@@ -0,0 +1,30 @@
# Hardnerd 广告正式发布 · 2026-10-30
用户明确要求把此前Hardnerd广告放上去并发布,暂停后已恢复授权。此次只发布HN,不携带DPL/FUC广告或其他本地未提交功能。
## 当前实现
- 素材:`public/images/ads/hn-ad-quality-20261030.png`,1962×801,SHA-256 `d90b99505237090b4936b3ea6fbc175605accce40c7aa8dee1b0940a3e85895b`;采用此前参考HN网站完成的深炭灰、绿紫光晕、渐变Hardnerd品牌字、独立眼镜H版本,不是旧纯黑版。
- 位置:文章正文之后、标签之前,首页当前展示最新文章时同样显示;栏目列表不增加广告。满行宽高比2.45,圆角12px,无扫光,保留键盘焦点轮廓。
- 模板:`components/hn-article-ad.blade.php`,独立加载`public/css/hn-article-ad.css`一次;生产文章模板直接引入HN组件,不调用本地DPL/HN/FUC汇总组件。
- 生产`config/advertising.php`仅包含HN配置,`HN_AD_ENABLED`默认true,`HN_AD_URL`默认`https://hardnerd.net/`。链接新窗口打开,含`sponsored noopener noreferrer`。本地保留其他广告配置及`hn.loc`开发落地页。
## Git 发布与验收
生产原提交`a5c5540b977eec4035ba64c1ffc1fa6b6f682152`;基于该提交建立隔离工作区,仅提交5个应用文件,推送既有`tom/fn_b.git`新分支`codex/hn-ad-20261030`,正式目录`/www/wwwroot/clashfreenode-new.com`检出功能提交`f0a0f34d8b687f1286d82e1f26ff72619b11a9e1`。现有未提交`generated-tags-cloud.blade.php`逐字保留,未触碰`data.ms`或其他实例。无需重建全站前端构建产物、数据库迁移或修改Nginx、调度、Resource服务。
以正式nginx身份清理Blade/响应缓存后,25项服务器侧验收通过、0失败:首页、最新文章`fn20261030`和系统代理/TUN教程各出现一次HN,CSS仅加载一次,链接及rel正确,位置在正文后标签前;`/freenode`列表无新增HN。图片/CSS的正式HTTPS响应200、类型正确、完整SHA与提交素材一致;未携带DPL/FUC素材。回执见`output/hn-ad-release-20261030/release.json`与`verification.json`。
已完成服务器侧验收,未做正式线上页面验收或打开HN落地页。本文档后续同步提交只更新文档,不改变已验收应用文件。
## 恢复与停用
恢复包:VPS-003 `/root/backups/cfn-hn-ad-20261030`,含发布前Git bundle、原HEAD/status、并行差异、原文章模板、发布及验收回执;目录0700,私密回执0600。
单独停用可在生产环境设置`HN_AD_ENABLED=false`,按当前配置缓存方式刷新配置,再以nginx身份清响应缓存;不要禁用HN业务网站或撤回其他广告。代码回退先检查有无后续提交,仅撤回本次HN配置/组件/CSS/图片及show模板中的HN include;不得整份覆盖新文章模板或回退之后发布的其他功能。
## 广告文案定点更新(2026-10-30)
用户指定将底部“了解 HN ↗”替换为“硬核专线架构,品质网络体验”。内置image_gen以原图为编辑目标,仅替换底部绿色文案并去除箭头,保留品牌图形、字形、主副标题和背景。新素材路径/尺寸/hash见当前实现;完整提示词 `output/hn-ad-release-20261030/quality-text-prompt.txt`,旧图保留回退。模板替代文字同步。
应用提交48a97f2820e3549580d3c7d1dff79197a9d0431e已推送codex/hn-ad-copy-20261030并在正式cfn检出;只增加新版图片和更新HN组件引用。24项服务器检查全部通过,含正式图片HTTPS完整SHA及页面引用/尺寸/链接/位置;没有HN业务站部署。回执 `output/hn-ad-copy-20261030/release.json` / `verification.json`;恢复点 `/root/backups/cfn-hn-ad-copy-20261030`。后续文档提交不改应用文件。已完成服务器侧验收,未做线上页面验收。
+2
View File
@@ -1,5 +1,7 @@
# 本地插画资源与配图
当前展示架构已于2026-10-30改为FNA独立静态副本;Resource仍管理原稿、图池与固定分配。新建文章、同步、退役和当前验收统一见[静态配图副本](LOCAL_ILLUSTRATIONS.md)。下文此前动态媒体访问及分配数量属于历史记录。
2026-10-27修正此前错误的本地配图实现。当前状态(2026-10-29):本地、独立test与正式cfn均已接入;正式资源为https://resource-v2.gemcook.net,22猫/15狗,84/90篇固定分配与test逐项一致。正式消费者仅fna-v3项目read/write,test仍独立只读。部署、备份、权限与323项服务器验收统一见[正式切换](RELEASE_PREFLIGHT_2026-10-28.md#正式切换2026-10-29)。下文“仅本地/正式未切换”为此前历史状态。
素材及图池事实由 [Resource V2 插画集合说明](/Users/hellcat/Documents/GemCodes/resource.loc/v2/docs/CFN_ILLUSTRATIONS.md) 维护,本页维护FNA_V3消费方式。仅本地,未提交、推送或部署。此前“只用12张猫图替换显示”没有完成原图池扩充;旧哈希算法也没有避免连续重复,相关旧验收不足以证明需求已完成。
+11
View File
@@ -0,0 +1,11 @@
# 插画交付接收
协议与画师操作唯一正文:[Resource交付说明](/Users/hellcat/Documents/GemCodes/resource.loc/v2/docs/ILLUSTRATION_DELIVERY.md)。
本项目新增 `illustrations:sync-deliveries`,开关 `ILLUSTRATION_DELIVERY_ENABLED=false` 默认关闭。VPS-003正式目录运行fna-illustration-delivery.timer(nginx,每分钟)。复用已有消费者凭据和LocalIllustrations下载/原子清单能力:只缓存本批资产,不执行全量旧文章同步;先验证所有交付资产已在清单/静态目录中,哈希一致才ACK;失败下轮重试,不重分配既有文章、不删除图片。没有新批次时只查交付队列,不下载图池。页面请求不调用该任务。
Resource持有唯一批次状态,FNA不复制完整提示词或私有原稿。Resource未完成的同步回执不影响已有静态图片。新增图片只扩充后续文章的候选池。
回退先停fna-illustration-delivery.timer和service、关闭开关;静态副本和旧配图保留。原同步/静态展示维护见[静态配图](LOCAL_ILLUSTRATIONS.md)。批次验收与具体SHA由Resource发布记录维护。
当前已上线,真实自动回执与既有停用图片的验收差异见[发布记录](/Users/hellcat/Documents/GemCodes/resource.loc/v2/docs/ILLUSTRATION_DELIVERY_RELEASE.md)。
@@ -0,0 +1,36 @@
{
"commit": "21bb77c17644087fa6624fb276911e7a0cd894bd",
"restored": 20,
"managed_articles": 178,
"verified_unique_image_urls": 33,
"article_core_unchanged": true,
"unrelated_local_selections_unchanged": true,
"source_references_and_disabled_states_unchanged": true,
"parallel_template_unchanged": true,
"example_slug": "fn20261014",
"example_original_image": "https://clashfreenode.com/images/illustrations/c7e661cdf0eb1a813b86efe8c1b062f9738fc6c945471cc990092706619fa34f.webp",
"example_article_http": 200,
"restored_original_assets": {
"fn20260731": "13caface-3d1e-4365-b460-2ea47d893d03",
"fn20260806": "d6a919eb-f66d-45de-81ee-26a3ca853270",
"fn20260816": "e27f185f-1127-4e62-93b3-433cfc541953",
"fn20260817": "d6cd3ea0-824b-4f5f-91e0-fc073c043f28",
"fn20260818": "c4a8150b-b41a-4567-89af-91bbd3ec9705",
"fn20260821": "13caface-3d1e-4365-b460-2ea47d893d03",
"fn20260827": "d6a919eb-f66d-45de-81ee-26a3ca853270",
"fn20260912": "e27f185f-1127-4e62-93b3-433cfc541953",
"fn20260913": "d6cd3ea0-824b-4f5f-91e0-fc073c043f28",
"fn20260914": "c4a8150b-b41a-4567-89af-91bbd3ec9705",
"fn20260917": "13caface-3d1e-4365-b460-2ea47d893d03",
"fn20260923": "d6a919eb-f66d-45de-81ee-26a3ca853270",
"fn20261003": "e27f185f-1127-4e62-93b3-433cfc541953",
"fn20261004": "d6cd3ea0-824b-4f5f-91e0-fc073c043f28",
"fn20261005": "c4a8150b-b41a-4567-89af-91bbd3ec9705",
"fn20261008": "13caface-3d1e-4365-b460-2ea47d893d03",
"fn20261014": "d6a919eb-f66d-45de-81ee-26a3ca853270",
"fn20261026": "e27f185f-1127-4e62-93b3-433cfc541953",
"fn20261027": "d6cd3ea0-824b-4f5f-91e0-fc073c043f28",
"fn20261028": "c4a8150b-b41a-4567-89af-91bbd3ec9705"
},
"verified_at": "2026-10-31T05:28:32Z"
}
@@ -0,0 +1,17 @@
# 独立图片副本保留修复 · 2026-10-31
用户明确要求修复:源端(Resource/ATOM管理)的删除或停用不得影响FNA已保存副本。此次恢复原图,不采用此前候选换图方案。
根因:5张源资产停用后,全量同步把20篇旧文章的本地selection置null,文件实际仍完整。首次交付实现已改为只缓存交付批次,停止触发全量旧文同步,但旧null映射留存。此次同步同时修正源端selection消失时误删本地关联的问题。
功能提交`21bb77c17644087fa6624fb276911e7a0cd894bd`,基于当前正式`26cb1ed7244de9209ec7494e8525a4d12f7609fa`隔离构造,仅LocalIllustrations和专项测试。源端各种不可用状态均保留已验证本地副本;本地文件也异常时报告pending但保留关联,不让同步破坏恢复信息。不改用户图片GET性能,不改Source、交付timer或广告,不重开test。
本地40项业务测试/305断言通过,覆盖停用、撤销发布/权限、源文件缺失/损坏、源selection消失、无网络读取和并发分配。恢复从备份的原Resource固定引用精确取回20个asset ID,只使用FNA既存且SHA一致的图片;不重新开启源资产、不替换成别的图片、不改Source引用/游标或文章正文。其余本地映射和并行生成模板须逐项保持。
执行恢复点:VPS-003 `/root/backups/cfn-independent-images-20261031/`;包含原本地清单、20项原关联恢复计划及最终验收JSON。此前备份`/root/backups/cfn-empty-images-20261031/`中的候选换图计划未执行。正式部署、HTTP与恢复覆盖结果以最终验收回执为准。
回滚代码可检回基线并清响应缓存;不要把null清单恢复覆盖到后来新增分配。如确需撤回本次数据修复,只能在锁内核对当前值仍为本次恢复值后逐项恢复目标20项旧值,保留其他文章、文件和交付数据。停用旧逻辑的全量同步,避免再次清空。
## 已完成
功能提交已推送`codex/independent-local-images-20261031`并部署正式站。2026-10-31 05:28:32 UTC完成20项原关联恢复,178篇资源文章均返回本站非空图片,33个实际引用的独立URL逐个HTTP200、Nginx静态交付及SHA验证通过;截图fn20261014详情HTTP200并包含原图。其余本地关联、Source全部引用/游标和资产停用状态、文章核心字段、并行模板摘要均不变。没有执行新文章发布、通知或IndexNow。已完成服务器侧验收,未做线上页面验收。详见[最终回执](INDEPENDENT_ILLUSTRATIONS_FIX_2026-10-31.json)。
+59
View File
@@ -0,0 +1,59 @@
# FNA 静态配图副本
用户2026-10-30确认:Resource保留素材/图池/固定分配,FNA保存公开展示副本,由本站Nginx提供图片。仅猫狗资源栏目,教程图片沿原路径不改;不改变Resource的其他调用方。
## 数据与请求路径
- `public/images/illustrations/<sha256>.<ext>`:图片本体,按内容去重,同图多篇只存一份。运行数据不进入Git。
- `storage/app/private/illustrations/manifest.json`:资产元数据和pool→slug→asset映射,0600;只含已公开图片地址,不含消费者密钥。写入加锁并通过rename原子切换,读取不加写锁。
- `LOCAL_ILLUSTRATIONS_MIRROR_ENABLED=true`:启用本地展示;Resource原开关与精确环境基址仍用于接收/同步。
- 文章模型读取只读本地清单,请求内复用解析结果;不发Resource请求、不查图片数据库、不算文件hash,也不在用户访问时下载或补图。
- 浏览器请求固定哈希地址,Nginx直接返回文件,支持ETag/Last-Modified/304,缓存一年且immutable;规则见[静态配置](../deployment/illustrations-static.nginx)。staging还须在该location保留noindex头。不存在或格式不符的路径直接404,不能回落Laravel动态路由。
## 创建文章和同步
新文章接收仍先向Resource取得持久分配,然后下载副本;核对注册域名/公开media UUID、大小上限20MiB、SHA-256及真实图片格式/像素上限,最后原子发布文件/清单,成功后才返回本地URL交给文章保存。相同内容复用文件,重试沿用原配图;下载失败不写入无效清单或返回远程URL。
```sh
php artisan illustrations:sync-local
# 仅在确需为既有公开文章补建Resource分配、且持有write权限时:
php artisan illustrations:sync-local --assign-missing
```
命令强制读取Resource实时快照,不采用失败回退缓存;预存池内图片和固定选择,整批校验完成后切换清单,并清站点响应/点赞侧栏缓存。清单切换前失败保留旧清单,未被引用的完整文件可留待后续复用,不自动清理。同步不发布/修改文章正文,不影响点赞计划、URL或计数。不新增服务器cron/后台任务。
## 不满意、撤回与删除
要替换图片,先在Resource修改受影响文章的selection,再同步FNA并刷新页面缓存;新哈希URL自然换图。仅移出pool不改变旧selection,扩池也不洗牌旧文章。
Resource物理文件丢失时,已验证的FNA副本仍可继续展示;本地文件丢失时浏览器会404,运行同步可重新下载,访问请求不负责修复。2026-10-31用户明确修正:源端删除、停用、撤销发布或授权均不影响FNA已有的独立副本与固定关联;源端selection消失时也保留本地关联。只有FNA本站明确撤图才停止展示。同步时若本地文件也缺失或损坏,仅报告pending并保留关联供恢复,不在用户请求时修复。同步不自动删除任何共享副本;退役需先确认无文章/正文引用,再清理指定副本及相关CDN缓存。
长期公开缓存意味着不能承诺撤销Resource后立即让所有历史URL失效。FNA副本是独立公开发布物,需单独处理引用、源站文件及缓存;不要把Resource的即时撤回语义套到FNA静态副本。
## 部署与恢复
先备份代码、环境、Nginx及旧清单;基于当前正式提交构造仅本次文件的Git提交并推送,保留已上线点赞功能和并行生成模板。先test检出→同步→核对覆盖和哈希→启用开关/静态location→验收,再沿同一提交更新正式并执行相同迁移。test和正式各保存一份副本/清单,不共享私有凭据。
回退仅关闭LOCAL_ILLUSTRATIONS_MIRROR_ENABLED并清配置/响应缓存,恢复原Resource显示路径;保留副本及Resource引用,不删除资产或回灌整库。新接收文章原始sThumb可能已经是本地URL,回退时继续保留静态文件和location。不要通过直接删除图片测试生产修复。
## 2026-10-30 执行与验收
功能提交`ce27dbdd1eb206a9b7e7ac9b5a1c77778ed75e03`(后续仅文档提交`c663829c6dcc4295c08e6665883380a0e9a37d0d`),基于最新正式`f315215f6f64cf1b200d67fc426a9071ff557a09`隔离构造并已推送`codex/static-illustrations-20261030`。保留已上线年度点赞及并行生成模板;没有复制本地旧Git历史或广告实现。
本地已启用,37张副本覆盖160篇;35项测试/277断言通过,涵盖下载校验、去重、失败原子性、并发分配、无网络读取,以及camelCase `sThumb`在模型/数组/JSON中的一致性。对外返回本站绝对URL,清单只存相对路径;侧栏缓存随同步清理。
test与正式均按同一功能提交部署。test 37张覆盖174篇,283项服务器检查通过,含关闭Resource客户端后的无缓存页面验证。正式37张覆盖176篇,246项服务器检查通过,正文/标题/slug/原始缩略图及年度点赞参数的部署前后摘要一致。最终HTTP、完整文件SHA、缓存/304/404、全量模型与数组同源图片、页面及真实接收helper既有分配重放结果见[本次发布回执](STATIC_ILLUSTRATIONS_RELEASE_2026-10-30.json)。未执行真实新文章接收、通知或IndexNow,未做线上页面验收。
VPS-003私有恢复点`/root/backups/cfn-static-illustrations-20261030/`保存原环境、Nginx、部署前身份摘要和逐项验收JSON。运行位置:正式`/www/wwwroot/clashfreenode-new.com`,test`/www/wwwroot/fna-v3-test`;两者独立目录和清单,静态location分别引入`/etc/nginx/snippets/fna-illustrations-production.conf`和`fna-illustrations-staging.conf`。新增目录由nginx写入,公开文件0644/目录0755,私有清单0600/目录0700。Source代码及其37张原文件保持原位;未新增定时同步或清理任务。
2026-10-30用户随后要求取消test,已下线;前述test验证为退役前历史结果,今后不作为在线入口。详见[test下线记录](TEST_RETIREMENT_2026-10-30.md)。
## 自动交付接收(2026-10-30)
新增按待交付批次触发的服务器定时同步,见[交付接收](ILLUSTRATION_DELIVERY.md)。此前“未新增定时同步”是静态副本首次上线时的记录。
## 2026-10-31 旧文章空白配图排查
服务器只读核对:当前FNA HEAD 26cb1ed7244de9209ec7494e8525a4d12f7609fa,47份静态资产文件均存在且SHA一致;178篇资源文章中20篇免费节点旧文章sThumb输出为null,包括fn20261014。Resource实时快照对应20项均为asset_disabled,可用猫图21张。根因为交付首次全量同步把已有5张停用资产所关联的20项本地映射置空;沿[交付发布记录](/Users/hellcat/Documents/GemCodes/resource.loc/v2/docs/ILLUSTRATION_DELIVERY_RELEASE.md)核实。不是本次重新停用或文件丢失。
已在VPS-003 `/root/backups/cfn-empty-images-20261031/`保存Resource一致性备份、引用/本地清单快照及精确20项候选替换计划。候选只使用当前可用猫图,避开相邻文章同图,计划仅更新相应selection与本地清单,不重启停用资产、不改正文/其他selection或游标。最初的换图方案未执行。用户随后明确要求保留原本地图片并授权修复,因此改为恢复原关联,源端5张资产仍保持停用,不执行候选换图计划。后续执行结果见[独立副本修复记录](INDEPENDENT_ILLUSTRATIONS_FIX_2026-10-31.md)。
@@ -128,3 +128,7 @@ ## 文章点赞增量发布(2026-10-29)
用户随后授权上线新增一次性年度额度,并补齐未配置教程。正式cfn应用提交更新为`ea394987069cc0e7a980c60ebe2dc845c03b5fbe`(已推送`codex/article-like-growth-20261029`);本次仅点赞功能、指定三列迁移及关联规范,不携带广告、其他本地修改或Resource变更。10篇教程已补缺项,原7篇既有参数保留,3篇全0新文补全默认值,184篇文章及174篇非编辑资源数据保留。现有调度仍每分钟唤起Laravel、业务任务每5分钟运行;为修复已存在的文件缓存权限问题,只有该站调度PHP改由nginx用户执行,并恢复6个root缓存项归属。以nginx运行已成功。
恢复点为VPS-003:/root/backups/cfn-likes-20261029/;精确额度、验证、当前文档提交及回退唯一正文见[文章自动点赞维护](ARTICLE_LIKES.md)和[发布回执](ARTICLE_LIKES_RELEASE_2026-10-29.json)。服务器侧HTTP通过,未做线上页面验收。test保持原部署,本次没有重新启用编辑API或改动统计、广告、配图授权。
## 静态配图副本增量发布(2026-10-30)
功能提交`ce27dbdd1eb206a9b7e7ac9b5a1c77778ed75e03`已推送并部署test和正式,基于最新正式f315215保留年度点赞及并行生成模板;未发布广告。Resource保留素材/图池/分配,FNA保存按SHA去重的公开副本,Nginx直接提供。37份文件覆盖正式176篇、test174篇;35项/277断言自动测试、test283项及正式246项服务器检查均通过。正文/原始字段和年度点赞参数摘要不变,未新增后台任务或Resource权限。机制、恢复点和退役边界见[静态配图维护](LOCAL_ILLUSTRATIONS.md),逐项回执见[验收JSON](STATIC_ILLUSTRATIONS_RELEASE_2026-10-30.json)。已完成服务器侧验收,未做线上页面验收。
@@ -0,0 +1,173 @@
{
"release_id": "daabedf9-a81c-49ca-995b-7b6832dd2254",
"published_at": "2026-10-31T06:58:28+00:00",
"phase": "complete",
"receipt": {
"publication_id": "c7f9be21-3914-43f1-b7e5-9e7b49ef224d",
"status": "published",
"articles": [
{
"content_key": "clash-routing-modes",
"article_id": 382,
"revision": 1,
"content_changed": true,
"url": "https://clashfreenode.com/a/clash-rule-global-direct.html"
},
{
"content_key": "system-proxy-vs-tun",
"article_id": 376,
"revision": 2,
"content_changed": true,
"url": "https://clashfreenode.com/a/system-proxy-vs-tun.html"
}
],
"effects": {
"indexnow": {
"status": "done",
"attempts": 1,
"http_status": 200,
"urls": [
"https://clashfreenode.com/a/clash-rule-global-direct.html",
"https://clashfreenode.com/a/system-proxy-vs-tun.html"
],
"submitted_at": "2026-10-31T06:58:29+00:00",
"result": "received"
},
"cache": {
"status": "done"
},
"search": {
"status": "done",
"method": "meilisearch",
"index": "cfn_articles_v3",
"documents": 2
},
"sitemap": {
"status": "done",
"method": "database-driven"
}
}
},
"readback": [
{
"content_key": "clash-routing-modes",
"article_id": 382,
"revision_matches": true,
"content_matches": true,
"body_sha256": "b9986ade5893115611f8a02070f5e98ba2fb8b7d9a100dff39e11ff60876c5c2",
"like_growth": {
"seven_day_remaining": 29,
"yearly": 50,
"one_year_target": 241,
"one_year_added": 0,
"one_year_started_at": "2026-10-31 06:58:28"
}
},
{
"content_key": "system-proxy-vs-tun",
"article_id": 376,
"revision_matches": true,
"content_matches": true,
"body_sha256": "255db797e5e1403ee779e960e2129558e160badf0fe53f1822250b8d45e0ddb3",
"like_growth": {
"seven_day_remaining": 0,
"yearly": 50,
"one_year_target": 106,
"one_year_added": 0,
"one_year_started_at": "2026-10-29 13:30:35"
}
}
],
"display_published_at_utc": "2026-10-31 02:10:28",
"http": {
"new_page": 200,
"chapter_anchors": [
"custom",
"groups",
"modes",
"order",
"troubleshoot",
"verify"
],
"images": [
{
"path": "/images/editorial/417b203a4af30200b6ed3b37d0b0e823a9b47db49e2d743b1110b35329cc5de8.png",
"status": 200,
"sha256_matches": true
},
{
"path": "/images/editorial/98a43bdd771dd4c6c5ec6b87bb5f0ebf679fa2b228dddbb764adecf50b0374e9.png",
"status": 200,
"sha256_matches": true
}
],
"links": [
{
"target": "/a/clash-verge-rev-windows.html#enable",
"status": 200,
"anchor_exists": true
},
{
"target": "/a/m173.html#enable",
"status": 200,
"anchor_exists": true
},
{
"target": "/a/mihomo-dns-leak.html#dns-2",
"status": 200,
"anchor_exists": true
},
{
"target": "/a/system-proxy-vs-tun.html#routing",
"status": 200,
"anchor_exists": true
},
{
"target": "/a/system-proxy-vs-tun.html#troubleshoot",
"status": 200,
"anchor_exists": true
}
],
"incoming_link": true,
"directory": {
"owner": "nginx",
"mode": "0o755"
},
"head": "77f9b09c58b46ef2bbe0882ec89194bf25aa82cd"
},
"local_browser": {
"checks": [
{
"width": 1360,
"scroll": 1360,
"headings": [
"01 三个模式,改变的是出口选择",
"02 换了节点没效果,可能换错了组",
"03 先看顺序,再看规则写得对不对",
"04 在 Verge Rev 里给一个网站添加规则",
"05 改完以后,检查一条新连接",
"06 几种常见现象,对应查哪里"
],
"brokenImages": [],
"tables": 2,
"images": 2
},
{
"width": 390,
"scroll": 390,
"headings": [
"01 三个模式,改变的是出口选择",
"02 换了节点没效果,可能换错了组",
"03 先看顺序,再看规则写得对不对",
"04 在 Verge Rev 里给一个网站添加规则",
"05 改完以后,检查一条新连接",
"06 几种常见现象,对应查哪里"
],
"brokenImages": [],
"tables": 2,
"images": 2
}
],
"blockedOrigins": []
}
}
@@ -0,0 +1,36 @@
# 规则、全局与直连教程 · 2026-10-31
## 本次授权与范围
用户要求“现在就来一篇,当检测触发了”。本次作为提前的人工触发登记到2026-10-26周的 `2026-10-26-manual-1` 槽位,不改变2026-11-02起的每周三篇计划。本篇已按真实发布回执计入当周额度。
新文内容键 `clash-routing-modes`,路径 `/a/clash-rule-global-direct.html`,栏目综合教程。两张解释图、一张沿用现有样式的封面。系统代理/TUN文章只在 `#choose` 前补一个新文 `#groups` 入口,其余内容不改。新文链接Windows入门 `#enable`、Mac入门 `#enable`、TUN `#routing` / `#troubleshoot`、DNS `#dns-2`。
## 资料与质量检查
2026-10-31阅读 Mihomo 官方运行模式、路由规则、手动/自动代理组文档,以及 Clash Verge Rev 名词解释、自定义规则文档。准确链接保留在正文。原创示例使用example.com,不把配置片段写成完整可直接导入的订阅。未开展客户端真机联网实测,此边界只留维护记录。
本地实际模板桌面1360和手机390检查:均无横向溢出、2张正文图无破图、2张表格正常渲染、6个章节锚点存在。浏览器请求先按本地origin白名单拦截;没有本机线上页面访问。初次检查发现本地Vite未运行,启动原5187开发服务后复检通过,未改样式。正式签名预览由VPS-003内部Kernel渲染,未在本机打开其线上资源。
## 发布与恢复
- release_id:`daabedf9-a81c-49ca-995b-7b6832dd2254`
- publication_request_id:`c7f9be21-3914-43f1-b7e5-9e7b49ef224d`
- draft hash:`6ebc848487be507cd71e61016bf1232f1fc7c28b4042f019ff63654c8e29c486`
- 正式冻结默认值:i7like 29,i365like 50,一次性年度目标241;显示偏移17280秒。旧文设置不变。
- 本地已通过API发表:新文ID366/版本1,TUN ID365/版本2;本地IndexNow禁用并返回skipped。
- 正式首次publish失败;原ID status确认尚无发表回执,草稿仍draft。VPS-003错误为ContentRenderer.php:83 mkdir Permission denied;公开图片目录 `public/images/editorial` 不存在,上级root:root0755,API运行身份nginx无法创建。私有资产上传目录nginx:nginx0700正常。
- 创建该专用目录并设nginx:nginx0755的操作被自动审批拒绝(持久生产权限变更);用户随后明确批准“允许,仅创建这个专用目录并继续发布”,已按该范围创建并验证;其他目录所有权与权限未改。沿原release恢复,未另起发布请求。
- 私有工作文件:本机 `/private/tmp/fna-modes-20261031/`;服务器原release台账位于 `storage/app/private/editorial-releases/daabedf9-a81c-49ca-995b-7b6832dd2254.json`。
## 最终验收
正式发布完成:2026-10-31 14:58:28北京时间(服务器回执06:58:28 UTC),新文ID382/版本1,TUN ID376/版本2。展示时间比实际时间提前17280秒(4小时48分);点赞29/50/241已回读,旧文106年度目标及起点保留。新文全文与冻结版、两文版本、三张上传图片文件SHA由发布封装回读一致。
IndexNow由VPS-003在14:58:29北京时间提交新文和旧文更新两条URL,HTTP200、attempts1;白色机仅转发SSH。缓存、Meilisearch与sitemap均done,phase complete。此结果表示通知接收,不表示搜索引擎已收录。
服务器侧真实HTTP:新文200,2张正文图200且SHA一致;5条正文关联链接200且锚点存在,TUN旧文入向链接存在,6个章节锚点齐全。目录nginx所有/0755回读通过。已完成服务器侧验收,未做线上页面验收。本机浏览器只验收本地实际模板。
周期台账已用原release回执record到2026-10-26-manual-1,实际发表时间用于计数;2026-11-02当周三个计划未改。正文、图源、PNG、渲染HTML、关系索引同步保存,机器可读回执见[发布证据](ROUTING_MODES_2026-10-31.json)。
如需回退,旧文可从API版本1创建回退草稿,新文保留同URL通过API修订;不直接SQL修改,也不为撤回图片删除共享内容寻址资源。专用图片目录是API后续发文必需部署项,新增部署前应检查该目录归属与nginx写入能力。
+7 -3
View File
@@ -1,6 +1,6 @@
# FNA_V3 SEO 优化建议与执行清单
评估日期:2026-10-22,Asia/Shanghai。状态:**分析与建议文档已完成;SEO-001 的部署定位已由用户确认,配置改造尚未实施;SEO-020 于2026-10-27完成本地教程正文更新,设备实测及生产验收未做,D02首页最新免费节点全文展示于2026-10-27本地完成,其余项目尚未实施**。本文件是后续 SEO 工作的唯一执行清单;按 `SEO-001` 至 `SEO-036` 跟踪,实施后在本文件更新结果,不另建重复的“最新版计划”。
评估日期:2026-10-22,Asia/Shanghai。状态:**分析与建议文档已完成;SEO-001 的部署定位已由用户确认,配置改造尚未实施;SEO-020 于2026-10-27完成本地教程正文更新,设备实测及生产验收未做,D02首页最新免费节点全文展示于2026-10-27本地完成,其余项目按分项记录;2026-10-31已发布编辑文章IndexNow通知与两个教程栏目sitemap(见SEO-013/033)**。本文件是后续 SEO 工作的唯一执行清单;按 `SEO-001` 至 `SEO-036` 跟踪,实施后在本文件更新结果,不另建重复的“最新版计划”。
本轮依据当前代码、当前本地数据库、重新取得的 HTTP 响应及受限浏览器检查形成结论。网站源码、样式和业务数据未作修改。当前三款 DPL 广告属于已存在的实现,纳入分析基准并保留。网站仍在独立本地副本中开发;用户随后确认未来替换现有 cfn,并支持同一套代码部署多个同类站点,ClashFreeNode 为主力站,尚未实际部署或迁移。
@@ -182,7 +182,7 @@ ## 5 执行总表
| [ ] | SEO-010 | 分类、标签、搜索的标题与语义层级 | P1 | 001、004 | 已确认 |
| [ ] | SEO-011 | 生成真实、干净的页面简介 | P1 | 010 | 已确认 |
| [ ] | SEO-012 | 分离真实内容日期并统一时间基准 | P1 | 003 | 已确认/条件性风险 |
| [ ] | SEO-013 | 统一 sitemap 的集合和 lastmod | P1 | 003、004、008、012 | 已确认 |
| [ ] | SEO-013 | 统一 sitemap 的集合和 lastmod | P1 | 003、004、008、012 | 部分实施:教程栏目,见正文 |
| [ ] | SEO-014 | 建立长期内链和内容导航 | P1 | 005、009、018 | 已确认/策略建议 |
| [ ] | SEO-015 | 整理标签与重复主题页 | P1 | 002、003 | 策略建议 |
| [ ] | SEO-016 | 隔离并同步本站搜索索引 | P1 | 008、032 | 已确认 |
@@ -202,7 +202,7 @@ ## 5 执行总表
| [ ] | SEO-030 | 文章接收、更新与删除的发布合同 | P0 发布前 | 003、008、017、029 | 已确认/条件性风险 |
| [ ] | SEO-031 | 正式主机、HTTPS 与 HTTP 服务质量 | P0 发布前 | 001、004 | 待部署验证 |
| [ ] | SEO-032 | 本地、预发布和生产资源隔离 | P0 发布前 | 001 | 已确认/条件性风险 |
| [ ] | SEO-033 | 规范 IndexNow 及搜索提交 | P2 | 003、004、030、032 | 已确认/待部署验证 |
| [ ] | SEO-033 | 规范 IndexNow 及搜索提交 | P2 | 003、004、030、032 | 部分实施:编辑发布通知,见正文 |
| [ ] | SEO-034 | SEO 自动回归与数据样例 | P1 | 跟随各批次 | 当前测试缺口 |
| [ ] | SEO-035 | 搜索平台与业务效果监测 | P1 上线后 | 001、002、036 | 待线上数据 |
| [ ] | SEO-036 | 发布、迁移、回滚与复核 | P0 发布时 | 前述必需项 | 待发布授权 |
@@ -352,6 +352,8 @@ ### SEO-013 统一 sitemap 的集合和 lastmod
**验收:** XML 解析、URL 编码、正式 host、状态、canonical、robots、noindex 做交叉校验;新增/撤稿/到期后集合及时变化;集合差异有可解释原因。Google 忽略 priority 与 changefreq,不应将调大这些数字作为优化工作。[Google sitemap 指南](https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap)
**2026-10-31定点实施:** 见[教程SEO通知](EDITORIAL_INDEXNOW.md)。仅编辑API新增/实质更新通知、独立回执/退避重试,以及client/advanced非空栏目进入sitemap;未完成本项所有全站建议,发布/验收以该正文为准。
### SEO-014 建立长期内链和内容导航
**优先级:P1。证据:E03。** 当前资源发现主要依赖列表首屏和“点赞活跃”;动态热门榜并不保证重要教程或可索引资源长期获得入口。
@@ -539,6 +541,8 @@ ### SEO-033 规范 IndexNow 及搜索提交
**验收:** 本地使用替身验证,不实际发送;正式获准后单条核验目标主机、验证文件和返回结果;删除事件不因目标已 404 而被本地逻辑永远过滤掉。IndexNow 表示通知采用该协议的搜索引擎,不能当成 Google 通用收录接口。Google Indexing API 仅支持其指定的招聘及直播事件页面,不适用于普通节点文章。[IndexNow 协议](https://www.indexnow.org/documentation)、[Google Indexing API 适用范围](https://developers.google.com/search/apis/indexing-api/v3/using-api)
**2026-10-31定点实施:** 见[教程SEO通知](EDITORIAL_INDEXNOW.md)。仅编辑API新增/实质更新通知、独立回执/退避重试,以及client/advanced非空栏目进入sitemap;未完成本项所有全站建议,发布/验收以该正文为准。
### SEO-034 SEO 自动回归与数据样例
**优先级:P1,随每批实现。** 当前仓库测试只有首页 200 示例和恒真示例,不能防止 URL、索引和发布规则回退。本轮未执行这些与审计目标无关的示例测试,也没有新增业务测试或修改代码。
@@ -0,0 +1 @@
{"staging": {"deployment": {"old_head": "76141453bbdbd14b13c69647c14226bae7250afc", "commit": "ce27dbdd1eb206a9b7e7ac9b5a1c77778ed75e03", "environment": "staging", "started_at": "2026-10-30T04:09:11Z", "identity": {"articles": 184, "core_sha256": "ca542384a1421a8770fc5d708114ab03d54086a513ea0741188ea7da0f67f6f7", "year_plans_sha256": null}, "status": "deployed", "final_sync": {"assets": 37, "selections": {"freenode": 84, "shadowrocketids": 90}, "pending": []}, "finished_at": "2026-10-30T04:11:01Z", "serialization_compatibility": true}, "verification": {"environment": "staging", "base_url": "https://test.clashfreenode.com", "commit": "ce27dbdd1eb206a9b7e7ac9b5a1c77778ed75e03", "checks": [{"check": "exact pushed commit", "passed": true, "detail": null}, {"check": "37 reviewed assets mirrored", "passed": true, "detail": null}, {"check": "one file per unique content hash", "passed": true, "detail": 37}, {"check": "local URL is content addressed", "passed": true, "detail": null}, {"check": "local bytes 7a11aea78504facad661c8577b573be6d7d2ab38d2264f9f703fbcd6e9663287.jpg", "passed": true, "detail": null}, {"check": "Nginx delivery 7a11aea78504facad661c8577b573be6d7d2ab38d2264f9f703fbcd6e9663287.jpg", "passed": true, "detail": 200}, {"check": "HTTP bytes 7a11aea78504facad661c8577b573be6d7d2ab38d2264f9f703fbcd6e9663287.jpg", "passed": true, "detail": null}, {"check": "public immutable success cache 7a11aea78504facad661c8577b573be6d7d2ab38d2264f9f703fbcd6e9663287.jpg", "passed": true, "detail": "public, max-age=31536000, immutable"}, {"check": "conditional response metadata 7a11aea78504facad661c8577b573be6d7d2ab38d2264f9f703fbcd6e9663287.jpg", "passed": true, "detail": null}, {"check": "staging image noindex 7a11aea78504facad661c8577b573be6d7d2ab38d2264f9f703fbcd6e9663287.jpg", "passed": true, "detail": null}, {"check": "local URL is content addressed", "passed": true, "detail": null}, {"check": "local bytes 342b38385bbca08ef00b1c373b3efa39d7bf255ae37418c2d13881d5b0f8d451.webp", "passed": true, "detail": null}, {"check": "Nginx delivery 342b38385bbca08ef00b1c373b3efa39d7bf255ae37418c2d13881d5b0f8d451.webp", "passed": true, "detail": 200}, {"check": "HTTP bytes 342b38385bbca08ef00b1c373b3efa39d7bf255ae37418c2d13881d5b0f8d451.webp", "passed": true, "detail": null}, {"check": "public immutable success cache 342b38385bbca08ef00b1c373b3efa39d7bf255ae37418c2d13881d5b0f8d451.webp", "passed": true, "detail": "public, max-age=31536000, immutable"}, {"check": "conditional response metadata 342b38385bbca08ef00b1c373b3efa39d7bf255ae37418c2d13881d5b0f8d451.webp", "passed": true, "detail": null}, {"check": "staging image noindex 342b38385bbca08ef00b1c373b3efa39d7bf255ae37418c2d13881d5b0f8d451.webp", "passed": true, "detail": null}, {"check": "local URL is content addressed", "passed": true, "detail": null}, {"check": "local bytes 0430cc5c9645fda3042b04c23296eb09b5cf6eddf7a8050cfff93c88f0d0ef36.jpg", "passed": true, "detail": null}, {"check": "Nginx delivery 0430cc5c9645fda3042b04c23296eb09b5cf6eddf7a8050cfff93c88f0d0ef36.jpg", "passed": true, "detail": 200}, {"check": "HTTP bytes 0430cc5c9645fda3042b04c23296eb09b5cf6eddf7a8050cfff93c88f0d0ef36.jpg", "passed": true, "detail": null}, {"check": "public immutable success cache 0430cc5c9645fda3042b04c23296eb09b5cf6eddf7a8050cfff93c88f0d0ef36.jpg", "passed": true, "detail": "public, max-age=31536000, immutable"}, {"check": "conditional response metadata 0430cc5c9645fda3042b04c23296eb09b5cf6eddf7a8050cfff93c88f0d0ef36.jpg", "passed": true, "detail": null}, {"check": "staging image noindex 0430cc5c9645fda3042b04c23296eb09b5cf6eddf7a8050cfff93c88f0d0ef36.jpg", "passed": true, "detail": null}, {"check": "local URL is content addressed", "passed": true, "detail": null}, {"check": "local bytes a79280393554d05df80a8936758cdea70b98a5fa539becc0240e339c8990068b.webp", "passed": true, "detail": null}, {"check": "Nginx delivery a79280393554d05df80a8936758cdea70b98a5fa539becc0240e339c8990068b.webp", "passed": true, "detail": 200}, {"check": "HTTP bytes a79280393554d05df80a8936758cdea70b98a5fa539becc0240e339c8990068b.webp", "passed": true, "detail": null}, {"check": "public immutable success cache a79280393554d05df80a8936758cdea70b98a5fa539becc0240e339c8990068b.webp", "passed": true, "detail": "public, max-age=31536000, immutable"}, {"check": "conditional response metadata a79280393554d05df80a8936758cdea70b98a5fa539becc0240e339c8990068b.webp", "passed": true, "detail": null}, {"check": "staging image noindex a79280393554d05df80a8936758cdea70b98a5fa539becc0240e339c8990068b.webp", "passed": true, "detail": null}, {"check": "local URL is content addressed", "passed": true, "detail": null}, {"check": "local bytes dcbab844e9f2f2b94ad71c9fd0c751e5b83dc8983d9aebf5a78f4e8399379fd7.jpg", "passed": true, "detail": null}, {"check": "Nginx delivery dcbab844e9f2f2b94ad71c9fd0c751e5b83dc8983d9aebf5a78f4e8399379fd7.jpg", "passed": true, "detail": 200}, {"check": "HTTP bytes dcbab844e9f2f2b94ad71c9fd0c751e5b83dc89Line truncated
@@ -0,0 +1,47 @@
{
"base": "ace6d74a18988697340ebcd15e2b79a4dee0e697",
"commit": "252e0c38cb85d0c1331063b1019a2bb13c27ac8a",
"files": [
"AGENTS.md",
"app/Http/Controllers/SitemapController.php",
"docs/maintenance/EDITORIAL_INDEXNOW.md",
"docs/maintenance/SEO_PLAN.md",
"resources/views/sitemap.blade.php",
"tests/Feature/EditorialApiTest.php",
"tests/Feature/EditorialReleaseTest.php"
],
"branch": "codex/tutorial-sitemap-20261031",
"backup_directory": "/root/backups/cfn-tutorial-sitemap-20261031",
"pushed": true,
"before_count": 25,
"after_count": 27,
"added": [
"https://clashfreenode.com/advanced",
"https://clashfreenode.com/client"
],
"checks": {
"article_core_preserved": true,
"publications_unchanged": true,
"indexnow_enabled": true,
"keyfile": {
"http_status": 200,
"body_matches_key": true
},
"retry_command": {
"processed": 0,
"pending": 0
},
"existing_business_scheduler": true,
"opcode_invalidation": true,
"generated_template_preserved": true,
"pages": {
"/": 200,
"/client": 200,
"/advanced": 200,
"/a/system-proxy-vs-tun.html": 200
}
},
"live_indexnow_notification_sent": false,
"head": "252e0c38cb85d0c1331063b1019a2bb13c27ac8a",
"status": "M resources/views/components/generated-tags-cloud.blade.php\n?? data.ms/"
}
+26
View File
@@ -0,0 +1,26 @@
# 综合教程周期写作
2026-10-31用户最终规则:每周三篇,每天北京时间15:00检查;文章展示时间随机往前0~6小时,精确到秒。原每周两篇、早晚两个窗口的规则已替换。Codex heartbeat `fna`,名称“FNA 综合教程|每周三篇”,ACTIVE,绑定本聊天,自2026-11-02当周开始。调度已修改;2026-10-31用户提前手动触发一篇已正式发布并计入当周台账,2026-11-02当周的三次计划保持不变。详见[首篇记录](ROUTING_MODES_2026-10-31.md)。
## 执行入口
项目根运行 `python3 tools/editorial/weekly.py due`。未到期、当日已发表或本周额度满则安静退出。台账唯一位置为`storage/app/private/weekly-tutorials/state.json`,Git忽略;不保存凭据。电脑/Codex需开启,不保证关机仍执行或开机立即补跑。
每个自然周(Asia/Shanghai,周一至周日),在周一/二、周三/四、周五/六/日三组里各随机选一天,计划时间均为15:00,三篇间隔至少24小时。首次计划持久化,同一周不反复抽取。首周旧两篇计划尚未开始,已按最新规则重建三篇;具体日期以台账为准。
- `due`返回`write`后,先生成稳定release UUID,用`weekly.py claim --slot SLOT --release-id UUID`锁定任务,再写稿。每次最多一篇,同一天不连发。
- `resume`表示已有未决release;先用[发布封装](EDITORIAL_RELEASE.md)的status查服务器,再沿原bundle、ID、草稿继续,不能创建另一篇。
- `synchronize`表示正文已经发布、后处理待完成;沿原publish请求重试同步,不重发正文。
- 发布完成或正文已提交但后处理pending时,用`weekly.py record --slot SLOT --receipt 私有发布结果.json`回写。只接受匹配release_id和真实published回执;用服务器事务时间计数,不用展示日期或本机收到结果的时间。
- 漏掉的本周时段在下次15:00检查时补一篇;未开始的往周欠额不累计。跨周未决操作先查原回执,真实成功记入实际发表周,避免重复或计错额度。
- 台账丢失、损坏或锁冲突时停止,先恢复/核对,不按空周补发。仅人工明确放弃无已发表结果的任务后可标记abandoned。人工另写文章只有明确登记替代时才占周期槽位。
## 内容与发布边界
写作规范、稳定文章与关联表唯一来源为[WRITING.md](../content/WRITING.md)。每篇先查正式目录与源稿,避免重复,官方一手资料核实事实,图解与缩略图沿现有风格。自然补下载/入门/专题内链,必要时只改直接相关旧文。公开内容不出现内部核验、未实测等说明,不编造设备实测。
新文点赞参数与展示偏移在API草稿中冻结;真实创建时间、回执和点赞起点仍真实记录。正文源、图片、渲染稿、关联表同任务维护。
生产固定经本机SSH→白色机VPS-001→正式业务服务器VPS-003。使用[固定发布命令](EDITORIAL_RELEASE.md),公网编辑API保持关闭,不在白色机部署写作服务。普通文章和图片通过内容API,源码/记录另做Git留档;程序/公共资源变更才单独Git部署,保留并行改动,不扩大成全站改版,不重建test。
用户授权周期内正常选题、写作、相关链接和正式发布,不逐篇再次确认。资料、权限或工具不足时保留草稿并报告真实缺口。只有有意义的完成、失败或需用户操作时通知,成功给标题和真实URL,不发每日检查流水。调度变更必须通过automation_update,不能手改调度文件或加系统cron替代。
+14
View File
@@ -0,0 +1,14 @@
.hn-article-ad {
position: relative;
min-width: 0;
aspect-ratio: 2.45;
margin: 20px 0;
overflow: hidden;
border: 1px solid #181b1e;
border-radius: 12px;
background: #181b1e;
}
.article-ad-group .hn-article-ad { margin: 0; }
.hn-image-ad__link { position: absolute; inset: 0; display: block; }
.hn-image-ad__link img { display: block; width: 100%; height: 100%; object-fit: cover; }
.hn-image-ad__link:focus-visible { outline: 3px solid #b4f047; outline-offset: -4px; }
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

@@ -34,7 +34,7 @@
<meta property="og:description" content="{{ $sDesc }}">
<meta property="og:type" content="{{ $sOgType }}">
<meta property="og:url" content="{{ url()->current() }}">
<meta property="og:image" content="{{ $sOgImg }}">
<meta property="og:image" content="{{ str_starts_with($sOgImg ?? '', '/') ? url($sOgImg) : $sOgImg }}">
{{-- 声明它是 PNG,并告诉浏览器它的实际尺寸 --}}
<link rel="icon" type="image/png" href="/sites/{{ config('app.site_code_short') }}/icon.png" sizes="166x166">
@@ -0,0 +1,12 @@
@if (config('advertising.hn.enabled') && config('advertising.hn.url') && is_file(public_path('images/ads/hn-ad-quality-20261030.png')))
@once
@push('styles')
<link rel="stylesheet" href="/css/hn-article-ad.css?v={{ filemtime(public_path('css/hn-article-ad.css')) }}">
@endpush
@endonce
<aside class="hn-article-ad hn-image-ad" aria-label="HN 图片广告">
<a class="hn-image-ad__link" href="{{ config('advertising.hn.url') }}" target="_blank" rel="sponsored noopener noreferrer" aria-label="广告:了解 Hardnerd 网络服务(新窗口打开)">
<img src="/images/ads/hn-ad-quality-20261030.png?v={{ filemtime(public_path('images/ads/hn-ad-quality-20261030.png')) }}" alt="Hardnerd 广告:探索全球网络无限可能。硬核专线架构,品质网络体验" width="1962" height="801">
</a>
</aside>
@endif
+2
View File
@@ -77,6 +77,8 @@
</div>
@include('components.hn-article-ad')
<div class="post-tags mt-3 mt-md-4">
<div class="">
@foreach($oArticle->oTags as $oTag)
+7
View File
@@ -7,6 +7,13 @@
<changefreq>daily</changefreq>
</url>
{{-- Only established tutorial landing pages; omit lastmod until a reliable content clock exists. --}}
@foreach($cCategories as $oCategory)
<url>
<loc>{{ rtrim(config('app.url'), '/') }}/{{ $oCategory->sSlug }}</loc>
</url>
@endforeach
{{-- 未过期的文章 --}}
@foreach($cArticles as $oArticles)
<url>
+2
View File
@@ -19,6 +19,8 @@
Schedule::command('article:sync-likes')->everyFiveMinutes();
Schedule::command('editorial:indexnow-retry')->everyFiveMinutes()->environments(['production'])->withoutOverlapping(10);
//Artisan::command('db:reCreate {sTableName?}', function ($sTableName = null) {
// // 1. 没传参数?直接亮红牌!
+113
View File
@@ -75,6 +75,7 @@ protected function setUp(): void
});
(require database_path('migrations/2026_10_27_190000_create_editorial_tables.php'))->up();
(require database_path('migrations/2026_10_29_200000_add_one_year_article_likes.php'))->up();
(require database_path('migrations/2026_10_31_150000_add_article_display_timestamp.php'))->up();
DB::table('categories')->insert([
['id' => 1, 'sSlug' => 'freenode', 'sName' => '资源'], ['id' => 3, 'sSlug' => 'windows', 'sName' => 'Windows'],
['id' => 10, 'sSlug' => 'advanced', 'sName' => '进阶教程'],
@@ -388,4 +389,116 @@ public function test_raw_script_markup_is_escaped_and_publish_request_id_cannot_
$this->publish($next, $request)->assertConflict();
$this->assertSame(1, DB::table('articles')->count());
}
private function enableEditorialIndexNow(): void
{
config(['editorial.indexnow_enabled' => true, 'editorial.base_url' => 'https://example.org',
'app.url' => 'https://example.org', 'app.site_code' => 'example.org',
'key.indexnow' => 'test-key-12345678']);
// API authentication in these tests is bound to the same origin.
file_put_contents($this->credential, json_encode(['project' => 'fna-v3', 'environment' => 'testing',
'base_url' => 'https://example.org', 'schema' => 'gemdocs.credential.v1', 'fields' => ['api_key' => $this->token]]));
}
public function test_editorial_indexnow_notifies_new_and_changed_content_once_but_not_noop(): void
{
$this->enableEditorialIndexNow();
Http::fake(['api.indexnow.org/*' => Http::response('', 200)]);
$item = $this->item();
$item['category_slug'] = 'advanced';
$draft = $this->draft([$item]);
$id = (string) Str::uuid();
$first = $this->publish($draft, $id)->assertOk()->assertJsonPath('effects.indexnow.status', 'done');
$this->assertTrue($first->json('articles.0.content_changed'));
$this->publish($draft, $id)->assertOk();
$this->postJson('/api/editorial/v1/publications/'.$id.'/synchronize')->assertOk();
Http::assertSentCount(1);
Http::assertSent(fn ($r) => $r->url() === 'https://api.indexnow.org/indexnow'
&& $r['host'] === 'example.org' && $r['urlList'] === ['https://example.org/a/example.html']);
$noop = $this->draft([$this->item('example', 1)]);
// The category change in this revision is itself meaningful.
$this->publish($noop)->assertOk()->assertJsonPath('effects.indexnow.status', 'done');
$same = $this->draft([$this->item('example', 2)]);
$this->publish($same)->assertOk()->assertJsonPath('effects.indexnow.reason', 'no-content-change');
Http::assertSentCount(2);
$changed = $this->item('example', 3);
$changed['body'] .= '<p>新的说明。</p>';
$this->publish($this->draft([$changed]))->assertOk()->assertJsonPath('effects.indexnow.status', 'done');
Http::assertSentCount(3);
}
public function test_editorial_indexnow_failure_retries_with_backoff_without_republishing(): void
{
$this->enableEditorialIndexNow();
Http::fake(['api.indexnow.org/*' => Http::sequence()->push('do not persist response secrets', 429)->push('', 202)]);
$draft = $this->draft([$this->item()]);
$result = $this->publish($draft)->assertOk()->assertJsonPath('status', 'published')
->assertJsonPath('effects.indexnow.status', 'pending')->assertJsonPath('effects.indexnow.http_status', 429);
$this->assertStringNotContainsString('do not persist', json_encode($result->json()));
$this->artisan('editorial:indexnow-retry')->assertExitCode(0);
Http::assertSentCount(1);
$this->travel(6)->minutes();
$this->artisan('editorial:indexnow-retry')->assertExitCode(0);
$this->getJson('/api/editorial/v1/publications/'.$result->json('publication_id'))->assertOk()
->assertJsonPath('effects.indexnow.status', 'done')->assertJsonPath('effects.indexnow.http_status', 202)
->assertJsonPath('effects.indexnow.attempts', 2);
$this->assertSame(1, DB::table('articles')->count());
$this->assertSame(1, DB::table('editorial_versions')->count());
$this->assertSame(1, DB::table('editorial_publications')->count());
$this->artisan('editorial:indexnow-retry')->assertExitCode(0);
Http::assertSentCount(2);
}
public function test_editorial_indexnow_does_not_send_disabled_or_mismatched_hosts_or_legacy_receipts(): void
{
Http::fake();
$draft = $this->draft([$this->item()]);
$result = $this->publish($draft)->assertOk()->assertJsonPath('effects.indexnow.status', 'skipped');
$this->enableEditorialIndexNow();
$legacy = $result->json('publication_id');
DB::table('editorial_publications')->where('id', $legacy)->update(['effects' => null]);
$this->postJson('/api/editorial/v1/publications/'.$legacy.'/synchronize')->assertOk()
->assertJsonPath('effects.indexnow.reason', 'legacy-publication');
config(['app.site_code' => 'wrong.example']);
$new = $this->draft([$this->item('another')]);
$this->publish($new)->assertOk()->assertJsonPath('effects.indexnow.reason', 'site-binding-mismatch');
Http::assertNothingSent();
}
public function test_editorial_indexnow_retries_skip_withdrawn_or_expired_articles(): void
{
$this->enableEditorialIndexNow();
Http::fake(['api.indexnow.org/*' => Http::response('', 503)]);
$result = $this->publish($this->draft([$this->item()]))->assertOk();
DB::table('articles')->update(['iStatus' => 0]);
$this->travel(6)->minutes();
$this->artisan('editorial:indexnow-retry')->assertExitCode(0);
$this->getJson('/api/editorial/v1/publications/'.$result->json('publication_id'))->assertOk()
->assertJsonPath('effects.indexnow.reason', 'no-current-indexable-url');
Http::assertSentCount(1);
}
public function test_sitemap_contains_only_active_nonempty_tutorial_roots_and_indexable_articles(): void
{
config(['app.url' => 'http://localhost']);
$this->publish($this->draft([$this->item()]))->assertOk();
DB::table('categories')->where('id', 3)->update(['iParentId' => 2]);
DB::table('categories')->insert(['id' => 2, 'sSlug' => 'client', 'sName' => '入门教程', 'iStatus' => 1]);
$xml = $this->get('/sitemap.xml')->assertOk()->getContent();
$this->assertStringContainsString('<loc>http://localhost/client</loc>', $xml);
$this->assertStringNotContainsString('<loc>http://localhost/advanced</loc>', $xml);
$advanced = $this->item('advanced-test');
$advanced['category_slug'] = 'advanced';
$this->publish($this->draft([$advanced]))->assertOk();
$xml = $this->get('/sitemap.xml')->assertOk()->getContent();
$this->assertSame(1, substr_count($xml, '<loc>http://localhost/advanced</loc>'));
$this->assertStringContainsString('/a/advanced-test.html</loc>', $xml);
$this->assertStringNotContainsString('<loc>http://localhost/windows</loc>', $xml);
DB::table('categories')->where('id', 10)->update(['iStatus' => 0]);
DB::table('articles')->where('iCategoryId', 3)->update(['iStatus' => 0]);
$xml = $this->get('/sitemap.xml')->assertOk()->getContent();
$this->assertStringNotContainsString('/advanced</loc>', $xml);
$this->assertStringNotContainsString('/client</loc>', $xml);
$this->assertStringNotContainsString('/a/advanced-test.html</loc>', $xml);
}
}
+290
View File
@@ -0,0 +1,290 @@
<?php
namespace Tests\Feature;
use App\Services\Editorial\ProcessApi;
use App\Services\Editorial\ReleaseRunner;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Http;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
#[\PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses]
#[\PHPUnit\Framework\Attributes\PreserveGlobalState(false)]
class EditorialReleaseTest extends \Tests\TestCase
{
private string $releaseRoot;
protected function setUp(): void
{
parent::setUp();
config(['database.default' => 'sqlite', 'database.connections.sqlite.database' => ':memory:',
'editorial.enabled' => false, 'editorial.base_url' => 'http://localhost',
'scout.driver' => 'collection', 'responsecache.enabled' => false, 'cache.default' => 'array']);
DB::purge('sqlite');
Http::preventStrayRequests();
Schema::create('categories', function (Blueprint $t) {
$t->id();
$t->string('sSlug');
$t->string('sName');
$t->integer('iParentId')->default(0);
$t->integer('iStatus')->default(1);
$t->integer('iSort')->default(0);
$t->integer('iShowChildren')->default(0);
$t->string('sHtmlClass')->nullable();
$t->text('aOpt')->nullable();
});
Schema::create('articles', function (Blueprint $t) {
$t->id();
$t->integer('iCategoryId');
$t->integer('iUserId')->default(1);
$t->string('sSlug')->unique();
$t->string('sTitle');
$t->string('sTitleSub')->nullable();
$t->text('sContent');
$t->string('sThumb')->nullable();
$t->integer('iStatus')->default(1);
$t->boolean('bPageThumb')->default(false);
foreach (['iViews', 'iLikeCount', 'i7like', 'i365like', 'iIsTop'] as $field) {
$t->integer($field)->default(0);
}
$t->timestamp('sLastLikedAt')->nullable();
$t->timestamps();
});
Schema::create('tags', function (Blueprint $t) {
$t->id();
$t->string('sSlug');
$t->string('sName');
$t->integer('iArticleCount')->default(0);
});
Schema::create('article_tag', function (Blueprint $t) {
$t->integer('iArticleId');
$t->integer('iTagId');
});
(require database_path('migrations/2026_10_27_190000_create_editorial_tables.php'))->up();
(require database_path('migrations/2026_10_29_200000_add_one_year_article_likes.php'))->up();
(require database_path('migrations/2026_10_31_150000_add_article_display_timestamp.php'))->up();
DB::table('categories')->insert([
['id' => 1, 'sSlug' => 'freenode', 'sName' => '资源'], ['id' => 3, 'sSlug' => 'windows', 'sName' => 'Windows'],
['id' => 10, 'sSlug' => 'advanced', 'sName' => '进阶教程'],
]);
DB::table('tags')->insert(['id' => 1, 'sSlug' => 'clash', 'sName' => 'Clash']);
$this->releaseRoot = sys_get_temp_dir().'/fna-release-test-'.Str::uuid();
config(['editorial.enabled' => false, 'editorial.release_directory' => $this->releaseRoot]);
}
protected function tearDown(): void
{
foreach (glob($this->releaseRoot.'/*') ?: [] as $file) {
unlink($file);
}
@rmdir($this->releaseRoot);
parent::tearDown();
}
private function bundle(): array
{
return ['operation' => 'prepare', 'release_id' => (string) Str::uuid(), 'articles' => [[
'content_key' => 'release-example', 'expected_revision' => 0, 'slug' => 'release-example',
'title' => '发布演练', 'summary' => '演练摘要', 'category_slug' => 'advanced',
'body' => '<h2 id="check">检查</h2><p>正文测试。</p>',
]]];
}
public function test_release_retry_after_lost_response_preserves_ids_and_single_publication(): void
{
$runner = app(ReleaseRunner::class);
$bundle = $this->bundle();
$prepared = $runner->run($bundle);
$repeat = $runner->run($bundle);
$this->assertSame($prepared['publication_request_id'], $repeat['publication_request_id']);
$this->assertSame(1, DB::table('editorial_documents')->value('revision'));
$this->assertFalse(config('editorial.enabled'));
$this->assertNull(config('editorial.process_credential'));
$review = $runner->run(['operation' => 'review', 'release_id' => $bundle['release_id']]);
$this->assertStringContainsString('正文测试', $review['previews']['release-example']);
$publish = ['operation' => 'publish', 'release_id' => $bundle['release_id'],
'expected_hash' => $review['review']['hash'], 'review_digest' => $review['review']['digest']];
// Server committed, but the caller lost its response before saving the local receipt.
app(ProcessApi::class)->call('POST', 'drafts/'.$prepared['draft_id'].'/publish', [
'request_id' => $prepared['publication_request_id'], 'expected_hash' => $review['review']['hash']]);
$done = $runner->run($publish);
$this->assertSame('complete', $done['phase']);
$again = $runner->run($publish);
$this->assertSame($done['receipt'], $again['receipt']);
$this->assertSame(1, DB::table('articles')->count());
$this->assertSame(1, DB::table('editorial_publications')->count());
$this->assertFalse(config('editorial.enabled'));
$this->assertNull(config('editorial.process_credential'));
$this->getJson('/api/editorial/v1/catalog')->assertStatus(503);
}
public function test_release_changed_input_and_unreviewed_publish_fail_closed(): void
{
$runner = app(ReleaseRunner::class);
$bundle = $this->bundle();
$runner->run($bundle);
try {
$runner->run(['operation' => 'publish', 'release_id' => $bundle['release_id']]);
$this->fail('Unreviewed publication accepted');
} catch (HttpException $e) {
$this->assertSame(409, $e->getStatusCode());
}
$bundle['articles'][0]['body'] .= '变动';
try {
$runner->run($bundle);
$this->fail('Changed bundle accepted');
} catch (HttpException $e) {
$this->assertSame(409, $e->getStatusCode());
}
$this->assertSame(0, DB::table('articles')->count());
$this->assertFalse(config('editorial.enabled'));
}
public function test_release_lock_and_failure_restore_process_permission(): void
{
mkdir($this->releaseRoot, 0700, true);
$lock = fopen($this->releaseRoot.'/runner.lock', 'c');
flock($lock, LOCK_EX);
try {
app(ReleaseRunner::class)->run($this->bundle());
$this->fail('Concurrent release accepted');
} catch (HttpException $e) {
$this->assertSame(409, $e->getStatusCode());
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
$bundle = $this->bundle();
$bundle['articles'][0]['category_slug'] = 'unknown';
try {
app(ReleaseRunner::class)->run($bundle);
$this->fail('Unknown category accepted');
} catch (HttpException $e) {
$this->assertSame(422, $e->getStatusCode());
}
$this->assertFalse(config('editorial.enabled'));
$this->assertNull(config('editorial.process_credential'));
$this->assertSame(0, DB::table('articles')->count());
}
public function test_release_expired_process_credential_is_rejected(): void
{
config(['editorial.enabled' => true, 'editorial.process_credential' => ['expires_at' => time() - 1]]);
$this->getJson('/api/editorial/v1/catalog')->assertStatus(401);
}
public function test_release_asset_batch_and_pending_effects_recover_without_republishing(): void
{
$bundle = $this->bundle();
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aXZkAAAAASUVORK5CYII=');
$sha = hash('sha256', $bytes);
$bundle['assets'] = [['name' => 'diagram', 'base64' => base64_encode($bytes)]];
$bundle['articles'][0]['body'] .= '<img src="file:diagram" alt="示意图">';
$runner = app(ReleaseRunner::class);
try {
$runner->run($bundle);
$review = $runner->run(['operation' => 'review', 'release_id' => $bundle['release_id']]);
$publish = ['operation' => 'publish', 'release_id' => $bundle['release_id'],
'expected_hash' => $review['review']['hash'], 'review_digest' => $review['review']['digest']];
config(['scout.driver' => null]);
$pending = $runner->run($publish);
$this->assertSame('published_pending', $pending['phase']);
$this->assertStringContainsString('/images/editorial/'.$sha.'.png', DB::table('articles')->value('sContent'));
$this->assertSame($sha, hash_file('sha256', public_path('images/editorial/'.$sha.'.png')));
config(['scout.driver' => 'collection']);
$done = $runner->run($publish);
$this->assertSame('complete', $done['phase']);
$this->assertTrue($done['readback'][0]['content_matches']);
$this->assertNotEmpty($done['published_at']);
$this->assertSame(1, DB::table('editorial_publications')->count());
// An external edit cannot be reported as verified merely because revision metadata matches.
DB::table('articles')->update(['sTitle' => '并行修改']);
$check = $runner->run(['operation' => 'status', 'release_id' => $bundle['release_id']]);
$this->assertSame('published_pending', $check['phase']);
} finally {
@unlink(app(\App\Services\Editorial\ContentRenderer::class)->privateImage($sha));
@unlink(public_path('images/editorial/'.$sha.'.png'));
}
}
public function test_release_superseded_draft_does_not_publish(): void
{
$runner = app(ReleaseRunner::class);
$bundle = $this->bundle();
$runner->run($bundle);
$review = $runner->run(['operation' => 'review', 'release_id' => $bundle['release_id']]);
$other = $bundle;
$other['release_id'] = (string) Str::uuid();
$other['articles'][0]['expected_revision'] = 1;
$other['articles'][0]['body'] = '其他编辑的新版本';
$runner->run($other);
try {
$runner->run(['operation' => 'publish', 'release_id' => $bundle['release_id'],
'expected_hash' => $review['review']['hash'], 'review_digest' => $review['review']['digest']]);
$this->fail('Superseded draft accepted');
} catch (HttpException $e) {
$this->assertSame(409, $e->getStatusCode());
}
$this->assertSame(0, DB::table('articles')->count());
$this->assertFalse(config('editorial.enabled'));
}
public function test_release_display_time_is_frozen_and_real_publish_time_is_preserved(): void
{
$this->travelTo(\Carbon\Carbon::parse('2026-11-02 15:37:42'));
$runner = app(ReleaseRunner::class);
$bundle = $this->bundle();
$prepared = $runner->run($bundle);
$offset = $prepared['draft']['articles'][0]['display_offset_seconds'];
$this->assertGreaterThanOrEqual(0, $offset);
$this->assertLessThanOrEqual(21600, $offset);
$this->assertSame($offset, $runner->run($bundle)['draft']['articles'][0]['display_offset_seconds']);
$review = $runner->run(['operation' => 'review', 'release_id' => $bundle['release_id']]);
$runner->run(['operation' => 'publish', 'release_id' => $bundle['release_id'],
'expected_hash' => $review['review']['hash'], 'review_digest' => $review['review']['digest']]);
$article = DB::table('articles')->first();
$this->assertSame('2026-11-02 15:37:42', $article->created_at);
$this->assertSame($article->created_at, $article->sYearLikeStartedAt);
$this->assertSame(now()->subSeconds($offset)->toDateTimeString(), $article->sDisplayPublishedAt);
$model = new \App\Models\Articles;
$model->forceFill(['created_at' => now(), 'sDisplayPublishedAt' => now()->subHours(4)->toDateTimeString()]);
$this->assertSame('4小时前', $model->sCreatedAtDiff);
$edit = $this->bundle();
$edit['articles'][0]['expected_revision'] = 1;
$edit['articles'][0]['body'] = '更新正文';
$runner->run($edit);
$review = $runner->run(['operation' => 'review', 'release_id' => $edit['release_id']]);
$runner->run(['operation' => 'publish', 'release_id' => $edit['release_id'],
'expected_hash' => $review['review']['hash'], 'review_digest' => $review['review']['digest']]);
$this->assertSame($article->sDisplayPublishedAt, DB::table('articles')->value('sDisplayPublishedAt'));
$this->travelBack();
}
public function test_release_tracks_indexnow_pending_and_recovers_without_a_new_publication(): void
{
config(['editorial.indexnow_enabled' => true, 'editorial.base_url' => 'https://example.org',
'app.url' => 'https://example.org', 'app.site_code' => 'example.org', 'key.indexnow' => 'test-key-12345678']);
Http::fake(['api.indexnow.org/*' => Http::sequence()->push('', 503)->push('', 200)]);
$runner = app(ReleaseRunner::class);
$bundle = $this->bundle();
$runner->run($bundle);
$review = $runner->run(['operation' => 'review', 'release_id' => $bundle['release_id']]);
$publish = ['operation' => 'publish', 'release_id' => $bundle['release_id'],
'expected_hash' => $review['review']['hash'], 'review_digest' => $review['review']['digest']];
$pending = $runner->run($publish);
$this->assertSame('published_pending', $pending['phase']);
$this->assertSame('pending', $pending['receipt']['effects']['indexnow']['status']);
Http::assertSentCount(1);
$this->travel(6)->minutes();
$this->artisan('editorial:indexnow-retry')->assertExitCode(0);
$done = $runner->run(['operation' => 'status', 'release_id' => $bundle['release_id']]);
$this->assertSame('complete', $done['phase']);
$this->assertSame('done', $done['receipt']['effects']['indexnow']['status']);
$this->assertSame(1, DB::table('articles')->count());
$this->assertSame(1, DB::table('editorial_publications')->count());
Http::assertSentCount(2);
}
}
@@ -0,0 +1,94 @@
<?php
namespace Tests\Feature;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
#[\PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses]
#[\PHPUnit\Framework\Attributes\PreserveGlobalState(false)]
class IllustrationDeliveryTest extends TestCase
{
private string $dir;
private string $id = '11111111-1111-4111-8111-111111111111';
private string $asset = '22222222-2222-4222-8222-222222222222';
private string $sha;
protected function setUp(): void
{
parent::setUp();
$this->app['env'] = 'production';
$this->dir = sys_get_temp_dir().'/delivery-fna-'.bin2hex(random_bytes(8));
mkdir($this->dir, 0700, true);
mkdir($this->dir.'/public');
file_put_contents($this->dir.'/credential.json', json_encode(['project' => 'fna-v3', 'base_url' => 'https://resource-v2.gemcook.net', 'token' => 'rsv2_'.str_repeat('a', 64)]));
config(['illustrations.enabled' => true, 'illustrations.local_enabled' => true, 'illustrations.delivery_enabled' => true, 'illustrations.base_url' => 'https://resource-v2.gemcook.net', 'illustrations.credential_file' => $this->dir.'/credential.json', 'illustrations.local_directory' => $this->dir.'/public', 'illustrations.local_manifest' => $this->dir.'/manifest.json']);
$this->sha = hash('sha256', 'verified-copy');
file_put_contents($this->dir.'/public/'.$this->sha.'.webp', 'verified-copy');
file_put_contents($this->dir.'/manifest.json', json_encode(['version' => 1, 'assets' => [$this->asset => ['sha256' => $this->sha, 'mime' => 'image/webp', 'bytes' => strlen('verified-copy'), 'url' => '/images/illustrations/'.$this->sha.'.webp']], 'selections' => ['freenode' => ['old-article' => 'old-asset']]]));
Http::preventStrayRequests();
Artisan::all();
\Illuminate\Support\Facades\Schema::create('articles', function ($t) {
$t->id();
$t->integer('iCategoryId');
$t->integer('iStatus');
$t->string('sSlug');
$t->timestamp('created_at')->nullable();
});
}
protected function tearDown(): void
{
File::deleteDirectory($this->dir);
parent::tearDown();
}
private function fake(int $sync = 0, int $ack = 200): void
{
Http::fake([
'https://resource-v2.gemcook.net/api/v2/pools/*' => Http::response(['data' => ['items' => [['asset_id' => $this->asset, 'url' => 'https://resource-v2.gemcook.net/media/'.$this->id]], 'selections' => [], 'unavailable' => [], 'next' => null]], $sync ? 503 : 200),
'https://resource-v2.gemcook.net/api/v2/illustration-deliveries' => Http::response(['data' => [['id' => $this->id, 'state' => 'awaiting_sync', 'fingerprint' => str_repeat('b', 64), 'assets' => [['asset_id' => $this->asset, 'sha256' => $this->sha, 'pool' => 'freenode']]]]]),
'https://resource-v2.gemcook.net/api/v2/illustration-deliveries/*/ack' => Http::response(['data' => ['state' => 'completed']], $ack),
]);
}
public function test_verified_copy_is_acknowledged_and_lost_ack_can_retry(): void
{
$this->fake(0, 503);
$this->artisan('illustrations:sync-deliveries')->assertExitCode(1);
Http::swap(new \Illuminate\Http\Client\Factory);
Http::preventStrayRequests();
$this->fake();
$this->artisan('illustrations:sync-deliveries')->assertExitCode(0);
$this->assertSame('old-asset', json_decode(file_get_contents($this->dir.'/manifest.json'), true)['selections']['freenode']['old-article']);
Http::assertSent(fn ($r) => str_ends_with($r->url(), '/ack') && $r['fingerprint'] === str_repeat('b', 64) && $r['manifest_sha256'] === hash_file('sha256', $this->dir.'/manifest.json'));
}
public function test_failed_sync_sends_no_ack(): void
{
$this->fake(1);
$this->artisan('illustrations:sync-deliveries')->assertExitCode(1);
Http::assertNotSent(fn ($r) => str_ends_with($r->url(), '/ack'));
}
public function test_corrupt_copy_sends_no_ack(): void
{
$this->fake();
file_put_contents($this->dir.'/public/'.$this->sha.'.webp', 'corrupt');
$this->artisan('illustrations:sync-deliveries')->assertExitCode(1);
Http::assertNotSent(fn ($r) => str_ends_with($r->url(), '/ack'));
}
public function test_disabled_worker_does_not_contact_resource(): void
{
config(['illustrations.delivery_enabled' => false]);
$this->artisan('illustrations:sync-deliveries')->assertExitCode(1);
Http::assertNothingSent();
}
}
+165
View File
@@ -0,0 +1,165 @@
<?php
namespace Tests\Feature;
use App\Models\Articles;
use App\Services\IllustrationPool;
use App\Services\LocalIllustrations;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use Tests\TestCase;
#[RunTestsInSeparateProcesses]
#[PreserveGlobalState(false)]
class LocalIllustrationsTest extends TestCase
{
private string $dir;
private string $bytes;
private string $sha;
private string $id = '11111111-1111-4111-8111-111111111111';
private string $pub = '22222222-2222-4222-8222-222222222222';
protected function setUp(): void
{
parent::setUp();
$this->app['env'] = 'production';
$this->dir = sys_get_temp_dir().'/fna-local-images-'.bin2hex(random_bytes(8));
mkdir($this->dir, 0700, true);
file_put_contents($this->dir.'/credential.json', json_encode(['project' => 'fna-v3', 'base_url' => 'https://resource-v2.gemcook.net', 'token' => 'rsv2_'.str_repeat('a', 64)]));
config(['illustrations.enabled' => true, 'illustrations.local_enabled' => true,
'illustrations.base_url' => 'https://resource-v2.gemcook.net', 'illustrations.credential_file' => $this->dir.'/credential.json',
'illustrations.local_directory' => $this->dir.'/public', 'illustrations.local_manifest' => $this->dir.'/private/manifest.json']);
$this->bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jp1sAAAAASUVORK5CYII=');
$this->sha = hash('sha256', $this->bytes);
Http::preventStrayRequests();
}
protected function tearDown(): void
{
File::deleteDirectory($this->dir);
parent::tearDown();
}
private function image(?string $id = null): array
{
return ['asset_id' => $id ?? $this->id, 'name' => 'cat.png', 'url' => 'https://resource-v2.gemcook.net/media/'.$this->pub];
}
private function fakeImages(bool $corrupt = false): void
{
Http::swap(new \Illuminate\Http\Client\Factory());
Http::preventStrayRequests();
Http::fake([
'https://resource-v2.gemcook.net/api/v2/assets/*' => Http::response(['data' => ['sha256' => $this->sha, 'mime' => 'image/png', 'bytes' => strlen($this->bytes)]]),
'https://resource-v2.gemcook.net/media/*' => Http::response($corrupt ? 'bad image' : $this->bytes, 200, ['Content-Type' => 'image/png']),
]);
}
public function test_content_hash_deduplicates_assets_and_page_reads_make_no_http_requests(): void
{
$this->fakeImages();
$local = app(LocalIllustrations::class);
$url = $local->storeSelection('freenode', 'fn1', $this->image());
$local->storeSelection('freenode', 'fn2', $this->image('33333333-3333-4333-8333-333333333333'));
$this->assertSame('/images/illustrations/'.$this->sha.'.png', $url);
$this->assertCount(1, glob($this->dir.'/public/*'));
$this->assertSame($this->bytes, file_get_contents($this->dir.'/public/'.$this->sha.'.png'));
Http::assertSentCount(3); // Two metadata reads, one content download.
Http::fake();
config(['illustrations.enabled' => false]); // Frontend survives Resource being disabled.
for ($i = 0; $i < 5; $i++) {
$a = new Articles(['iCategoryId' => 1, 'sSlug' => 'fn1', 'sThumb' => 'https://old.invalid/image']);
$this->assertSame(url($url), $a->sThumb);
$this->assertSame($a->sThumb, $a->toArray()['sThumb']);
$this->assertSame($a->sThumb, json_decode($a->toJson(), true)['sThumb']);
}
Http::assertNothingSent();
}
public function test_corrupt_download_preserves_old_mapping_and_publishes_no_partial_file(): void
{
$this->fakeImages();$local = app(LocalIllustrations::class);
$local->storeSelection('freenode', 'fn1', $this->image());
$before = file_get_contents($this->dir.'/private/manifest.json');
$this->fakeImages(true);
unlink($this->dir.'/public/'.$this->sha.'.png');
try { $local->storeSelection('freenode', 'fn2', $this->image());$this->fail('Expected invalid download rejection'); }
catch (\RuntimeException $e) { $this->assertStringContainsString('integrity', $e->getMessage()); }
$this->assertSame($before, file_get_contents($this->dir.'/private/manifest.json'));
$this->assertSame([], glob($this->dir.'/public/*'));
$this->assertSame([], glob($this->dir.'/private/.image-*'));
}
public function test_off_origin_publication_is_rejected_without_any_network_request(): void
{
$image = $this->image();$image['url'] = 'https://example.com/media/'.$this->pub;
try { app(LocalIllustrations::class)->storeSelection('freenode', 'fn1', $image);$this->fail('Expected source rejection'); }
catch (\RuntimeException $e) { $this->assertSame('Unregistered illustration source', $e->getMessage()); }
Http::assertNothingSent();
}
public function test_new_article_assignment_downloads_before_returning_local_url_and_retry_reuses_it(): void
{
$this->fakeImages();
Http::fake(['https://resource-v2.gemcook.net/api/v2/pools/freenode/selections' => Http::response(['data' => ['selections' => ['fn1' => $this->image()]]])]);
$first = IllustrationPool::forArticle('freenode', 'fn1');
$this->assertSame(url('/images/illustrations/'.$this->sha.'.png'), $first);
$this->assertSame($first, IllustrationPool::forArticle('freenode', 'fn1'));
$this->assertSame($first, url(app(LocalIllustrations::class)->thumbnail('freenode', 'fn1')));
Http::assertSentCount(4); // Two assignment requests; content downloaded once.
}
public function test_source_withdrawal_disabling_and_deletion_preserve_independent_local_copies(): void
{
$this->fakeImages();$local = app(LocalIllustrations::class);$image = $this->image();
$local->storeSelection('freenode', 'fn1', $image);$local->storeSelection('freenode', 'fn2', $image);
Http::fake();
foreach (['publication_revoked', 'asset_disabled', 'asset_inactive', 'access_revoked', 'file_missing', 'file_corrupt', 'file_symlink'] as $reason) {
$result = $local->synchronize(['freenode' => ['items' => [], 'selections' => [], 'unavailable' => ['fn1' => $reason]]]);
$this->assertSame([], $result['pending']);
$this->assertSame('/images/illustrations/'.$this->sha.'.png', $local->thumbnail('freenode', 'fn1'));
}
// A deleted upstream selection is absent even from the unavailable map.
$local->synchronize(['freenode' => ['items' => [], 'selections' => [], 'unavailable' => []]]);
$this->assertNotNull($local->thumbnail('freenode', 'fn1'));
$this->assertNotNull($local->thumbnail('freenode', 'fn2'));
$this->assertFileExists($this->dir.'/public/'.$this->sha.'.png');
Http::assertNothingSent();
}
public function test_sync_reports_missing_local_file_without_erasing_its_assignment(): void
{
$this->fakeImages();$local = app(LocalIllustrations::class);
$local->storeSelection('freenode', 'fn1', $this->image());
unlink($this->dir.'/public/'.$this->sha.'.png');
Http::fake();
$result = $local->synchronize(['freenode' => ['items' => [], 'selections' => [], 'unavailable' => ['fn1' => 'asset_disabled']]]);
$this->assertSame(['freenode:fn1' => 'asset_disabled'], $result['pending']);
$state = json_decode(file_get_contents($this->dir.'/private/manifest.json'), true);
$this->assertSame($this->id, $state['selections']['freenode']['fn1']);
Http::assertNothingSent();
}
public function test_missing_manifest_never_fetches_resource_or_returns_remote_fallback(): void
{
$this->assertNull(IllustrationPool::thumbnail(['iCategoryId' => 1, 'sSlug' => 'fn1'], 'https://old.invalid/image'));
$this->assertSame('/tutorial.png', IllustrationPool::thumbnail(['iCategoryId' => 3, 'sSlug' => 'guide'], '/tutorial.png'));
Http::assertNothingSent();
}
public function test_sync_does_not_overwrite_concurrent_article_assignments(): void
{
$this->fakeImages();$local = app(LocalIllustrations::class);$old = $this->image();
$local->storeSelection('freenode', 'fn1', $old);
$baseline = $local->selectionBaseline();
$new = $this->image('33333333-3333-4333-8333-333333333333');
$local->storeSelection('freenode', 'fn1', $new);
$local->storeSelection('freenode', 'fn2', $new);
$local->synchronize(['freenode' => ['items' => [$old], 'selections' => ['fn1' => $old], 'unavailable' => []]], $baseline);
$state = json_decode(file_get_contents($this->dir.'/private/manifest.json'), true);
$this->assertSame($new['asset_id'], $state['selections']['freenode']['fn1']);
$this->assertSame($new['asset_id'], $state['selections']['freenode']['fn2']);
}
}
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Fixed local SSH -> VPS-001 -> VPS-003 transport. No local HTTP or direct fallback."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
import sys
import tempfile
OPERATIONS = ('catalog', 'source', 'prepare', 'review', 'publish', 'status')
REMOTE_COMMAND = 'cd /www/wwwroot/clashfreenode-new.com && exec runuser -u nginx -- php artisan editorial:release'
def ssh_command():
options = ['-F', '/dev/null', '-T', '-o', 'StrictHostKeyChecking=yes',
'-o', 'PreferredAuthentications=password', '-o', 'PubkeyAuthentication=no',
'-o', 'NumberOfPasswordPrompts=1', '-o', 'ConnectTimeout=15',
'-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3',
'-o', 'ControlMaster=no', '-o', 'ControlPath=none',
'-o', 'ClearAllForwardings=yes', '-o', 'PermitLocalCommand=no']
jump = shlex.join(['ssh', *options, '-W', '45.153.247.44:22', '[email protected]'])
return ['ssh', *options, '-o', 'ProxyCommand=' + jump, '[email protected]', REMOTE_COMMAND]
def atomic_json(path, data):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp = tempfile.mkstemp(prefix=path.name + '.', dir=path.parent)
try:
with os.fdopen(fd, 'w') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(temp, path)
finally:
if os.path.exists(temp):
os.unlink(temp)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('operation', choices=OPERATIONS)
parser.add_argument('--input', type=Path, help='JSON request, without operation; stdin if omitted')
parser.add_argument('--output', type=Path, required=True, help='Private JSON result; review includes HTML, never load its online assets locally')
args = parser.parse_args()
raw = args.input.read_bytes() if args.input else sys.stdin.buffer.read(48 * 1024 * 1024 + 1)
if len(raw) > 48 * 1024 * 1024:
parser.error('Input exceeds 48 MiB')
payload = json.loads(raw or b'{}')
if not isinstance(payload, dict) or ('operation' in payload and payload['operation'] != args.operation):
parser.error('Invalid operation payload')
payload['operation'] = args.operation
helper = Path(__file__).with_name('ssh_askpass.py').resolve()
env = os.environ.copy()
env.update(SSH_ASKPASS=str(helper), SSH_ASKPASS_REQUIRE='force', DISPLAY=':0')
try:
result = subprocess.run(ssh_command(), input=json.dumps(payload, ensure_ascii=False).encode(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, timeout=660)
try:
reply = json.loads(result.stdout)
except (ValueError, UnicodeError):
reply = {'ok': False, 'error': 'SSH/server response unavailable. Query status with the original release_id; no direct fallback.',
'transport_exit': result.returncode}
atomic_json(args.output, reply)
print(json.dumps({'ok': reply.get('ok', False), 'phase': reply.get('data', {}).get('phase'),
'result_file': str(args.output.resolve()), 'transport_exit': result.returncode}))
return result.returncode if result.returncode in (0, 1, 2) else 1
except subprocess.TimeoutExpired:
atomic_json(args.output, {'ok': False, 'error': 'Transport timed out; publication may have completed. Query original release_id.'})
return 1
if __name__ == '__main__':
raise SystemExit(main())
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""Only OpenSSH may consume this helper's output; never run it interactively."""
import os
import re
import sys
from pathlib import Path
if __name__ == '__main__':
prompt = sys.argv[1] if len(sys.argv) == 2 else ''
match = re.fullmatch(r"root@(104\.168\.30\.40|45\.153\.247\.44)'s password: ?", prompt)
if not match or os.environ.get('SSH_ASKPASS_REQUIRE') != 'force':
raise SystemExit(2)
root = Path('/Users/hellcat/Documents/GemDocs/AI版')
sys.path.insert(0, str(root / 'tools'))
import credentials
resource = {'104.168.30.40': 'VPS-001', '45.153.247.44': 'VPS-003'}[match[1]]
try:
password = credentials.get_field(root, resource, 'password')
os.write(1, password.encode())
except Exception:
raise SystemExit(2)
+72
View File
@@ -0,0 +1,72 @@
import unittest
from datetime import datetime, timedelta
import copy
from weekly import due, new_week, record, ZONE
from release import ssh_command, REMOTE_COMMAND
class WeeklyTests(unittest.TestCase):
def state(self):
return {'starts_on': '2026-11-02', 'weeks': {'2026-11-02': {'slots': [
{'slot_id': str(i), 'status': 'planned', 'planned_at': f'2026-11-0{day}T15:00:00+08:00',
'release_id': None, 'published_at': None} for i, day in enumerate([2, 4, 6])
]}}}
def test_random_plans_have_three_distinct_days_at_fifteen(self):
for _ in range(200):
slots = new_week('2026-11-02')['slots']
times = [datetime.fromisoformat(s['planned_at']) for s in slots]
self.assertEqual(len({t.date() for t in times}), 3)
self.assertTrue(all(t.hour == 15 and t.minute == t.second == 0 for t in times))
self.assertTrue(all(b-a >= timedelta(hours=24) for a, b in zip(times, times[1:])))
def test_missed_slot_catches_up_without_two_same_day(self):
state = self.state()
now = datetime(2026, 11, 4, 15, tzinfo=ZONE)
self.assertEqual(due(state, now)['slot']['slot_id'], '0')
slot = state['weeks']['2026-11-02']['slots'][0]
slot.update(status='published', published_at=now.isoformat())
self.assertEqual(due(state, now)['reason'], 'already_published_today')
self.assertEqual(due(state, now+timedelta(days=1))['slot']['slot_id'], '1')
def test_retry_pending_is_not_a_new_article(self):
state = self.state()
slot = state['weeks']['2026-11-02']['slots'][0]
slot.update(release_id='original', status='publishing')
self.assertEqual(due(state, datetime(2026, 11, 9, 15, tzinfo=ZONE))['action'], 'resume')
response = {'ok': True, 'data': {'release_id': 'original', 'phase': 'published_pending',
'published_at': '2026-11-08T16:11:10+08:00',
'receipt': {'status': 'published', 'publication_id': 'receipt', 'articles': [{'url': '/a/example.html'}]}}}
record(state, '0', response, datetime(2026, 11, 9, 15, tzinfo=ZONE))
self.assertEqual(slot['published_at'], '2026-11-08T16:11:10+08:00')
self.assertEqual(due(state, datetime(2026, 11, 9, 15, tzinfo=ZONE))['action'], 'synchronize')
response['ok'] = False
before = copy.deepcopy(state)
with self.assertRaises(ValueError):
record(state, '0', response, datetime(2026, 11, 9, 15, tzinfo=ZONE))
self.assertEqual(before, state)
def test_next_week_does_not_publish_unstarted_backlog(self):
state = self.state()
now = datetime(2026, 11, 9, 15, tzinfo=ZONE)
result = due(state, now)
if result['action'] == 'write':
self.assertTrue(result['slot']['slot_id'].startswith('2026-11-09'))
for i, slot in enumerate(state['weeks']['2026-11-02']['slots']):
slot.update(status='published', published_at=f'2026-11-0{2+i}T16:00:00+08:00')
self.assertEqual(due(state, datetime(2026, 11, 6, 15, tzinfo=ZONE))['reason'], 'weekly_quota_met')
def test_transport_always_forces_white_host_and_fixed_remote_command(self):
command = ssh_command()
proxy = next(a for a in command if a.startswith('ProxyCommand='))
self.assertIn('[email protected]', proxy)
self.assertIn('-W 45.153.247.44:22', proxy)
self.assertIn('StrictHostKeyChecking=yes', proxy)
self.assertIn('ControlPath=none', proxy)
self.assertEqual(command[-2], '[email protected]')
self.assertEqual(command[-1], REMOTE_COMMAND)
self.assertEqual(command[1:3], ['-F', '/dev/null'])
if __name__ == '__main__':
unittest.main()
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Weekly writing quota and missed-window recovery; never publishes by itself."""
import argparse
from datetime import datetime, timedelta
import fcntl
import json
from pathlib import Path
import secrets
import sys
from zoneinfo import ZoneInfo
from release import atomic_json
ZONE = ZoneInfo('Asia/Shanghai')
STATE = Path(__file__).resolve().parents[2] / 'storage/app/private/weekly-tutorials/state.json'
def week_start(now):
return (now - timedelta(days=now.weekday())).date().isoformat()
def new_week(key):
monday = datetime.fromisoformat(key).replace(tzinfo=ZONE)
while True:
times = [monday + timedelta(days=secrets.choice(days), hours=15)
for days in ([0, 1], [2, 3], [4, 5, 6])]
if all(b - a >= timedelta(hours=24) for a, b in zip(times, times[1:])):
return {'slots': [{'slot_id': f'{key}-{i + 1}', 'planned_at': t.isoformat(), 'status': 'planned',
'release_id': None, 'published_at': None, 'urls': []} for i, t in enumerate(times)]}
def published_slots(state):
return [s for w in state['weeks'].values() for s in w['slots'] if s.get('published_at')]
def due(state, now):
if now.date().isoformat() < state['starts_on']:
return {'action': 'wait', 'reason': 'not_started'}
key = week_start(now)
state['weeks'].setdefault(key, new_week(key))
published = published_slots(state)
for slot in published:
if slot['status'] == 'published_pending':
return {'action': 'synchronize', 'slot': slot}
if any(datetime.fromisoformat(s['published_at']).astimezone(ZONE).date() == now.date() for s in published):
return {'action': 'wait', 'reason': 'already_published_today'}
# Uncertain old work must be reconciled before creating a new release or applying the quota.
for week in sorted(state['weeks']):
for slot in state['weeks'][week]['slots']:
if slot.get('release_id') and not slot.get('published_at') and slot['status'] != 'abandoned':
return {'action': 'resume', 'slot': slot}
count = sum(week_start(datetime.fromisoformat(s['published_at']).astimezone(ZONE)) == key for s in published)
if count >= 3:
return {'action': 'wait', 'reason': 'weekly_quota_met'}
for slot in state['weeks'][key]['slots']:
if slot['status'] == 'planned' and datetime.fromisoformat(slot['planned_at']) <= now:
return {'action': 'write', 'slot': slot}
return {'action': 'wait', 'reason': 'not_due'}
def record(state, slot_id, response, now):
if response.get('ok') is not True:
raise ValueError('No successful server response')
data = response['data']
receipt = data.get('receipt', {})
if receipt.get('status') != 'published' or data.get('phase') not in ('complete', 'published_pending'):
raise ValueError('No committed publication receipt')
slot = next(s for w in state['weeks'].values() for s in w['slots'] if s['slot_id'] == slot_id)
if slot.get('release_id') != data['release_id']:
raise ValueError('Release does not match claimed slot')
# Record actual server transaction timestamp, not the time a delayed response was received.
published_at = data.get('published_at')
if not published_at:
raise ValueError('Missing server publication timestamp')
instant = datetime.fromisoformat(published_at).astimezone(ZONE)
if instant > now + timedelta(minutes=5):
raise ValueError('Publication timestamp is in the future')
slot.update(status='published' if data['phase'] == 'complete' else 'published_pending',
published_at=instant.isoformat(), publication_id=receipt['publication_id'],
urls=[a['url'] for a in receipt['articles']], receipt_phase=data['phase'])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('operation', choices=['due', 'claim', 'record'])
parser.add_argument('--slot')
parser.add_argument('--release-id')
parser.add_argument('--receipt', type=Path)
args = parser.parse_args()
now = datetime.now(ZONE)
STATE.parent.mkdir(parents=True, exist_ok=True)
with open(STATE.with_suffix('.lock'), 'a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
# Missing/corrupt state must be reconciled with server receipts, not reset to an empty quota.
state = json.loads(STATE.read_text())
result = due(state, now)
if args.operation == 'claim':
import uuid
release_id = str(uuid.UUID(args.release_id))
if result['action'] != 'write' or result['slot']['slot_id'] != args.slot:
raise ValueError('Requested slot is not due')
result['slot'].update(status='drafting', release_id=release_id)
elif args.operation == 'record':
record(state, args.slot, json.loads(args.receipt.read_text()), now)
result = {'action': 'recorded', 'slot_id': args.slot}
atomic_json(STATE, state)
print(json.dumps(result, ensure_ascii=False))
if __name__ == '__main__':
try:
main()
except Exception as error:
print(json.dumps({'action': 'blocked', 'reason': str(error)}))
sys.exit(1)