Compare commits

..
5 changed files with 148 additions and 88 deletions

No files matched your search

@@ -8,6 +8,7 @@
use App\Services\TomTool\Telegram\Slave as TeleSlave; use App\Services\TomTool\Telegram\Slave as TeleSlave;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\File;
use Carbon\CarbonImmutable;
class FreenodeController extends Controller class FreenodeController extends Controller
{ {
@@ -22,7 +23,8 @@ public function filePut(Request $oRequest)
$sSubSiteCodeShort = $aData["site_code_short"]; $sSubSiteCodeShort = $aData["site_code_short"];
$aRaw = $aData["raw"]; $aRaw = $aData["raw"];
$sDate = date('Ymd'); // Subscription links use Beijing's calendar day, independently of app.timezone.
$sDate = CarbonImmutable::now('Asia/Shanghai')->format('Ymd');
$sSuffix = "nodes"; $sSuffix = "nodes";
$sRawKey = $sDate . $sSuffix; $sRawKey = $sDate . $sSuffix;
$sUniqueToken = hash_hmac('sha256', $sRawKey, 'wocaonide'); $sUniqueToken = hash_hmac('sha256', $sRawKey, 'wocaonide');
@@ -47,7 +49,7 @@ public function filePut(Request $oRequest)
} }
$sFileSavePath = $sSubSiteCodeShort."/".$sShortToken; $sFileSavePath = $sSubSiteCodeShort."/".$sShortToken;
$sFileSaveName = date("Ymd")."-".$sClient.$sExtension; $sFileSaveName = $sDate."-".$sClient.$sExtension;
$sFilePathFull = $sFileSavePath."/".$sFileSaveName; $sFilePathFull = $sFileSavePath."/".$sFileSaveName;
if (!File::isDirectory($sFileSavePath)) { if (!File::isDirectory($sFileSavePath)) {
+42 -20
View File
@@ -107,7 +107,7 @@ public static function fail(string $sChatCode = 'admin'): self
// new // new
public static function notify(string $sChatCode = 'admin'): self public static function notify(string $sChatCode = 'admin'): self
{ {
return self::start("notification", $sChatCode); return self::start("fail", $sChatCode);
} }
@@ -275,29 +275,51 @@ private function _send_master(): Flow
$aData = $this->buildDataTom(); $aData = $this->buildDataTom();
if ($this->enableSlaveQueue) { if ($this->enableSlaveQueue) {
return ServiceHttpQueue::start("telegram_master")->arg($aData)->save(); $oFlow = ServiceHttpQueue::start("telegram_master")->arg($aData)->save();
} else {
$oFlow = Flow::start("_send_master");
$sUrlMaSterBase = $_ENV["url_master_base"] ?? "";
if (!$sUrlMaSterBase) {
throw new \Exception("未设置env的url_master_base");
}
$sUrlMasterPost = "https://".$sUrlMaSterBase."/api/telegram/post";
try {
$oHttpV2 = HttpV2::make($sUrlMasterPost);
if ($this->enableAsync) {
$oHttpV2 = $oHttpV2->enableAsync();
}
$r = $oHttpV2->enableJsonAs()->setData($aData)->send();
if ($this->enableAsync) {
return $oFlow->sData("async")->done("async");
} else {
$a = json_decode($r, true);
$isDone = $a["isDone"] ?? false;
if ($isDone) {
return $oFlow->done();
} else {
return $oFlow->fail($r);
}
}
} catch (\Throwable $e) {
$oFlow = $oFlow->fail($e->getMessage());
}
} }
$flow = Flow::start("operations notification"); return $oFlow;
try {
$root = dirname(__DIR__, 4);
require_once $root . '/ops/AdminNotice.php';
$this->operationsEventKey ??= bin2hex(random_bytes(16));
$receipts = \LegacyOperations\AdminNotice::submit($root, $aData, $this->operationsEventKey);
return $flow->done('TeleHub accepted ' . implode(',', $receipts));
} catch (\Throwable $error) {
return $flow->fail($error->getMessage());
}
}
private ?string $operationsEventKey = null;
public function forOperationsQueueRow(int $id): self
{
$this->operationsEventKey = 'queue.' . $id;
return $this;
} }
// 直接从本地发到tg,几乎用不上,都走master了
private function _send_local(): Flow private function _send_local(): Flow
{ {
if ($this->enableSlaveQueue) { if ($this->enableSlaveQueue) {
+29
View File
@@ -0,0 +1,29 @@
# 免费节点订阅接收
Nodehub只负责接收和托管产物;上游生成、内核校验和站点分发见[master01维护正文](/Users/hellcat/Documents/GemCodes/dd.loc/docs/maintenance/FREENODE.md)。项目身份和访问规则见[GemDocs项目档案](/Users/hellcat/Documents/GemDocs/AI版/10-项目/nodehub.md)。
## 订阅日期契约
`POST /api/freenode/file/put`由`Api/v1/FreenodeController::filePut()`接收,参数仍为`site_code_short`和各格式`raw`,接口及链接算法不变。
接收时通过`CarbonImmutable::now('Asia/Shanghai')`确定一次业务日期,目录令牌和所有格式文件名均使用同一日期。应用默认时区仍为UTC,不改整个应用的日期、任务或日志。与master01按北京时间生成的当天链接保持一致;当天首次正常分发前不保证新日期文件已存在。
旧实现用UTC的`date()`,北京时间00:15、06:15两轮会写到前一天目录,直到12:15一轮才产生当天文件。2026-10-21已确认该问题;本次改动仅修复订阅接收日期,不移动历史文件、不复制旧节点伪造未来批次。
## 回归验证
`php vendor/bin/phpunit tests/Feature/FreenodeDateTest.php --do-not-cache-result`在隔离临时目录运行真实接收控制器,模拟北京时间零点前后以及00:15、06:15、12:15同步时刻,核对三种格式的日期、目录、内容以及全局UTC时区保持不变。Telegram被替换为测试对象,不访问网络或真实公开目录。
2026-10-21本机PHP 8.4.1通过5项、35断言。macOS本机使用真实PHP二进制`/usr/local/Cellar/php/8.4.1_1/bin/php`运行,避免Herd包装器导致PHPUnit隔离子进程启动失败。生产部署及验收结果另按实际记录。
## 发布与恢复
通过Git提交、服务端推送仓库,再将线上工作树更新到明确提交。提交只包括控制器、上述测试和本文;保留已有权限及未跟踪文件。部署前在服务器保存旧提交、控制器原字节/权限、工作区状态和当日订阅哈希;回退只还原本次控制器并记录代码版本,不reset整个有并行改动的工作树,不清除公开订阅目录。数据库、环境配置和系统时间不需要改动。
## 2026-10-21 部署验收
- 功能提交`0a1698b69d514a649a63040053fae1d96f30b7f4`,分支`codex/subscription-beijing-date`。按用户线上部署授权,通过SSH传送增量Git bundle,在Nodehub服务器侧推送既有`tom/nodehub`仓库,再更新工作树到明确提交;未从本机访问Git HTTP。
- 生产基线`d8aa76e7ad754b0dd4501efe2c91c9e7004fd43d`;旧控制器原文/权限、工作区状态、当日10文件哈希及激活记录在`/var/backups/nodehub-subscription-date-20261021/`。原有大量权限差异及未跟踪文件均保留,部署前后工作区状态摘要完全一致。未改全局UTC、数据库、环境、Nginx或系统时钟,未重启服务。
- 生产PHP 8.4.14通过5项、35断言。实际PHP-FPM另在隔离临时目录中模拟UTC `2026-10-21T16:15:00Z`与`22:15:00Z`(北京时间明日00:15/06:15),三格式均生成20261022对应目录和文件,响应成功、全局UTC未变、stderr为0;虚构内容与临时脚本已清理,没有伪造明天公开订阅。结果记录在同备份目录`fpm-date-check.json`。
- 通过master01现有接口重放当前已验证批次,四站全部成功;接收端10文件逐份哈希通过,URI/Sing-box精确一致,Clash与既有首尾空白处理后的内容一致。Nodehub服务器正常HTTPS请求这10份当日订阅全部200,响应哈希与文件一致。
- 已完成服务器侧验收,未做线上页面验收。未等到明天实际定时触发;已用实际FPM模拟对应跨日时段验证本次缺陷。后续若上游抓取、原生校验或网络另行失败,仍按各自错误调查,不把本次日期修复等同于整个链路永不失败。
-66
View File
@@ -1,66 +0,0 @@
<?php
declare(strict_types=1);
namespace LegacyOperations;
final class AdminNotice
{
public static function bot(string $code): string
{
return match ($code) {
'log' => 'log',
'warn', 'warning' => 'warning',
'fail', 'error' => 'error',
'notify', 'notification' => 'notification',
'base', 'admin', '' => 'base',
default => throw new \DomainException('Unregistered operations notification category'),
};
}
public static function submit(string $projectRoot, array $data, string $eventKey): array
{
$target = (string) ($data['sChatCode'] ?? '');
if (!in_array($target, ['', 'base', 'admin'], true) || !empty($data['iChatId']) || !empty($data['sBotToken'])) {
throw new \DomainException('Explicit Telegram recipients require their own publisher');
}
if (!empty($data['sPhotoUrl']) || !empty($data['sFileUrl'])) {
throw new \DomainException('Attachments require their original publisher');
}
$configPath = '/etc/telehub-operations/' . hash('sha256', $projectRoot) . '.json';
$config = json_decode((string) @file_get_contents($configPath), true, 16, JSON_THROW_ON_ERROR);
$bot = self::bot($data['sBotCode'] ?? '');
$text = (string) ($data['sMsg'] ?? '');
if (trim($text) === '') {
throw new \DomainException('Empty operations notification');
}
$title = '【' . $config['project'] . '/生产 - 运行通知】' . "\n";
$room = 4096 - mb_strlen($title, 'UTF-8');
$receipts = [];
foreach (mb_str_split($text, $room, 'UTF-8') as $part => $body) {
$payload = json_encode(['bot' => $bot, 'target' => 'base', 'text' => $title . $body], JSON_THROW_ON_ERROR);
$http = curl_init('https://telehub.gemcook.net/api/v1/messages');
curl_setopt_array($http, [
CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 4, CURLOPT_TIMEOUT => 15, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json', 'Accept: application/json',
'Authorization: Bearer ' . $config['key'],
'Idempotency-Key: ' . $eventKey . '.' . $part,
],
]);
$response = curl_exec($http);
$status = curl_getinfo($http, CURLINFO_RESPONSE_CODE);
curl_close($http);
$receipt = is_string($response) ? (json_decode($response, true)['data'] ?? []) : [];
if (!in_array($status, [200, 202], true) || empty($receipt['id'])) {
throw new \RuntimeException('TeleHub submission unconfirmed (HTTP ' . $status . ')');
}
if (in_array($receipt['status'] ?? '', ['failed', 'uncertain', 'cancelled'], true)) {
throw new \RuntimeException('TeleHub delivery requires review: ' . $receipt['id']);
}
$receipts[] = $receipt['id'];
}
return $receipts;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace Tests\Feature;
use App\Http\Controllers\Api\v1\FreenodeController;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use Tests\TestCase;
class FreenodeDateTest extends TestCase
{
public static function receivingTimes(): array
{
return [
'before Beijing midnight' => ['2026-10-21T15:59:59Z', '20261021'],
'Beijing midnight' => ['2026-10-21T16:00:00Z', '20261022'],
'midnight scheduled delivery' => ['2026-10-21T16:15:00Z', '20261022'],
'morning scheduled delivery' => ['2026-10-21T22:15:00Z', '20261022'],
'noon scheduled delivery' => ['2026-10-22T04:15:00Z', '20261022'],
];
}
#[DataProvider('receivingTimes')]
#[RunInSeparateProcess]
#[PreserveGlobalState(false)]
public function testReceiverWritesAllFormatsUnderBeijingDate(string $instant, string $date): void
{
$previousDirectory = getcwd();
$previousTimezone = date_default_timezone_get();
$directory = sys_get_temp_dir().'/nodehub-date-test-'.bin2hex(random_bytes(6));
mkdir($directory, 0700);
// Keep the real controller and filesystem, but never send Telegram in a test.
$telegram = Mockery::mock('alias:App\Services\TomTool\Telegram\Slave');
$telegram->shouldReceive('log')->once()->andReturnSelf();
$telegram->shouldReceive('enableDetail')->with(false)->once()->andReturnSelf();
$telegram->shouldReceive('send')->once();
try {
config(['app.timezone' => 'UTC', 'app.is_loc' => true]);
date_default_timezone_set('UTC');
CarbonImmutable::setTestNow(new CarbonImmutable($instant));
chdir($directory);
$raw = ['v2ray' => 'fixture-uri', 'clash' => 'fixture-clash', 'singbox' => 'fixture-singbox'];
$request = Request::create('/api/freenode/file/put', 'POST', ['site_code_short' => 'cfn', 'raw' => $raw]);
$response = (new FreenodeController())->filePut($request);
self::assertTrue($response->getData(true)['isDone']);
$token = substr(hash_hmac('sha256', $date.'nodes', 'wocaonide'), 0, 16);
foreach ($raw as $format => $content) {
$extension = $format === 'clash' ? '.yaml' : '.txt';
self::assertSame($content, file_get_contents($directory.'/cfn/'.$token.'/'.$date.'-'.$format.$extension));
}
self::assertCount(3, glob($directory.'/cfn/*/*'));
self::assertSame('UTC', date_default_timezone_get());
self::assertSame('UTC', config('app.timezone'));
} finally {
CarbonImmutable::setTestNow();
date_default_timezone_set($previousTimezone);
chdir($previousDirectory);
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
$file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
}
rmdir($directory);
Mockery::close();
}
}
}