Files
jccp_a/laravel/tests/Feature/ContentCenterTest.php
T

415 lines
23 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace Tests\Feature;
use App\ContentCenter\ArticleArtifact;
use App\ContentCenter\LinkedText;
use App\ContentCenter\PackageTable;
use App\ContentCenter\Publication;
use App\ContentCenter\ReformatPublished;
use App\ContentCenter\RenumberTitles;
use App\Services\Ranking\ArticleDocument;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Yaml\Yaml;
use Tests\TestCase;
final class ContentCenterTest extends TestCase
{
public function createApplication()
{
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
private string $root;
protected function setUp(): void
{
parent::setUp();
URL::forceRootUrl('http://ttc.loc');
Http::preventStrayRequests();
$this->root = sys_get_temp_dir().'/ttc-content-test-'.Str::uuid();
File::makeDirectory($this->root.'/vuepress/node_modules/.bin', 0755, true);
File::makeDirectory($this->root.'/vuepress/docs/jccp', 0755, true);
File::makeDirectory($this->root.'/laravel/storage/app/weekly-ranking', 0755, true);
ArticleDocument::write($this->root.'/laravel/config/ranking-merchants.json', '{"version":1,"merchants":{}}');
file_put_contents($this->root.'/vuepress/node_modules/.bin/vuepress', '<?php $dest=$argv[array_search("--dest",$argv)+1];mkdir($dest,0755,true);file_put_contents($dest."/index.html","isolated test build");');
config(['content_center.environment' => 'local', 'content_center.enabled' => true, 'content_center.atom_key' => str_repeat('k', 40), 'content_center.atom_url' => 'http://atom.loc', 'content_center.site_root' => $this->root, 'content_center.node' => PHP_BINARY, 'cache.default' => 'array']);
}
protected function tearDown(): void
{
File::deleteDirectory($this->root);
parent::tearDown();
}
private function input(int $generation = 1): array
{
return ['source_key' => 'telegram:-1001234567890:album:99', 'revision' => str_repeat('a', 64), 'generation' => $generation, 'title' => '测评标题', 'text' => '<script>bad()</script> {{ danger }}', 'sent_at' => '2026-10-24 08:01:01', 'images' => []];
}
private function signed(string $path, array $data, ?string $nonce = null)
{
$body = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$time = (string) time();
$nonce ??= bin2hex(random_bytes(16));
$sig = hash_hmac('sha256', $time."\n".$nonce."\nPOST\n".$path."\n".hash('sha256', $body), str_repeat('k', 40));
return $this->call('POST', $path, [], [], [], ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json', 'HTTP_X_CONTENT_TIME' => $time, 'HTTP_X_CONTENT_NONCE' => $nonce, 'HTTP_X_CONTENT_ENVIRONMENT' => 'local', 'HTTP_X_CONTENT_SIGNATURE' => $sig], $body);
}
public function test_preview_authenticates_and_does_not_write_or_build(): void
{
$this->postJson('/api/content/v1/preview', $this->input())->assertUnauthorized();
$nonce = bin2hex(random_bytes(16));
$response = $this->signed('/api/content/v1/preview', $this->input(), $nonce)->assertOk();
$markdown = $response->json('artifact.markdown');
$this->assertStringContainsString('&lt;script&gt;', $markdown);
$this->assertStringContainsString('<div v-pre>', $markdown);
$this->assertSame([], File::files($this->root.'/vuepress/docs/jccp'));
$this->signed('/api/content/v1/preview', $this->input(), $nonce)->assertStatus(409);
}
public function test_signed_preview_and_publish_preserve_an_empty_caption(): void
{
$bytes = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', true);
$image = ['sha256' => hash('sha256', $bytes), 'mime' => 'image/gif', 'bytes' => strlen($bytes)];
$input = array_replace($this->input(), ['text' => '', 'images' => [$image]]);
$response = $this->signed('/api/content/v1/preview', $input)->assertOk();
$this->assertStringContainsString('/content-assets/'.$image['sha256'].'.gif', $response->json('artifact.markdown'));
$directory = $this->root.'/vuepress/docs/.vuepress/public/content-assets';
File::ensureDirectoryExists($directory);
file_put_contents($directory.'/'.$image['sha256'].'.gif', $bytes);
$payload = ['approval_id' => (string) Str::uuid(), 'approved_hash' => $response->json('artifact_hash'), 'input' => $input];
$this->signed('/api/content/v1/publish', $payload)->assertOk()->assertJsonPath('receipt.artifact_hash', $payload['approved_hash']);
unset($input['text']);
$this->signed('/api/content/v1/preview', $input)->assertUnprocessable()->assertJsonValidationErrors('text');
$input['text'] = null;
$this->signed('/api/content/v1/preview', $input)->assertUnprocessable()->assertJsonValidationErrors('text');
}
private function reviewInput(): array
{
return array_replace($this->input(), ['title' => '#测试云 #vless', 'text' => "#测试云 #vless\n\n📊 主观评分\n稳定 ★★☆☆☆\n速度 ★★☆☆☆\n延迟 ★★★☆☆\n性价比 ★★★☆☆\n(以上评分仅供参考)\n\n😀机场自介:\n自介内容\n\n😀 链接导航\n官网:点击进入\n\n😀主观点评\n点评内容 <script>bad()</script> {{ danger }}\n\n😀翻翻墙提醒您\n原始提醒"]);
}
public function test_review_has_existing_ttc_format_and_only_existing_tags(): void
{
$a = app(ArticleArtifact::class)->build($this->reviewInput());
$meta = Yaml::parse(explode('---', $a['markdown'])[1]);
$this->assertSame(['机场测评', '每天测速'], $meta['tags']);
$this->assertSame('测试云机场测速 ★ 10', $meta['title']);
$this->assertSame(10, $meta['scoreTotal']);
$this->assertSame('2026-10-24 16:01:01', $meta['createTime']);
foreach (['::: tip 天天测提醒您', '::: important 天天测打分', '::: important 天天测点评', '## 机场自介', '## 链接导航', '## 节点测试'] as $part) {
$this->assertStringContainsString($part, $a['markdown']);
}
$this->assertStringContainsString('点评内容', $meta['excerpt']);
$this->assertStringContainsString('ttc-rating-excerpt', $meta['excerpt']);
$this->assertStringNotContainsString('频道导入', $a['markdown']);
$this->assertStringNotContainsString('<script>', $a['markdown']);
$this->assertStringContainsString('<div v-pre>', $a['markdown']);
}
public function test_rating_emoji_keep_native_format_title_and_score(): void
{
$input = $this->reviewInput();
$input['text'] = str_replace(
['速度 ★★☆☆☆', '延迟 ★★★☆☆'],
['速度 😀🚀★👩🏻‍💻★☆☆☆ 🔥', '⏱️ 延迟:★★ 🇯🇵★☆☆ ✨'],
$input['text'],
);
$artifact = app(ArticleArtifact::class)->build($input);
$meta = Yaml::parse(explode('---', $artifact['markdown'])[1]);
$this->assertSame('测试云机场测速 ★ 10', $meta['title']);
$this->assertSame(10, $meta['scoreTotal']);
$this->assertStringContainsString('速度:★★☆☆☆', $artifact['markdown']);
$this->assertStringContainsString('延迟:★★★☆☆', $artifact['markdown']);
$this->assertStringContainsString('::: important 天天测打分', $artifact['markdown']);
}
public function test_ambiguous_or_missing_rating_stars_are_not_guessed(): void
{
foreach (['速度 😀🔥', '速度 ★★/★★★', '速度 2星'] as $badScore) {
$input = $this->reviewInput();
$input['text'] = str_replace('速度 ★★☆☆☆', $badScore, $input['text']);
$artifact = app(ArticleArtifact::class)->build($input);
$this->assertStringNotContainsString('::: important 天天测打分', $artifact['markdown']);
}
}
private function repairJob(bool $normalizeEmptyTags = false): array
{
$input = $this->reviewInput();
$old = app(ArticleArtifact::class)->build($input);
File::makeDirectory($this->root.'/vuepress/docs/.vuepress', 0755, true);
$old['markdown'] = "---\ntitle: legacy\ntags: { }\n---\n<div v-pre>legacy</div>";
unset($old['title'],$old['format_version']);
$hash = ArticleArtifact::hash($old);
$id = (string) Str::uuid();
$dir = $this->root.'/laravel/storage/app/private/content-center/publications';
File::makeDirectory($dir, 0700, true);
$receipt = ['source_key' => $input['source_key'], 'approval_id' => $id, 'artifact_hash' => $hash, 'generation' => $input['generation'], 'permalink' => $old['permalink'], 'status' => 'published'];
foreach ([hash('sha256', $input['source_key']), $id] as $key) {
file_put_contents($dir.'/'.$key.'.json', json_encode($receipt));
}
$markdown = $normalizeEmptyTags ? Publication::siteMarkdown($old['markdown']) : $old['markdown'];
file_put_contents($this->root.'/vuepress/docs/'.$old['relative_path'], $markdown);
return ['input' => $input, 'old_artifact' => $old, 'expected_hash' => $hash, 'approval_id' => $id];
}
public function test_format_repair_keeps_approval_permalink_and_is_idempotent(): void
{
$job = $this->repairJob();
$a = app(ReformatPublished::class)->run($job);
$this->assertTrue($a['changed']);
$this->assertSame($job['approval_id'], $a['receipt']['approval_id']);
$this->assertSame($job['old_artifact']['permalink'], $a['receipt']['permalink']);
$this->assertFalse(app(ReformatPublished::class)->run($job)['changed']);
}
public function test_format_repair_accepts_site_normalized_empty_tags(): void
{
$job = $this->repairJob(normalizeEmptyTags: true);
$path = $this->root.'/vuepress/docs/'.$job['old_artifact']['relative_path'];
$this->assertStringContainsString('tags: []', file_get_contents($path));
$repair = app(ReformatPublished::class)->run($job);
$this->assertTrue($repair['changed']);
$this->assertSame(Publication::siteMarkdown($repair['artifact']['markdown']), file_get_contents($path));
$this->assertFalse(app(ReformatPublished::class)->run($job)['changed']);
}
public function test_format_repair_rejects_an_unreviewed_replacement_hash(): void
{
$job = $this->repairJob();
$path = $this->root.'/vuepress/docs/'.$job['old_artifact']['relative_path'];
$job['replacement_hash'] = str_repeat('0', 64);
try {
app(ReformatPublished::class)->run($job);
$this->fail('Expected the candidate version to be rejected');
} catch (HttpException $exception) {
$this->assertSame(409, $exception->getStatusCode());
$this->assertSame($job['old_artifact']['markdown'], file_get_contents($path));
}
}
public function test_format_repair_restores_old_article_on_build_failure(): void
{
$job = $this->repairJob(normalizeEmptyTags: true);
file_put_contents($this->root.'/vuepress/node_modules/.bin/vuepress', '<?php exit(1);');
try {
app(ReformatPublished::class)->run($job);
$this->fail('Expected failure');
} catch (\RuntimeException) {
$this->assertSame(Publication::siteMarkdown($job['old_artifact']['markdown']), file_get_contents($this->root.'/vuepress/docs/'.$job['old_artifact']['relative_path']));
}
}
public function test_format_repair_rejects_concurrent_edit(): void
{
$job = $this->repairJob();
file_put_contents($this->root.'/vuepress/docs/'.$job['old_artifact']['relative_path'], 'concurrent edit');
$this->expectException(HttpException::class);
app(ReformatPublished::class)->run($job);
}
public function test_legacy_receive_cannot_bypass_content_review(): void
{
$this->postJson('/api/article/receive/schema', ['cmd' => 'new'])->assertStatus(410);
$this->assertSame([], File::files($this->root.'/vuepress/docs/jccp'));
}
public function test_wrong_hash_cannot_publish(): void
{
$this->signed('/api/content/v1/publish', ['approval_id' => (string) Str::uuid(), 'approved_hash' => str_repeat('0', 64), 'input' => $this->input()])->assertStatus(409);
$this->assertSame([], File::files($this->root.'/vuepress/docs/jccp'));
}
public function test_approved_publication_is_idempotent_and_old_generation_cannot_overwrite_new(): void
{
$input = $this->input(20);
$artifact = app(ArticleArtifact::class)->build($input);
$payload = ['approval_id' => (string) Str::uuid(), 'approved_hash' => ArticleArtifact::hash($artifact), 'input' => $input];
$one = $this->signed('/api/content/v1/publish', $payload)->assertOk()->assertJsonPath('receipt.status', 'published');
$this->signed('/api/content/v1/publish', $payload)->assertOk()->assertJsonPath('receipt.approval_id', $payload['approval_id']);
$this->assertSame(1, count(File::files($this->root.'/vuepress/docs/jccp')));
$old = $this->input(10);
$this->signed('/api/content/v1/publish', ['approval_id' => (string) Str::uuid(), 'approved_hash' => ArticleArtifact::hash(app(ArticleArtifact::class)->build($old)), 'input' => $old])->assertStatus(409);
}
public function test_failed_build_restores_source_and_preserves_previous_dist(): void
{
File::makeDirectory($this->root.'/vuepress/docs/.vuepress/dist', 0755, true);
file_put_contents($this->root.'/vuepress/docs/.vuepress/dist/index.html', 'previous');
file_put_contents($this->root.'/vuepress/node_modules/.bin/vuepress', '<?php exit(1);');
$input = $this->input();
$artifact = app(ArticleArtifact::class)->build($input);
try {
app(Publication::class)->publish(['approval_id' => (string) Str::uuid(), 'approved_hash' => ArticleArtifact::hash($artifact), 'input' => $input]);
$this->fail('Expected build failure');
} catch (\RuntimeException) {
$this->assertFileDoesNotExist($this->root.'/vuepress/docs/'.$artifact['relative_path']);
$this->assertSame('previous', file_get_contents($this->root.'/vuepress/docs/.vuepress/dist/index.html'));
}
}
public function test_delete_removes_only_owned_article_and_blocks_old_approved_publish(): void
{
$input = $this->input();
$artifact = app(ArticleArtifact::class)->build($input);
$payload = ['approval_id' => (string) Str::uuid(), 'approved_hash' => ArticleArtifact::hash($artifact), 'input' => $input];
$this->signed('/api/content/v1/publish', $payload)->assertOk();
file_put_contents($this->root.'/vuepress/docs/jccp/existing.md', 'keep me');
$delete = ['source_key' => $input['source_key'], 'deletion_id' => (string) Str::uuid()];
$this->signed('/api/content/v1/delete', $delete)->assertOk()->assertJsonPath('receipt.status', 'deleted');
$this->assertFileDoesNotExist($this->root.'/vuepress/docs/'.$artifact['relative_path']);
$this->assertSame('keep me', file_get_contents($this->root.'/vuepress/docs/jccp/existing.md'));
$this->signed('/api/content/v1/delete', $delete)->assertOk();
$this->signed('/api/content/v1/publish', $payload)->assertStatus(409);
}
public function test_delete_build_failure_restores_original_and_retry_succeeds(): void
{
$input = $this->input();
$artifact = app(ArticleArtifact::class)->build($input);
$payload = ['approval_id' => (string) Str::uuid(), 'approved_hash' => ArticleArtifact::hash($artifact), 'input' => $input];
$this->signed('/api/content/v1/publish', $payload)->assertOk();
$builder = $this->root.'/vuepress/node_modules/.bin/vuepress';
$original = file_get_contents($builder);
file_put_contents($builder, '<?php exit(1);');
$data = ['source_key' => $input['source_key'], 'deletion_id' => (string) Str::uuid()];
try {
app(Publication::class)->delete($data);
$this->fail('expected build failure');
} catch (\RuntimeException) {
}
$this->assertFileExists($this->root.'/vuepress/docs/'.$artifact['relative_path']);
$this->signed('/api/content/v1/publish', $payload)->assertStatus(409);
file_put_contents($builder, $original);
$this->signed('/api/content/v1/delete', $data)->assertOk();
$this->assertFileDoesNotExist($this->root.'/vuepress/docs/'.$artifact['relative_path']);
}
private function packageFixture(): array
{
return ['headers' => ['套餐', '流量', '月付', '季付', '半年', '年付', '一次性'], 'rows' => [['基础', '100GB', '10.00', '×', '×', '×', '×']]];
}
public function test_hidden_official_link_and_separate_frozen_package_table_follow_legacy_layout(): void
{
$input = $this->reviewInput();
$input['text'] = str_replace('官网:点击进入', "官网:点击进入\n套餐:https://example.com/package\n论坛:https://www.ffqla.net/thread-932-1-1.html", $input['text']);
$offset = LinkedText::length(substr($input['text'], 0, strpos($input['text'], '点击进入')));
$input['links'] = [['offset' => $offset, 'length' => 4, 'url' => 'https://example.com/shop?a=1&b=2']];
$input['package_table'] = $this->packageFixture();
$a = app(ArticleArtifact::class)->build($input);
$md = $a['markdown'];
$this->assertStringContainsString('href="https://example.com/shop?a=1&amp;b=2"', $md);
$this->assertStringContainsString('>点击进入</a>', $md);
$this->assertStringContainsString('## 套餐价格', $md);
$this->assertStringContainsString('100GB', $md);
$nav = explode('## 套餐价格', explode('## 链接导航', $md)[1])[0];
$this->assertStringNotContainsString('论坛', $nav);
$this->assertStringNotContainsString('套餐', $nav);
Http::assertNothingSent();
$input['package_table']['rows'][0][2] = '12.00';
$this->assertNotSame(ArticleArtifact::hash($a), ArticleArtifact::hash(app(ArticleArtifact::class)->build($input)));
}
public function test_package_parser_uses_first_markdown_table_and_discards_active_markup(): void
{
$html = '<div class="markdown-body"><table><thead><tr>';
foreach ($this->packageFixture()['headers'] as $v) {
$html .= '<th>'.$v.'</th>';
}
$html .= '</tr></thead><tbody><tr>';
foreach ($this->packageFixture()['rows'][0] as $v) {
$html .= '<td onclick="bad()">'.$v.'<script>bad()</script></td>';
}
$html .= '</tr></tbody></table><table><tr><td>ignore</td></tr></table></div>';
$t = PackageTable::parse($html);
$this->assertSame($this->packageFixture(), $t);
$rendered = PackageTable::render($t);
$this->assertStringNotContainsString('script', $rendered);
$this->assertStringNotContainsString('onclick', $rendered);
}
public function test_missing_package_data_cannot_silently_publish_or_fetch_during_build(): void
{
$input = $this->reviewInput();
$input['text'] .= "\n论坛:https://www.ffqla.net/thread-932-1-1.html";
$this->expectException(\RuntimeException::class);
app(ArticleArtifact::class)->build($input);
}
public function test_package_fetch_rejects_redirect_to_unregistered_host(): void
{
Http::fake(['https://www.ffqla.net/*' => Http::response('', 302, ['Location' => 'http://127.0.0.1/private'])]);
$this->expectException(\RuntimeException::class);
app(PackageTable::class)->fetch('https://www.ffqla.net/thread-932-1-1.html');
}
public function test_title_sequence_counts_published_articles_and_retries_keep_number(): void
{
$one = $this->reviewInput();
$one['source_key'] = 'first';
$a = app(ArticleArtifact::class)->build($one);
$this->assertStringContainsString('测试云机场测速 ★ 10', $a['markdown']);
$two = array_replace($one, ['source_key' => 'second']);
$preview = app(ArticleArtifact::class)->build($two);
$this->assertSame($a['title'], $preview['title']);
$id = (string) Str::uuid();
$receipt = app(Publication::class)->publish(['approval_id' => $id, 'approved_hash' => ArticleArtifact::hash($a), 'input' => $one]);
$b = app(ArticleArtifact::class)->build($two);
$this->assertStringContainsString('测试云机场测速(第2次)', $b['title']);
$this->assertNotSame(ArticleArtifact::hash($preview), ArticleArtifact::hash($b));
$again = app(Publication::class)->publish(['approval_id' => $id, 'approved_hash' => ArticleArtifact::hash($a), 'input' => $one]);
$this->assertSame($receipt, $again);
$this->assertSame($a['title'], app(ArticleArtifact::class)->build($one)['title']);
}
public function test_same_title_previews_cannot_publish_duplicate_sequence(): void
{
$one = $this->reviewInput();
$one['source_key'] = 'first';
$two = array_replace($one, ['source_key' => 'second']);
$a = app(ArticleArtifact::class)->build($one);
$b = app(ArticleArtifact::class)->build($two);
app(Publication::class)->publish(['approval_id' => (string) Str::uuid(), 'approved_hash' => ArticleArtifact::hash($a), 'input' => $one]);
$this->expectException(HttpException::class);
app(Publication::class)->publish(['approval_id' => (string) Str::uuid(), 'approved_hash' => ArticleArtifact::hash($b), 'input' => $two]);
}
public function test_existing_titles_are_numbered_by_date_and_preserve_body_and_permalink(): void
{
$dir = $this->root.'/vuepress/docs/jccp/';
foreach (['z' => ['2026-01-01', '念云机场测评 & 测速'], 'a' => ['2026-02-01', '念云机场测评 & 测速']] as $file => [$date,$title]) {
file_put_contents($dir.$file.'.md', "---\ntitle: '$title ★ 10'\nbaseTitle: '$title'\ncreateTime: '$date'\npermalink: /jccp/$file/\ntags: [机场测评]\n---\n原文不可改\n");
}
File::makeDirectory($this->root.'/vuepress/docs/.vuepress', 0755, true, true);
$plan = app(RenumberTitles::class)->run();
$this->assertSame(2, $plan['changed']);
$first = ArticleDocument::read($dir.'z.md');
$second = ArticleDocument::read($dir.'a.md');
$this->assertSame('念云机场测速 ★ 10', $first['meta']['title']);
$this->assertSame('念云机场测速(第2次) ★ 10', $second['meta']['title']);
$this->assertSame('/jccp/a/', $second['meta']['permalink']);
$this->assertSame("原文不可改\n", $second['body']);
$this->assertSame(0, app(RenumberTitles::class)->run()['changed']);
}
}