Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9971b6fab5 | ||
|
|
7b46eed243 | ||
|
|
2c92a857e8 | ||
|
|
d552b8a592 | ||
|
|
a11df4fe56 | ||
|
|
42813c30cb | ||
|
|
0f78c664ff | ||
|
|
30b36f01c6 | ||
|
|
66ded03d80 | ||
|
|
c5513e18b9 | ||
|
|
a50fc3f77d | ||
|
|
9c6ef63a81 | ||
|
|
ac797a3b1f | ||
|
|
d8057f06e0 | ||
|
|
21a6bcff34 | ||
|
|
5a55fae630 | ||
|
|
29752628df | ||
|
|
b91e4b82e2 | ||
|
|
824d0f4167 | ||
|
|
6f6abdfc05 | ||
|
|
3beacbd172 | ||
|
|
3ddbf98057 | ||
|
|
ed4ec7fd71 | ||
|
|
7e9d65ccae | ||
|
|
4065f1d755 | ||
|
|
ab3d13bc69 | ||
|
|
7919a9f33f | ||
|
|
fb5d6a90d4 | ||
|
|
0744b9ac99 | ||
|
|
8afb1d44fb | ||
|
|
6a7e941c8a | ||
|
|
6e09553f91 | ||
|
|
3e9e6606fc | ||
|
|
f584444183 | ||
|
|
4ab037711f | ||
|
|
89bbc2a211 | ||
|
|
ce2a2ad578 | ||
|
|
c0e86a7deb | ||
|
|
5a75c839b9 | ||
|
|
08100a207f | ||
|
|
435fe9dc8d | ||
|
|
7b1d04547e | ||
|
|
6c7e7c8318 | ||
|
|
28ccc0e964 | ||
|
|
2022184583 | ||
|
|
f236c58935 | ||
|
|
7446b045a3 | ||
|
|
0501711267 |
No files matched your search
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers\V2\Admin;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Services\CustomerService\Settings;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
class CustomerServiceController extends Controller
|
||||
{
|
||||
public function fetch(Settings $settings) { return $this->success($settings->all()); }
|
||||
public function save(Request $request, Settings $settings) {
|
||||
$data=$request->validate([
|
||||
'enabled'=>'required|boolean','base_url'=>'present|nullable|url:http,https|max:255',
|
||||
'website_token'=>'present|nullable|string|max:255', 'working_hours'=>'present|nullable|string|max:200',
|
||||
'offline_title'=>'required|string|max:100','offline_message'=>'required|string|max:500',
|
||||
'ticket_url'=>'required|string|max:500','telegram_enabled'=>'required|boolean',
|
||||
'telegram_bot_code'=>'required|regex:/^[a-z0-9_-]+$/|max:64',
|
||||
'telegram_target_code'=>'required|regex:/^[a-z0-9_-]+$/|max:64',
|
||||
]);
|
||||
$data['base_url']=rtrim($data['base_url']??'', '/');
|
||||
$data['website_token']=$data['website_token']??'';
|
||||
$data['working_hours']=$data['working_hours']??'';
|
||||
if ($data['enabled'] && (!$data['base_url'] || !$data['website_token'])) {
|
||||
throw ValidationException::withMessages(['enabled'=>'启用客服需要服务地址和网站标识']);
|
||||
}
|
||||
$parts=parse_url($data['base_url']);
|
||||
if ($data['base_url'] && (!$parts || isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment']) || !empty($parts['path']))) {
|
||||
throw ValidationException::withMessages(['base_url'=>'请填写不带路径或认证信息的服务源地址']);
|
||||
}
|
||||
if (!str_starts_with($data['ticket_url'],'/') || str_starts_with($data['ticket_url'],'//') || preg_match('/[\\\\\x00-\x20]/',$data['ticket_url'])) {
|
||||
throw ValidationException::withMessages(['ticket_url'=>'工单入口必须是本站绝对路径']);
|
||||
}
|
||||
admin_setting(['customer_service'=>$data]);
|
||||
return $this->success($settings->all());
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,8 @@ class AdminRoute
|
||||
'prefix' => 'config'
|
||||
], function ($router) {
|
||||
$router->get('/fetch', [ConfigController::class, 'fetch']);
|
||||
$router->get('/customerService', [\App\Http\Controllers\V2\Admin\CustomerServiceController::class, 'fetch']);
|
||||
$router->post('/customerService', [\App\Http\Controllers\V2\Admin\CustomerServiceController::class, 'save']);
|
||||
$router->get('/telegramTicket', [\App\Http\Controllers\V2\Admin\TelegramTicketController::class, 'fetch']);
|
||||
$router->post('/telegramTicket', [\App\Http\Controllers\V2\Admin\TelegramTicketController::class, 'save']);
|
||||
$router->post('/telegramTicketBind', [\App\Http\Controllers\V2\Admin\TelegramTicketController::class, 'bindCode']);
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Services\Plugin\HookManager;
|
||||
use App\Utils\CacheKey;
|
||||
use App\Utils\Helper;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class LoginService
|
||||
{
|
||||
@@ -110,7 +111,17 @@ class LoginService
|
||||
$user->password_algo = NULL;
|
||||
$user->password_salt = NULL;
|
||||
|
||||
if (!$user->save()) {
|
||||
// Password recovery invalidates every existing login, including the caller's.
|
||||
// Commit both changes together so a revocation failure cannot leave old sessions valid.
|
||||
$saved = DB::transaction(function () use ($user) {
|
||||
if (!$user->save()) {
|
||||
return false;
|
||||
}
|
||||
$user->tokens()->delete();
|
||||
return true;
|
||||
});
|
||||
|
||||
if (!$saved) {
|
||||
return [false, [500, __('Reset failed')]];
|
||||
}
|
||||
|
||||
@@ -152,4 +163,4 @@ class LoginService
|
||||
|
||||
return $url;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
namespace App\Services\CustomerService;
|
||||
|
||||
class Settings
|
||||
{
|
||||
public const DEFAULTS = [
|
||||
'enabled' => false, 'base_url' => '', 'website_token' => '',
|
||||
'working_hours' => '工作日早9点至晚5点',
|
||||
'offline_title' => '当前没有在线客服',
|
||||
'offline_message' => '您可以在这里留言,客服上线后会尽快回复。',
|
||||
'ticket_url' => '/#/tickets', 'telegram_enabled' => false,
|
||||
'telegram_bot_code' => 'base', 'telegram_target_code' => 'base',
|
||||
];
|
||||
public function all(): array
|
||||
{
|
||||
return array_replace(self::DEFAULTS, array_intersect_key((array) admin_setting('customer_service', []), self::DEFAULTS));
|
||||
}
|
||||
public function publicConfig(): array
|
||||
{
|
||||
return array_diff_key($this->all(), array_flip(['telegram_enabled','telegram_bot_code','telegram_target_code']))
|
||||
+ ['online_count'=>max(0,min(3,(int)admin_setting('customer_service_display_count',1)))];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
# XB 通用客服集成 / Chatwoot 本地试用
|
||||
|
||||
## 范围与状态
|
||||
|
||||
当前默认外观见 [XB 共用客服外观](#xb-共用客服外观)。本页其他按日期记录的样式调整属于实施历史。
|
||||
|
||||
## 2026-11-07 Fuc 本地焦点与遮挡修复
|
||||
|
||||
仅 `theme/Fuc/assets/chatwoot.mjs` 与 `customer-service.css` 的主题适配层变更:原生 SDK 关闭后恢复启动按钮焦点的行为保留;鼠标/触屏输入不显示残留光圈,键盘导航显示主题色焦点提示,覆盖 Safari 的系统蓝色 outline。手机用户菜单展开期间隐藏启动按钮与客服窗,菜单关闭恢复。没有修改 XB 共用客服、HN 外观、服务端配置、会话或接待规则。
|
||||
|
||||
IAB 实际打开/关闭 iframe 后,启动按钮仍获得焦点,outline 为 none;键盘焦点仍有主题色光圈。菜单开关与客服可见性回读通过。iOS 模拟器仅完成刷新观察,原生点击控制失败,未完成实际开关复验。未发消息,未发布。详细记录及本地截图见 `codex/output/fuc-theme/ui-sweep-20261107/` 与 [Fuc 集中复核](FUC_THEME.md#2026-11-07-前台集中复核本地完成未发布)。
|
||||
|
||||
用户2026-11-02明确:产品目标是XB通用客服版本,FUC-XB只是演示/验收实例。2026-11-03明确要求客服归XB共用功能,并在说明后台按实例配置后回复“弄”,已据此批准本地核心迁移;当前实现见下一节。DPL未启用;HN原生样式试用见下节。客服系统尚未部署到生产。
|
||||
|
||||
## HN 原生挂件预览(2026-11-06)
|
||||
|
||||
HN 在 `http://hn.loc/` 预览 Chatwoot 原生圆形按钮与聊天窗,使用同一台本地 Chatwoot 的独立账号与网站收件箱。通过 HN 本地数据库的 `theme_ez.native_support_website_token` 配置公开挂件标识,EZ 入口仅在 HN 实例且访问来源为 `http://hn.loc` 时加载官方 SDK。Chatwoot iframe 只允许该来源嵌入。HN 使用原生主题色、品牌和布局,按网站收件箱来源跳过 FUC-XB 的自定义挂件样式与离线脚本。此预览无 XB 身份映射或 Telegram 桥接。
|
||||
|
||||
现有本地 Chatwoot 安装管理员同时管理 HN 收件箱,FUC-XB 坐席与会话未迁入。回退时仅从 HN 本地的 `theme_ez` 设置移除 `native_support_website_token`,保留其余主题字段和收件箱历史。XB 共用客服设置与发布流程沿用现有实现。
|
||||
|
||||
本地验收完成:HN 首页渲染自己的公开挂件配置,Chatwoot iframe 返回默认蓝色及原生品牌标记,HTTP 响应限制只由 `http://hn.loc` 嵌入。FUC-XB 首页继续加载现有样式。5 项 PHP 设置测试和 5 项 Node 挂件回归通过。内置浏览器已从 HN 仪表盘展开原生聊天窗,截图 `codex/output/chatwoot/hn-native-widget-20261106.jpg`。本轮只验收打开和显示,未测试消息收发或发布线上。
|
||||
|
||||
## XB共用层迁移(2026-11-03,本地已完成)
|
||||
|
||||
授权:用户明确纠正“客服系统是做进xb里,不是主题”,在确认共用后台、实例隔离配置范围后指示“弄”。这次仅本地核心代码/验收,不授权提交、推送或生产发布。保留既有并行修改。
|
||||
|
||||
- 唯一设置为当前实例v2_settings的`customer_service`;Settings类默认关闭。管理API为`/api/v2/<secure_path>/config/customerService`,复用原admin与log中间件,匿名和非管理员拒绝。可配置服务源、公开website token、工作时间、离线标题/说明、站内工单路径、TG开关和TeleHub bot/target代号。无新数据库结构,不保存TG明文token。
|
||||
- XB后台新增“客服系统”入口及独立配置页`/<secure_path>/customer-service`,由本站管理员token授权API;没有改public/assets/admin第三方构建产物。当前本地为`http://xb.loc/fuc-qa-admin/customer-service`。原独立验收实例没有管理员,按ACC-005约定创建并真实登录核实;未修改其他实例管理员。
|
||||
- 共用routes/web.php渲染所有主题时输出公开显示配置并加载`public/customer-service/widget.mjs`;主题不再初始化客服。Fuc模板移除旧块、config移除两个字段,旧模块仅保留空兼容文件;演示实例旧字段已迁移并移除。未启用实例不加载SDK。其他主题走相同共用渲染路径,尚未逐主题页面复验。
|
||||
- 离线说明通过固定Chatwoot模板适配`xb-offline.js`,严格校验父窗口origin/source,使用textContent显示,不传XB身份或秘密;工单入口限定本站路径。在线卡片不附加离线说明。现工作时间“周一至周五 9:00–17:00”,显示留言说明及工单链接。
|
||||
- TG桥启动读取`xb-settings.php`当前XB实例配置,bot/target仍从TeleHub安全管道读取;保留原账本、引用回复、上班下班和自动回复标注。运行中每30秒检查运行设置(开关、源地址、TG代号),变化则安全退出,须重启接待进程应用;显示文案改变无需重启桥,只刷新访客页。当前仍是本机临时接待进程,没有系统自启。生产部署时需明确实例环境、Chatwoot凭据/receipt与状态目录、TeleHub执行环境,不能把本地默认fuc-acceptance当生产配置。
|
||||
|
||||
验收:4项PHP/13断言验证默认关闭、主题设置不启用共用客服、管理员权限、保存回读、危险URL拒绝;3项Node验证URL/隐私/单次加载及离线父源隔离、内容更新和在线状态清除;6项Python桥测试通过。真实HTTP管理员登录、匿名403、保存回读、核心唯一初始化和适配脚本200均通过,证据`core-customer-service-acceptance.json`。
|
||||
|
||||
IAB实际登录XB,进入共用客服配置页,切换启用开关、编辑工作时间、保存并刷新回读通过;离线挂件实际显示标题/时间/留言/工单链接,截图`xb-core-admin-20261103.jpg`、`xb-core-offline-20261103.jpg`位于codex/output/chatwoot。此前浏览器断连后已恢复验收。TG首次重启数次TLS失败,之后重试日志确认Bridge ready;本轮未重新发送TG引用/上下班测试,不扩大旧双向验收结论。
|
||||
|
||||
迁移前演示设置在忽略的`codex/output/chatwoot/core-settings-before.json`;恢复时只恢复customer_service与旧主题两字段的任务范围,撤销共用加载器/后台入口及模板适配,再启动匹配旧桥;保留其他主题配置、聊天数据、TG账本,不整库回滚。未提交、推送、部署生产。后文主题接入及“不涉及核心”为迁移前历史阶段,不代表当前实现。
|
||||
|
||||
用户2026-11-01要求“在xb里搭一个chatwoot,接到FUC-XB看看”,随后强调不是老FUC。
|
||||
|
||||
接入目标为当前XB的 `theme/Fuc` 和 `instances/fuc-acceptance` 独立本地验收实例,入口 `http://xb.loc`(回环8594)。不以 `fuc.loc`、`fuc-new.loc` 或线上FUC为运行/写入目标,不复制它们的用户、会话或订单。DPL/HN仍使用各自配置。
|
||||
|
||||
Chatwoot配置在 `integrations/chatwoot/`,官方社区版 `chatwoot/chatwoot:v4.19.1-ce`,独立PostgreSQL/Redis/存储卷,专用Colima profile `xb-chatwoot`。管理与挂件服务使用固定本地域名 `http://chatwoot.loc`;用户提供管理员凭据后,本任务已执行 `install-domain.py`,hosts/Nginx已配置并通过完整检查;恢复目录 `/private/var/tmp/xb-chatwoot-domain-20261101-195541/`。内部宿主只监听127.0.0.1:8596,数据库和Redis不发布宿主端口。不新增生产域名、反代或系统登录自启。VM显式只读挂载本集成目录;VM内应用与数据库均存独立卷。
|
||||
|
||||
**本地搭建与接入已完成;2026-11-02内置浏览器已完成挂件展开与样式检查,浏览器消息收发/实时推送尚未复验。** Chatwoot网页、Sidekiq、PostgreSQL和Redis均运行;数据库/Redis健康。FUC-XB首页、Chatwoot登录页和官方SDK均HTTP200,宿主服务端口仅127.0.0.1:8596。真实访客消息进入管理员收件箱,管理员真实API回复出现在访客消息接口;合成测试会话编号1。未启用AI自动回复,不代表支付、订单查询或人工实际接待已验收。
|
||||
|
||||
实际Chatwoot镜像摘要:`sha256:04895c7bd0550d9e74b45b7202787b56f7ee4e891ebbde0c429c8c32901b97cf`。首次空库启动时AI SDK初始化提示installation_configs尚不存在,官方prepare退出0完成建库,后续启动正常;AI能力不在本次范围。初始化已按上游完成安装标记,登录页不再重定向首次安装向导。管理员拥有本地安装者与收件箱管理员权限,已真实API登录成功。
|
||||
|
||||
凭据边界:默认模板密码未通过上游复杂度校验,事务回滚且账户数量为0;随后为本服务生成独立强密码,保存为GemDocs `ACC-XB-CHATWOOT-LOCAL`,不改模板或其他项目密码、不降低上游规则。另按用户明确交付及保存要求登记本机管理员 `ACC-MACOS-HELLCAT-ADMIN`,实际sudo认证通过;两者用途和秘密记录独立。
|
||||
|
||||
验收证据:`codex/output/chatwoot/http-acceptance.json`;两项挂件隔离/URL检查与原主题9项接口检查通过。GemDocs离线检查通过:19项目、590文档、5986链接、541对象。没有提交、推送、生产发布或线上访问。
|
||||
|
||||
浏览器验收(2026-11-02):此前连接器不可用,现Codex内置浏览器已恢复。首次打开xb.loc为502,现场核实回环8594/8595没有监听,按FUC_THEME既有命令启动独立integration-serve后恢复;未修改代码或系统配置。IAB实际打开首页并展开客服,确认蓝白聊天气泡、圆角、阴影、输入框及“由Chatwoot支持”品牌均可见,当前外观不是CSS完全缺失。保留原生样式,未发送测试消息、登录后台或复验WebSocket推送。截图 `codex/output/chatwoot/widget-iab-20261102.jpg`。独立本地服务为临时进程,退出后需按FUC_THEME重新启动。
|
||||
|
||||
## 地址登记
|
||||
|
||||
| 字段 | 本次范围 |
|
||||
| --- | --- |
|
||||
| 本地代码地址 | `/Users/hellcat/Documents/GemCodes/xb/integrations/chatwoot`,Fuc挂件在XB的`theme/Fuc` |
|
||||
| 线上代码地址 | 未部署,本次不涉及线上 |
|
||||
| 本地域名 | Chatwoot `http://chatwoot.loc`;FUC-XB `http://xb.loc` |
|
||||
| 线上域名 | 无 |
|
||||
| 反代域名 | 不涉及白色机/线上反代;本机Nginx只把chatwoot.loc转给回环8596 |
|
||||
|
||||
## Telegram客服回复接入(TeleHub base,本地试用)
|
||||
|
||||
2026-11-02用户先要求借用HN Key测试,发现HN生产Webhook正在使用后,明确改为“用telehub的base测试”。HN Token、Webhook、配置始终未改,也未将HN Key写入Chatwoot。
|
||||
|
||||
本次现场通过TeleHub本地应用只读取启用的 `bot=base`、`target=base` 加密配置,getMe确认 `@telehub_base_bot`,getWebhookInfo为空、pending0,目标为已配置本人私聊。仅warning/notification承担现有内容审核回调,base没有Webhook;本任务不setWebhook/deleteWebhook,不动这些审核机器人、TeleHub权限/调用方/发送队列或原有代码。
|
||||
|
||||
按用户指定机器人进行的客服试用是普通运行汇报API之外的独立回复桥:`integrations/chatwoot/telegram-bridge.py` 轮询本机Chatwoot网站收件箱新消息,再用base发给已配置私聊;TG长轮询收取引用回复,按已送达消息编号回写对应网站会话。不是Chatwoot原生Telegram客户收件箱。`telehub-base.php`只读既定加密存储,经继承私有管道把Token/目标交给进程内存,不写入配置文件、命令行参数、日志或Chatwoot数据库,也不将Token复制为另一凭据正文。本任务明确选择base,不进行分类降级或机器人替换。
|
||||
|
||||
仅接受目标私聊本人的纯文字引用回复,且引用消息必须在桥接账本中属于当前收件箱;拒绝其他人、群聊、未关联消息和裸发消息。私有SQLite保存消息映射、update_id、处理状态和已接收更新;新消息只从首次启动时间起处理,历史聊天不重放。TG更新先持久化再推进offset;未知投递/写回不自动重试,避免重复发消息。非关联更新只保存为ignored,不转发到网站。当前是单收件箱文字测试,最多检查本机前10页会话,不是正式多客服/附件方案。
|
||||
|
||||
启动:`python3 -u integrations/chatwoot/telegram-bridge.py`。本次为临时本机进程运行,没有登录自启或系统调度;文件锁拒绝重复本地实例。日志 `codex/output/chatwoot/telegram-bridge.log`,状态 `integrations/chatwoot/private/telegram-bridge.sqlite`,均不提交。停止仅退出该桥进程,保留账本,不执行清空pending或删除Webhook;TeleHub其他出站发送不受影响。重启前确认base仍无Webhook/没有其他接收者,出现冲突先停测试,不抢回通道。
|
||||
|
||||
验收:精确本人/私聊/引用绑定/群聊拒绝检查通过;真实本地会话3、入站消息7已通过base送到目标私聊,Telegram确认sent。用户随后确认已引用回复;现场回读TG update 650651667为applied,对应网站会话3新增客服回复消息8,访客接口HTTP200并包含“收到”,真实网站→TG→本人引用回复→网站双向验收通过。证据 `codex/output/chatwoot/telegram-acceptance.json`。一次Telegram长轮询TimeoutError后正常续收,未重复写回。原普通HTTP网站↔客服收件箱验收仍为先前独立结果。
|
||||
|
||||
自动化与TG转发相互独立:桥只转发非私密入站消息(message_type=0),不因机器人已回复而跳过,也不转发机器人的出站回复。2026-11-02检查时原临时桥进程已退出、旧日志有SSLEOFError;沿用原账本和offset恢复,消息12/16/19已确认sent,未重发已有sent项或改Webhook。当前仍为临时进程,无系统自启;恢复后TG引用回复未重新实测。
|
||||
|
||||
## Telegram自动回复标注(2026-11-02)
|
||||
|
||||
用户要求对已触发自动回复的TG通知标注,避免人工重复回答。独立桥接读取Chatwoot消息的`content_attributes.automation_rule_id`作为自动化来源凭据;公开出站自动化回复之前只有一条未回复客户消息、且间隔不超过120秒时才关联。多条客户消息导致归属含糊、私密备注、人工回复、陈旧回复均不猜测为自动回答;这是保守关联,不承诺覆盖并发/所有机器人类型。
|
||||
|
||||
已确认的通知显示“✅ 已自动回复,请先查看回复内容,避免重复答复”,附自动回复摘要;尚未检测到自动回复显示待人工查看。若自动回复后到,调用`editMessageText`更新原TG通知,不另发重复通知,不改变原telegram→conversation引用映射。新增私有`auto_annotations`账本,记录自动回复消息ID及applied/unknown状态,失败保留原通知、不重发或自动反复编辑。TG原生not modified视为已应用;消息/摘要按UTF-16限制截断。通知标题采用XB通用名称,不再写死FUC-XB。
|
||||
|
||||
验证:4项Python测试覆盖人工/私密/多条/陈旧消息排除、后续未答问题不误标、长度限制、晚到回复编辑同条且仅一次;全部通过。实际既有网站客户消息19对应自动回复20,原TG通知真实编辑成功,账本applied;未新增验证消息或改Webhook,未再次让用户引用测试。只部署本地桥进程,无生产发布或系统自启。旧脚本备份`codex/output/chatwoot/before-auto-annotation/telegram-bridge.py`,变更前账本一致性备份在忽略的`integrations/chatwoot/private/before-auto-annotation.sqlite`。回退仅停新桥、恢复脚本、沿用当前原账本启动;不还原旧库重放新消息,新注释表可保留。
|
||||
|
||||
## 欢迎页空白的解释(2026-11-02)
|
||||
|
||||
本版本`widget/views/Home.vue`使用`flex-1 justify-end`在固定高欢迎页靠底排列TeamAvailability和ArticleContainer;当时未绑定帮助中心文章模块,所以只显示继续对话卡片,上方大片空白是布局结果,不是消息加载故障或必须等触发的隐藏内容。随后用户明确要求显示文章,已按下一节完成本地门户接入;原生欢迎页高度及内容布局未改。
|
||||
|
||||
## 帮助中心文章演示(2026-11-02)
|
||||
|
||||
按用户“帮助中心文章显示出来看看”的要求,在当前Chatwoot本地账号3内通过IAB后台创建`XB 帮助中心`(slug=`xb-help`),新增已发布的`zh_CN`语言并设默认,保留初始化的English语言。新建并发布三篇中文演示文章:1“新手入门:如何开始使用”、2“充值成功后还没到账怎么办”、3“如何联系人工客服”;当前未分类。内容为本地演示说明,不导入XB用户/订单/生产知识,不承诺具体到账时限。
|
||||
|
||||
通过现有收件箱设置将帮助中心关联到网站收件箱1;只保存该当前演示收件箱,不修改DPL/HN、原自动回复链接或XB核心。门户本地入口`http://chatwoot.loc/hc/xb-help/zh_CN`,原网站帮助文档`xb.loc/#/knowledge`仍是另一入口。
|
||||
|
||||
真实IAB刷新xb.loc后,在挂件欢迎页看到“最受欢迎文章”、三篇标题与“查看所有文章”;点击入门文章,嵌套阅读视图显示完整标题/正文并成功返回列表。截图`codex/output/chatwoot/help-articles-widget-20261102.jpg`与`help-article-reader-20261102.jpg`,最终保留文章列表供用户查看。此为原生文章模块填充效果,不是缩短窗口高度;未另外修改布局、重建镜像或发布生产。
|
||||
|
||||
撤回演示时先在收件箱1取消关联门户;文章可保留草稿/归档,不删除聊天或整库恢复,不将取消关联理解为删除门户和资料。
|
||||
|
||||
## 原生样式预览(2026-11-01)
|
||||
|
||||
用户要求先看Chatwoot原有样式。本次并未把Fuc CSS套进Chatwoot iframe;此前仅配置Fuc紫色和客服按钮/欢迎文案。现移除SDK的自定义按钮文案/外观参数,仅保留中文语言;本地收件箱恢复上游schema默认颜色,清除自定义欢迎标题/副标题并关闭试用固定问候。FUC-XB页面主题本身保留,挂件继续加载官方SDK与官方CSS。原收件箱显示配置备份在 `integrations/chatwoot/private/style-before-default.json`;未移除官方品牌,也未接AI。
|
||||
|
||||
## 去除访客挂件底部品牌(2026-11-02)
|
||||
|
||||
按用户明确要求,仅修改本地社区版访客挂件:从固定v4.19.1-ce镜像提取`app/views/widgets/show.html.erb`保存为`integrations/chatwoot/widget-show.html.erb`,品牌行为差异为`chatwootWebChannel.disableBranding=true`,由上游原生组件不渲染品牌入口。Compose仅在rails服务只读挂载该模板,重建容器后仍保留;不改编译资源、数据库功能开关、许可证、XB核心或原生蓝白样式。升级镜像时须对比上游模板重新合并,不能盲用旧模板。回退为移除rails的该单文件挂载并重建rails,保留storage及所有数据卷。
|
||||
|
||||
IAB刷新xb.loc并实际展开会话,确认输入框、消息仍可见,底部品牌文字和外链从可见页面/可访问树消失;截图`codex/output/chatwoot/widget-no-branding-20261102.jpg`。本轮未发送消息复验TG。后台入口`http://chatwoot.loc/app/login`;随后按用户明确要求,使用已登记的专属管理员凭据在IAB实际登录成功,进入账号3的会话后台并切到“所有的”,可见3个既有测试会话。未发送新消息或修改后台配置。截图`codex/output/chatwoot/admin-login-20261102.jpg`。未提交/推送/生产部署。
|
||||
|
||||
## 挂件间距修正(2026-11-02)
|
||||
|
||||
上游Branding组件禁用品牌时仍渲染`<div class="p-3" />`,留下24px空底栏。既有本地widget模板增加只针对直接空底栏的CSS:`#app .relative.flex.flex-col.h-full > .p-3:empty { display: none; }`。IAB重新载入并返回欢迎页,DOM实测空栏高度0,卡片底部和左右各16px;未改卡片字体、消息或输入框。截图`codex/output/chatwoot/widget-spacing-20261102.jpg`。 随后用户指出对话页输入框贴底;源码核实ChatFooter原生`mb-1`只有4px,既有模板增加`#app footer:has(#chat-input) { margin-bottom: 20px; }`,与输入区原有20px左右留白对齐。已重启本地rails(冷启动约数分钟),本地挂件HTTP200且渲染输出包含20px规则;随后IAB连接恢复,实际进入会话页,实测输入区margin-bottom与距视口底边均20px,视觉复验已完成。截图`codex/output/chatwoot/composer-spacing-20261102.jpg`。
|
||||
|
||||
## 使用教程自动回复(2026-11-02)
|
||||
|
||||
用户此前保存的是“预设回复”,它是客服手动用`/`调用的快捷话术,不会自行发送。随后按明确要求,通过IAB后台创建并启用“使用教程自动回复”:消息已创建;条件全部满足:Incoming Message、Message Content包含任意独立关键词`怎么使用`/`如何使用`/`怎么用`/`使用教程`、收件箱为当前演示网站;动作发送消息。仅作用于账号3的当前网站收件箱,未改变预设回复或其他实例。
|
||||
|
||||
回复内容:使用教程请查看`http://xb.loc/#/knowledge`,按设备选择教程,有问题继续留言。这是当前演示实例的地址,正式/其他实例需要使用各自教程地址,不是XB通用生产默认。
|
||||
|
||||
IAB真实访客发送“请问怎么使用?”,会话中实际收到机器人自动回复和可点击教程地址,通过端到端验证;未以仅保存成功代替触发验收。截图`codex/output/chatwoot/tutorial-autoreply-20261102.jpg`。该规则为关键词规则,不是AI语义问答。TG登录状态不可直接读取;2026-11-03已按用户要求增加私聊上班/下班手动命令,见下节。
|
||||
|
||||
## 接入方式
|
||||
|
||||
仅Fuc主题新增 `chatwoot_base_url`、`chatwoot_website_token` 两个可选配置;为空时不加载SDK,不发请求。模板通过独立 `assets/chatwoot.mjs` 初始化官方挂件,页面切换不会重复加载。客户端拒绝脚本协议、URL用户信息、路径/查询参数和HTTPS页面降级到HTTP。
|
||||
|
||||
本次只在 `fuc-acceptance` 配置这两个值。Website Token是公开挂件标识,不是管理员API凭据;后者不进入主题。访客使用匿名会话,不发送XB登录token、用户邮箱、订单或订阅信息,不伪造已认证身份。本次没有AI模型接入或自动业务查询;欢迎语是收件箱固定问候,不等于AI回答。网站原工单继续可用。
|
||||
|
||||
不涉及XB app/config/routes、数据库结构、共用依赖、主题加载/发布机制变更,按独立主题与专属本地配置实施,无核心修改。保留原Fuc0.7.0并行改动。
|
||||
|
||||
## 启动与停止
|
||||
|
||||
依赖:Colima、Docker CLI、Docker Compose。专用VM首次创建:
|
||||
|
||||
```sh
|
||||
colima start --profile xb-chatwoot --vm-type vz --cpu 2 --memory 4 --disk 24 --mount /Users/hellcat/Documents/GemCodes/xb/integrations/chatwoot:ro
|
||||
```
|
||||
|
||||
运行命令在XB根目录执行,包装器固定选择专用Docker context,不依赖用户当前context:
|
||||
|
||||
```sh
|
||||
sh integrations/chatwoot/manage status
|
||||
sh integrations/chatwoot/manage start
|
||||
sh integrations/chatwoot/manage stop
|
||||
```
|
||||
|
||||
首次初始化先生成本地 `.env`(600),按 `.env.example` 生成随机数据库密码和SECRET_KEY_BASE,不能提交。再执行 `manage prepare`、`manage setup`,最后 `manage start`。`setup.py` 只通过GemDocs字段读取器读取ACC-XB-CHATWOOT-LOCAL的username/password(用户名沿ACC-005约定,密码为本服务独立强密码),以stdin传给Rails;不存在才创建管理员,已有不覆盖密码。网站收件箱及管理员成员按唯一名称/关系复用。回执与原主题配置备份仅在忽略的 `integrations/chatwoot/private/`。
|
||||
|
||||
后续启动不重新初始化,不执行删除卷、整库恢复或重设管理员密码。暂停整个专用VM可运行 `colima stop --profile xb-chatwoot`,不停止其他Colima profile。未配置登录自启,Mac重启后须启动VM并核实服务。
|
||||
|
||||
## 复用能力与限制
|
||||
|
||||
- ATOM:已评估统一管理入口;本地试用暂不登记/接入OIDC,Chatwoot使用独立账号与权限。正式化时再处理平台登记和认证适配。
|
||||
- DomainHub:已评估地址配置;本次仅本地固定入口和主题专属配置,暂不新增客户端/发布配置。
|
||||
- TeleHub:本次无运行汇报需求,不新增事件/调用方或外发。Chatwoot未配置SMTP和外部渠道。
|
||||
- 官方版本检查仍可能向Chatwoot Hub发送基本安装信息;`DISABLE_TELEMETRY=true`关闭统计指标和事件遥测,不宣称绝对离线。外部模型调用未启用。
|
||||
|
||||
## 恢复
|
||||
|
||||
先在 `fuc-acceptance` 恢复 `private/fuc-theme-settings-before.json` 的两个集成字段(原不存在则移除),保留其他并行主题设置;恢复后确认页面不再加载Chatwoot SDK。主题代码撤回仅移除本次模板条件块、新增挂件文件及两个配置字段,不整文件覆盖Fuc的其他修改。试用开始时的局部主题恢复副本在 `codex/output/chatwoot/before/`,只供差异核对。
|
||||
|
||||
`manage stop`保留全部聊天与数据库卷。需要删除试用数据/VM时另行确认具体范围,不把停止解释为清空。生产发布不在本次范围,尚未提交、推送或部署。
|
||||
|
||||
## 官方依据
|
||||
|
||||
- [Docker与社区版部署](https://developers.chatwoot.com/self-hosted/deployment/docker)
|
||||
- [固定版本发布](https://github.com/chatwoot/chatwoot/releases/tag/v4.19.1)
|
||||
- [网站挂件模型与官方SDK初始化](https://github.com/chatwoot/chatwoot/blob/v4.19.1/app/models/channel/web_widget.rb)
|
||||
|
||||
## TG上班下班与隐藏帮助中心(2026-11-03)
|
||||
|
||||
用户要求帮助中心先不显示,并以TeleHub base私聊“上班/下班”控制客服状态。当前演示收件箱1的portal关联已通过API取消并回读为空;三篇文章及门户保留,原关联记录在忽略的private/portal-before-hide.json,不删除或停用公共门户。IAB连接不可用,本轮未完成刷新后的视觉复验。
|
||||
|
||||
桥接仅接受已配置base私聊本人的非引用、精确“上班”或“下班”(允许首尾空白);其他人、群聊、引用消息或整句聊天不触发。引用消息仍按原客服回复路径处理。分别调用当前账号3的profile availability为online/offline,并将该账号auto_offline设false,避免TG接管后浏览器闲置使其自动离线;不改变其他账号或实例。API回读availability及auto_offline均匹配才确认成功,命令与确认发送分开记账,确认发送失败不重放状态命令。状态失败记unknown,不自动重放。下线仍保留访客留言和自动回复。
|
||||
|
||||
6项测试通过;实际offline→online两次API切换和profile回读通过,最终恢复变更前online,auto_offline为false。桥已启动沿用原账本/offset,无Webhook或系统自启变更;尚待用户真实在base发送命令验证TG入口,不把模拟路由和API切换当真实TG命令验收。回退:停止桥、撤销authorized_shift/set_shift命令处理,按原账号将auto_offline恢复true;上下线状态按用户当时选择,不盲目恢复历史状态。
|
||||
|
||||
用户2026-11-03随后改为“显示帮助中心”:通过账号3门户列表精确查到xb-help(id1),恢复收件箱1的portal_id=1;访客挂件HTTP响应的portal配置已回读为xb-help,中文仍为三篇。未改TG上班下班、自动回复或文章内容;本轮未做浏览器视觉复验。此前portal-before-hide.json未包含可用门户ID,不能当作完整关联备份,后续从门户列表按账号及slug核实。
|
||||
|
||||
## 离线卡片四行版(2026-11-03)
|
||||
|
||||
按用户确认的四行布局调整:当前没有在线客服;客服在线时间:工作日早9点至晚5点(读XB实例设置);给客服留言 >;到用户中心提交工单 >。隐藏原预计回复说明和额外留言段落,沿用原Chatwoot按钮事件,仅替换按钮文字,工单链接仍为实例配置的本站路径。上线后移除离线时间/工单入口,恢复原聊天按钮文字和提示。当前演示实例工作时间及共用默认文案已更新。
|
||||
|
||||
DOM测试已覆盖四行顺序、文案、来源校验、单次渲染及上线清除;通过。初次更新仅改脚本,未变URL;用户刷新仍看到旧版。现场确认静态脚本Cache-Control为public,max-age=31556952,浏览器可缓存一年。模板改为按脚本File.mtime输出版本查询参数,并重启本地rails;访客模板实际输出版本URL通过。IAB随后刷新、展开卡片,真实确认四行文案及顺序,“给客服留言 >”能进入输入框并成功返回;截图codex/output/chatwoot/offline-four-lines-20261103.jpg。视觉复验已完成。后续脚本更新会自动变更版本URL。
|
||||
|
||||
## 卡片图标和标题微调(2026-11-03)
|
||||
|
||||
按用户连续指示,在线时间复用原AvailabilityText的灰色类及字号/行高(由隐藏的原生提示元素读取),不再单独设深色14px段落。留言入口用细线chevron加淡蓝圆形衬底,工单链接用16px外跳图标,移除两个字面量大于号,保留原按钮点击行为。仅当前演示收件箱1标题更新为“FUC-XB 客服系统”,API已回读确认;挂件header预计回复小字通过适配脚本隐藏,不改在线/离线状态计算。
|
||||
|
||||
DOM测试通过(来源校验、图标、灰字类、header副标题隐藏、上线清除和留言按钮恢复)。原模板按文件mtime自动更新脚本URL,避免旧缓存。内置浏览器本轮先报browser.user不可用,重连后transport closed,视觉复验尚未完成;未切换外部浏览器。
|
||||
|
||||
## 常见问题精简与原生箭头(2026-11-03)
|
||||
|
||||
用户最新要求:文章区改为“常见问题”,隐藏“查看所有文章”,只显示原入门文章并将入口标题改为“如何开始使用”。适配仅隐藏其他两项入口,不删除/归档文章,不替换原文章点击处理。随后明确要求留言箭头用原生样式,已移除新增圆底SVG并恢复Chatwoot原生i-lucide-chevron-right;工单仍用外跳图标。演示收件箱标题最新为“FUC-XB客服系统”,移除空格;首次保存遇本地500,重试及API回读成功。
|
||||
|
||||
两项DOM测试通过,覆盖唯一文章入口及原点击事件保留、原生箭头恢复等。内置浏览器本轮连接不可用,新增改动视觉复验未完成;脚本URL随mtime变化可刷新加载。
|
||||
|
||||
## 帮助中心数据与内嵌阅读页纠正(2026-11-03)
|
||||
|
||||
用户指出阅读页仍有面包屑/更新时间、门户内部仍为未分类并列出三篇。确认上一轮仅在挂件首页隐藏按钮,未改变后台文章状态,属于不完整处理。本次改为真实数据:账号3/xb-help新建zh_CN分类faq(id1)“常见问题”,文章1标题改“如何开始使用”并归该分类、保持published;文章2/3撤回draft,内容不删除。变更前数据保存在忽略的private/help-before-faq-data.json。移除首页按标题过滤其他文章的临时代码,展示内容以真实发布集合为准;保留“常见问题”区标题及隐藏“查看所有文章”的明确展示要求。
|
||||
|
||||
内嵌阅读页通过单独只读挂载article-show-plain.html.erb替代官方plain show模板,直接渲染标题与正文,不调用包含面包屑及更新时间的article_header。只作用show_plain_layout内嵌布局;完整门户其他布局未改。不改文章内容或更新时间数据字段。已重建本地rails加载挂载;升级镜像须对比上游plain模板合并,回退移除该挂载并重建,不整库还原。
|
||||
|
||||
实际公开HTTP验收:门户含“常见问题”、不含“未分类”,仅一个公开文章链接;该文章内嵌HTML标题正确、无原面包屑包装及更新时间。证据codex/output/chatwoot/help-portal-faq-acceptance.html与help-article-clean-acceptance.html;两项DOM测试通过。内置浏览器再次不可用,本轮视觉复验未完成,不能把HTTP通过称为页面验收。
|
||||
|
||||
## 挂件文章缓存与内置浏览器复验(2026-11-03)
|
||||
|
||||
随后重连IAB成功,实际复现整页刷新仍显示旧三篇。根因是上游widget/store/modules/articles.js优先使用localStorage中chatwoot_most_read_articles_<slug>_<locale>缓存,默认有效24小时,而非文章数据未保存。widget-show模板在官方widget模块启动前仅移除当前portal的文章缓存键(含:ts),让每次挂件加载重新获取已发布文章;不清除游客身份、会话或其他存储。已重启本地rails加载模板。
|
||||
|
||||
IAB实际刷新后首页仅有“常见问题/如何开始使用”,进入文章实际显示正确标题及正文,无面包屑、更新时间;原游客会话仍保留。截图codex/output/chatwoot/faq-cache-fixed-20261103.png和article-clean-iab-20261103.png。已完成本地页面验收,保留客服首页;未发布生产。
|
||||
|
||||
## 在线卡片客服头像(2026-11-03)
|
||||
|
||||
在线卡片右侧“管”来自GroupedAvatars对在线管理员姓名的默认文字头像,并非站点logo。按用户要求,给本地Chatwoot管理员id1通过profile头像接口上传薄荷绿底深绿耳机PNG;源图在integrations/chatwoot/assets/support-avatar.svg,PNG同目录。使用真实账号头像,因此同一客服的对话头像也会同步更新;未改XB主题。上游available_agents同样存在24小时localStorage缓存,模板仅清理当前websiteToken的chatwoot_available_agents键及:ts,使刷新重新读取客服信息,保留访客会话。
|
||||
|
||||
IAB已刷新并实见在线卡片右侧为耳机图标,证据codex/output/chatwoot/support-avatar-iab-20261103.png;本地验收完成,未发布生产。
|
||||
|
||||
用户指定客服对外显示名为“FUC-XB人工客服:gavin”。本地管理员id1的profile.display_name已通过API更新,profile及agents.available_name均回读一致;内部name仍为管理员,登录信息不变。
|
||||
|
||||
## 顶部明确状态与网站默认图标(2026-11-03)
|
||||
|
||||
用户随后指定移除标题旁绿点、右侧显示“人工客服在线中”,并将默认客服图标改用网站。挂件适配隐藏原生圆点,在header.actions加入状态文字徽标,has-online-agents为false时显示“人工客服已离线”,跟随原生状态更新。XB共用widget接入从当前网站rel=icon取图标URL,经现有受信父页面消息传递,iframe仅接受父站同源HTTP(S)图标,用于在线卡片头像展示;不硬编码FUC主题路径。此前耳机账号头像仍留Chatwoot档案,卡片展示由网站默认图标覆盖。五项Node测试通过(新增在线/离线状态切换、同源图标校验和无重复徽标)。
|
||||
|
||||
IAB实际验收:对话历史署名显示“FUC-XB人工客服:gavin”;欢迎页顶部绿点消失,右侧为在线文字徽标,卡片显示当前网站favicon。截图codex/output/chatwoot/site-icon-presence-iab-20261103.png。已完成本地显示验收,未发布生产。
|
||||
|
||||
## 聊天头像一致性修正(2026-11-03)
|
||||
|
||||
用户指出聊天消息仍显示耳机,确认上一轮网站图标仅作用首页GroupedAvatars。现扩展到AgentMessage的user-thumbnail-box与UnreadMessage的row--agent-block头像节点,统一使用同一受信网站图标;不影响游客头像、消息附件。另将本地管理员档案中实际存储的耳机PNG替换为当前网站fuc-mark导出的PNG(assets/site-avatar.png,使用本地容器ImageMagick转换),确保档案默认也一致。API更新200;五项Node测试通过,新增聊天头像与附件不变检查。
|
||||
|
||||
内置浏览器重连后已实际刷新、滚动至消息11,人工客服历史回复旁显示网站图标,耳机已消失。截图codex/output/chatwoot/message-site-avatar-iab-20261103.png;本地页面验收完成。
|
||||
|
||||
## 客服口径及机器人头像区分(2026-11-03)
|
||||
|
||||
用户最新要求统一“人工客服”为“客服”。顶部状态现为“客服在线中/客服已离线”,欢迎卡片“在线”改“客服在线中”;本地账号display_name改为“FUC-XB客服:gavin”,profile和agents.available_name回读一致。用户同时明确机器人保留机器人头像,适配跳过署名“机器人”的消息,恢复原头像子节点可见性;客服消息继续网站图标。五项Node测试通过,覆盖机器人不被网站图标覆盖。
|
||||
|
||||
## 通用标题与上下班随机展示人数(2026-11-03)
|
||||
|
||||
最新标题为“客服系统”(本地收件箱1 name已API保存并回读),欢迎卡片为“客服在线中”。顶部在线徽标为“当前有 N 个客服在线”。N按用户明确要求是展示随机值,不是Chatwoot真实坐席数:每次受权TG“上班”处理器经availability回读后,以secrets.randbelow(3)+1生成;“下班”保存0。通过xb-settings.php --online-count=0..3写入当前XB实例独立v2_settings.customer_service_display_count并回读,故不同实例各自抽取且刷新不重抽。未迁移或改动其他实例。Chatwoot inbox API不允许additional_attributes更新,最初尝试实测未保存,最终实现已移除该路线。
|
||||
|
||||
Settings.publicConfig公开有界online_count,匿名GET /customer-service/status仅返回启用实例展示人数(禁用返回0,no-store);共用widget在可见页面每15秒读取并向受信iframe发送,不传访客身份。integration-router对status走Laravel路由,不按静态文件拦截。配置变更比对只包含既有TG运行字段,人数更新不会触发桥接退出。
|
||||
|
||||
已完成真实本地set_shift('online')及独立字段保存回读,本轮抽取3;IAB实见“客服系统/当前有 3 个客服在线/客服在线中”,且对话署名“FUC-XB客服:gavin”、机器人原生chatwoot_bot.png无网站图标覆盖。截图codex/output/chatwoot/support-count-title-iab-20261103.png。Python 6项、Node 5项、PHP 5项17断言通过,状态接口实测online_count=3。TG桥接已重启加载最终代码(本轮会话15040),Ready日志正常;未让用户实际从TG发送新上下班指令,不将处理器验收称为TG端到端验收。未发布生产。
|
||||
|
||||
用户最新微调:顶部在线徽标文案改为“当前客服在线数:N”,沿用现有每次上班独立随机1–3及下班0的逻辑。
|
||||
|
||||
最新顶部在线文案为“客服在线数:N”,删除“当前”二字,其余行为不变。
|
||||
|
||||
用户要求查看头像叠放效果:欢迎卡片按展示人数补足网站图标头像,36px尺寸、相邻重叠16px、白色描边,最多4个;保留实际坐席,不新增账号。当前展示3人,IAB已实际见3个重叠图标及最新“客服在线数:3”。截图codex/output/chatwoot/stacked-avatars-iab-20261103.png,3项DOM测试通过。本次为本地展示预览。
|
||||
|
||||
## 本地502恢复(2026-11-04)
|
||||
|
||||
本次502来自XB本地独立预览进程退出:8594/8595均无监听,xb.loc返回502;Chatwoot返回200且全部容器健康。按既有命令node scripts/theme-fuc/integration-serve.mjs重启(本回合session67129),XB恢复HTTP200,客服状态接口正常返回online_count=3。未更改业务代码、数据、代理或其他实例配置。当前仍为临时预览进程,非系统自启动服务。
|
||||
|
||||
## 三个真实客服账号与TG随机值班(2026-11-04)
|
||||
|
||||
用户最终明确改为在Chatwoot创建三个真实普通客服账号,每次TG上班随机1–3个上线,并从上线集合随机选一人值班,且三个头像任意配置。已在本地账号3收件箱1建立gavin(id2)、alex(id3)、ryan(id4),角色agent、auto_offline=false,加入收件箱;分别配紫/绿/金三色人物头像,PNG源在integrations/chatwoot/assets/agent-*.png。账号邮箱为xb-support-<name>@chatwoot.loc,仅本地确认,不发送邀请。原管理员id1保留管理用途并退出在线坐席集合,历史管理员回复不改写。
|
||||
|
||||
移除xb-offline.js全部头像覆盖及补足假头像代码,原生GroupedAvatars和消息头像直接使用实际客服头像,机器人保持原生头像。TG set_shift用管理员接口改变三账号availability并逐一回读,上班抽取1–3的不同账号、从中选一人;下班全部下线。实际在线集合必须与选定集合一致才保存展示人数。值班身份及上线ID落在忽略的private/agent-duty.json,令牌名册在private/agent-roster.json(0600),只供本地桥接读取,不回显或提交。发送TG引用回复改由值班账号api_access_token认证,实际message.sender就是该账号,历史署名不会因下一次值班改变。上班确认消息包含值班名。原随机展示人数实现由真实在线人数取代;现有15秒人数刷新保留。
|
||||
|
||||
本次真实set_shift上班已验收gavin/ryan两人在线、选中ryan,并以ryan专用令牌GET profile验证身份;未发送聊天测试消息。Python6项及Node5项通过。桥接已启动最终代码(本轮session95212)。TG用户实际发新上下班指令及引用回复的端到端验收尚未执行;未发布生产。
|
||||
|
||||
IAB最终已实际刷新欢迎页:在线数2、两个原生不同颜色头像,与API读回的gavin/ryan集合一致。截图codex/output/chatwoot/real-agent-roster-20261104.png;本地页面验收完成。
|
||||
|
||||
2026-11-07,FUC-XB 本地账号 3 的收件箱 1 将原三个坐席更新为远航(2,海边背影)、白茶(3,橘猫)、溪林(4,窗边咖啡)。头像来自先前预览的 Unsplash 照片。TG 名册同步昵称并沿用原有账号、令牌和值班 ID。Chatwoot 回读确认三个署名及头像文件,内置浏览器确认聊天记录显示溪林及新头像。旧显示资料和头像的本地回退备份为 `integrations/chatwoot/private/fuc-avatar-before-20261107.json`。
|
||||
|
||||
后续子项目各维护三个客服展示身份,接入后每四个月轮换一个展示身份。各项目独立记录轮换日期。当前只配置 FUC-XB 的首组三个身份,轮换执行安排待各项目接入时落实。
|
||||
|
||||
## 旧管理员同名冲突清理(2026-11-04)
|
||||
|
||||
用户要求自然三个客服且历史头像一致。已先备份private/agent-conflict-before.json,再在本地账号3/收件箱1事务处理:管理员id1 name/display_name恢复“管理员”、保持offline、退出InboxMember;原以gavin名义发出的公开演示消息id3/8/11由sender1归到真实gavin(id2),同收件箱原分配给管理员的会话归gavin。未改消息正文、机器人消息、其他账号/实例或认证资料。该局部演示数据归属调整有明确用户修复授权与ID备份,非生产历史批量改写。
|
||||
|
||||
API回读收件箱成员恰为gavin2/alex3/ryan4,管理员仅管理身份且offline。IAB刷新后消息11署名gavin、原生头像地址为gavin.png,与在线卡片同一用户;截图codex/output/chatwoot/gavin-conflict-fixed-20261104.png。已完成本地数据及页面验收。
|
||||
|
||||
用户最新要求:顶部状态徽标由“客服在线数:N”改回“客服在线中”,离线继续显示“客服已离线”;真实三账号随机上线、值班回复及原生头像不变。
|
||||
|
||||
2026-11-06 本地 502 恢复。`xb.loc` 返回 502,8594/8595 无监听,按既有 `node scripts/theme-fuc/integration-serve.mjs` 命令恢复本地预览。Chatwoot SDK 可取,但带 XB 来源的挂件请求超时,单独重启 Rails 容器并等待 Puma 就绪。Chatwoot HTTP 恢复 200,内置浏览器已刷新 XB 并展开右侧客服,确认显示“客服在线中”“继续对话”和常见问题。截图 `codex/output/chatwoot/recovered-20261106.png`。
|
||||
|
||||
## XB 默认与 Fuc 客服皮肤(2026-11-06)
|
||||
|
||||
共用在线文案为顶部“人工在线中”、欢迎卡片“人工客服在线中”。Fuc 主题通过 `assets/chatwoot.mjs` 与 `assets/customer-service.css` 提供紫色、青色和用户区深色皮肤。Chatwoot 适配层只接受匹配网站来源的父框架消息,并从该来源加载固定 Fuc 样式路径。聊天窗内的皮肤仅作用于 Fuc。
|
||||
|
||||
本地内置浏览器已验证 Fuc 紫色预览、顶部与卡片文案,以及继续对话按钮颜色。截图 `codex/output/chatwoot/fuc-support-skin-20261106.png`。现有 5 项挂件测试通过,青色和深色未做浏览器验收。
|
||||
|
||||
Fuc 配色复核:访客气泡原由 Chatwoot 内联设置蓝色背景,现由 Fuc 皮肤覆盖为对应主题实色。在线徽标使用同一实色及白字,离线徽标保持中性色。内置浏览器实测紫色版徽标和访客气泡背景均为 `#6658dc`,截图 `codex/output/chatwoot/fuc-support-highlight-20261106.png`。5 项现有挂件测试通过。
|
||||
|
||||
Fuc 在线徽标改用独立的成功态配色。Fuc 原生 CSS 有绿色 `badge-success`,客服皮肤沿用绿色语义并采用浅绿底、深绿字,深色模式有独立配色。访客气泡继续使用主题色。内置浏览器已验收浅色在线徽标,截图 `codex/output/chatwoot/fuc-support-success-20261106.png`。
|
||||
|
||||
福云本地试用 Chatwoot 原生长按钮,文字为「联系客服」。聊天窗沿用原生右下角浮动布局,开关时页面、套餐卡片和页脚保持原来的尺寸与位置。站内弹窗显示期间暂隐客服窗,关闭弹窗后恢复。内置浏览器核对了桌面开关前后的布局以及购买确认弹窗的层级。此试用仅在本地。
|
||||
|
||||
2026-11-06 用户批准在本地将按钮做成 XB 共用默认,配色按各站设置或主题保留。已启用客服的主题通过 `public/customer-service/widget.mjs` 和 `launcher.css` 共用「联系客服」长按钮、右尾三点气泡和 48 像素圆形 X。桌面浮窗与按钮右侧对齐,间隔 12 像素。手机全屏模式沿用 Chatwoot 窗内的关闭入口。内置浏览器已验收 Xboard 蓝色和 Fuc 紫色的尺寸、间距与开关,并确认禁用时不加载挂件。原五项挂件测试通过。本地变更尚未发布。
|
||||
|
||||
Fuc 访客聊天窗使用福云后台的深蓝灰底色、卡片和边框。欢迎卡片与 FAQ 按用户要求放在聊天窗底部。深色标题、客服消息、链接与输入框统一跟随主题。内置浏览器已验收紫色主题的明暗切换、对话页及深色欢迎区的底部对齐。回退时按本次差异恢复挂件入口、共用样式和 Fuc 皮肤文件即可,无需恢复设置或聊天数据。
|
||||
|
||||
Fuc 用户中心的「联系客服」及展开后的关闭叉号共用返回顶部按钮的常态、悬停和焦点配色,分别对应紫色、青色和深色样式。内置浏览器已验证紫色常态及悬停下三者背景与边框颜色一致,并保存两态截图 `codex/output/chatwoot/fuc-support-launcher-match.png`、`codex/output/chatwoot/fuc-support-close-match.png`。
|
||||
|
||||
Fuc 用户中心的客服长按钮和关闭按钮沿用返回顶部按钮的背景变色。两者无描边,焦点光圈仅在键盘导航时显示。内置浏览器已验证紫色主题下鼠标打开和关闭时均无描边或光圈,截图 `codex/output/chatwoot/fuc-support-no-border.png`、`codex/output/chatwoot/fuc-support-close-no-border.png`。
|
||||
|
||||
Fuc 用户中心客服按钮仅在支持悬停的设备上悬停时或按下时变色。键盘焦点只显示焦点光圈。内置浏览器已验证深色模式打开、关闭后移开鼠标时按钮恢复常态色,即使按钮仍有焦点。截图 `codex/output/chatwoot/fuc-support-hover-reset.png`。
|
||||
|
||||
2026-11-06 本地 FUC-XB 收不到 Telegram 客服通知,检查发现临时桥已停止,而 XB 的 Telegram 接待仍启用并指向 TeleHub base。沿用原账本重启后,Telegram API 确认会话 2 的待转发消息 23、25 已发送。原有发送结果未知的消息 21 未重发。本机仍为临时运行,无系统自启。
|
||||
|
||||
Fuc 用户中心在客服面板或未读预览显示时隐藏「返回顶部」,关闭后恢复。桌面预览与聊天面板共用右侧对齐及离关闭按钮 12 像素的间距。内置浏览器实测聊天窗开关和按钮恢复,并临时模拟 SDK 未读类验证预览容器定位。未新增客服消息。
|
||||
|
||||
Fuc 未读预览隐藏客服署名后的来源文字,「查看新消息」及箭头使用当前主题强调色。内置浏览器确认聊天框加载新版样式,并用未读组件的标记验证来源隐藏及紫色明暗、青色浅色取值。未发送新消息触发真实预览。
|
||||
|
||||
Fuc 未读预览将关闭按钮、卡片和「查看新消息」的两段间距统一为 12 像素,入口去掉右内边距以对齐卡片。内置浏览器测得原预览卡片下方为 20 像素、入口右边缩进 10 像素。刷新后用预览结构验证新版间距和对齐。
|
||||
|
||||
未读卡片列表保留 12 像素底部内边距,让最后一张卡片的阴影留在滚动区域内,同时保持卡片到「查看新消息」的原间距。内置浏览器实测原卡片底边与裁切边重合,并用预览结构验证修复后两处均为 12 像素。
|
||||
|
||||
Fuc 客服窗恢复 Chatwoot 原生底色、顶部和卡片外观,保留首页布局、在线徽标、头像、常见问题、操作强调色及未读预览细节。内置浏览器已核对本地首页顶部无自定义渐变、卡片使用原生阴影、继续对话保留紫色,截图 `codex/output/chatwoot/fuc-native-card.png`。
|
||||
|
||||
原生外观仅用于浅色模式。Fuc 深色模式继续使用原有深蓝灰背景、顶部渐变和卡片配色。内置浏览器在本地真实挂件核对两种模式,深色截图 `codex/output/chatwoot/fuc-card-dark-restored.png`。
|
||||
|
||||
本地 TG 桥支持网站单图消息(PNG、JPEG、GIF、WebP,最大 20 MiB),允许无正文,原图以 Telegram 文件发送并带可引用的说明。附件只从已配置 Chatwoot 同源的 Active Storage 路径下载,重定向仍受同源限制。用原发送账本防重并保留自动回复标注。已重启本地桥并核实会话 2 的图片消息 39 获 Telegram 发送确认。未实测引用这条图片回复;多图、其他附件和 Telegram 到网站的图片转发不在本次范围。
|
||||
|
||||
Fuc 公开首页与用户中心共用客服入口的配色、字重、字号和交互样式。字号使用固定像素,避免两处页面根字号不同导致按钮宽度差异。内置浏览器已核对本地紫色浅色模式的常态和悬停,两处均为 48 像素高。
|
||||
|
||||
## XB 共用客服外观
|
||||
|
||||
用户指定将 FUC-XB 本地确认的客服外观设为 XB 共用默认。启用客服的实例通过 `public/customer-service/launcher.css` 和 `panel.css` 共用入口、聊天窗、在线徽标、输入框和未读预览。在线徽标使用中性灰底和静态实心绿点,绿点与文字间隔 5 像素。浅色卡片沿用 Chatwoot 原生外观,深色使用共用的深蓝灰基底。
|
||||
|
||||
2026-11-07,顶部状态徽标放在右侧操作区。左侧标题从当前 XB 实例读取网站名,显示「网站名客服系统」。内置浏览器已核对本地欢迎页和对话页均显示「富蕴客服系统」,在线状态位于右侧。
|
||||
|
||||
各实例在各自 Chatwoot 网站收件箱设置挂件颜色。需要跟随站内实时换色的主题可以向受信聊天框发送 `xb-support-theme`,传入六位十六进制的 `accent`、`solid` 和可选的 `headerTint`,以及布尔值 `dark`。Fuc 用此接口同步紫色、青色和明暗模式,并为入口提供对应的按钮颜色。每个站点保留自己的收件箱和客服配置。HN 原生挂件目前仍是独立本地预览,正式接入 XB 客服时使用共用入口并沿用 HN 自己的收件箱。新接入沿用客服原有启用开关。
|
||||
|
||||
本次变更在 XB 本地代码中实施。5 项挂件回归通过,覆盖无主题适配器时加载共用样式和使用收件箱颜色。内置浏览器在 `xb.loc` 确认对话气泡为 Fuc 紫色、在线徽标使用静态绿点和 5 像素间距。其他实例尚未逐站验收。回退时同步恢复共用样式、Chatwoot 适配脚本和 Fuc 颜色适配器的对应版本。
|
||||
@@ -0,0 +1,47 @@
|
||||
# FUC → XB 本地迁移演练
|
||||
|
||||
2026-11-03;状态:**独立试导及VIP期初接入完成,39项XB回归通过;后续用户已明确要求完成VIP自动升级,已在独立插件实现并通过本地测试,唯一实现及当前状态见[VIP模块](FUC_VIP.md)。** 未切站,营业接入后置。来源见[迁移研究](FUC_MIGRATION_STUDY.md),业务决定见[功能对照](FUC_XB_FEATURE_COMPARISON.md)。下文期初阶段的“自动升级尚未实现”由此后续结果覆盖。
|
||||
|
||||
## 本地隔离与范围
|
||||
|
||||
本次授权为本地试导和测试钱包入账,不含生产迁移、源站退款、共享核心改造、节点切换或发布。使用既有13:42:26快照,不再次访问生产。实例为`fuc-migration-test`,数据库`instances/fuc-migration-test/database/rehearsal.sqlite`,环境、缓存和日志独立,目录700、文件600;不启动Web、调度或Horizon,不配置支付/邮件服务。`xb.loc`仍是原合成验收站,不展示真实用户数据;DPL/HN未被本次工具读写。源快照SHA256保持研究记录值。
|
||||
|
||||
## 已完成的导入和验证
|
||||
|
||||
| 项目 | 结果 |
|
||||
| --- | --- |
|
||||
| 用户 | 11,542全量试导;密码哈希、UUID、邀请关系、u/d、总额度、到期和佣金逐用户回读通过;不继承旧会话或管理员权限 |
|
||||
| 历史权益 | 296账号映射166个隐藏/停售/不可续费历史权益记录、3个权限组;用户自身字节和确切到期不变,不调用开通/流量重置;尚未证明真实节点集合等价 |
|
||||
| 钱包 | 原422.19元+13笔/3用户完整预购实付3,228.68元=测试库3,650.87元;逐用户及总和一致;佣金钱包仍16.32元 |
|
||||
| 旧账 | 原4,770订单及全部13表共38,901行存入独立`private/legacy-readonly.sqlite`;只读连接写入被拒绝;XB原生订单池为空,不重播历史支付/返佣,不参与新交易折抵 |
|
||||
| 身份例外 | 原指定邮箱1人,随后用户明确要求剩余3个缺后缀账号统一补`@dove.com`;已更新私有映射、字段投影及测试库,4个映射均通过严格格式/重复检查,当前邮箱待核查0人;源站原值不变。原无token的26账号保持空值,不生成正式新token |
|
||||
| 幂等/回退 | 重跑仅核对、不加钱;导入第101行故障全事务回滚通过;另在私有副本中先写钱包及独立幂等账本、再注入故障,两者共同回滚通过 |
|
||||
| XB业务 | 37项检查通过:原生模型/HTTP内核读取、资料/订阅/订单接口、原生VIP百分比、使用退回余额购买并开通、取消返还、再次取消不重复返还;临时订单/账号/节点/登录令牌全部回滚 |
|
||||
| 密码范围 | 用FUC同算法合成bcrypt测试正确/错误密码登录API;旧用户哈希保持,不掌握真实用户明文密码,未声称全员真实登录通过 |
|
||||
|
||||
测试通过后,测试库仍保留11,542个迁移用户和上述钱包金额,原生订单、临时节点及登录令牌均为0。没有提交、推送、发布或为本轮修改XB共享代码/迁移文件。
|
||||
|
||||
补后缀前已私有备份身份映射、字段投影、测试库和幂等账本;限定仅3个缺`@`账号的email字段变化,其余逐用户字段必须一致。邮件修正和导入指纹同事务更新;随后重跑导入及37项原生检查。此处只证明地址语法可用,不证明收件箱存在或已验证收信。
|
||||
|
||||
## 仍待完成的业务与兼容性
|
||||
|
||||
**用户最新收窄范围**:客户端明确改为有感迁移、重新导入新站订阅;不再开发旧URL兼容或安排无感切换验收。新站商品营业配置、真实收款和发信接入后面再做。以下旧订阅模拟结果只作历史研究证据,不再作为实施待办;已迁UUID/token不自动轮换。
|
||||
|
||||
**VIP期初已按确认规则本地应用,自动升级尚未实现。** 用户明确旧累计以`total_pay`为准、扣预购返还后最低0、钱包全额返还。11,542人的期初累计存入私有幂等库`vip_opening`(不是XB共享表),测试库`discount`按该累计计算;3个退款账号完成回读,其中1人累计归零、期初折扣改变,其余用户金额/权益和折扣不变。最新39项检查及重复导入核对通过;未改XB共享代码或数据库结构,没有给其他实例启用VIP。原账单差值留档,不再要求旧账重建。自动升级功能仍需实现。
|
||||
|
||||
应用前备份在`private/before-confirmed-vip-opening/`;只有核对原导入指纹及全部用户非折扣字段一致后,才允许更新确认的折扣、私有累计账本及导入指纹,操作同事务完成。用户确认范围和聚合结果在`confirmed-rules.json`、`rehearsal-results.json`,期初逐用户值为`private/vip-opening.jsonl`,3个退款账号回读为`private/confirmed-vip-opening-readback.json`。这些均不公开、不提交Git。
|
||||
|
||||
**旧订阅尚未实现真实无感接替。** 原版实际路由`/sub/{token}/{subtype}`及`/api/v1/client/subscribe/{subtype}?token=...`在XB返回404。离线模拟入口重写到既有`/api/v1/client/subscribe?token=...&flag=...`后,Clash、sing-box、V2Ray两类旧路径均生成含原UUID的配置;别名`singbox→sing-box`、`v2ray→general`,畸形token/未知格式拒绝。只验证配置生成,合成节点为`.invalid`,没有联网、部署重写、迁移域名或接入节点。其他旧格式及真实客户端待验证。XB的`subscribe_path`配置能改变基础路径,但不能单独处理类型后缀。
|
||||
|
||||
361个历史账号有旧IP数量限制,不将其等同XB设备限制;当前未过期权益中此类限制为0人,原值留档。28元旧`pending_activation`记录继续隔离,不重复返还。正式销售商品尚未配置,购买测试仅使用临时套餐并回滚。支付/邮件/验证码外部联调未执行。
|
||||
|
||||
## 证据与恢复
|
||||
|
||||
忽略目录`codex/output/fuc-migration-20261103/`包含:
|
||||
|
||||
- `rehearsal-results.json`:全量试导、资金/权益守恒及两类故障回滚、重复执行证据。
|
||||
- `rehearsal-verify-results.json`:37项实际XB模型/HTTP内核/业务服务检查。
|
||||
- `rehearsal-setup.php`、`rehearsal-bootstrap.php`、`rehearsal.py`、`rehearsal-verify.php`、`rehearsal-rollback-probe.py`:本地专用CLI工具,不是生产导入器。
|
||||
- `private/`:只读旧账、独立幂等账本、退款映射与VIP异常记录;不提交Git、不由网页提供。
|
||||
|
||||
导入工具只接受固定测试实例标记、快照SHA、空目标库和一致的映射指纹;重复运行发现用户状态不同会停止,不能覆盖后续业务。测试库是可删除的演练产物,不是正式目标库。退出本次试验仅处理该专用实例及其私有试验产物,不恢复或覆盖其他实例;当前保留证据供后续复核。
|
||||
@@ -0,0 +1,91 @@
|
||||
# FUC → FUC-XB 用户迁移研究
|
||||
|
||||
2026-11-03;状态:**生产快照研究及独立本地试导已完成;11,542用户写入专用测试库、37项XB检查通过。未修改FUC生产或XB核心,未切站。** 本地试导范围、资金结果、VIP/订阅未完成项及恢复唯一见[本地迁移演练](FUC_MIGRATION_REHEARSAL.md)。下文“未导入”等为初始只读研究阶段记录,当前执行状态以上述演练为准;尚不具备直接无损切站条件。
|
||||
|
||||
## 用户最新迁移决定(2026-11-03)
|
||||
|
||||
用户已要求:新增实例级可关闭的VIP升级,其他子项目默认关、FUC-XB开;已付未履约预购迁移后退钱包,原管理员订单也迁移;不要旧自动续订;客户端随后明确改为有感迁移、重新导入新站订阅,不做旧URL兼容;旧账只读归档,新站显示新业务、不影响XB折抵返佣。新站营业接入后面再做。最新边界唯一见[功能对照最新边界](FUC_XB_FEATURE_COMPARISON.md#用户已明确的新边界2026-11-03本节覆盖下方旧建议)。下文旧建议保留证据性质,不能继续实施已放弃的预购队列/自动续订/无感兼容。
|
||||
|
||||
## VIP全量差值核对(2026-11-03)
|
||||
|
||||
用户随后明确:迁移累计以旧`total_pay`为准,不按账单重建;预购退款扣减后的累计最低0,钱包仍全额返还。已将`max(0, total_pay-预购返还)`用于独立测试库的期初折扣及私有累计账本,39项检查通过;本节差值只归档,不再阻塞基线。自动升级模块尚未实施,源站未修改。
|
||||
|
||||
此前只核对3个预购退款账号,不是已完成全量账务对账。用户要求说明数量后,基于同一私有快照对11,542个现存账号比较旧`total_pay`与现存套餐已付账单完整金额(按`paid_gateway/paid_balance/paid_admin`状态、排除充值商品`code`,网关混付含余额贡献):955个账号不相等,其中旧累计较小941、较大14;731个旧累计为0但存在已付套餐账单,1个有累计但没有对应现存已付套餐账单。
|
||||
|
||||
这是**字段与现存账单的算术差值,不是955个已确认错账或损失账号**。旧累计算法、账单保存范围、管理员付款标记和历史处理版本均尚需解释;不能直接覆盖用户VIP或将旧累计与完整退款机械相减。仅36个差值账号当前账单中带余额/充值/管理员付款标记,不能把全部差值归因于余额支付。
|
||||
|
||||
3个有效预购退款账号中,2个旧累计与现存套餐已付账单合计不同、1个完全一致;其中1人完整退款额大于旧累计,直接相减为负。具体身份、各自金额和订单只保存在`private/vip-three-account-readback.json`;全量明细在`private/vip-all-account-comparison.json`,聚合口径在`vip-all-account-comparison-summary.json`。本次仅只读计算,没有调整测试库VIP、退款金额或生产数据。
|
||||
|
||||
本轮尚未执行钱包退款、用户导入、VIP核心实现、源站订单变更、节点切换或上线。
|
||||
|
||||
## 来源、目标与保护
|
||||
|
||||
来源是目前对外服务的FUC生产站(福云123.com),`site-jp01 /www/wwwroot/fuuuu.cloud`,现场HEAD `fea0d886f77a19a7b174836262917f7a735b2a5f`,与本地新版`fuc-new.loc`参考一致。“旧FUC”在本任务指相对于FUC-XB的现行业务站,不是本地旧目录`fuc.loc`。用户授权先把用户数据取回本地、研究迁移风险,不包含正式导入、改造核心或上线。
|
||||
|
||||
研究目标是独立的FUC-XB实例/数据库,尚未创建迁移运行库;当前`xb.loc`继续是合成数据验收站。不能把FUC数据合并到DPL/HN,不能覆盖根`.env`或`instances/hn`。主题0.11.0本地与已列API验收通过,真实支付、邮件、验证码及客户端联网未完成外部联调;旧FUC的预购、自动续订、会员等业务也不能由主题样式代替。
|
||||
|
||||
采集沿本机SSH→已登记白色机→site-jp01,使用既有受信主机密钥、准确资源凭据字段;数据库连接只在目标机内从其配置交给PDO。未打开线上网站,也未运行FUC应用入口、Cron、邮件或支付。数据直接经SSH压缩流写入本地,不在服务器生成明文备份文件,不输出用户明细、密码哈希或订阅令牌。
|
||||
|
||||
私有产物位于XB忽略目录`codex/output/fuc-migration-20261103/private/`:目录700、文件600,父目录700,Git排除;未挂载到网页、运行服务或共享数据库。`snapshot.jsonl.gz`为研究所需13张表的一致性摘录,**不是全库灾备**。排除用户二步验证密钥、API密钥、提现地址、注册IP及备注/封禁理由;未采集会话、登录IP历史、节点地址/密钥、支付商配置、全局应用密钥。密码哈希和订阅token仅存在私有数据文件中。
|
||||
|
||||
## 快照证据
|
||||
|
||||
- 快照时间:2026-11-03 **13:42:26 UTC+8**,应用时区现场核实为`Asia/Taipei`。导出PHP CLI默认时区为UTC,不把它当成应用时区;原到期/注册字符串按应用时区转换为Unix秒。
|
||||
- 全部所选表为InnoDB,以`REPEATABLE READ`、`READ ONLY`、`WITH CONSISTENT SNAPSHOT`读取;逐表导出数量、尾部完成记录及gzip完整性已核对。生产业务写入0;没有暂停原服务。
|
||||
- 压缩文件2,334,996字节;SHA256 `18f8346061922da82075f3d1d040f51247f23432b26e29ea2bfe73d8b7117103`。
|
||||
- user 11,542;order 4,770;invoice 4,769;paylist 5,528;link 11,517;product 14;renewal_quote 214;user_money_log 193;payback 5;invite_up 333;user_coupon 12;vip_map 4;plan_queue 0。**plan_queue为空不代表没有已付预购,真实待激活状态在order。**
|
||||
- 13:51追加只读统计:43个启用/显示节点均标为VMess,等级1、分组1;没有读取地址或密钥,未逐条联网。该附加元数据不与13:42账务快照混称同一事务。
|
||||
|
||||
## 可以保留的基础数据
|
||||
|
||||
| 对象 | 实测结果 | 迁移约束 |
|
||||
| --- | --- | --- |
|
||||
| 账号 | 11,542,规范化邮箱无重复,UUID全有效且无重复 | ID只在独立空目标库按映射保留;不能对其他实例按同ID覆盖 |
|
||||
| 密码 | 11,542均为PHP可识别bcrypt;原FUC生成的合成密码哈希由XB Helper正确验过,错误密码拒绝 | pass→password,不二次哈希,不回收/重置密码;未掌握或测试真实用户明文密码,不声称全员真实登录已验收 |
|
||||
| 钱包 | 26人非零,共422.19元;无负数/分以下金额 | Decimal转换为42,219分,投影逐用户及总和守恒,不走充值/支付回调 |
|
||||
| 返利钱包 | 4人非零,共16.32元 | 独立转为commission_balance 1,632分;不能与钱包混合、再次发放历史返佣 |
|
||||
| 流量 | user.transfer_enable/u/d均为字节 | 保留原值;SKU的bandwidth是GB,不能再次给用户字节值乘GB;不调用开通/重置服务 |
|
||||
| 到期 | 有效付费等级195人,含1管理员;等级1另101人 | 保留原Unix秒,不用导入日重新计算期限;失效日期不得转为XB的NULL不限时 |
|
||||
| 邀请关系 | 无缺失邀请人、自指或循环 | 先映射全部用户ID,再赋invite_user_id,不重新触发邀请奖励 |
|
||||
| 订阅token | 11,516条关联有效用户;无重复;26账号没有token;另1条孤儿link | 可保留有效token;无token仅在批准后生成新token;孤儿token隔离,不重新分配给其他用户 |
|
||||
| 安全状态 | 当前MFA、封禁、影子封禁均0;原管理员1人 | 研究投影所有is_admin/is_staff均false;旧管理员单独人工确认,不自动继承权限;不复制会话/全局密钥 |
|
||||
|
||||
离线投影输出`private/user-projection.jsonl`,只作为字段核对,**不是可直接执行的导入文件**。其中plan_id标为未解决、next_reset_at为空占位,不得直接加载进运行库。逐用户余额、返利、u/d、总额度、到期和UUID保留;余额/返利/已用/剩余字节总和断言通过,未执行流量重置、目标DB写入或管理员授权。
|
||||
|
||||
## 确定风险与处置要求
|
||||
|
||||
| 风险 | 本次证据 | 必须如何处理 |
|
||||
| --- | --- | --- |
|
||||
| 旧额度被新商品覆盖 | 195个当前有效付费等级账号中126人的额度不同于当前同SKU:97人更少、29人更多 | 当前user额度/u/d/到期为迁移基线;按历史权益建立映射,不能套当前SKU开通。101个等级1用户也不能改成XB默认1GB/24h新用户试用 |
|
||||
| 已付预购丢失或提前生效 | 17笔pending中13笔关联现存3个用户,其中1人11笔;4笔属已删除用户。另有1笔现存用户的旧pending_activation且账单paid_gateway | 按原ID顺序保留权益;原规则是到期或流量耗尽才取下一笔,不可一次叠加时长/额度或重播支付回调;旧状态1笔先核实是否已履约,不能自动再激活 |
|
||||
| 自动续订/优惠不兼容 | 开关34人;当前有效付费中13人开启且报价ready。13笔有效预购报价12 ready、1 review;有效当前/预购记录中2笔user_price与账单完整付款额不一致 | XB没有FUC同等队列/自动扣余额报价流程;完整保留renewal_quote及来源,不能按尾款推算,也不能默默关闭用户权益或擅自改成当前价 |
|
||||
| 周期/流量策略不同 | 原商品30/90/365天,活动400/183天;原套餐总流量可耗尽后提前切换下一包。XB常规续费按日历月累加,有按月重置逻辑 | 原剩余期按确切秒/字节保留;历史包不设默认月重置;后续固定天数产品、排队及耗尽触发需要专门设计,主题换色不能解决 |
|
||||
| 异常邮箱 | XB实际email:strict验证4个账号不通过,含1个有付费等级和余额的原管理员 | 私有异常表人工核实真实邮箱/管理员归属;不伪造地址,不放宽全站验证,不直接丢弃含余额账号 |
|
||||
| 孤儿/旧账状态 | 47笔订单找不到用户,含4 activated、4 pending;1条孤儿订阅;另外存在pending_payment/payment_pending旧状态 | 留只读历史档案并单独核对,不给新用户复用旧ID,不把旧账导成新待扣款订单;原网关在途回调需切站账本处理 |
|
||||
| VIP与优惠叠加 | 94人有当前会员折扣:90人8%、3人12%、1人15%;FUC有累计消费升级。FUC折扣连乘,XB券与VIP同基数累计 | 不能只搬一个discount字段就宣称规则一致;例如8%会员+10%券,FUC应付82.8%,当前XB应付82%。保留累计消费/已约定续订优惠,未来规则单独确认 |
|
||||
| URL和节点接替 | 旧URL为/sub/token及历史类型路由,XB默认/s/token/flag;当前43个启用节点均VMess,UUID可保留,但未接入XB | 保留UUID/token可减少换配置;域名、路径、旧客户端格式/参数、节点代理和计费须专项验证。当前未发现启用SS节点,SS passwd与XB uuid的差异不应冒充本次现网阻塞,但未来混合协议需另查 |
|
||||
| 误用注册/开通服务 | XB createUser会重哈希密码、生成新UUID/token并可能赠试用;OrderService会开通/重置/余额/返佣处理 | 正式导入须是有逐项清单和守恒检查的专用事务,关闭/规避普通注册与订单副作用;不调用现成API“重放”旧用户或旧订单 |
|
||||
|
||||
另有2,198个账号保留非零auto_reset_day(当前付费等级中14个),但当前相关重置实现已注释,不能按遗留字段自动开启XB每月重置。待迁移的历史周期先按现有额度/u/d保留,试迁移再核对实际调度和后续重置策略。
|
||||
|
||||
源码依据:FUC `src/Utils/Hash.php`、`src/Models/VipMap.php`、`src/Services/Cron.php`的orderToPlan/planQueue_pendingToActivation/_plan_to_user、`src/Services/RenewalPricing.php`、`src/Services/Subscribe.php`及`src/Services/Subscribe/V2Ray.php`;XB `app/Utils/Helper.php`、`app/Http/Requests/Passport/AuthLogin.php`、`app/Http/Middleware/Client.php`、`app/Services/UserService.php`、`app/Services/OrderService.php`、`app/Services/CouponService.php`、`app/Services/TrafficResetService.php`、`app/Models/Plan.php`及`app/Models/Server.php`。不依据旧模型表名推断当前运行状态。
|
||||
|
||||
## 追加方向:沿用XB业务规则(2026-11-03)
|
||||
|
||||
用户明确要求尽量不改XB代码、不动原有业务逻辑。两边功能差异、可用原生配置处理的部分、旧特殊权益处置及不能靠主题补齐的部分,统一见[功能对照与方案](FUC_XB_FEATURE_COMPARISON.md)。不据此自动开始导入或改造。
|
||||
|
||||
追加只读核查:13笔有效预购中11笔属于同一个原管理员账号,另外2笔各属于一个普通账号。是否为测试单尚未经用户确认,仍全部保留为待处置权益;账号/订单/账单明细只放`private/queued-11-details.json`及私有对照表,不写入普通文档。混付的完整账单合计需包含余额贡献,不能直接取旧order.user_price尾款。
|
||||
|
||||
## 建议路线与正式迁移关卡
|
||||
|
||||
1. **保持FUC继续服务**。先完成独立FUC-XB试迁移设计:用户/钱包/当前权益、历史只读账本、预购队列/续订报价的承接方案;按需提出具体XB核心变更申请,未批准前不修改共用核心。
|
||||
2. **先隔离演练**。在独立非公开目标库试导,禁止付款、发信、回调、自动续订、外部队列。逐用户核对邮箱、密码哈希、余额分、UUID/token、邀请关系、当前额度/u/d/到期及历史权益;特测11笔排队、400/183天、余额+网关混付、review报价、等级1和管理员。验证重复运行不重发权益/金额,失败全事务回退。当前仅做了内存投影,没有执行这次运行库演练。
|
||||
3. **业务补齐后联调**。需要真实支付回调、邮件/验证码、旧订阅URL/客户端、节点对接与计费、权限,以及共享宿主DPL/HN不受影响的验收。沿既有访问审批/服务器侧路线,不以本地主题页面通过替代。
|
||||
4. **切换单独批准**。正式迁移前安排源站冻结窗口:FUC注册/下单/充值/自动续订及在途回调、节点最终流量上报按明确水位排空;最终一致性快照+增量核对,原数据库备份及明确代码版本保留。研究快照不能在以后直接覆盖线上。
|
||||
5. **回滚保留增量**。若新站已产生付款/消耗,先保存新站交易和流量账本、按业务主键对账后再回切;不能恢复旧快照后丢弃切换后的订单、余额和流量。不要让两个系统同时扣费或消费同一预购权益。
|
||||
|
||||
本轮没有用户迁移、账号改密/创建、支付、节点切换、DB迁移、推送或部署;没有为恢复主题而改XB核心。已完成服务器侧只读采集及本地离线研究,未做线上页面验收。
|
||||
|
||||
## 产物与检查
|
||||
|
||||
`codex/output/fuc-migration-20261103/`内:`summary.json`、`deeper-summary.json`、`contract-results.json`、`projection-results.json`为聚合证据;`private/`内快照、私有异常ID和字段投影不提交Git、不在报告输出值。`probe.php`/`snapshot.php`/`clock.php`/`access.php`为本次受限只读采集;`analyze.py`/`deeper.py`/`project.py`/`validate-contracts.php`为离线研究,**没有写入目标数据库的导入器**。原始快照尾标/行数/gzip/SHA、文件权限与Git排除、真实哈希格式、合成密码兼容、XB严格邮箱校验、资金和流量投影守恒均已核对。
|
||||
+153
-21
@@ -1,6 +1,121 @@
|
||||
# Fuc:新版 FUC 用户主题适配
|
||||
|
||||
当前版本 **0.6.1**。2026-10-30重新对照小龙最新FUC源码,已同步新Logo、认证页独立云图标、侧栏对齐和深浅字标,修正原适配中的CSS加载顺序、跨页面样式污染、页脚与首页滚动导航/轮播差异。管理员后台与XB核心未改。2026-10-30完成本地合成数据复查和主题包;2026-10-31随XB统一功能提交1ded402推送、发布为可选主题,DPL/HN仍保持Stellar/EZ。FUC业务后端/数据不在本批范围,部署与恢复见[共用后端](UNIFIED_BACKEND.md)。
|
||||
2026-11-07 原生标志发布候选 Fuc 0.12.20:用户选择 Cool 主题原生折叠标志,登录/注册/找回密码、侧栏、首页和浏览器图标统一使用旧 FUC `cool1.png` 原始图案。原 PNG 字节嵌入 SVG,首页保留正式「福云」字标。资源引用更新缓存版本。发布范围仅品牌素材及其缓存引用;不包含本地折福试稿或其他未发布 UI/客服修改。回退基线为 `2c92a857e8da54c16c4861b25ea420f560ccc032`;发布验收以任务回执为准。
|
||||
|
||||
## Fuc 0.12.19 compatibility release — 2026-11-07
|
||||
|
||||
Based on production d552b8a592314d3e28ed261f213a49e272346f57, preserving the node ordering change. Mobile sidebar uses native vertical scrolling, desktop keeps PerfectScrollbar and the original hover indentation. Mobile dashboard tutorial buttons, subscription controls and chart stay inside their cards. Touch/narrow form controls have at least 16px fonts, touch login does not autofocus, and menu logic follows CSS matchMedia breakpoints.
|
||||
|
||||
Release candidate: all 55 core/DOM/motion/app/palette checks passed. Local evidence: 40 DOM/motion/app checks; 80 Chromium route-width measurements across 320–1440px; short/tall checkout dialogs; macOS Safari 375px layout. iOS 18.1 XS showed the new 16px control font, but final focus/keyboard-dismissal/navigation verification is incomplete because native inspector control did not execute reliably. No physical iPhone 13, Android/Windows or Firefox acceptance is claimed.
|
||||
|
||||
No shared business logic, admin UI, customer-service module, test accounts or payment-preview behavior included. Production client/tutorial links and pinned-announcement behavior retained. Deployment must record the prior real release path as well as SHA: the old directory name is a11df4f while its HEAD is d552b8a. Rollback is an atomic current symlink switch to that recorded path, without restoring the business database.
|
||||
|
||||
当前版本 **0.12.4**,已沿Git发布到独立FUC-XB测试站。IAB桌面/手机页面、动态交互、钱包下单/VIP升级/取消退款及XB原版后台验收已完成;旧FUC、DPL/HN未切换。真实支付、邮件、节点/客户端联网仍后置,不能据此宣布正式营业。完整范围及回执见[FUC-XB测试站](FUC_XB_STAGING.md#2026-11-04-最终验收隔离测试范围通过)。
|
||||
|
||||
## 0.12.4 隔离线上页面验收与修复(2026-11-04)
|
||||
|
||||
本轮只调整Fuc主题及其专属测试;测试站独立vhost/MIME和额外门禁另见部署文档,未新增XB核心兼容改造,管理员仍用锁定原版资源。
|
||||
|
||||
- 0.12.2修正余额全额付款的商品金额展示,按XB原生历史价值口径包含钱包和折抵;分别显示钱包、旧套餐折抵、在线本金,已取消钱包标注已退回。结算仍由XB原订单决定。
|
||||
- 0.12.3修复模式切换重挂LINK导致Chromium卸载CSS、页面闪白/失去样式;公共样式留在原位,新模式样式有序加载成功后才提交页面。亮暗与公开/用户切换实际回归。
|
||||
- 0.12.4下单确认的最终金额改为下单后确认,避免把标价误称VIP后实际支付;文档分类mt-n1只去掉负边距,符合已批准的可用布局例外。原模板/CSS文件不修改。
|
||||
- 46项Node测试、19份原CSS/26模板/Pace及原UI库字节完整性、ZIP源码/CRC/ESM闭包通过。1280×720及390×844实际检查用户所有菜单、公开/认证/订单/内容详情、手机导航;Pace请求中3px进度、紫绿亮暗保存、绿色火箭290°/tada、弹窗取消/重入及FAQ展开/折叠/搜索通过。未宣称与旧FUC生产实时数据逐像素截图比对。
|
||||
- 原生钱包100元开通后VIP升9.2折;下一笔续费原生92元,取消返92,VIP累计/到期不变。测试夹具及会话精确清理,迁移用户资金全量复核无意外差异。
|
||||
|
||||
运行提交`28ccc0e964a9ff9ee917a15f99c6f0140174e7cf`。交付包`codex/output/fuc-theme/Fuc-0.12.4.zip`,SHA256 `1695853b5c3bb54aef5c783cf4f01d436fdf525cbc6791401c81f529ae69be21`;0.12.1配色恢复及旧版本记录保留如下。0.12.0本地VIP、0.11.0四季为历史状态;用户后来要求原紫/绿,不能按旧章节重新生成四季。
|
||||
|
||||
## 0.12.1 恢复原版配色(2026-11-04)
|
||||
|
||||
用户明确要求撤回四季主题及首页跟随变色。该轮本地主题为**0.12.1**,只保留原版亮色紫/绿、暗色紫及亮/暗/系统模式;公开首页恢复原版固定紫色,不受用户区配色影响。0.11.0四季方案为历史,不能按下文旧指令重新生成季节扩展。
|
||||
|
||||
- 保留当前0.12.0的VIP、客服、接口与既有菜单明暗归一修正,未以旧主题整目录覆盖。只移除季节选项/生成器/seasonal.css及加载路径,流量图恢复原来的紫/橙/红色。原CSS/素材未改。
|
||||
- 浏览器旧spring偏好归回原绿色cyan,summer/autumn/winter归回默认紫色;原purple/cyan保持。启动清理旧data-fuc-season/data-fuc-palette和--season-*覆盖,保留明暗及其他偏好。设置恢复原模板的“亮色主题选择”和“暗色主题选择”,保留序列化选中项修正。
|
||||
- 主题版本及自身ESM/模板/样式查询版本升为0.12.1,防止缓存混用。原0.12.0完整相关文件备份于codex/output/fuc-theme/palette-revert-20261104/before/;不回退其他聊天修改或XB核心。
|
||||
- 41项现有核心/DOM/交互/应用及旧偏好恢复测试通过;19份原CSS、26份惰性模板、Pace及原UI库字节完整性通过。
|
||||
- 内置浏览器在xb.loc隔离合成账号实际保存紫/绿及亮/暗,读回原style-purple/style-cyan与menu-light/menu-dark;设置仅紫/绿两项,原暗色紫选项保留。选择绿色后首页背景仍rgb(60,34,153)、blend normal;无季节CSS链接和root季节标记。未触及真实业务数据。
|
||||
|
||||
交付包Fuc-0.12.1.zip:642个文件、7,596,466字节、SHA256 `0d1025875a2e8fa4b469b8faa397de674ee7bf79ef15b37a02695bee156254e5`;CRC、源码逐字及ESM运行依赖闭包通过,包内无seasonal运行样式。回执、截图与仅本任务差异在codex/output/fuc-theme/palette-revert-20261104/。
|
||||
|
||||
本地及FUC-XB独立线上测试站均已恢复。用户明确批准同步后,Git提交`7446b045a3702b967cc40456040fdb4210bf19da`已推送测试分支并原子切换到独立release;真实Nginx/FPM及登记HTTPS反代的资源摘要、入口保护、缓存头和公共配置回读通过。已完成服务器侧验收,未做线上页面验收。旧版本0501711保留用于回退;DPL/HN及旧FUC未发布或切换。发布与回退见[FUC-XB测试站](FUC_XB_STAGING.md)。
|
||||
|
||||
## 0.11.0 按原绿色重做四季与火箭联动(2026-11-03)
|
||||
|
||||
用户明确否定0.10.0的灰暗配色,要求参考原绿色的明度/饱和度,并将原绿色直接作为春;另指出商店小火箭应随配色变化。本轮已替代旧四季:紫色保留,春·原版绿色、夏·晴空蓝、秋·杏叶橙、冬·冰川蓝,共五个选项。旧`cyan`偏好自动解析为春,旧春樱粉也转为原绿色,无重复绿色选项。
|
||||
|
||||
- 春季用户亮色直接加载原`style-cyan.css`,不叠加自定义季节颜色。夏/秋/冬也以该文件为底,分别将每个颜色转色相30°/222°/65°,保留原色各自的饱和度、明度、透明度、悬停与渐变层次;移除0.10.0的灰暗主色及染色页面/暗色背景。`seasonal-css.py`只生成配色与滤镜声明,不改变几何或动画。
|
||||
- 原绿色火箭滤镜为290°,四季分别为290°/320°/152°/355°;保留原图与原动画,只用原版同类CSS滤镜,不修改图片。暗色也覆盖原版强制紫色/无滤镜的规则,侧栏、按钮和火箭保持对应季节。
|
||||
- 恢复原`core/app.js`的菜单/顶栏明暗类归一逻辑:原模板同时含menu-light/menu-dark,亮色只保留menu-light、暗色只保留menu-dark。修复先前原紫色菜单覆盖绿色、普通菜单浅字难读的问题,系统亮暗切换也同步处理。FUC原文件未改。
|
||||
- 41项Node契约/DOM/交互测试、19份原CSS/26份模板/Pace/UI库完整性、运行语法与ZIP源码/CRC/ESM闭包通过。右侧现有IAB实际保存切换四季×亮暗8种桌面组合,火箭滤镜、按钮RGB和菜单渐变均符合各自原绿色色阶;四季390px切换均无横向溢出。侧栏、顶栏、套餐卡布局尺寸保持,火箭仍有原版运动。另回归冬季首页和登录页配色;最终保留春季亮色预览。没有重新进行业务API、支付或邮件联调。
|
||||
|
||||
证据:`codex/output/fuc-theme/seasons-refresh-tests.tap`及`season-refresh/`内browser.json、mobile.json、8份桌面/4份手机截图、seasons-overview.jpg、package.json。0.10.0主题ZIP与`before-season-refresh-20261103/`保留用于本轮回退。本轮仅Fuc主题、专属工具与文档,没有新增XB核心、管理员或API修改;未提交/推送/生产部署。
|
||||
|
||||
## 原版内置配色核查(2026-11-03)
|
||||
|
||||
用户询问原版是否隐藏其他主题色。只读核对新版FUC当前HEAD `fea0d886f77a19a7b174836262917f7a735b2a5f` 的活动用户header、样式目录和设置保存控制器:完整配色仅`style-purple.css`和`style-cyan.css`,选项也仅紫/绿。`style-cyan_back.css`是旧绿色备份,与当前绿色只差Logo滤镜及空白,不是第三套配色;`dark-layout.css`为统一暗色覆盖。`color.css`只定义绿/紫基础变量,Bootstrap通用状态色不是额外整站主题。原`themeDark`虽然保存且选项为purple,但活动header没有按它选择独立暗色CSS。XB的四季配色为本次新增,不是原版隐藏主题。本次未修改FUC或XB运行代码,也未访问线上。证据:`codex/output/fuc-theme/original-palette-audit-20261103.json`。
|
||||
|
||||
## 0.10.0 春夏秋冬配色(本地)
|
||||
|
||||
历史方案:配色已由0.11.0按用户反馈替代,以下仅保留当时实现与验收记录。
|
||||
|
||||
按用户要求,在原紫色、绿色之外增加春·樱花粉、夏·湖水蓝、秋·枫叶橙、冬·霜雪蓝。四套均支持原有亮色、暗色与跟随系统模式,主题偏好只保存于当前浏览器。桌面从齿轮进入面板设置,手机从头像菜单进入面板设置,选择“配色主题”并保存,沿用原提示及1000ms后刷新。
|
||||
|
||||
- `assets/palettes.mjs`维护六套白名单和四季颜色变量;`scripts/theme-fuc/seasonal-css.py`从原紫色CSS提取颜色声明,再追加`seasonal-surfaces.css`中的亮暗表面规则,生成`assets/native/seasonal.css`。原紫/绿CSS、FUC源文件及原动画时长未改,新增规则只在四季配色时启用。
|
||||
- 覆盖首页、认证页、侧栏/顶栏、按钮、卡片、表单、页签、弹窗、表格、Pace与流量图。保留危险、警告等语义颜色;公开首页Logo保持白色可读,用户区Logo随四季调色。
|
||||
- 修复面板选项经HTML序列化后丢失当前选中项的问题;配色、亮暗模式和菜单状态在刷新后正确回读。旧的空置暗色配色下拉替换为四季说明,原亮/暗/系统模式入口保留。
|
||||
- 本轮仅Fuc独立主题与专属工具,无XB核心、管理员或API修改,没有提交、推送、上线或切换DPL/HN。此前独立批准的核心安全修复不属于本轮配色。
|
||||
|
||||
验收:39项Node契约/DOM/交互测试通过;原19份CSS、26份惰性模板、Pace及UI库完整性通过。仅使用当前聊天右侧IAB,四季×亮暗共8种桌面组合实际保存/刷新,其侧栏、顶栏、首张套餐卡几何与原绿色基线完全相同;四季390px手机切换均无横向溢出。另核验冬季首页、登录页、流量图/图例,春季刷新回读、暗色侧栏与原绿色回切;追加四季浅色字标均为rgb(94,88,115),避免缓存中的暗色字标颜色污染。色彩对比度测试覆盖白色主按钮文字及暗色链接;未将本轮配色检查写成外部支付/邮件等业务复验。
|
||||
|
||||
证据:`codex/output/fuc-theme/seasons-tests.tap`、`seasons-browser.json`、`seasons-mobile.json`、`season-*.jpg`、`seasons-settings.jpg`、`seasons-overview.jpg`及`package-seasons.json`。保留0.9.0包和`before-seasons-20261102/`主题文件备份,回退仅恢复Fuc主题,不还原其他工作区文件或后端。
|
||||
|
||||
## 0.9.0 再次复核与可安装交付(2026-11-02)
|
||||
|
||||
本轮目标是让Fuc作为正常XB主题使用,不要求用户先选择或切换某个生产实例。所有业务仍调用安装该主题的XB同源API,沿用目标XB已有的支付、邮件、验证码和节点配置;本轮没有新增XB核心适配或管理员修改,也没有提交、推送、部署或切换DPL/HN主题。
|
||||
|
||||
- 新版FUC当前参考HEAD为`fea0d886f77a19a7b174836262917f7a735b2a5f`,前端无未提交改动。相对前次参考,套餐和自动续订提示新增续订报价说明;已重新导出当前原模板。XB无FUC自动续订报价,相关可选include保持惰性,不伪造数据。
|
||||
- 登录/注册恢复原`auth.js`的等待文案、成功后OK确认弹窗及确认后进入用户中心;错误保留原组件。订阅重置恢复原二次确认的图标、文字、确定/取消按钮。工单、回复、提醒等成功提示按原1000ms、返利按1500ms后刷新当前数据,旧页面请求不再覆盖新页面。
|
||||
- 修复FAQ关闭时`aria-expanded`被误置为true、箭头无法复位的问题,保留原Bootstrap对同组问题的联动;实际右侧IAB已观测展开`collapse show`/true和收起`collapse`/false。
|
||||
- 加入真实动画时长的切页复现,发现并修复Bootstrap弹窗过渡尚未结束就销毁组件后的`focus`空引用。离页先完成原组件待执行的过渡回调并解绑下一弹窗回调,再清理遮罩与滚动锁;旧页面提示一并关闭。
|
||||
- 今日流量接入XB已有`user/stat/getTrafficLog`,使用StatUserJob已计倍率的u/d,避免再次乘倍率;圆环拆分剩余、历史、今日。接口不可用仍显示未知。无订阅时恢复原空流量/不可订阅状态,签到按钮不再错误显示已签到。
|
||||
- Trojan复制入口使用XB现有`flag=general&types=trojan`,其他复制/导入使用已存在的协议flags;保留订阅地址已有参数,不新增后端路由。社群入口取XB的`telegram_discuss_link`,不继承FUC频道;首页导航反映当前登录态。商店显示XB实际返利比例和套餐重置规则,不保留FUC专属注册流量奖励/提现门槛的虚假占位承诺,原横幅DOM与样式保留。账户等级没有XB对应字段,显示未知,避免把长套餐名称挤入Level窄列。
|
||||
- 当前套餐新增手动续费/重置流量的周期入口,套餐由XB按当前用户权限返回;修复已有用户续费被新购库存或停售标记误挡的问题。仍以后端下单校验为准,不开放隐藏管理员套餐或绕过续费权限。
|
||||
|
||||
本轮验收:**36项Node契约/DOM/交互与异步切页测试通过;18组真实XB HTTP回归通过;此前独立批准的密码重置修复5项/21断言复验通过**。19份原CSS、Pace和原UI库字节核对、26份惰性模板完整性、运行语法、ZIP CRC、包与源码逐文件匹配及ESM引用闭包通过。密码重置单元测试须按下文业务约束的完整隔离命令运行;缺少`APP_ENV=testing`时迁移保护会阻止初始化,不能将该错误当成业务回归失败。
|
||||
|
||||
IAB本轮对照了9个桌面用户页面的原版布局和组件参数,侧栏宽260px、顶栏位置/字体/过渡一致;短内容与长内容引起是否出现6px滚动条,页面宽度会相应变化,不作为CSS漂移。右侧原生标签实测15个390px用户/详情/订单路由,无页面级横向溢出、损坏图片或未替换占位符。登录成功确认、订阅重置确认内容与原版一致;隔离站实际创建12元待付订单、取消并刷新回读已取消,无真实付款和待付遗留。手动续费入口实际选择月付并进入正确套餐确认页,未重复开通。组件测试另覆盖停售已购套餐续费及旧优惠码回包不误打开新页面弹窗。
|
||||
|
||||
证据在`codex/output/fuc-theme/`:`readiness-tests.tap`、`readiness-integration.txt`、`readiness-auth-tests.txt`、`readiness-desktop-geometry.json`、`readiness-mobile.json`、`readiness-login-success.jpg`、`readiness-reset-confirm.jpg`、`readiness-order-canceled.jpg`及`package-readiness.json`。主题包可安装与本地同源业务验收已完成;真实支付/验证码服务、邮件投递及客户端联网仍未做外部联调,不能称为这些外部链路已验收,亦不声称所有业务数据和状态已逐帧、逐像素证明一致。此前用户确认的文档/订单布局补偿、XB必要字段和缺失FUC后端能力边界继续有效。
|
||||
|
||||
## 0.8.0 动态与交互对照
|
||||
|
||||
用户再次要求动态效果与原版一致,并明确由AI自行查找、只复用当前右侧内置浏览器标签。本轮仅修改Fuc主题与专属工具,没有新增XB核心或管理员修改;上一节记录的找回密码核心修复是此前独立批准事项。
|
||||
|
||||
- 对照仍为新版`fuc-new.loc`,HEAD `4eff00023420175662792769d1d2ee1c16d9bb68`,前端路径无未提交变化。复用现有IAB的XB和FUC标签,没有新建浏览器或标签。
|
||||
- 从FUC原文件按明确边界提取未改动的jQuery 3.4.1、Popper、Bootstrap 4.3.1、PerfectScrollbar、Hammer、Waves;原SweetAlert2、SmoothScroll和首页Bootstrap 5.0.0-beta1一起本地化。首页Bootstrap5保留自己的data API,不覆盖用户区Bootstrap4插件;XB主题没有执行FUC业务脚本或重复加载Pace,接口仍仅接入XB。`vendor-interactions.py`可重建,`verify-native.py`逐字核对源文件,原许可证说明保留。
|
||||
- 原弹窗进出/遮罩/滚动锁、页签淡出淡入、FAQ高度折叠、按钮波纹、下拉菜单、工具提示、返回顶部1000ms和首页500速率平滑滚动改用原组件。侧栏复原hover类带来的文字位移、折叠后的悬停展开/移出收回、切换图标、500ms状态过渡、200ms图表重排、原Hammer阈值250px的侧栏滑动收回及手机遮罩;用户已批准保留的旧页面布局补偿现在随侧栏260/80px以原300ms过渡。
|
||||
- 商店层级改为每个XB套餐一个原版分组页签,周期价格呈现为该组内月/季/年等原卡片。套餐/周期组合使用独立DOM标识,实际建单仍提交原XB plan_id与period。重置流量卡只在当前套餐允许时出现。
|
||||
- 购买恢复原版优惠码弹窗→订单确认弹窗,保留真实XB优惠检查和建单。自动续订等XB缺失能力继续禁用;支付仍进入XB订单流程,不伪造FUC的财务/排队续订后端。原独立purchase路由保留兼容入口。
|
||||
- 去掉切页时先清空样式和重建空白用户壳的中间态。公共样式保留,新样式准备完成后与完整内容一次切换;页面滚动在切换完成后复位,点击当前菜单同样加载并恢复默认页签。窗口未跨布局断点时保留当前菜单状态。ApexCharts恢复原版默认动画,移除先显示自制圆环的占位跳变;离页销毁图表。深浅切换恢复原版刷新,面板保存采用原版提示后1000ms刷新。ES模块、原模板/样式索引、桥接样式及UI库增加版本缓存标识。
|
||||
|
||||
验收:22项接口契约、DOM和原组件生命周期测试通过;19份原CSS、26份惰性HTML、Pace及新提取库原文完整性通过。在现有IAB实际观测FAQ的`collapsing`、页签退出`fade active`、手机首页导航`navbar-collapse collapsing`,确认侧栏hover expanded/移出收回、手机遮罩d-block/d-none,以及原Hammer阈值的拖动使侧栏回到menu-hide。原弹窗完成真实XB零元建单和开通;新套餐分组后再次确认套餐/周期正确持久化,测试产生的最后一笔待付零元单已通过隔离OrderService取消。深浅切换刷新后body类均正确。HTTP本地域名采用原ClipboardJS的execCommand兼容路径,内置浏览器原生点击后已读取确认本地订阅链接,测试剪贴板随后清空。所有操作限独立验收站;没有生产付款、上线或管理员变更。
|
||||
|
||||
证据:`motion-audit.json`、`motion-tests.tap`、`motion-order-modal.jpg`、`motion-plans.jpg`,均在`codex/output/fuc-theme/`。原版本地提前续订按钮本次点击未弹出提示,因此购买过程按原`couponForm/buyForm`源码、模板和组件原文核对;不将未观测到的原站购买流程记为逐帧对比通过。此验收覆盖列出的组件和状态,不把不同业务数据、必要字段或缺失后端能力描述为全站所有状态像素相同。
|
||||
|
||||
## 0.7.0 真实 XB 对接与验收
|
||||
|
||||
- 认证使用真实同源API;支持邮箱验证码、邀请注册、邮件快速登录、密码找回、登录设备撤销和XB的过期会话403。登录页移除XB不支持的令牌输入,保留必要字段。无效邮件登录链接显示错误后允许正常密码登录。
|
||||
- 对接Turnstile、reCAPTCHA v2/v3;按本站公开配置加载官方SDK,不降低或跳过后端验证。SDK契约用测试替身验证,未执行真实验证码服务联调。
|
||||
- 订单、周期、优惠码、余额抵扣、取消和状态回读使用XB结果。支付type=0显示本地生成的二维码,type=1支持URL或经重建的支付表单,type=-1只有data=true作为结算成功;持续回读订单状态。HTML响应不执行脚本。StripeCredit使用Stripe托管输入组件及token接口;真实支付插件/回调、Stripe外部支付均未验收。
|
||||
- 钱包使用XB余额和礼品卡检查/兑换/记录;佣金转入、配置允许的提现方式、财务工单按XB流程。账户页接入真实会话、提醒和Telegram绑定指令(仅配置启用时),不伪造原FUC不具备的能力。新增Markdown文档及表格清洗渲染,保留正文安全链接;修复工单详情路由和页面切换后旧请求覆盖当前操作对象的问题。
|
||||
- `http://xb.loc`已由用户执行安装器并验证HTTP200,右侧Codex IAB可登录。它连接`instances/fuc-acceptance/`内独立SQLite与真实Laravel内核,Node/PHP只监听回环8594/8595。独立环境从迁移初始化,不复制DPL/HN或FUC数据;HTTP外部调用受阻,邮件/其他任务使用测试替身,订单开通任务真实执行。
|
||||
- **18组真实HTTP/API回归通过**:认证与拒绝错误密码、主题入口/敏感文件404、订单创建/取消/零元开通、订阅重置、Clash Meta/Sing-box输出、优惠金额及订单所有权、礼品卡一次性兑换、邀请/佣金、工单闭环、提现工单、提醒、文档等列表、改密、邮箱验证码重置、撤销会话403。邮件只验证本地验证码契约,没有外发。
|
||||
- **16项静态契约/DOM测试通过**:认证失效、支付返回分支、危险表单过滤、Markdown链接/表格、安全清洗、套餐数量/周期/零价、必填认证字段,以及验证码和Stripe SDK替身。19份CSS、26份惰性HTML和原Pace脚本/CSS完整性通过;PHP和运行模块语法通过。
|
||||
- **右侧IAB真实页面验收**:测试账号登录、工单创建/详情/回复/关闭、提醒保存回读、文档详情与FAQ展开、零元订单创建/结算/已完成回读;首页、注册、找回表单已检查。11个用户菜单页面390px基础检查无横向溢出、损坏图片、未替换字段或加载错误;桌面关键页面已操作并截图。此结果不表示全站所有数据状态逐像素一致。
|
||||
- 证据:`codex/output/fuc-theme/integration-20261101.json`、`real-browser-20261101.json`、`real-order-20261101.jpg`、`real-dashboard-20261101.jpg`。
|
||||
|
||||
尚未完成:目标站真实邮件收件、验证码服务、支付渠道付款/回调和客户端联网联调,生产发布/切换。本地隔离验收不替代这些项目。此前发现的XB找回密码不撤销旧登录会话问题,用户已于2026-11-01明确批准本地修复并测试:密码保存和撤销全部登录令牌现在同事务完成;5项单元测试/21断言及增强的18组HTTP回归通过,未提交、推送或上线。唯一行为、批准及回退记录见[业务约束](BUSINESS_RULES.md#找回密码撤销登录会话2026-11-01本地已批准修复)。这项独立安全修复不是主题适配所需,主题ZIP不含后端修复。
|
||||
|
||||
公共能力核对:沿用XB的DomainHub地址配置、现有ATOM/TeleHub后端能力;Fuc不新增后台、凭据、汇报任务或常驻调度。
|
||||
|
||||
用户本轮明确确认两个例外:**文档/订单旧模板保留可用布局补偿;XB认证、提现等保留必要字段和流程,采用FUC样式**。不以这两类差异扩展为XB核心改造授权,也不把全站描述为所有状态逐像素一致。
|
||||
|
||||
@@ -32,7 +147,7 @@ XB 工作区为 `/Users/hellcat/Documents/GemCodes/xb`,实现为独立主题 `
|
||||
|
||||
## 页面覆盖
|
||||
|
||||
以下路由均有本地页面验收。模板路径相对于新版 FUC 的 `resources/views/tabler/`。
|
||||
以下路由历史合成验收与本轮真实验收范围分别见上文。模板路径相对于新版 FUC 的 `resources/views/tabler/`。
|
||||
|
||||
| XB 路由/区域 | FUC 原模板 | XB 行为 |
|
||||
| --- | --- | --- |
|
||||
@@ -41,12 +156,12 @@ XB 工作区为 `/Users/hellcat/Documents/GemCodes/xb`,实现为独立主题 `
|
||||
| register | auth/register.tpl | 邮箱验证码、注册、邀请码、密码确认 |
|
||||
| forget / reset | password/reset.tpl、token.tpl | 发邮箱验证码后设置新密码 |
|
||||
| dashboard | user/index.tpl | 账户、公告、订阅、教程、ApexCharts流量图 |
|
||||
| plans | user/product.tpl | 原商店横幅、周期页签、套餐卡、库存、购买 |
|
||||
| plans | user/product.tpl | 原商店横幅、套餐分组页签、周期卡、库存、购买 |
|
||||
| myplan | user/plan.tpl、plan/ajax_planLog.tpl | 当前订阅、购买记录、订单详情入口 |
|
||||
| orders | user/order/index.tpl | XB完整订单集的本地20条分页 |
|
||||
| purchase | user/order/create.tpl | 套餐核对、优惠码、创建订单 |
|
||||
| checkout | user/order/view.tpl | 订单详情、付款方式、取消、状态回读 |
|
||||
| wallet | user/code.tpl、code/ajax_moneyLog.tpl | 余额、原充值布局、钱包记录页签 |
|
||||
| wallet | user/code.tpl、code/ajax_moneyLog.tpl | 余额、礼品卡兑换、兑换记录页签 |
|
||||
| invite | user/invite.tpl、invite/ajax_affMoneyLog.tpl | 生成/复制链接、佣金记录分页、原弹窗转入钱包/申请提现 |
|
||||
| profile | user/profile.tpl | 原彩色设置卡、个人资料、改密、重置订阅、提醒设置弹窗 |
|
||||
| tickets / ticket/:id | user/ticket.tpl、ticket/detail.tpl | 原弹窗创建、关闭、回复、关闭后禁止回复 |
|
||||
@@ -66,40 +181,57 @@ XB 工作区为 `/Users/hellcat/Documents/GemCodes/xb`,实现为独立主题 `
|
||||
|
||||
`assets/native.mjs` 负责原模板数据绑定及结构适配;`assets/app.mjs` 负责同源XB API、路由、提交、状态;bridge.css仅补交互、弹窗/焦点、只读输入外观及用户确认保留的Tabler容器补偿;此前长套餐名与钱包按钮额外排版覆盖已移除。原CSS仅做本地依赖路径转换。文本、真实数据、功能能力与源站不同,不声称真实FUC运行页面逐像素截图比对通过。
|
||||
|
||||
XB未提供的FUC功能保留原位置并有不可用说明:独立钱包充值/流水、自动续订、签到、昵称保存、TG绑定、原FUC二步验证、IP解封、账号删除和原登录/IP记录。累计付款、在线设备、今日用量及奖励流量等未知字段显示“—”;不使用FUC静态快照假数据。提醒设置采用XB到期/流量提醒,提现提交XB财务工单,不声称原USDT系统已接入。仅Trojan专用订阅入口提示使用通用订阅;其他格式按XB本地协议flags构造,未进行客户端真实联网验证。
|
||||
XB未提供的FUC功能保留原位置并有不可用说明:独立现金充值/通用钱包流水、自动续订、签到、昵称保存、原FUC二步验证、IP解封、账号删除和原登录/IP记录。累计付款、在线设备及奖励流量等未知字段显示“—”;今日用量由XB流量日志提供,日志加载失败时显示“—”;不使用FUC静态快照假数据。提醒设置采用XB到期/流量提醒,提现提交XB财务工单,不声称原USDT系统已接入。Trojan专用入口使用XB通用格式加types筛选;其他格式按XB本地协议flags构造,未进行客户端真实联网验证。
|
||||
|
||||
## 接口、安全与验证范围
|
||||
|
||||
只调用同源 `/api/v1/…`,auth_data原样放Authorization;默认sessionStorage,勾选记住设备才用localStorage,预览与正式缓存隔离。401清缓存回登录,HTTP200业务失败、非JSON、超时和加载错误均有提示。金额按分、套餐流量按GB、用量按字节;优惠码随创建订单提交,由后端校验;库存及最终应付以后端为准。订单与返利分页、工单全列表按当前XB控制器契约实现。
|
||||
只调用同源 `/api/v1/…`,auth_data原样放Authorization;默认sessionStorage,勾选记住设备才用localStorage,预览与正式缓存隔离。401及XB未登录/过期403清缓存回登录,HTTP200业务失败、非JSON、超时和加载错误均有提示。金额按分、套餐流量按GB、用量按字节;优惠码随创建订单提交,由后端校验;库存及最终应付以后端为准。订单与返利分页、工单全列表按当前XB控制器契约实现。
|
||||
|
||||
验证码组件仍未接入,启用captcha或登录配置读取失败时禁用认证提交;没有降低验证。支付保留type/data,支持标准URL跳转及余额/无跳转状态回读;嵌入HTML、扫码、Stripe等格式未完整适配,会提示使用原主题。未做真实付款、邮件发送、账号创建/改密、资金转入/提现或生产操作;本地流程全部是合成API。
|
||||
验证码、支付的当前实现与真实验收边界见0.7.0章节;不能将SDK替身或零元结算当成外部验证码、真实支付验收。
|
||||
|
||||
0.5历史本地验收:18个二级/认证路由分别在1280和390像素检查,无页面级横向溢出、缺失图片、未绑定占位符或内联处理器;9种空列表和503错误提示;套餐周期、FAQ展开、原弹窗工单创建/回复/关闭、订单创建/演示结算、密码修改/找回、佣金转入/演示提现、深浅主题设置已实际点击。当时原CSS17份/惰性HTML25份完整性与6项接口隔离测试通过。后端源码契约检查不能代替真实业务验收。
|
||||
|
||||
## 开发、复核与交付
|
||||
|
||||
当前日常入口是`http://xb.loc`,使用右侧Codex IAB。启动独立真实验收站:
|
||||
|
||||
```bash
|
||||
# 首次初始化;目录已存在时setup拒绝覆盖,不要重复seed
|
||||
php scripts/theme-fuc/integration-setup.php
|
||||
php scripts/theme-fuc/integration-seed.php
|
||||
node scripts/theme-fuc/integration-serve.mjs
|
||||
# 另一终端执行真实接口验收,仅访问xb.loc的隔离环境
|
||||
node scripts/theme-fuc/integration-test.mjs
|
||||
```
|
||||
|
||||
`instances/fuc-acceptance`是本地测试数据,不提交、不部署、不复用生产凭据。脚本内的example.test账号和密码是合成测试值。服务启动时确认8594/8595空闲,不接管HN的8592/8593;退出服务会停止自己启动的PHP。旧`dev.py`是合成API演示,不能与真实验收站同时占用8594,也不作为正式对接证据。固定域名安装器已由用户执行,后续不要重复改系统配置。
|
||||
|
||||
运行使用原生ES modules,无需build。复核命令:
|
||||
|
||||
```bash
|
||||
php scripts/theme-fuc/import-native.php
|
||||
python3 scripts/theme-fuc/vendor-native.py
|
||||
python3 scripts/theme-fuc/verify-native.py
|
||||
python3 scripts/theme-fuc/reference.py
|
||||
node --test scripts/theme-fuc/core.test.mjs
|
||||
python3 scripts/theme-fuc/dev.py
|
||||
# DOM测试依赖仅装入忽略的验收工具目录,不修改共享锁文件
|
||||
npm install --prefix codex/output/fuc-theme/test-tools --no-audit --no-fund --ignore-scripts [email protected]
|
||||
node --test scripts/theme-fuc/dom.test.mjs scripts/theme-fuc/motion.test.mjs scripts/theme-fuc/app.test.mjs scripts/theme-fuc/palettes.test.mjs
|
||||
python3 scripts/theme-fuc/verify-native.py
|
||||
python3 scripts/theme-fuc/package.py
|
||||
```
|
||||
|
||||
本轮临时诊断监听`127.0.0.1:8594`,`#/home`为首页、`#/demo`进入合成用户区。旧8592已被HN的PHP进程占用,本轮没有停止或替换它。演示不会连接真实数据库;`/?fixture=empty#/demo`、`/?fixture=error#/tickets`、`/?fixture=normal#/demo`仍可用于状态检查。
|
||||
原版素材重新导入只在确认参考源码更新后执行`import-native.php`、`vendor-native.py`与`reference.py`,不把导入当普通构建。`bundle-vendor.mjs`只重建Fuc自己的运行依赖,锁定现有esbuild/qrcode/marked/DOMPurify版本并输出版本、SHA256和许可证;不自动更新共享依赖。外部SDK依据[Turnstile官方文档](https://developers.cloudflare.com/turnstile/get-started/client-side-rendering/)、[reCAPTCHA文档](https://developers.google.com/recaptcha/docs/v3)、[Stripe token文档](https://docs.stripe.com/js/tokens/create_token?type=card)对接。
|
||||
|
||||
固定入口计划为`http://xb.loc`,**尚未配置/验收**:本机Nginx重载需要管理员权限,`sudo -n`返回需要密码。已准备可审阅脚本`install-preview-domain.py`,只新增xb.loc回环映射及反向代理到8594,先备份、配置检查失败回退,保留HN/DPL配置,不扩大监听;目前只做语法检查,未执行系统写入。用户在本机终端运行后还须回读HTTP:
|
||||
历史0.11.0交付包`codex/output/fuc-theme/Fuc-0.11.0.zip`,643个运行文件,7601363字节,SHA256 `2eae7736bc6da9158b4ce2563aff049f2893a51a5b333ba25419b2dee0bf526f`。ZIP完整性、源码逐字匹配、ESM引用闭包及不含测试数据/私密配置/管理员文件检查通过。0.10.0、0.9.0及0.6.1包保留用于对照与回退。
|
||||
|
||||
```bash
|
||||
sudo /usr/local/bin/python3 /Users/hellcat/Documents/GemCodes/xb/scripts/theme-fuc/install-preview-domain.py
|
||||
```
|
||||
Fuc在XB中已是系统主题,不能声称通过后台“上传同名主题”升级成功。正式发布沿Git流程部署明确提交,只更新该主题并通过现有ThemeService发布资源;启用由目标实例配置决定,不自动切换DPL/HN。各ES模块引用已带0.11.0版本,避免升级后旧模块缓存混用。生产发布前保存目标主题版本和选择,回退只恢复Fuc主题及该实例主题选择,不恢复其他聊天或整库变更。
|
||||
|
||||
这项固定入口待管理员操作,不能将临时端口记录为已完成的日常域名。
|
||||
打包收尾发现并行任务新增可选Chatwoot配置与模块,予以保留;包收集Fuc运行模块并核对Blade入口和ESM引用,避免遗漏文件。本次没有验证该并行客服服务,空配置时不会加载外站SDK。GemDocs本轮摘要已同步,离线结构检查通过(19项目、591文档、6005链接、542对象及13个岗位/科室绑定),不替代业务验收。
|
||||
|
||||
运行使用原生ES modules,无需build。安装包 `codex/output/fuc-theme/Fuc-0.6.1.zip` 只含运行文件和本地静态依赖,不含导出脚本、编译缓存、预览数据、私有配置或管理员文件。完整性报告 `native-integrity.json`,逐页证据 `secondary-browser-audit.json`、`secondary-*.png`;截图/日志在codex/output,不提交Git。部署及切换需另行任务;本次未执行。
|
||||
|
||||
本次安装包核对:623个运行文件,ZIP 7438172字节,SHA256 `7f9dbc518e7aedad28709a9a1d2e5c3f7ff9f509efdda774efca71f373427998`。主题包不含参考页、合成数据、系统配置安装器或管理员文件。
|
||||
### 用户中心专属公告
|
||||
|
||||
本轮文档已同步GemDocs的dpl/fuc主题摘要;全库离线检查通过(19项目、584文档、5643链接、535对象),该检查不代表运行或业务验收。
|
||||
在原生 XB 公告中添加标签 `dashboard-only` 后,FUC 主题将公告放在用户中心的「置顶公告」,从「网站公告」列表过滤。用户中心会跨页查找该标签,其他公告继续按原生排序显示。「最新公告」使用第一条普通公告。
|
||||
|
||||
## 0.12.12 用户中心教程、下载与侧栏
|
||||
|
||||
侧栏菜单项在鼠标离开时清除悬停状态,避免收起后保留原版悬停缩进。侧栏和账号菜单的「使用教程」使用福云文档中心。用户中心各平台的「安装教程」直达对应文档,macOS Clash Verge Rev 使用原文档已发布的 `/macos/clash-verge-reg/` 路径。
|
||||
|
||||
「立即下载」沿用 DPL 的 Resource 固定安装包地址,覆盖 Clash Verge Rev、Hiddify 和 Android Clash Meta。iOS 使用各自的 App Store 页面,旧 sing-box VT 已下架,入口改为官方 sing-box MT。Resource 未提供 Clash Nyanpasu,本主题的 Windows x64、macOS Apple Silicon 和 Intel 入口使用其官方对应版本安装包。改动限 Fuc 主题,客户端选择和 XB 接口保持原样。
|
||||
@@ -0,0 +1,54 @@
|
||||
# FUC-XB VIP 自动升级(本地完成)
|
||||
|
||||
2026-11-03。用户明确要求完成VIP自动升级、本地测试、其他子项目默认关闭、仅FUC-XB开启、先不动线上。本次在当前XB `master` 工作区新增独立插件及主题适配;没有修改订单/支付/钱包/返佣核心文件,没有提交、推送或部署。此前密码安全及客服等并行差异不属于本次VIP修改。
|
||||
|
||||
## 规则与实例开关
|
||||
|
||||
- 默认满100/200/360元为小福/中福/大福,减8/12/15%(9.2/8.8/8.5折),XB原生后台插件设置可调整。
|
||||
- 迁移期初为`max(0,旧total_pay-预购返还)`,不按旧账单回算;历史订单价格不变,钱包仍全额返还。源决定见[功能边界](FUC_XB_FEATURE_COMPARISON.md)。
|
||||
- 套餐开通成功后累计实际钱包支付+在线应付本金,排除手续费、券优惠和折抵;充值、佣金转余额、未付/取消、重置流量单不累计,一次性流量套餐累计。
|
||||
- 本单按下单时优惠,开通后升级用于下一单,不追补旧订单;券和折抵保持XB算法。
|
||||
- 保留人工折扣,实际优惠取人工与VIP较大值;关闭恢复人工折扣、保留VIP账本。
|
||||
|
||||
普通插件源`plugins/VipLoyalty/`,码`vip_loyalty`;不加入`plugins-core`自动安装列表。原生安装默认`is_enabled=false`,业务配置默认`enabled=false`,两项都开才生效,不随主题或域名自动开启。
|
||||
|
||||
仅在`fuc-migration-test`(私有迁移测试,无Web)和`fuc-acceptance`(`http://xb.loc`,合成数据)安装开启。DPL/HN未安装/开启,未读写它们的业务库。`scripts/vip-loyalty/local-setup.php`只接受这两个实例及本地标记;安装前SQLite备份在各自`storage/app/vip-before-install/`。真实迁移数据不挂到`xb.loc`。
|
||||
|
||||
## 独立数据及原生接入
|
||||
|
||||
插件安装目标库才创建`fuc_vip_accounts`(期初/累计/人工及生效折扣)与`fuc_vip_entries`(唯一键消费/冲回账本)。不改`v2_user`或`v2_order`结构,沿用原生`v2_user.discount`结算;不导旧订单进入原生折抵/返佣池。
|
||||
|
||||
`order.create.before`同步用户折扣;`order.open.before`在XB开通事务内累计,和套餐一起提交/回滚。锁顺序为订单→用户→VIP账户,`purchase:{order_id}`唯一键阻止重试重复累计;并发用户累计由用户行锁串行处理。原钩子及开通顺序不变。
|
||||
|
||||
后台继续使用XB插件编辑器。插件自己的服务提供者仅为本插件保存增加校验,其他插件调用原实现。门槛递增、优惠不倒退、金额最多两位小数、优惠0至100%;启用状态的损坏配置会明确阻止创建/开通,避免静默漏记,管理员修复后可重试。关闭状态不激活VIP。修改规则后下次访问VIP信息或下单重新计算。
|
||||
|
||||
## 接口与命令
|
||||
|
||||
- `GET /api/v1/user/vip`:原生用户认证;返回等级、实际优惠、累计、下一等级及差额。
|
||||
- `GET/POST /api/v2/{后台安全路径}/vip`:原生管理员认证,校验保存设置,匿名/普通用户拒绝。
|
||||
- `vip:import-opening FILE --reference=快照SHA256`:私有JSONL每行含整数`user_id`、`uuid`、非负整数`opening_cumulative_cents`。按UUID确认身份,同摘要/金额重复执行不变;禁止覆盖不同期初或在新消费后补期初;整批事务。不动钱包/套餐。
|
||||
- `vip:reverse-consumption ORDER_ID AMOUNT_CENTS REFERENCE`:只登记**实际退款完成后**的VIP消费冲回,不能超过该单尚未冲回本金;同凭证重复执行不再扣。它不退款、不动钱包。XB没有已完成订单退款的统一钩子,不伪造自动退款功能。
|
||||
|
||||
## 主题与本地验证
|
||||
|
||||
Fuc 0.12.0沿用原VIP卡片/等级名称,显示累计和升级差额;购买页显示优惠生效时序。关闭/未安装插件时回退。原19份CSS、26模板、Pace及依赖字节检查通过,未改原动画。
|
||||
|
||||
| 验证 | 结果 |
|
||||
| --- | --- |
|
||||
| VIP专项 | 18项/58断言:默认关闭、实付累计、下一单升级、重复开通、回滚、人工折扣/开关、期初/冲回幂等、配置及权限 |
|
||||
| 原生订单/礼品卡 | 无VIP安装的内存库4项/13断言 |
|
||||
| 主题 | 42项Node测试,含VIP原卡片与关闭回退 |
|
||||
| 迁移用户 | 11,542人期初接入;39项原生回归再次通过,临时交易全部回滚 |
|
||||
| 双进程 | 私有副本同时开同一单,仅1条消费、累计100元、8%优惠,不写迁移原库 |
|
||||
| 真HTTP内核 | 12项:期初100→原价300实付276→累计376→下一单255;重复支付不累计、取消返还/冲回及最终回滚 |
|
||||
| 浏览器 | 用户原右侧IAB标签显示等级/累计/差额通过;截图在忽略产物中。后台设置保存/权限用原生API验证,未切换浏览器账户验收后台页面 |
|
||||
|
||||
证据在忽略目录`codex/output/fuc-migration-20261103/`:`vip-unit-tests.log`、`vip-native-regression-tests.log`、`vip-theme-tests.log`、`vip-concurrency-results.json`、`vip-http-flow-results.json`、`rehearsal-verify-results.json`、`vip-dashboard.png`。私有源快照、身份、期初及副本维持700目录/600文件,不提交Git。
|
||||
|
||||
主题包`codex/output/fuc-theme/Fuc-0.12.0.zip`:643文件、7,600,972字节,SHA256 `120c0a358110042b22f992d2673fbfe8e67f1bd62c1930fef7b690cf31968011`,CRC/源码字节通过。包只含主题,VIP插件单独安装,不能只换主题就宣称VIP启用。
|
||||
|
||||
## 恢复与边界
|
||||
|
||||
关闭业务开关或禁用插件恢复人工优惠并保留累计。原生卸载会删除插件表,不能用卸载代替保留账本的关闭。安装前备份仅在本地且无后续新业务时适合整库恢复;已有新业务时先保留新账本、按变更恢复,不能直接覆盖。
|
||||
|
||||
保持有感迁移:重新登录并导入新站订阅,不新增旧URL兼容。营业套餐、真实支付/邮件/节点外部接入按用户要求后置。本轮无线上操作、真实付款或生产发布;本地VIP完成不代表整个新站已营业。
|
||||
@@ -0,0 +1,56 @@
|
||||
# FUC → FUC-XB 正式切换与回退
|
||||
|
||||
2026-11-05。隔离导入提交、独立回读、入口与节点切换和回退均通过。用户已授权在各项准备通过后立即切换,并开放注册、支付宝和微信进入正式运营。
|
||||
|
||||
## 时间窗口
|
||||
|
||||
用户确认预留 **60 分钟**,窗口内正式站进入临时维护并完全停服。顺利时预计完整维护 **20–35 分钟**,覆盖前台、后台、业务 API、交易、订阅及旧节点服务。旧订阅用户需要手动导入新订阅,个人恢复时间另算。这些是准备完毕后的规划值。
|
||||
|
||||
11,549 个源账号在一次性 MariaDB 库正式式提交用时 63.05 秒,独立进程读回用时 1.11 秒。正式快照、旧付款核对、节点同步和放行验证各需额外时间。窗口第 35 分钟仍达不到放行条件时启动回退。新站未接收业务写入时,预留 **5–10 分钟**恢复旧站并核验。晚到付款归属不清时取消当次切换,恢复旧站后继续查账。
|
||||
|
||||
## 切换前准备
|
||||
|
||||
1. 就绪后立即开始 60 分钟窗口。放行时开放注册、支付宝和微信。真实扣款演练按已确认范围跳过,开支付前仍须验证两代回调的路由归属、签名校验及维护期间的重试和对账路径。
|
||||
2. 锁定正式域名 `福云123.com`(`xn--123-9i9dj97q.com`)及 www 的切换范围。两套应用均在 site-jp01,优先在原机切换 Nginx 上游。另核对旧站别名、支付通知与旧节点入口,所有可写旧库的入口均纳入冻结。教程域名沿独立路由。正式入口使用正式 `APP_URL`、订阅域名及回调域名。若测试别名仍与正式入口共用目标库,正式放行前关闭测试别名的业务访问。
|
||||
3. 生成恢复包。保存现网及候选配置、旧站 Cron 与进程状态、受影响节点入口及权限组、源库一致性备份、目标库备份和校验值。私有包留在已登记服务器。现场读回旧站 `/www/wwwroot/fuuuu.cloud` 的提交 `fea0d886f77a19a7b174836262917f7a735b2a5f`、旧 FPM `/run/php/php-fpm.sock`。XB 测试站当前主题提交为 `29752628df2ded838082215ce8d4e1598887683b`,FPM 使用 `/run/php/php8.4-fuc-xb-test.sock`。窗口开始前再比对 HEAD、虚拟主机摘要和证书。发现变化时先核实,再生成恢复包。
|
||||
4. 正式导入命令为 `python3 /var/www/wwwroot/fuc-xb-test/current/scripts/fuc-xb-launch/run-final-import.py <窗口目录名>`。计划将同机 `fuc_xb_test` 升格为正式库,以保持机器账号和商户配置的位置。正式入口放行前须切断旧测试别名对业务页面和 API 的访问,仅保留已经验收的机器接口。隔离 Nginx 实际从旧站夹具切到 XB 应用并切回,验证了维护门禁和回调分路。正式域名证书、XB 资源与模拟回调此前已在回环监听通过。
|
||||
5. 22 条已测 Xboard-Node 线路可用于放行。用户确认 FUC 节点不设固定最低内存门槛。HK02 纳入候选,需单独核实启动、连通、流量入账及稳定性。已逐台确认 23 台登记主机当前 XrayR 进程只接旧 FUC,均监听 443。旧日本 13/14 为父节点 156 的两条已关闭影子条目。父节点心跳已停约 15 天,但原订阅指向的 `151.242.165.111:443` 仍能建立 TCP 连接,且在现有资产和中转记录未找到对应控制入口。仍须证明该旧线路停止承接存量连接,或查明控制入口并纳入停服。
|
||||
6. 两代回调按路径分路。历史旧单使用正式域名的 `/payment/notify/epay`,XB 新单使用 `/api/v1/guest/payment/notify/EPay/<支付通道 UUID>`。启用前须将两条 XB 通道当前测试回调域名改为正式域名,并回读生效配置。旧站停写后不得把旧路径转给 XB,也不得把旧通知转回能写旧库的应用。按空中支付官方查询接口和两代本地账本核对。支付平台确认终止前,仍可支付或归属不清的旧单阻止开始维护窗口。
|
||||
|
||||
以上步骤全部通过后才开始计时。
|
||||
|
||||
## 窗口内操作
|
||||
|
||||
| 时间 | 操作 | 继续条件 |
|
||||
| --- | --- | --- |
|
||||
| 0–5 分钟 | 正式站入口及旧别名进入临时维护,前台、后台、订阅和业务 API 停止服务,旧节点停止接入并断开旧会话,旧 FUC 的续订及业务调度停止。收尾已在途的旧节点计量和后台事务后锁住旧库业务写入。支付通知进入维护处理流程,暂缓确认并保留商户重试与对账依据。 | 外部只看到维护状态,旧节点拒绝连接,旧库写入停止,最后一批流量和已在途任务有可核对的结果。 |
|
||||
| 5–12 分钟 | 按旧站订单、账单和商户侧只读记录核对在途付款与最终流量,记录交易和流量检查点。 | 旧订单没有归属不明的在途款,最后流量已确认,冻结后两次关键摘要一致。若出现需要恢复旧库写入才能处理的晚到付款,回退当次切换。 |
|
||||
| 12–23 分钟 | 确认旧站停写后先做一份完整旧库备份,验证成功后再取迁移快照。将新投影及旧站全部公告导入已锁定的 XB 实例,逐户核对流量、有效期、分组、钱包和 VIP,核对提前续订返还的订单与金额,旧账另存只读。 | 旧库完整备份和校验通过。用户、权益、钱包、VIP、退款及公告回读通过。未知套餐、账号冲突或核对差异须先解决。 |
|
||||
| 23–30 分钟 | 按计划切换节点权限与正式域名上游。保留公众写入门禁,在服务器侧用合成验收账号检查登录、套餐、正式订阅 URL、原生 V2 拉取、连通、记账和无权账号拒绝。确认测试入口、管理入口、两代支付回调各自路由准确。 | 配置检查、TLS、登录、订阅和代表节点验证全通过。旧入口的业务写入仍关闭。 |
|
||||
| 30–35 分钟 | 放行新站。按已批准范围启用注册、钱包与支付,发布新订阅导入指引。核对第一批业务事件、节点流量、队列、错误率和旧付款回调。 | 记录新站放行时刻和首笔业务事件,保留旧站恢复包。 |
|
||||
|
||||
切入口前先验证候选配置的完整 Nginx 配置树,再将候选文件写入同目录的临时文件,通过原子重命名替换正式域名对应的 `/etc/nginx/conf.d/fuc-20261024.conf`。重新执行 `nginx -t`,通过后用 `systemctl reload nginx` 平滑加载。校验或加载失败时立刻恢复与恢复包摘要一致的配置并重新检查。切换验证在服务器侧执行,公众访问走正式域名现有解析。
|
||||
|
||||
### 旧库全量备份和公告
|
||||
|
||||
- 确认所有旧写入口停止、节点最后一批流量入账、已在途付款对清后,在站点宿主创建 root 专用的 `private/cutover-YYYYMMDDTHHMMSSZ` 目录。保存权限为 0600 的 `freeze-verified.json`,包含 `verified_utc`(UTC ISO 8601)、源库名 SHA-256 `database_sha256` 及四项实测结论 `old_ingress_maintenance`、`old_business_writers_stopped`、`old_nodes_drained`、`payments_drained`。在同目录保存 `target-verified.json`,字段为 `database`、已部署完整 Git 提交 `release` 及两项已验证布尔值 `public_writes_blocked`、`writers_stopped`。两份证明须由现场检查生成。正式导入命令依次完成备份、备份恢复和投影、事务提交、独立回读。
|
||||
- 现场旧库含 InnoDB 和 MyISAM。用 MariaDB 单库锁表全量导出,包含表结构、数据、触发器、例程和事件定义。旧库备份单独保留在原宿主非公开目录,包含 gzip CRC、完成标记、备份 SHA-256 和表清单校验。任何失败都阻止导入。需要恢复时,先在隔离库回读备份,恢复期间禁用业务入口并核对事件调度,按受影响范围决定数据恢复。
|
||||
- 公告读取最终冻结源库。原公告 ID、标题、正文、时间、显示状态和相对排序迁至 XB 原生公告,原等级及置顶标记保存为标签。旧库完整备份保留原始字段。旧公告导入使用目标事务,遇到目标公告冲突即停止,独立回读验证条数、可见数和内容摘要。用户公告页读取原生 API 的全部分页。迁移不触发公告群发。
|
||||
|
||||
## 回退
|
||||
|
||||
**放行前,或确认 XB 没有新的真实业务写入时**,先保持两边的业务门禁。关闭本次放行的独立 XB 节点监听并确认已有会话已断开,再恢复节点权限和正式入口。原子恢复旧 Nginx 配置并通过 `nginx -t` 后平滑加载,恢复旧节点入口及流量上报,核对旧站登录、旧订阅、节点连通和账务检查点。确认旧站可以接单后再恢复交易入口和原 FUC Cron,旧回调继续走旧站。目标 XB 数据先保留取证,需要恢复测试环境时只恢复目标库备份。验证旧站恢复后通知用户。
|
||||
|
||||
**放行后若已有真实写入**,先冻结 XB 新交易及两边的相关入口,保留两套账本和回调,导出切换点之后的新付款、钱包变动、退款、VIP、权益、注册、订阅凭据与流量增量。按商户订单号和用户逐笔核对,保证每笔资金只入账一次。先决定修复 XB 继续营业,或批准把核对后的增量补回旧站,再开放对应入口。此阶段耗时由实际写入量决定,不能承诺 5–10 分钟。
|
||||
|
||||
立即停止放行的条件包括快照与账目对不上、回调归属未确认、正式订阅错误、节点权限串组、关键登录或节点连接持续失败。恢复时以冻结点及首笔真实写入标记判断采用哪条路径。
|
||||
|
||||
## 已核实证据
|
||||
|
||||
- 当前 Nginx active,旧站与 XB FPM 套接字存在,正式域名证书至少还有七天有效期,root 下有一条旧 FUC 的活跃 Cron 匹配记录。当前虚拟主机摘要与上次回环验证前一致。
|
||||
- 11,549 个源账号及 1 个合成账号的回滚演练通过,283 个旧权益映射到四个隐藏套餐,14 笔提前续订退款合计 ¥3,384.47。四档重置包的合成钱包支付通过。见[测试站验收](FUC_XB_STAGING.md)。
|
||||
- 22 条节点的真实连通、记账和三类撤权通过。正式回环 TLS 和模拟回调通过。旧付款检查点来自 11 月 5 日演练快照,正式窗口须重新取数。
|
||||
- 私有切回演练使用同版本 Xboard-Node、XB 原生 V2 和 AnyTLS,旧侧使用合成网页、回调及 VMess 节点。验收了旧链路连接、旧入口冻结、XB 入口切换、普通组生效及特殊组拒绝、实际流量入账、关新监听断已有会话、旧配置摘要恢复及旧链路重连。现场两个公网配置及测试环境文件摘要一致,临时进程、数据库、凭据和上传二进制均清理。回执在 `codex/output/fuc-xb-launch-ready-20261105/private/` 的 `cutover-import-drill-*.stdout` 与 `cutover-entry-node-drill-*.stdout`。
|
||||
- 补充演练已验证 InnoDB、MyISAM、触发器、例程及禁用事件可以从脚本生成的备份恢复。旧 FUC 当次只读盘点共 47 张表,其中 3 张为 MyISAM。真实 18 条公告全部导入一次性库,独立读回、可见性、排序与重复保护通过。主题四页 18 条的回归通过,Fuc 0.12.10(`5a55fae630d8a59bbe7604190b228cfbc1ad1154`)已由私有 Git 发布到隔离测试站,服务器侧已核实部署。正式备份待停写后创建,正式公告待切换窗口导入。
|
||||
- 重新核实旧账后发现未付款记录的 `paylist.datetime` 为 0,必须按账单创建时间和商户单号核对。使用空中支付官方只读接口验证已支付对照单,并查询 32 条旧付款尝试,2 条在商户侧仍未支付,其余返回查询失败码。两条待付记录仍需关单或查明有效期,随后检查晚到回调。HK02 当前运行旧 XrayR,24445 端口空闲,已有 Python 3.5,未安装 Xboard-Node。
|
||||
- 新导入流程在同机一次性库演练了备份恢复和投影,提交 11,549 个用户、14 笔预购退款和 18 条公告,清除测试会话。独立回读通过,同快照重复执行无写入。演练提交 63.64 秒、回读 1.30 秒,演练库已删除。
|
||||
@@ -0,0 +1,102 @@
|
||||
# FUC-XB 外部联调验收(2026-11-04)
|
||||
|
||||
**本页保留11月4日旧XrayR诊断;当前已按用户要求更换验收对象为Xboard-Node原生V2,11月5日重迁11548用户并通过三类撤权实测,见[最新验收](FUC_XB_V2_REACCEPTANCE.md)。不再修旧XrayR,不将其缺陷作为新站阻塞,未切正式站。** 同一已有订单只改变Accept请求头,两渠道均404→200→404,正常页面的1元金额/支付URI/二维码证据通过。节点为XrayR0.9.4拒绝空名单并保留旧授权,详见下方最新诊断。旧404记录保留为历史失败证据,不再作为当前支付商故障结论。
|
||||
|
||||
## 授权、环境与代码范围
|
||||
|
||||
用户要求继续真实邮件、节点、客户端联网验收,随后明确规避真实支付、尽量扩大不扣款验证;收件人指定mukaitao,并要求由AI自行查看收件箱。只验收独立测试站,不切旧FUC、不发布DPL/HN。
|
||||
|
||||
- 应用仍为`28ccc0e964a9ff9ee917a15f99c6f0140174e7cf` / Fuc0.12.4,后台子模块仍`ef5f43da335092cbff8fdf0ad7ff9b4d92d7d0d7`。
|
||||
- 本轮只增加`scripts/fuc-xb-acceptance/`专属工具与维护说明;工具独立Git分支`codex/fuc-xb-external-acceptance-20261104`,经白色机推送、按精确版本检出,应用current没有切换。
|
||||
- 唯一保留的运行配置变更:**测试实例自己的原生singbox订阅模板**升级为仓库已有现代模板,不改共用默认模板、XB核心/API/业务逻辑、数据库结构或管理员。
|
||||
- 注册、常驻邮件、真实支付渠道、节点、worker/cron最终均保持未启用;本次临时连接能力不等于正式营业配置已完成。
|
||||
|
||||
## 分项结果
|
||||
|
||||
| 项目 | 结论 | 已验证范围 |
|
||||
| --- | --- | --- |
|
||||
| 验证码邮件 | 通过 | XB真实HTTP内核→原生SendEmailJob/Dispatcher→Resend→指定Proton收件箱 |
|
||||
| 通知邮件 | 通过 | 原生MailService→既有企业SMTP→同一收件箱 |
|
||||
| 邮件认证 | 通过 | 两封均由fu@gemcook.net发出,IAB实读正文正常,SPF/DKIM/DMARC均通过 |
|
||||
| 支付本地业务链路 | 通过 | 真实MySQL/原生HTTP内核37项受控验证,全事务回滚;实际扣款0 |
|
||||
| 真实支付商未付款创建 | 部分通过 | 原商户/密钥只读匹配;旧FUC实际mapi协议两渠道均code=1并返回payurl |
|
||||
| 最终收银台 | 通过不付款收银证据检查 | 原404由工具缺Accept:text/html导致;同一已有订单对照两渠道404→200→404,正常页面1元/支付URI/二维码及错误金额拒绝通过;不等于实付到账 |
|
||||
| 原生订阅与客户端 | 通过 | sing-box1.14.3实际导入完整原生订阅,仅替换本地inbound;严格TLS1.3;VMess/WS/TLS联网 |
|
||||
| 上下行与记账 | 通过 | 真实出口193.111.31.52;65536字节下载、30720字节上传回显;XB用户/节点均累计u=78676、d=349204 |
|
||||
| 无效订阅/禁用后订阅 | 通过 | 无效token403;禁用合成QA后其原订阅403、原生节点下发用户为0 |
|
||||
| **已保存配置撤权** | **未通过** | 节点收到用户数1→0后仍存活且TLS正常,旧VMess配置重启客户端后仍可新建连接至原出口 |
|
||||
| 清理与迁移数据保护 | 通过 | 临时节点/API桥/客户端停止,QA组/用户/节点及流量夹具删除、队列排空、原令牌/配置恢复;11542人全字段与VIP期初复核无意外差异 |
|
||||
|
||||
### 邮件实收边界
|
||||
|
||||
仅向`[email protected]`发送两封本次验证码/通知,不向迁移用户发送。IAB复用已登录的正确邮箱,仅打开这两封信;验证码没有复制进日志、截图或文档。通知截图为`codex/output/fuc-xb-live-acceptance-20261104/mail-notification-inbox.jpg`。
|
||||
|
||||
既有旧FUC邮件配置在同宿主只读取得,密钥只交给认证组件,没有复制到本机或提交。验收在独立PHP进程、MySQL事务、进程内缓存与同步任务连接执行,验证同消息键不重发,结束回滚临时配置/日志并清除验证码。**没有验证常驻邮件队列生命周期、入站邮件、自动回复或Resend控制台登录**;邮件实收不能替代这些未执行项。
|
||||
|
||||
### 支付结果与定位
|
||||
|
||||
原生37项覆盖订单创建、收银台访问本身不自动开通、未付款取消、钱包混合支付本金与手续费分离、签名/商户/渠道/状态/金额/精度校验、非法payload拒绝、受控正确回调同步开通、重复回调幂等、冲突交易号、取消后迟到回调拒绝,以及VIP只累计套餐本金、下一单折扣。受控签名通知是测试进程主动构造,**不是支付商真实成功回调或结算**。
|
||||
|
||||
XB原生EPay走submit.php;旧FUC普通用户实际走mapi.php(只读核实生产源码,未调用旧站购买接口)。两者当前均进入pay.airspay.top中间页,再自动POST到其明确给出的下游。首次submit两渠道404,补正常Origin/Referer后仍404;mapi返回code=1、有payurl,但GET该地址仍是自动提交中间页,继续后两渠道同样404、响应摘要相同。mapi对照最初误用中间页转换后的上游商户号而报签名失败,按原商户重新签名后两渠道code=1;这不是XB原生签名测试失败。由此不能认定改用mapi就能解决,也不能认定旧FUC当前可正常收款;没有真实扣款验证这个结论。
|
||||
|
||||
**历史判断,已被下方同单对照推翻:当时认为需先修复支付商上游。** 未改商户设置、未猜新地址、未改XB支付插件,没有自动重试扣款、退款或扫描付款码。所有请求只用合成隔离单号和1元未付款金额;签名地址/响应留服务器private,未提交Git。中间页HTTP200仅表示第一跳可达,旧回执的`real_cashier_access_passed`字段不作为最终通过依据,新工具已更名为`gateway_entry_reachable`。
|
||||
|
||||
首次工具Payment.uuid错误使用36字符,原生字段只有8字符,数据库拒绝并回滚,尚未访问网关;已按原生Helper修正。该错误导致私有测试应用日志出现本次商户密钥,已对精确匹配字节等长遮盖,验证仅1文件2处改变,inode/权限不变;删除本工具遗留临时文件,旧站日志和PHP安全限制均未改。没有轮换业务密钥或清空日志。
|
||||
|
||||
### 单节点、客户端与撤权风险
|
||||
|
||||
只在VPS016新增独立短时进程/端口25443、受限环回API桥28766和专属QA组,未接入旧FUC全部节点。仅一个合成用户、100MiB/1小时/1设备限制;原XrayR配置、二进制摘要和原进程PID107692前后均保持。
|
||||
|
||||
使用之前已验真的官方sing-box1.14.3 Linux amd64,SHA256为`768d31fa7f68debc067bb4626539498a1e8751d36a7b99e1a54bee6a23815f93`。第一次原生完整配置导入发现旧DNS格式已被该客户端删除,采用现有仓库模板修正**本实例配置**后通过完整check和实际联网。没有降低TLS验证,证书主机仍jp02.gembox-dns.com。下载官方二进制时工具64MiB上限不足,扩大单文件读取上限后SHA相符;上传回显第一次缺Content-Type,修正验收请求后30720字节回显通过,均不是XB核心修复。
|
||||
|
||||
临时模板原值备份:服务器private/live-acceptance-20261104/singbox-template-before.json。新模板来自运行版本中已有的`scripts/node-onboarding/sing-box-template.json`,SHA256=`32168fd207632602d4f99f6c66c4d2c3e2399dc0ec3726d9e5b0be1564db3d81`;回退只恢复该实例原订阅模板并清除设置缓存,不回灌业务数据。
|
||||
|
||||
**撤权失败有独立正反证据**:禁用后原生可下发用户0、订阅403,节点API确实返回200且用户数由1变0;节点仍监听,前后严格TLS1.3握手成功。两次停止后重新启动已保存完整配置,第二次记录curl退出0、回包22字节、出口仍为193.111.31.52,排除了“节点已经停止所以连不上”的假通过。最新已定位XrayR0.9.4的空名单拒绝分支,见下方;未修改共用XB逻辑或重启原节点。临时节点已停止,泄留QA授权不再有可用监听。
|
||||
|
||||
这里验证的是**一个VMess/WS/TLS节点和Linux sing-box客户端**。Clash仅验证原生格式包含准确QA节点;未覆盖全部旧节点/协议、各手机桌面客户端或Mac系统TUN,不据此宣称全量客户端通过。
|
||||
|
||||
## 清理、数据与服务保护
|
||||
|
||||
先停止临时节点/API桥,按实际监听表确认25443/28766关闭并移除复制的门禁Cookie/节点API密钥;随后只排空traffic_fetch/stat两队列,再按日志中的精确用户/节点/组清理,恢复原server_token及push/pull配置。普通bind受到TIME_WAIT影响曾误判端口仍占用,已按ss监听确认,工具已修正,不重启原服务或放宽端口。
|
||||
|
||||
最终独立测试库节点0、支付配置0、订单0、会话0、非期初VIP流水0,无常驻测试worker/cron;仍仅原永久合成QA/测试套餐保留。全量11542旧用户、166历史套餐、3组及11542份VIP期初回读,意外字段差异0,钱包365087分、佣金1632分不变。测试Redis6388、库权限隔离、debug关闭、注册关闭及六个服务active复核通过。旧FUC HEAD/vhost/FPM/cron摘要不变,服务器侧旧站HTTPS200/TLS验证通过;没有做旧正式站页面验收。
|
||||
|
||||
## 证据入口与下一步
|
||||
|
||||
脱敏回执在`codex/output/fuc-xb-staging-20261104/private/`,原始带签名响应/客户端配置只在服务器private;本机收件实读和工具版本记录在`codex/output/fuc-xb-live-acceptance-20261104/`,均不提交原始用户数据或秘密。
|
||||
|
||||
- 邮件:live-mail-run1.json,以及live目录mail-inbox-receipt.json。
|
||||
- 支付:live目录payment-result.json(37项);live-cashier-browser-headers1、live-mapi-merchant1、live-mapi-processor1.json。
|
||||
- 联网/记账:live-client-run2、live-node-accounting1.json。
|
||||
- 撤权失败:live-node-revoke-diagnose1.json;其进程非零为真实未通过,不忽略错误冒充成功。
|
||||
- 清理:live目录private/node-stop.json、live-node-cleanup1.json。
|
||||
- 全量保护:external-final-data1、external-final-safety1、external-old-source1.json。
|
||||
- 日志精确脱敏:live-payment-log-redaction3.json。
|
||||
|
||||
下一步只处理节点端空名单撤权并重跑保存配置拒绝测试;支付404误判已通过同单对照消除,无需为此修改XB支付插件;涉及XB核心的具体方案须先按[AI工作规则](AI_WORK_RULES.md)获批。后续正式营业仍另行确认新快照/冻结增量、正式商品/支付/邮件/全量节点配置和切换,不以本轮测试副本直接替代旧站。
|
||||
|
||||
## 最新诊断:支付误判与XrayR最后用户撤权(2026-11-04)
|
||||
|
||||
用户要求继续查清两项原因。诊断期间未新建支付单、未付款、未启用测试节点或改XB核心;原QA节点/API桥保持inactive,原XrayR PID107692及二进制摘要不变。
|
||||
|
||||
### 支付:验收脚本漏HTML Accept,已纠正
|
||||
|
||||
既有[支付监测专题](PAYMENT_HEALTH.md#2026-11-01-fuc与hn微信对照两处检测误判已定位)早已记录同类问题;上一轮专属验收脚本没有复用该请求头,错误地把工具结果报告成支付商故障。本轮复用原两笔1元未付款签名表单,同一服务器/目标/方法/正文/User-Agent,只切换Accept:text/html:支付宝和微信都是无Accept=404、有Accept=200正常扫码收银页、再去掉=404。对200正文离线调用运行版本QrEvidence,两渠道均1元金额/支付URI/二维码渲染证据true,错误金额2元均拒绝,无已知过期/参数变化等业务错误;不访问二维码URI。
|
||||
|
||||
因此当前证据支持**不付款收银台生成通过**,不能继续声称支付商坏了或要求改XB插件。实际扣款、真实成功回调、资金到账仍按用户要求跳过。没有验证浏览器扫码/付款交互。只修专属cashier.py/cashier-api.py的HTML Accept,补回归防止假404和过期200误判;本地5项工具检查通过,其中新增2项支付回归。XB现有HttpsTransport已含HTML Accept,原生浏览器跳转也不需本次核心改造。
|
||||
|
||||
证据:codex/output/fuc-xb-staging-20261104/private/investigation-payment-accept1.json、investigation-payment-ab1.json、investigation-payment-qr1.json。原始签名表单/收银HTML仍只在服务器private,不输出二维码、签名或密钥。
|
||||
|
||||
### 节点:旧XrayR0.9.4拒绝空名单,根因已确定,修复未实施
|
||||
|
||||
现场二进制version为XrayR0.9.4,SHA仍31c3beef7afb1a167dc631d16cec881ea6d3049cb0718dd8157e51da14b5296d。读取本次QA节点journal命中一次`users is null`,总删除用户计数为0,初始添加1人;与前轮XB下发人数1→0、订阅403但旧配置仍新建连接的证据一致。
|
||||
|
||||
官方同版本[newV2board/v2board.go](https://github.com/XrayR-project/XrayR/blob/v0.9.4/api/newV2board/v2board.go#L192-L246)的GetUserList先更新ETag,再解析users;人数0直接报users is null。[controller.go](https://github.com/XrayR-project/XrayR/blob/v0.9.4/service/controller/controller.go#L193-L292)遇此错误直接返回,跳过比较与删除,保留旧userList。后续空名单ETag相同,304又使控制器复用旧列表,因此不是多等一个拉取周期就能解决。
|
||||
|
||||
**影响边界是使用该逻辑的节点名单变空,典型为删掉/禁用/过期最后一名有效用户;不据此声称删任意非最后用户都失败。** XB已经正确筛除该用户,修改XB禁用逻辑、给空列表塞假用户或定时重启整机都不是本问题的合适处理。
|
||||
|
||||
后续方案:在FUC-XB独立QA进程验证可正确处理空名单的节点程序,或在节点端修正空名单语义及成功解析后再确认ETag;保持正常接口失败时旧名单保护,不把网络失败当空名单。需覆盖2→1、1→0、304、失败恢复、旧保存配置新连接拒绝和原服务保护,再考虑正式节点。**本轮只定位,未替换或修补节点二进制,没有改旧FUC/DPL/HN服务。**
|
||||
|
||||
现场证据:codex/output/fuc-xb-investigation-20261104/private/node-readonly.json。源码与日志已定位根因;新增的无外网namespace假面板2→1→0实验因自动审批服务额度不足未执行,不声称该额外实验通过。自动审批未判定操作不安全,命令没有执行。
|
||||
|
||||
以上为11月4日当时状态。11月5日已按新授权完成工具Git发布与GemDocs更正,并用Xboard-Node原生V2重新迁移/验收;当前结果以[最新验收](FUC_XB_V2_REACCEPTANCE.md)为准。
|
||||
@@ -0,0 +1,102 @@
|
||||
# FUC 与 FUC-XB 功能差异及沿用XB规则方案
|
||||
|
||||
2026-11-03;状态:**功能分析已完成;随后用户明确授权本地迁移测试,已完成独立库试导及37项XB检查,未修改共享核心或上线。** 实际试导、测试钱包入账及仍未实现的VIP/订阅范围见[本地迁移演练](FUC_MIGRATION_REHEARSAL.md);下文旧“未导入/未返还”记录指初始研究阶段。业务方向仍为尽量沿用XB原有逻辑,本地测试不授权生产操作。
|
||||
|
||||
来源:本地新版FUC当前源码及本轮生产快照;目标:当前XB共用后端与Fuc 0.11.0主题。下表比较代码能力,不把FUC存在功能入口当成生产全部已启用;生产配置只确认[迁移研究](FUC_MIGRATION_STUDY.md)列明的范围。
|
||||
|
||||
## 用户已明确的新边界(2026-11-03,本节覆盖下方旧建议)
|
||||
|
||||
后续执行:用户明确要求完成VIP自动升级、仅FUC本地开启、其他实例默认关闭、不动线上;已按范围完成独立插件及本地验证,当前实现唯一见[VIP模块](FUC_VIP.md)。下文“尚未实施”属于此前设计阶段,不代表当前VIP状态。
|
||||
|
||||
补充执行状态:用户明确要求剩余3个缺邮箱后缀账号统一加`@dove.com`;已完成私有映射、字段投影及本地测试库修正,严格格式/唯一性检查通过,邮箱待核查现为0人;源站不变。下文较早“3个异常邮箱待核查”记录由本决定替代。
|
||||
|
||||
1. **VIP新增范围**:本次指定的功能例外,共用XB提供VIP升级能力;按实例隔离,其他子项目默认关闭、FUC-XB开启,不随主题自动开启。默认满100/200/360元分别减8/12/15%,后台可调整。
|
||||
2. **累计原则**:购买套餐计消费,同一笔钱只计一次;充值、佣金转入本身不重复计。VIP之外沿用XB原交易规则,优惠券不改成FUC连乘算法。
|
||||
3. **VIP最新方案(期初已本地试算,自动升级未实施)**:用户已明确迁移前累计以旧`user.total_pay`字段为准,不根据账单重新计算或覆盖,955个差值只归档。预购返钱包后扣减累计、重算下一单折扣,新消费完成再累计;旧单价格不变、不补差。用户已明确“按0处理”,因此期初累计为`max(0, total_pay-本次预购返还)`,钱包仍全额入账。该规则已应用独立本地测试库的期初折扣及私有累计账本,全量回读和39项原生检查通过。示例400退300→累计100、下一单9.2折;再买原价300实付276→累计376、后续8.5折。永久保级/保留旧累计资金池草案废弃;此处业务边界已全部明确。
|
||||
4. **预购返钱包**:有效已付且未履约预购按完整已付款(原余额贡献+实际在线付款)转入新钱包,不按现售价或旧订单尾款核算;不再迁入自动激活队列。dove订单同样纳入,旧单只读归档、不作为新订单重放,不删除源账或重复返佣。
|
||||
5. **旧功能与历史**:不要原自动续订,不新增自动扣余额/锁价流程;旧账只读归档,新站显示新业务,旧单不参与XB折抵/返佣。原管理员新站邮箱由用户明确指定,已通过格式及重复检查,仅在私有身份映射/本地研究投影更新,不改旧站或运行库。
|
||||
6. **客户端与原权益(用户最新更正)**:改为有感迁移,用户在新站重新登录、获取并重新导入新订阅;不新增旧订阅URL兼容层,不再以无感接替为目标。已迁UUID/token不因这次决定自动轮换;钱包、返利、当前额度/u/d/到期保留。DPL/HN不合并,管理员后台保持XB。
|
||||
|
||||
最新范围:用户要求先列VIP累计与账单差值;新站套餐营业配置、真实支付/发信等接入后面再做,不作为当前执行任务。全量差值定义、数量及退款账号核对见[迁移研究的VIP全量核对](FUC_MIGRATION_STUDY.md#vip全量差值核对2026-11-03)。
|
||||
|
||||
其他业务边界已明确;VIP以本节最新讨论方案核对,不再沿用已被澄清的永久保级草案,也不据本次核对自动实施财务或核心变更。其他3个异常邮箱和额外28元旧状态记录先做技术核查,若确有身份资料或履约证据缺口,再就具体对象说明。原生收付款、退款金额及原VIP数据仍需按最终冻结快照逐单对账,不能把研究快照直接当成正式执行清单。
|
||||
|
||||
本次再次核对发现:3个有效pending退款账号中,1个旧total_pay小于拟返还完整金额,不能直接做total_pay减退款;需区分账单完整支付、旧VIP累计实际贡献和历史统计缺陷,先逐笔对账。返钱包金额仍以完整实付为准,VIP统计不得凭字段机械相减算负数。剩余3个异常邮箱在当前快照没有余额/返利及有效付费权益,保留身份/历史后核查,不猜真实收信地址。28元旧pending_activation虽已付,但快照不能证明未履约,因此不自动混入13笔退款。上述均为技术/数据核查,尚未修改任何运行数据。
|
||||
|
||||
参考快照:13笔有效pending完整已付额3,228.68元,其中原管理员11笔3,165.76元;另1笔pending_activation为28元,履约状态未定,不自动重复返还。规则摘要在忽略目录`codex/output/fuc-migration-20261103/confirmed-rules.json`,身份映射在私有目录。**尚未执行VIP核心开发、钱包返还、运行库导入、源站业务变更、节点切换或生产发布。**
|
||||
|
||||
## 功能对照
|
||||
|
||||
| 功能 | FUC实现 | 当前XB / FUC-XB实现 | 按用户方向建议 |
|
||||
| --- | --- | --- | --- |
|
||||
| 密码登录 | bcrypt,独立cookie/会话 | 同样可验证bcrypt,使用XB会话令牌 | 一次性搬哈希,用户重新登录;不复制会话/密钥,不重哈希旧哈希 |
|
||||
| 找回密码 | 邮件中的重置token链接 | 邮箱验证码重置 | 使用XB邮件/验证码流程,主题保留必要字段,不改认证核心 |
|
||||
| 二步验证 | GA/TOTP接口与字段 | 当前标准登录链无等价GA校验 | 当前快照启用0人;保留XB现状,不新增认证分支 |
|
||||
| 邮箱和管理员 | 旧账号可能不是规范邮箱,原管理员标记 | email:strict校验,XB独立管理权限 | 4个异常账号人工核对;管理员单独处理,不把旧权限自动批量赋予 |
|
||||
| 套餐数据结构 | 一个SKU对应固定时长与总流量,30/90/365天额度各自不同 | 一个plan有多个价格周期,plan流量额度固定 | 可用不同XB套餐记录表达不同额度;只配数据,不改plan/价格模型 |
|
||||
| 当前额度与到期 | 用户当前值独立于现售SKU | user也存额度、u/d、到期 | 逐用户保留旧值;126个不同于新SKU的账号不得重新开通覆盖。需要时用隐藏过渡套餐区分历史额度,不自动开放续售 |
|
||||
| 后续购买周期 | 按固定天数,含183/400天活动包 | 普通周期按日历月累加;一次性套餐不限时、用完止 | 旧到期时间原样迁;未来商品走XB月/季/年规则。183/400天作为历史权益处理,不新增自定义周期算法 |
|
||||
| 预购/提前续订 | 付款后排队,当前到期或耗尽才激活下一笔 | 付款完成即按新购/续费/换套餐开通,没有原FUC那种已付包队列 | 新订单采用XB;旧13笔另行逐笔确认处置,不批量激活、不直接累计时长/流量 |
|
||||
| 自动续订 | 用户开关、余额扣款、独立锁定续订报价 | 当前标准链无等价自动扣余额续订 | 不仿造自动扣款;切站前确认34人开关及相关承诺,说明未来转手动续费。尚未关闭任何人的原开关 |
|
||||
| 流量重置 | 当前有效新套餐总额,耗尽触发下一包;遗留auto_reset字段不能当成当前调度 | 可配月初、按月、从不重置、年初、按年等 | 历史总流量套餐可用XB原生“不重置”;未来按本站XB配置。不新增耗尽自动激活逻辑 |
|
||||
| 换套餐/折抵 | 不同SKU也可排队,按旧流程处理 | 区分新购/续费/升级,具备剩余折抵规则 | 新交易沿XB设置和算法;历史订单不直接塞入completed订单池,避免参与新折抵计算 |
|
||||
| 钱包/余额抵扣 | 元计价,充值/余额/网关混付独立账单 | 分计价,订单按XB流程抵扣余额 | Decimal一次性换单位、保持资产,不重放充值、开通或退款事件 |
|
||||
| 自选金额在线充值 | FUC有钱包充值购买流程 | 当前标准用户接口及Fuc主题未对接等价自选金额充值 | 采用XB直接买套餐、兑换码入账、佣金转钱包;不为复制充值页另造收款流程 |
|
||||
| 礼品卡 | 余额礼品卡及消费记录 | XB原生兑换码/礼品卡,可有多种奖励及限制 | 用XB自己的兑换/记录;旧已使用卡仅归档,未使用卡须单独核对,不能直接搬状态数字 |
|
||||
| 会员/VIP | 按累计消费升级,8/12/15%等级折扣 | 支持用户折扣字段,当前标准链无同等累计消费升等 | 原有94人的折扣与历史续订承诺先核对;若采用原生用户折扣,未来按XB算法,不补动态升等器 |
|
||||
| 会员+优惠码 | 折扣依次连乘 | 券与用户折扣按同一原价累计 | 未来沿XB规则并修正说明;不能宣称相同。例如100元、8%会员+10%券,FUC82.80元,XB82.00元 |
|
||||
| 返利/提现 | money_aff、旧返利账、旧申请流程与门槛 | commission_balance、原生转钱包、提现财务工单 | 保留金额和邀请关系;之后用XB审核/门槛/工单,不复制旧扣款与自动打款逻辑 |
|
||||
| 到期后的免费体验 | FUC具有降级/赠体验配置流程 | XB可配置新注册试用;没有同等到期自动降级流程 | 保留当前101个等级1账号的实际期限/流量,不能当新注册重新赠送;后续到期按XB原规则 |
|
||||
| 每日签到 | 可配置签到赠流量 | 当前标准XB无等价接口;Fuc签到已禁用 | 保持未开放,前台可说明/隐藏;不修改用户流量服务添加签到 |
|
||||
| 节点授权与计费 | node_class + node_group、旧面板接口 | XB权限组、节点API与计费链 | 映射权限组,保留UUID,使用XB节点对接;当前43个启用节点均VMess,但接口接替和联网未验收,不把搬用户当节点已迁 |
|
||||
| 订阅地址/格式 | /sub/token/subtype、旧api类型路由等 | 可配订阅路径,使用token及flag/types等协议选择 | 优先原生配置保留域名/主路径;旧后缀与客户端参数逐项对照。必要反代重写仅作为候选,不改订阅核心,也未部署 |
|
||||
| 历史订单/累计流量 | 旧订单、账单、钱包日志、transfer_total等 | XB独立订单/返佣/统计模型 | 旧账保留独立只读档案,当前u/d继续计费;不伪造新订单、返佣或把累计流量加回当前u/d |
|
||||
| 工单/公告/文档 | FUC独立表、路由和模板内容 | XB原生工单、公告、知识库;主题已接对应接口 | 新业务用XB;旧内容按需另做一次性转换/归档,本轮13表快照没有包含所有历史工单/正文 |
|
||||
| TG/通知/邮件 | 原站独立绑定/机器人/邮件配置 | XB原生绑定/通知/邮件流程 | 不复制旧机器人/全局密钥;本次联系值为空,不承诺旧会话/绑定无缝继承;真实投递需单独联调 |
|
||||
| 主题偏好 | 原版panel_option保存在用户资料 | 当前Fuc配色/亮暗/菜单偏好保存在浏览器 | 接受前端偏好范围;若需账号跨设备同步,另讨论,不加字段/API冒充无改动 |
|
||||
| 管理员后台 | FUC原后台 | XB自带后台 | 保持XB后台及权限体系,不复制FUC后台 |
|
||||
|
||||
## 再次确认:哪些可直接沿用XB
|
||||
|
||||
“可直接沿用”指复用当前XB原生业务,不代表FUC每个细节相同,也不代表所有外部链路已做生产验收。本轮进一步核对`app/Http/Routes/V1/UserRoute.php`、主题实际API调用及业务服务。
|
||||
|
||||
- **原生业务可直接使用**:正常邮箱账号登录/注册/找回与改密/登录设备;套餐查询、创建/支付/取消/查询订单、优惠码、余额抵扣、手动续费与换套餐/折抵;可配置流量重置;余额/佣金钱包、礼品卡、邀请返佣及提现财务工单;当前用量/到期显示;订阅查看/复制/导入和安全重置;节点列表、公告、知识库与FAQ、工单。以上采用XB自己的校验、计算和状态流程,保留其必要字段。FUC resetURL本身也同时更新UUID/节点密钥,XB resetSecurity同时更新UUID/token,不能误认为FUC仅改token。
|
||||
- **无需新增业务逻辑,但需一次性数据/配置和演练**:bcrypt、余额/返利元转分、邀请ID、当前额度/u/d/到期、UUID/token、各等级/权限组、旧套餐配置;固定用户折扣可按XB字段表达,但未来叠加/升等不等价。4个异常邮箱、126个历史额度与新SKU不同的账号单独处理。旧订阅完整URL/参数与43节点接替须配置、联调,不能只搬token就认定完成。
|
||||
- **当前XB无法原样承接的FUC规则**:已付预购排队及耗尽后自动激活、自动扣余额续订/锁价、FUC固定天数商品按原方式售卖续期、累计消费自动升VIP及原折扣连乘、自选金额在线充值、签到赠流量、GA二步验证、到期自动降级赠体验。旧订单/累计流量及账号跨设备主题偏好的原样展示也不是现有字段直接复制即可完成。这里只确认差异,未新增兼容逻辑。
|
||||
- **原生能力与真实验收分开**:支付渠道/回调、实际邮件与验证码、Telegram绑定、旧客户端订阅及节点联网/计费尚需专项联调;Telegram未列入本轮“完全确认可用”名单。当前用户路由只有getBotInfo,不能仅凭未挂路由的旧unbind方法认定解绑已接入或故障已触发。
|
||||
|
||||
## 此前推荐落地范围(VIP与预购处理以最新边界为准)
|
||||
|
||||
1. **数据与配置能做的**:迁移账号哈希、UUID/token、邀请关系、余额/返利及当前流量/到期;使用独立FUC-XB库和XB既有套餐/权限组/重置配置。导入只是后续候选方案,本轮没有编写运行库导入器或执行数据修改。
|
||||
2. **历史特殊权益先确认**:13笔预购中,同一个原管理员账号占11笔,另外2笔属于2个普通账号;11笔是否为测试单未知,不能自行排除。管理员测试单若获明确确认和处置授权可按批准范围处理;普通用户的已付权益需先定人工承接/补偿方案,不能擅自换余额或作废。另1笔旧pending_activation已付记录仍单列核查。
|
||||
3. **新交易统一采用XB原规则**:手动续费、日历月周期、本站重置设置、原生优惠叠加/折抵、返佣与提现工单。旧自动续订/固定天数活动/累计消费升等不在XB里复刻。切站前必须确认受影响权益和说明,不能默默取消原承诺。
|
||||
4. **保留无法等价承接的边界**:若必须原样自动执行FUC预购耗尽激活、自动扣余额及锁价,这不是单纯数据配置能解决的。在不改XB业务逻辑的要求下,应先暂缓切站或确定人工处置;不以外置脚本/插件自动扣款来规避用户“不动原有业务逻辑”的意图。
|
||||
5. **可以只在主题层修正文案**:本次发现Fuc套餐卡/确认弹窗仍用30/90/365天等固定展示值,而XB实际续期按日历月。后续应显示XB真实月/季/年周期,文案改动不改变计费算法。当前只列出问题,未修改主题。
|
||||
|
||||
## XB代码改动盘点与VIP后续范围(2026-11-03,只读核对)
|
||||
|
||||
**当前实际改动按任务区分:**
|
||||
|
||||
- FUC界面/动画/配色/API适配在独立`theme/Fuc/`及`scripts/theme-fuc/`,不是重写XB订单、支付或节点服务。
|
||||
- 本聊天此前单独获批的共享核心修复在`app/Services/Auth/LoginService.php`及其单元测试:找回密码成功时,同事务撤销该用户全部旧登录令牌。批准、测试、未上线及回退唯一记录在[业务约束](BUSINESS_RULES.md#找回密码撤销登录会话2026-11-01本地已批准修复)。主题ZIP不含后端修复。
|
||||
- 当前用户迁移/VIP研究阶段仅修改维护文档和忽略目录中的离线工具、私有身份投影;没有实现VIP、改业务配置或导入运行库。
|
||||
- 当前共享工作区还存在独立客服改动:`app/Http/Controllers/V2/Admin/CustomerServiceController.php`、`app/Services/CustomerService/Settings.php`、`app/Http/Routes/V2/AdminRoute.php`、`routes/web.php`及客服测试。代码用于客服设置、挂件注入与管理入口,不是本轮VIP或迁移引入。本轮只读识别,未修改/回退,不能以本轮说明代替其授权或验收。
|
||||
|
||||
**VIP后续最小范围建议,尚未实施:**
|
||||
|
||||
| 范围 | 内容 | 隔离要求 |
|
||||
| --- | --- | --- |
|
||||
| 独立VIP模块或插件 | 等级规则、有效累计、升级/重算、防重复计数 | 按实例开关,默认关闭;不以主题名自动启用 |
|
||||
| VIP数据存储 | 门槛/折扣配置、用户累计/等级及订单处理台账 | 独立数据和唯一业务键;具体表/字段在实现方案确定,不混入旧订单折抵/返佣池 |
|
||||
| XB现有接入点 | 核对已有`order.create.before`与`order.open.after`等插件扩展点,连接VIP折扣和完成消费累计 | 优先复用现有机制;仍需验证人工折扣、重试/并发、价格生效顺序及开关关闭行为,不提前承诺零核心文件改动 |
|
||||
| 后台配置 | VIP开关、等级门槛/折扣管理 | 延续XB后台样式与权限;其他实例原行为必须回归 |
|
||||
| Fuc主题展示 | 当前等级、有效累计、升级进度、实际折扣 | 只读VIP信息,价格以后端为准;先修正日历月文案 |
|
||||
| 一次性迁移工具 | 用户/权益映射、预购款入新钱包、VIP期初对账、旧账归档 | 不是新增运行时自动退款/续订流程;默认只读预演,执行另有清单与幂等核对 |
|
||||
|
||||
VIP属于用户本次明确要求的新增行为,开启后会影响对应用户等级/折扣;“可关闭”不等于没有业务改动。订单开通、支付金额、钱包扣款、优惠券叠加、折抵、返佣、流量周期及节点鉴权算法不为复刻FUC而重写。若核查现有扩展点确有缺口,再在具体方案中列出必要核心接入差异、影响与验证,不能把插件或外置脚本当作绕过核心边界的理由。当前只完成范围核对,未据此写入VIP核心代码或上线。
|
||||
|
||||
## 验证和事实边界
|
||||
|
||||
本轮核对了两边当前源码、真实私有快照、账单/成功网关记录与已完成离线守恒结果;没有调用注册、充值、支付、开通、返佣等运行API,没有修改业务配置,没有运行预购队列或自动续订任务,没有更改XB核心/主题运行代码,也没有重测/部署支付、节点或邮件链路。对比来源及证据可从[迁移研究](FUC_MIGRATION_STUDY.md)继续定位。
|
||||
|
||||
关键源码:FUC `src/Services/Cron.php`、`RenewalPricing.php`、`Payment.php`、`src/Models/VipMap.php`、`src/Controllers/PasswordController.php`、`UserController.php`、`src/Controllers/User/MoneyController.php`及`app/routes.php`;XB `app/Services/OrderService.php`、`PlanService.php`、`UserService.php`、`TrafficResetService.php`、`CouponService.php`、`app/Models/Plan.php`、`Order.php`、`Server.php`、`app/Http/Controllers/V1/User/TicketController.php`、`GiftCardController.php`、`app/Http/Requests/Passport/AuthLogin.php`及`routes/web.php`;Fuc展示层`theme/Fuc/assets/native.mjs`的days/pData及wallet/invite适配。
|
||||
@@ -0,0 +1,137 @@
|
||||
# FUC-XB 独立线上测试站
|
||||
|
||||
## 当前:2026-11-05新快照与原生V2已重验通过
|
||||
|
||||
按用户要求重新从旧FUC正式站只读取得11548用户,事务刷新本测试库,14笔预购返钱包338447分,钱包380666分、佣金1632分、VIP期初11548份全量核对通过。节点采用与DPL/HN相同Xboard-Node二进制和原生V2机器接口,单AnyTLS严格TLS/真实联网/记账、最后用户禁用/过期/流量耗尽后旧配置拒绝均通过;临时节点、机器、QA和复制凭据已清理。23项FPM、26项HTTPS、12项钱包/VIP交易回归及重复期初通过,旧站/DPL/HN未切换或发布。当前应用仍28ccc0e/Fuc0.12.4;下文11542人及旧XrayR记录属于历史。唯一新数据、授权、回退和验证边界见[原生V2重新验收](FUC_XB_V2_REACCEPTANCE.md)。
|
||||
|
||||
## 授权与当前状态(2026-11-04)
|
||||
|
||||
用户要求先建立独立线上测试站,验收后再单独决定正式切换。本次不切旧FUC,不发布DPL/HN。用户另外明确批准将本地已演练的11,542名旧FUC用户的邮箱、密码哈希、钱包、套餐权益和VIP期初上传至原FUC宿主的新私有目录并导入独立测试库;此前未明确具体敏感数据目的地的一次上传被自动审批拒绝,没有执行,取得精确批准后才上传。
|
||||
|
||||
**隔离测试范围的最终验收已完成:Fuc0.12.4(28ccc0e)已部署,服务器、迁移数据、真实内置浏览器页面/交互及XB原版后台通过。当前入口`https://fuc-xb-test.tomtojapan.online/stage-login`,使用原测试入口账号密码。未切正式站。随后按用户追加要求完成外部联调:邮件实收及单VMess原生订阅/联网/记账通过,支付404随后查明为专属验收脚本漏HTML Accept的误判,同单对照正常收银证据通过;节点则定位旧XrayR0.9.4拒绝空名单,修复尚未实施,不具备正式切换结论。分项结果、清理和限制唯一见[外部联调验收](FUC_XB_EXTERNAL_ACCEPTANCE.md)。**
|
||||
|
||||
| 项目 | 已核实值 |
|
||||
| --- | --- |
|
||||
| 本地代码 | `/Users/hellcat/Documents/GemCodes/xb` |
|
||||
| 本地域名 | 本实例不适用;`xb.loc`为另一个本地合成验收实例 |
|
||||
| 线上代码 | `site-jp01 -> /var/www/wwwroot/fuc-xb-test/current` |
|
||||
| 线上域名 | `https://fuc-xb-test.gemcook.net`,A记录45.8.112.190、DNS-only |
|
||||
| 反代域名 | `https://fuc-xb-test.tomtojapan.online/stage-login`,经白色机精确反代;原`/stage-access`保留 |
|
||||
| 发布 | `codex/fuc-xb-staging-20261104`,`28ccc0e964a9ff9ee917a15f99c6f0140174e7cf`,Fuc0.12.4 |
|
||||
| 后台资源 | 原XB子模块`ef5f43da335092cbff8fdf0ad7ff9b4d92d7d0d7` |
|
||||
| 实体目录 | `/var/www/wwwroot/fuc-xb-test/releases/28ccc0e964a9ff9ee917a15f99c6f0140174e7cf`;0501711、7446b04等旧release保留回退 |
|
||||
|
||||
代码由独立Git索引创建测试分支,经白色机既有Git中转推送,再由目标机从原仓库检出精确SHA。没有覆盖归档发布,没有提交本地实例、快照、凭据、客服/HN等其他任务改动。Composer按锁文件安装无dev依赖,不升级旧站PHP或依赖。
|
||||
|
||||
## 2026-11-04 配色恢复发布(历史0.12.1)
|
||||
|
||||
用户明确批准把本地已验收的原版配色恢复同步到本测试站。运行提交`7446b045a3702b967cc40456040fdb4210bf19da`,主题0.12.1;只包含Fuc配色、缓存版本及相关测试/主题说明,app/plugins/config/routes/composer.lock树均与原0501711相同,未运行迁移或升级依赖。保留VIP、入口保护及当前反代,不切旧FUC/DPL/HN。
|
||||
|
||||
本机以独立Git索引从0501711创建窄提交,不使用当前主分支或其他聊天的暂存区。Git bundle经已登记白色机中转导入并推送原测试分支,目标机按精确SHA创建新release、复用相同锁定依赖/后台版本并使用原ThemeService生成公开资源,最后原子切current链接;没有上传压缩包覆盖代码。旧release和shared实例配置保留。
|
||||
|
||||
服务器侧Nginx/FPM与登记的HTTPS反代均读回0.12.1;入口401、无访问Cookie404、noindex/no-store、公共配置及app/native/palettes/原样式SHA验证通过。季节CSS不再存在于新源码/公开目录;紫/绿原CSS保留。shared环境、专用Nginx/FPM配置摘要及旧FUC HEAD不变,无服务重启、数据库迁移或业务数据写入。本次未登录业务用户,也未做线上页面验收;本地桌面/390px保存切换与41项测试见[主题验收](FUC_THEME.md#0121-恢复原版配色2026-11-04)。
|
||||
|
||||
首次验收把重复Cache-Control头转成普通字典,只看到`no-cache, private`而误判no-store缺失,脚本自动回退到0501711。核对确认响应同时包含`private, no-store`,改为读取全部同名响应头后重新激活并通过,未为此改Nginx或放宽缓存策略。
|
||||
|
||||
回退:私有记录`/var/www/wwwroot/fuc-xb-test/private/palette-restore-20261104/rollback.json`保存旧/新精确目标;将current链接原子切回`releases/0501711267c859d834fbf5ff94484212c3bb3f69`并重新请求根HTML/资源验证即可。旧PHP/公开资源各自在原release内,shared环境和数据不回灌。首次自动回退已实际验证旧入口仍可用;该轮最终状态为7446b04/0.12.1,现已由下文0.12.4替代。脱敏回执、本地包、任务备份和发布脚本在`codex/output/fuc-theme/palette-revert-20261104/`。
|
||||
|
||||
## 实例隔离
|
||||
|
||||
- 运行用户`fucxbtest`、`XB_INSTANCE=fuc-xb-test`;私密环境、storage与框架缓存放`shared/`,发布目录的`instances/fuc-xb-test/`仅链接到本实例。
|
||||
- 新MySQL库/专用用户`fuc_xb_test`,只授予该库权限;新APP_KEY,没有复制旧站密钥。
|
||||
- 独立Redis:回环6388、专用密码、`fuc-xb-test-redis.service`、128MB上限,配置`/var/www/wwwroot/fuc-xb-test/etc/redis.conf`。旧6379不变。
|
||||
- 新FPM池`/etc/php/8.4/fpm/pool.d/fuc-xb-test.conf`、回环socket`/run/php/php8.4-fuc-xb-test.sock`,ondemand/4子进程。配置检查后只平滑重载FPM。
|
||||
- 新Nginx配置`/etc/nginx/conf.d/fuc-xb-test.conf`,内部验收监听`127.0.0.1:8766`。旧站虚拟主机未改;新域名80保留ACME,其余跳转HTTPS;443使用独立证书和额外入口保护。
|
||||
- 注册关闭;无真实支付方式/节点;邮件流程、Telegram、支付监测及订单/注册/邮件汇报关闭;没有配置cron、worker或Horizon。原生余额支付的订单开通仍使用XB的同步开通逻辑。
|
||||
- 主题Fuc0.12.4(沿用原紫/绿及固定首页;最新修复见最终验收);VIP仅本测试实例启用,其余实例配置未动。后台仍是XB原版。
|
||||
|
||||
## 额外测试入口保护
|
||||
|
||||
原入口为`/stage-access`,先用额外HTTP Basic密码换取1小时、Secure/HttpOnly/SameSite=Strict的测试Cookie,再进入应用。其余请求必须携带此Cookie;前台API仍独立验证XB Bearer令牌。不能把Basic强加到每个API请求,否则会与XB的Authorization头冲突。
|
||||
|
||||
用户明确批准后新增同账号同密码的`/stage-login`表单入口,解决IAB不支持HTTP Basic认证的问题。独立Git代码`scripts/fuc-xb-stage-gate/`,提交`cc3e26076cf1277455e4ab8216dca6d39227a37b`,运行于`/var/www/wwwroot/fuc-xb-stage-gate`。原Basic保留,XB登录与权限不变;签名CSRF及Cookie匹配、精确Origin校验、10次/分钟/IP(burst20)、安全Cookie、noindex/no-store/CSP均已实测。原密码仅验证其既有哈希,没有新增明文凭据或改库。部署检查实际FPM用户可读,Referrer-Policy使用same-origin以支持正常浏览器Origin。21项真实HTTPS保护检查通过,内置浏览器实际登录成功。回退按该目录README,仅撤新增表单位置/专用脚本,不关闭原门禁。
|
||||
|
||||
未认证入口返回401且不发Cookie;即使提交Bearer头也无法绕过测试Cookie。无Cookie请求返回404,私密路径始终403/404。访问日志关闭、全站noindex和private/no-store。Nginx中Cookie随机值属于私密配置,不复制到普通文档。密码只登记GemDocs专用凭据,详见[实例资源](/Users/hellcat/Documents/GemDocs/AI版/30-私有资源/资源/实例/INS-FUC-XB-TEST.md)。本机不因此获准访问项目线上网页。
|
||||
|
||||
## tomtojapan测试反代(2026-11-04)
|
||||
|
||||
用户明确要求测试站使用tomtojapan.online,单独覆盖本次新入口的默认IP加端口选型。访问入口为`https://fuc-xb-test.tomtojapan.online/stage-access`,白色机精确代理到原`fuc-xb-test.gemcook.net`;域名仍解析到登记白色机反代,不指向业务宿主。
|
||||
|
||||
复用当前橙云泛域DNS与Origin CA(SAN含一级泛域,有效至2041-10-09),没有改DNS、证书或共享map。独立代码`scripts/fuc-xb-test-proxy/`已推送`codex/fuc-xb-test-proxy-20261104`,白色机稀疏检出到`/var/www/wwwroot/fuc-xb-test-proxy`,运行提交`a1da019299a8a00794892c7c692df38adc98ce56`。专用`/etc/nginx/conf.d/fuc-xb-test-proxy.conf`链接到该Git目录的nginx.conf;原有配置摘要保持;最终Nginx/SSH active、22端口监听,已登记weiwei和gdog入口本次均HTTPS200/TLS0。
|
||||
|
||||
保留原额外密码、Secure/HttpOnly测试Cookie与XB Bearer权限;上游Host/SNI固定为源站并严格TLS验证。URL路径和查询、认证头及Cookie转发;只转换当前别名的Origin/Referer,跨站值不转换。Location、Cookie域和精确正文主机名重写覆盖JSON转义URL,品牌不替换;noindex/private/no-store保留,不写完整请求URL或令牌日志。源站APP_URL/业务代码不改,原测试入口密码与QA账号继续使用。源测试HTTPS vhost仅额外信任白色机104.168.30.40/32的X-Forwarded-For;受控IPv4实测由原白色机连接地址变为实际测试客户端45.8.112.190,伪造转发头及直接源站伪造均未生效,临时诊断路由已移除。原配置私密备份在源测试private/before-white-realip-v2.conf,回退仅移除本次三条real-IP指令(有后续修改时局部合并,不整份覆盖)。
|
||||
|
||||
26项服务器侧端到端验收通过(最新0.12.4已重跑):CF入口HTTPS、401无凭据Cookie、无访问门404、HTTP跳转仍在别名、额外密码、主机Cookie、前台/Pace/后台资源、敏感路径、JSON地址、QA原生POST登录、VIP/Bearer、匿名不泄露登录响应、套餐查询参数、订阅URL别名及普通用户后台403。只验证订阅接口返回地址,客户端真实导入/联网仍后置;真实WebSocket未握手测试;线上页面已按下文独立验收。临时QA令牌按实际令牌精确撤销,没有创建订单或调用支付。
|
||||
|
||||
白色机备份`/root/codex-backups/fuc-xb-test-proxy/20261104-071416`保存原文件摘要与本次新增映射记录。回退只移除专用链接,`nginx -t`后平滑reload;不撤源站、不删库、不运行其他反代部署器。首轮部署在写配置前因Python3.10不支持datetime.UTC停止;兼容修复后按Git新版本部署,未升级解释器或放宽安全设置。唯一跨项目登记见[PRX-FUC-XB-TEST](/Users/hellcat/Documents/GemDocs/AI版/30-私有资源/资源/反代/PRX-FUC-XB-TEST.md)。
|
||||
|
||||
## 迁移数据与例外
|
||||
|
||||
源为2026-11-03已演练的只读快照,不是正式切换数据。正式切换仍须刷新快照、处理冻结和最终差异,不以本次测试副本替换正式库。
|
||||
|
||||
- 11,542名旧用户、166个隐藏历史套餐、3个权限组,全字段规范化摘要在MySQL回读一致。
|
||||
- 旧用户钱包365,087分(含13笔预购退款322,868分),佣金1,632分;VIP期初11,542份按已确认净额导入并校验UUID/快照SHA。VIP导入没有改变钱包或创建旧订单。
|
||||
- 不继承旧管理员/员工标记;仅按ACC-005既定管理员约定,在测试实例核验既有密码后激活同一账号的管理员权限,没有改其密码。旧正式站账号未改。
|
||||
- 新增1名虚拟QA和1个标明“不提供线路”的测试套餐;总用户11,543。QA余额100,000分为合成测试数据,不算旧站迁移资金。测试套餐容量显式null,按XB原生规则表示不限制,避免缺省0被判售罄。
|
||||
- 原旧账仍为本地只读归档,没有插入本测试站原生订单/佣金表。测试完成后原生订单0,未新增真实付款、邮件或节点。
|
||||
|
||||
实现及既有业务边界见[VIP](FUC_VIP.md)、[迁移演练](FUC_MIGRATION_REHEARSAL.md)、[主题](FUC_THEME.md)。
|
||||
|
||||
## 首次部署验收(历史;当前最终结果见下节)
|
||||
|
||||
- 12项MySQL真实XB HTTP内核检查:100元期初享9.2折,300元套餐按276元开通,累计376元升级8.5折,下一单255元;重复开通不重复累计、取消返余额、退款资格冲回不擅自操作钱包。临时数据全部事务回滚。
|
||||
- 两独立PHP进程并发开通:MySQL只产生一条100元消费记录、原生折扣8%,测试临时行清理。宿主禁用PHP proc_open,保留该安全限制,由Python启动两个进程,没有放宽PHP设置。
|
||||
- 23项真实Nginx/FPM HTTP检查:测试入口、安全Cookie、私密路径、主题/Pace资源SHA、原生配置、注册关闭、QA及既定管理员登录、VIP、普通用户403、原生后台及锁定后台资源200。测试登录令牌已撤销。
|
||||
- 首次部署未做线上浏览器页面验收;当前页面验收见下节。真实支付、邮件或客户端联网仍是后置营业联调。
|
||||
- DNS已在内置CF新增并回读,现仅该测试A指向45.8.112.190;Let's Encrypt证书有效至2027-02-02 05:48:17 UTC,专用续期hook先检查再reload Nginx。目标机验证证书/SNI、401入口、无Cookie404及认证后前台/资源200;白色机从外部独立请求入口为401、TLS校验0。初次紧随异步reload的握手曾读到旧证书,重新验证通过,没有放宽证书校验。
|
||||
- 最终11,542旧用户钱包365,087分/佣金1,632分、原生订单0、VIP期初11,542、非期初记录0、测试令牌0;额外1虚拟QA。旧FUC HEAD、原vhost/FPM/cron文件摘要未变,原站HTTPS200/TLS0,六个相关服务active。
|
||||
- 测试入口/QA密码已按字段登记GemDocs唯一私有凭据,服务器临时JSON中的明文密码字段已移除,运行所需密码哈希、私密Cookie和身份ID保留。
|
||||
|
||||
脱敏回执、脚本和私有传输物位于本地忽略目录`codex/output/fuc-xb-staging-20261104/`;目标私有日志在测试站`private/`,目录700,数据不挂Web。
|
||||
|
||||
## 停用与恢复
|
||||
|
||||
测试站独立,可以先撤下其专用Nginx配置并`nginx -t`后reload,关闭仅`fuc-xb-test-redis.service`,撤下其专用FPM池并检查后reload。保留新库、shared、私有回执和Git版本用于复核,不自动删库/回灌旧库。恢复测试站时反向恢复这些专用文件和服务,不覆盖旧FUC的.env、数据库、客户端文件、vhost、cron或已有Redis。
|
||||
|
||||
原站基线(HEAD及原vhost/FPM/cron文件摘要)在测试站`private/old-site-baseline.json`。配置初始化时曾修正本实例目录私密umask造成的遍历权限,并把专用Redis配置放到本实例目录,不扩大旧`/etc/redis`权限;此后实际FPM及MySQL验收通过。
|
||||
|
||||
|
||||
## 2026-11-04 最终验收(隔离测试范围通过)
|
||||
|
||||
当前运行`28ccc0e964a9ff9ee917a15f99c6f0140174e7cf` / Fuc0.12.4。测试站代码、入口脚本及反代分别沿Git提交/推送/精确检出发布;旧FUC、DPL/HN未发布或切换。本轮没有新增XB核心、业务API、数据库结构或管理员资源修改。前端显示、独立测试vhost及门禁的修复不改变XB原有订单结算。
|
||||
|
||||
| 范围 | 本轮实际结果 |
|
||||
| --- | --- |
|
||||
| 全量迁移回读 | 页面测试清理后再次对3权限组、166历史套餐、11,542用户逐字段核对授权快照:意外差异0。仅既定管理员标志及该账号登录时间/更新时间变化;钱包365,087分、佣金1,632分,11,542份VIP期初/UUID/快照引用一致。 |
|
||||
| 期初幂等 | MySQL事务内重复执行全部11,542份期初,用户/VIP全行摘要及钱包不变;冲突金额拒绝,最终回滚。 |
|
||||
| 原生交易与并发 | 12项MySQL真实HTTP内核检查通过;100元期初→300元套餐实付276→累计376元→下一单255。两独立PHP进程开通只产生1笔100元累计、8%折扣,精确清理。PHP proc_open仍禁用。 |
|
||||
| 浏览器真实下单 | 合成QA钱包1000元→100元套餐钱包开通→余额900元、累计100元、小福9.2折、30天/100GB。再由“我的套餐”续费,原生订单92元;创建后钱包808元,二次确认取消后恢复900元,累计和到期时间不变。没有外部支付。 |
|
||||
| 桌面与手机 | IAB实际检查公开首页、登录/注册/找回及重置、用户中心、套餐、钱包、我的套餐、订单/详情、邀请、设置、工单/详情、节点、公告、文档/详情和FAQ。桌面1280×720、手机390×844;未见页面横向溢出/坏图。订单长表只在卡片内横向滚动。关闭工单无法回复,120字符长文本正常换行。 |
|
||||
| 动态交互与配色 | 原Pace请求中3px进度条实际显示;紫/绿保存、原绿色火箭hue-rotate(290deg)/tada、亮暗、菜单折叠/手机遮罩、点击空白关闭、购买/优惠码弹窗取消和重入、FAQ异步展开/折叠/搜索、公开手机导航均实际操作。原19份CSS/26模板/Pace/UI库字节完整性通过;未声称旧FUC生产实时数据截图逐像素一致。 |
|
||||
| XB原版后台 | 既定管理员实际登录;原主题管理显示Fuc0.12.4为当前主题;VIP插件开启,100/8、200/12、360/15配置原值保存后重新打开一致。桌面和390px导航可用、无横向溢出。QA管理API403、管理员200。后台锁定提交ef5f43d未改;队列异常/0进程是本隔离站有意不启动worker的状态,不是营业验收通过。 |
|
||||
| 自动回归 | 本地隔离内存库27项/92断言(VIP18、原生订单4、已批准密码重置修复5);当前主题46项Node测试、原素材核对及ZIP源码/CRC/ESM闭包通过。 |
|
||||
| 当前发布HTTP | 0.12.4真实Nginx/FPM23项、白色机端到端HTTPS26项通过,包含原生登录/VIP/RBAC/订阅URL别名、资源、缓存、私密路径。新增表单21项保护及10项MIME/无认证资源检查通过。所有本轮令牌精确撤销。 |
|
||||
| 配置与旧站 | 专用库权限、Redis6388、private700/.env640、debug关闭、注册/真实支付/节点/邮件/汇报关闭,无测试cron/worker。六个相关服务active;旧FUC HEAD和原vhost/FPM/cron摘要不变、HTTPS200/TLS0。白色机原配置及weiwei/gdog入口检查通过。 |
|
||||
| 恢复与收尾 | 测试库私有gzip备份恢复至同宿主临时独立库,41表行数/数据摘要一致;运行库未变,临时库移除。GUI两笔订单、1笔VIP消费/流量重置、2文档、1公告、1已关闭工单及消息、两条GUI会话均按ID/归属白名单清理并留私有恢复备份。QA完整基线恢复;最终原生订单0、佣金日志0、非期初VIP0、测试会话0。 |
|
||||
|
||||
实际发现并修复的问题:
|
||||
|
||||
1. 测试vhost未识别`.mjs`,200却返回application/octet-stream,浏览器拒绝ESM白屏。只在独立测试vhost设application/javascript,原认证门仍生效。
|
||||
2. 钱包全额付款后XB原生total_amount为0,主题误显示商品免费。显示金额改为XB原生历史套餐价值口径total_amount + balance_amount + surplus_amount - surplus_credit,并分别展示钱包/旧套餐折抵/在线本金;零外部待付显示“确认开通”。仅主题展示,结算不改。
|
||||
3. 模式切换反复挪动已加载LINK,Chromium临时卸载CSS造成闪白/无样式。保留已激活CSS,准备有序的新模式样式并加载完成后再提交页面;新增真实DOM样式节点保留/顺序回归。此前无样式截图保留为问题证据,不计为通过。
|
||||
4. 购买确认曾把未考虑VIP的标价叫“实际支付”。现保留标价并明确“下单后确认”,实际金额只读原生订单;不在主题再实现折扣/结算逻辑。
|
||||
5. 文档旧模板mt-n1负间距导致标题/分类重叠。仅bridge.css去掉该处负边距,桌面/手机分类间距0px,无重叠,符合用户已确认的可用布局例外。
|
||||
|
||||
发布链:0.12.2/f236c58→0.12.3/2022184→0.12.4/28ccc0e。当前ZIP `codex/output/fuc-theme/Fuc-0.12.4.zip`,SHA256 `1695853b5c3bb54aef5c783cf4f01d436fdf525cbc6791401c81f529ae69be21`。应用回退用private中对应发布rollback记录原子恢复上一个release,并验证根HTML/模块版本;不回灌shared数据。门禁/MIME回退独立,见scripts/fuc-xb-stage-gate/README.md及其私有备份。
|
||||
|
||||
用户先批准Windows路线,后明确批准本轮本机IAB只访问指定测试反代;属本次例外,不改变全局访问边界。HTTP Basic工具能力受限后,用户另行批准同账号同密码的表单入口;未注入Cookie或放宽认证。QA退出并确认受保护路由要求重新登录后,按账号切换规则更换日本/新加坡节点并在实际IAB核对出口不同,再登录管理员;管理员退出后恢复原节点,TUN与系统HTTP/HTTPS代理全部保持开启。
|
||||
|
||||
VirMach登录曾被自动审批拦截,未提交成功且后续未继续。收尾脚本读取全部会话元数据的查询也被自动审批拦截,已缩至本次QA/获准管理员的具体会话ID后通过。没有为验收扩大其他账号/网站访问。
|
||||
|
||||
回执/截图在本地忽略目录`codex/output/fuc-xb-staging-20261104/`:final-124-*-acceptance、final-data3、final-counts2、final-safety3、final-source2、ui-cleanup1及final-ui-records.json;原始凭据/备份仅private。真实支付、邮件、节点/客户端联网、真实WebSocket未验收;正式营业仍须独立完成相应配置和联调,以及新快照/冻结增量/切换决定。
|
||||
|
||||
## 最终验收主导与正式切换边界
|
||||
|
||||
用户本次明确指定由当前主程主导最终验收。此为当前FUC-XB任务安排,不改长期人事岗位、不授权正式切换。统一核对:迁移身份/权益/钱包/VIP守恒与重复导入、原生订单/折抵/返佣边界、前台桌面和移动端/动画、后台权限、反代全路径/缓存、恢复步骤及临时测试数据收尾,分别给出通过项与剩余问题。
|
||||
|
||||
真实支付、邮件、节点/客户端联网沿已确认的营业后置边界;正式迁移须另取新快照、核对冻结和增量,并由用户决定切换。不能将本次11月3日快照、服务器侧反代检查或测试站可访问写成正式营业全部通过。
|
||||
@@ -0,0 +1,60 @@
|
||||
# FUC-XB 新快照迁移与原生V2重新验收(2026-11-05)
|
||||
|
||||
**本轮最新用户迁移与Xboard-Node原生V2验收通过,未切正式站。** 应用仍28ccc0e/Fuc0.12.4,后台仍XB锁定子模块。没有修改XB业务核心或DPL/HN部署;专属工具在scripts/fuc-xb-refresh,独立Git分支codex/fuc-xb-external-acceptance-20261104。
|
||||
|
||||
## 用户范围与保护
|
||||
|
||||
用户明确要求与DPL/HN采用同一节点程序/原生V2机器接口,重新迁移正式站用户到既有隔离测试站并重验。源站/测试站均在site-jp01,源正式库只读;正式站与既有节点不切换。钱包、VIP、邮箱修正规则沿此前确认,真实付款继续跳过。
|
||||
|
||||
用户另明确批准将本次合成QA机器令牌和既有测试门禁Cookie,经白色机复制到VPS016的/var/www/wwwroot/fuc-xb-acceptance/private/v2-20261105,仅本次独立节点验收,root私有,30分钟限时,结束停止/移除。首次启动被自动审批以未精确授权这份副本到目的地拒绝,命令未执行;取得明确批准后才执行。未复制迁移用户、生产机器令牌或DPL/HN秘密。
|
||||
|
||||
## 新快照、备份与迁移结果
|
||||
|
||||
- 旧FUC源HEAD保持fea0d886f77a19a7b174836262917f7a735b2a5f。
|
||||
- 只读一致性快照:2026-11-05 01:53:13 UTC,即北京时间09:53:13;SHA256 d32bf214f2a5277b8434f75e953acb88d255dce09f0c3b2967bd862eba030db2,13表38933行,用户11548(上轮11542,多6人)。快照/敏感投影只在原宿主测试private,不回传本机或提交Git。
|
||||
- 刷新前仅测试库41表完整备份,独立临时库实际恢复核验全表行数/内容摘要一致,验证后删除临时恢复库;备份private/refresh-20261105-before/fuc_xb_test.sql.gz,SHA256 8810c12e0fcbdbe637089711e808df68cd1722161499e9a9f3329267d3817bd1,mode600,保留恢复。
|
||||
- 新迁移11548用户、167隐藏历史套餐、3原权限组。当前字节额度/u/d/到期、密码哈希、UUID、佣金和邀请关系按快照投影;沿精确4人邮箱修正。26人无旧订阅链接,生成持久随机新token;用户沿已确认有感迁移重新导入,无旧URL兼容。
|
||||
- 14笔有效已付未履约预购完整转新钱包338447分(3384.47元),不重放自动激活、旧自动续订或历史返佣。迁移用户钱包380666分(3806.66元)、佣金1632分;VIP11548份按max(0,旧total_pay-预购返还)计算,1人归零。
|
||||
- 旧账另归档private/refresh-20261105/legacy-readonly.sqlite,38933行完整,mode400、只读打开/拒绝DELETE实测;SHA256 3f2650574ef20fa0455b0cdb9020a888cdfa800d1e230328553c634aeac12b40。旧订单不进入XB原生订单表。
|
||||
- 保留原合成QA账号认证,其用户/套餐ID按新数据避让,100000分合成钱包单独计算;总用户11549、总套餐168、仅1个合成销售套餐。只有既定管理员被授予管理权限,不继承其他旧管理员/员工。
|
||||
- 全字段回读意外差异0、VIP期初不匹配0;重复11548份VIP期初整表不变、冲突金额拒绝,没有重复退款或升级。原生订单/佣金流水/非期初VIP/会话均0;管理员登录造成的时间字段与既定权限单列。
|
||||
|
||||
首次快照校验漏零行表而误报,重读已有完整快照修正计数后通过,未重复导出。第一次刷新因测试库旧流量重置日志而安全停在写入前;在已完整备份前提下,专属工具将其随旧测试用户事务清理后成功刷新,没有为此改XB核心。
|
||||
|
||||
## Xboard-Node与原生V2的实际验收
|
||||
|
||||
| 项目 | 本轮结果 |
|
||||
| --- | --- |
|
||||
| 程序 | VPS016现用DPL/HN相同Xboard-Node二进制;SHA256 55bf71fa9d9f2048d3255ae7c0af929a41897ca7743f6ead34132a6ca4c79043,与旧XrayR无关 |
|
||||
| 节点范围 | 单个独立AnyTLS、25443;合成组/机器/用户,迁移用户不分配到该QA节点;独立限时进程,无共享正式服务重启 |
|
||||
| 接口 | /api/v2/server/machine/nodes、handshake、config、user、report、machine/status均实际200/304;独立机器ID/token认证;原生轮询,WebSocket未启用/未验收 |
|
||||
| 权限 | 实际源站接口精确发现1节点;错误令牌403、错误机器403、未归属节点400、缺门禁404。不是只靠QA桥拒绝模拟通过 |
|
||||
| 订阅/客户端 | 完整原生sing-box订阅,仅替换本地inbound;官方sing-box1.14.3,严格TLS1.3、证书/SNI验证、真实出口193.111.31.52、65536字节下载和30720字节上传回显通过;Clash格式节点身份正确 |
|
||||
| 记账 | 合成用户与节点实际u/d同步入账:第一例43137/231500字节,第二例38945/126000字节,第三例38945/126001字节;原生report、流量/统计队列处理通过 |
|
||||
| 禁用最后用户 | 用户下发1→0;订阅403;节点前后仍TLS1.3存活;重启客户端用保存的旧配置,新连接被拒绝 |
|
||||
| 过期最后用户 | 新合成身份正向联网与记账后过期,下发1→0、订阅403、保存配置新连接拒绝;旧QA不复活 |
|
||||
| 流量耗尽最后用户 | 新合成身份先正向联网/记账,再耗尽;下发1→0,节点仍存活而保存配置被拒。XB原生此时订阅仍200可刷新,保持此设计,没有把200误判为联网授权仍有效 |
|
||||
| 原服务保护 | DPL/HN现有dpl-node PID110612、二进制/unit摘要,以及原XrayR PID107692前后保持;不据此宣称重新验收全部DPL/HN客户端 |
|
||||
|
||||
机器接口按节点实际登记源站执行。网页测试反代的CF规则对机器发现直测返回403,未用它证明原生权限,也未改CF规则或网页反代;客户端订阅及网页API仍经既有别名,26项HTTPS检查通过。
|
||||
|
||||
工具第一次QA组创建采用不支持的批量赋值而失败,事务未创建夹具;已按原生new/save修正。第三个客户端场景遇普通bind把TIME_WAIT误判占用,核对后用同一身份续跑通过;工具改为ss检查实际监听。流量耗尽订阅200是原生isAvailable行为,不改XB核心来迎合测试的错误403预期。
|
||||
|
||||
## 其他回归、清理与边界
|
||||
|
||||
- 刷新后23项真实Nginx/FPM接口、管理员/QA登录、VIP、套餐、权限、主题/Pace/原后台资源通过;26项真实HTTPS反代/认证/参数/缓存/订阅URL检查通过,令牌精确清理。
|
||||
- 12项真实MySQL/HTTP内核原生钱包开通/VIP升级/下一单折扣/取消返钱包/消费冲回通过,全事务回滚;没有真实付款或邮件群发。工具4项V2桥作用域检查与5项收银/兼容桥回归通过。
|
||||
- 本轮没再发真实邮件或新建支付商订单;沿用11月4日两封实收/SPF/DKIM/DMARC和同单HTML Accept对照/金额/二维码证据,不能写成本轮重新实付或重新收信。实际扣款、支付商成功回调、到账按用户要求未做。
|
||||
- 先停止临时节点/API桥,确认25443/28766监听关闭,移除复制的Cookie/机器令牌、环境文件和生成kernel配置;再排空本次流量/统计队列,删除精确3名合成QA、组、节点、机器及统计/负载记录,恢复原推拉设置。基线用户/组/节点/机器数与钱包恢复。
|
||||
- 最终测试节点0、机器0、真实支付配置0,注册/常驻邮件/汇报关闭,无测试cron/常驻worker;六个服务active,库权限/Redis6388隔离、私有文件权限、旧FUC HEAD/vhost/FPM/cron摘要与服务器侧HTTPS正常。没有切正式站。
|
||||
- 本轮为服务器侧重验,未重做网页动画/手机界面人工操作;主题/后台版本未变,既有IAB界面结果单独沿11月4日记录。只验收一个AnyTLS节点/原生V2机器链路与Linux sing-box,未接入全部旧正式节点、未覆盖全部协议/手机客户端/Mac TUN。
|
||||
|
||||
## 证据与恢复
|
||||
|
||||
本机脱敏元数据:codex/output/fuc-xb-v2-reacceptance-20261105/;远程回执本机镜像:codex/output/fuc-xb-staging-20261104/private/v2-*-20261105.json。用户快照/投影/旧账与SQL备份只在测试宿主private。
|
||||
|
||||
关键回执:fresh-snapshot-verified、refresh-backup、refresh-receipt、fresh-full-readback-idempotency、fresh-final-full-readback、node-start、client-positive-initial、revoke-banned、phase-expired、quota-native-final、native-auth-source、node-panel-cleanup、fresh-native-wallet-vip、refresh-final-safety、refresh-final-old-source;过期单例完整JSON在服务器private/refresh-20261105/phase-expired.json,合成客户端/节点操作均有失败和续跑记录,不抹除失败回执。
|
||||
|
||||
恢复只针对本隔离测试实例:停用测试写入口后,将已验证旧测试SQL备份恢复fuc_xb_test、根据恢复库中的唯一合成QA及销售套餐回填QA身份ID(密码不变)并核对旧期初引用;先比较当前状态,不能把本次SQL恢复到正式FUC或DPL/HN。正式切换仍需另行确定窗口、刷新快照与增量处理、营业商品/全量节点配置和回退,不以本次快照自动替换正式站。
|
||||
|
||||
当前数据入口为服务器private/refresh-20261105的manifest/projection及refresh-applied回执;旧private/rehearsal-native.jsonl.gz、data-manifest.json及旧import-stage/final-data脚本是11月3日冻结演练,保留作历史,不能再用其11542人常数验收或导入当前库。
|
||||
@@ -31,6 +31,8 @@
|
||||
| PAYMENT_HEALTH.md | 共用支付每6小时检测、自动开关、人工停用/旧回调保护、独立TeleHub告警与生产验收 |
|
||||
| RESOURCE_CLIENT_DOWNLOADS.md | DPL客户端下载接入resource、固定链接、架构选择、Git迁移版本与验收/回退 |
|
||||
| BRANDING.md | DPL当前Logo唯一源文件、历史候选误用来源、静态副本及纠正范围 |
|
||||
| FUC_XB_EXTERNAL_ACCEPTANCE.md | FUC-XB真实邮件实收、零扣款支付、单节点/客户端/记账及收银台404和撤权失败 |
|
||||
| FUC_XB_V2_REACCEPTANCE.md | 11月5日正式用户新快照11548人、原生V2机器/Xboard-Node联网记账与三类撤权验收 |
|
||||
| FUC_THEME.md | Fuc 独立主题、本地预览、安装包、接口契约及未验收边界 |
|
||||
| ARCHITECTURE.md | 服务入口、前后端边界、配置来源、开发与检查 |
|
||||
| BUSINESS_RULES.md | XB全项目套餐流量按10GB四舍五入,以及邮件、提醒、账号与支付等约束 |
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# 接手验收状态
|
||||
|
||||
## 2026-11-05 FUC-XB新快照与原生V2重新验收通过
|
||||
|
||||
只读正式快照11548用户、14笔预购返钱包338447分;新测试库钱包380666分/佣金1632分、VIP期初11548,全字段及重复导入无意外差异。DPL/HN同SHA的Xboard-Node独立进程走原生V2机器接口,AnyTLS严格TLS/实际联网/记账及最后用户禁用、过期、耗尽后三类旧配置拒绝通过;耗尽订阅200是原生可刷新行为,未改XB。临时节点/机器/QA和批准复制的Cookie/机器令牌已清理,原服务不变;23项FPM、26项HTTPS、12项钱包/VIP和9项工具检查通过。应用仍28ccc0e/Fuc0.12.4,无XB核心改动或正式切换。本轮服务器侧验收,界面/邮件/零付款收银证据按日期分开。唯一结果与回退见[最新验收](FUC_XB_V2_REACCEPTANCE.md)。
|
||||
|
||||
|
||||
## 2026-11-04 FUC-XB外部联调:整体未通过,未切正式站
|
||||
|
||||
两封真实邮件由Resend/企业SMTP送达指定Proton收件箱并由IAB实读,SPF/DKIM/DMARC通过;原生MySQL/HTTP支付37项受控验证通过、实际扣款0;单VMess原生订阅由sing-box1.14.3导入,严格TLS1.3、真实出口/65536字节下载/30720字节上传及XB流量记账通过。测试实例原生singbox模板更新为仓库已有现代格式,无XB核心变更。真实支付商submit/mapi两路最终收银台均404;禁用QA后订阅403、下发用户0,但保存配置仍可新建连接,不能宣称可正式营业。临时节点/桥/客户端及精确QA数据已清理、队列排空、原节点不变;11542人全字段/VIP/钱包及旧FUC服务保护复核通过。唯一证据、限制与后续见[外部联调](FUC_XB_EXTERNAL_ACCEPTANCE.md)。
|
||||
|
||||
|
||||
## 2026-10-31统一生产发布
|
||||
|
||||
XB+DPL+HN已按用户授权一并提交、推送、上线同一后端;DPL Stellar、HN EZ保持,其他已安装主题发布可选。108项PHP测试554断言、14项Node测试、三主题服务器构建及两站服务器侧入口/资源/实例隔离验收通过。日报昨天08点至今天08点已启用,首期DPL8/HN2,均sent/attempts=1。详细版本、恢复、边界见[共用后端](UNIFIED_BACKEND.md)和[注册日报](REGISTRATION_REPORT.md)。未做线上页面验收,无真实订单/付款测试。
|
||||
|
||||
@@ -12,12 +12,6 @@ DPL、HN共享同一app/config/routes/vendor代码根;各自的数据库、用
|
||||
|
||||
后台保存的手动顺序用于区内的同序号节点、无编号节点及其他地区。此规则随 XB 后端版本进入各实例,发布以实例的 Git 提交和服务器侧订阅回读为准。
|
||||
|
||||
2026-11-07 用户授权上线。XB 主分支实现提交 `6e29d4f`,福云 XB 实例在 site-jp01 部署 `d552b8a`,DPL 和 HN 在 site-jp02 部署 `0bca3f1`。两台服务器分别从各自原生产版本更新同一排序实现。
|
||||
|
||||
三个生产实例的 PHP-FPM 均通过 Clash Verge 订阅生成验收。福云 XB 57 条,其中 33 个分身紧跟主节点。DPL 和 HN 各 23 条。发布前后权限组可见节点集合一致。HN 现有节点权限组使用内存测试用户,福云 XB 和 DPL 使用既有用户覆盖主要订阅。验收范围是订阅内容与策略组顺序,未刷新本机 Clash,也未做线上页面验收。
|
||||
|
||||
两台服务器的 `/root/codex-backups/xb-display-order-20261107/` 按发布提交保存代码备份和回读。回退前先确认当前 Git 提交与并行改动,仅回退本次发布。福云 XB 的原提交为 `a11df4f`,DPL/HN 的原提交为 `8642c1b`。回退后以对应 FPM 重新生成订阅核实。
|
||||
|
||||
## 唯一主题目录
|
||||
|
||||
所有主题以XB根目录下的 `theme/` 为唯一源:
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
FRONTEND_URL=http://chatwoot.loc
|
||||
SECRET_KEY_BASE=generate-128-hex-characters
|
||||
POSTGRES_HOST=postgres
|
||||
POSTGRES_DATABASE=chatwoot
|
||||
POSTGRES_USERNAME=chatwoot
|
||||
POSTGRES_PASSWORD=generate-random-password
|
||||
REDIS_URL=redis://redis:6379
|
||||
ENABLE_ACCOUNT_SIGNUP=false
|
||||
FORCE_SSL=false
|
||||
ACTIVE_STORAGE_SERVICE=local
|
||||
RAILS_LOG_TO_STDOUT=true
|
||||
RAILS_MAX_THREADS=3
|
||||
WEB_CONCURRENCY=1
|
||||
SIDEKIQ_CONCURRENCY=3
|
||||
DEFAULT_LOCALE=zh_CN
|
||||
DISABLE_TELEMETRY=true
|
||||
|
||||
# Extra HTTPS origins apply only to the inbox whose website URL matches this value.
|
||||
XB_WIDGET_PRIMARY_ORIGIN=
|
||||
XB_WIDGET_EXTRA_ORIGINS=
|
||||
@@ -0,0 +1,3 @@
|
||||
.env
|
||||
private/
|
||||
__pycache__/
|
||||
@@ -0,0 +1,11 @@
|
||||
<% content_for :head do %>
|
||||
<%= render 'public/api/v1/portals/articles/meta_head',
|
||||
article: @article, portal: @portal, locale: @locale, og_image_url: @og_image_url %>
|
||||
<% end %>
|
||||
|
||||
<div class="max-w-5xl mx-auto space-y-4 w-full px-4 md:px-8 py-4">
|
||||
<h1 class="text-3xl font-semibold leading-normal md:tracking-normal md:text-4xl text-slate-900 dark:text-white"><%= @article.title %></h1>
|
||||
</div>
|
||||
|
||||
<%= render 'public/api/v1/portals/articles/article_body',
|
||||
parsed_content: @parsed_content, content_padding: 'py-4' %>
|
||||
@@ -0,0 +1,60 @@
|
||||
name: xb-chatwoot
|
||||
x-app: &app
|
||||
image: chatwoot/chatwoot:v4.19.1-ce
|
||||
env_file: .env
|
||||
environment:
|
||||
RAILS_ENV: production
|
||||
NODE_ENV: production
|
||||
INSTALLATION_ENV: docker
|
||||
volumes:
|
||||
- storage:/app/storage
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
services:
|
||||
rails:
|
||||
<<: *app
|
||||
entrypoint: docker/entrypoints/rails.sh
|
||||
volumes:
|
||||
- storage:/app/storage
|
||||
- ./widget-show.html.erb:/app/app/views/widgets/show.html.erb:ro
|
||||
- ./xb-offline.js:/app/public/xb-offline.js:ro
|
||||
- ./article-show-plain.html.erb:/app/app/views/public/api/v1/portals/articles/show.html+plain.erb:ro
|
||||
command: [bundle, exec, rails, s, -p, '3000', -b, 0.0.0.0]
|
||||
ports:
|
||||
- '127.0.0.1:8596:3000'
|
||||
sidekiq:
|
||||
<<: *app
|
||||
command: [bundle, exec, sidekiq, -C, config/sidekiq.yml]
|
||||
postgres:
|
||||
image: pgvector/pgvector:pg16
|
||||
environment:
|
||||
POSTGRES_DB: chatwoot
|
||||
POSTGRES_USER: chatwoot
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
|
||||
volumes:
|
||||
- postgres:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'pg_isready -U chatwoot -d chatwoot']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
restart: unless-stopped
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
command: [redis-server, --appendonly, 'yes']
|
||||
volumes:
|
||||
- redis:/data
|
||||
healthcheck:
|
||||
test: [CMD, redis-cli, ping]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
storage:
|
||||
postgres:
|
||||
redis:
|
||||
@@ -0,0 +1,79 @@
|
||||
<!DOCTYPE html>
|
||||
<% native_hn_widget = @web_widget.website_url == 'http://hn.loc'
|
||||
primary_origin = @web_widget.website_url
|
||||
extra_origins = primary_origin == ENV['XB_WIDGET_PRIMARY_ORIGIN'] ? ENV.fetch('XB_WIDGET_EXTRA_ORIGINS', '').split(',').map(&:strip) : []
|
||||
%>
|
||||
<html>
|
||||
<head>
|
||||
<title><%= @global_config['INSTALLATION_NAME'] %></title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
|
||||
<meta name="robots" content="noindex">
|
||||
<script>
|
||||
window.chatwootWebChannel = {
|
||||
avatarUrl: <%= raw json_escape(@web_widget.inbox.avatar_url.to_json) %>,
|
||||
hasAConnectedAgentBot: <%= raw json_escape(@web_widget.inbox.agent_bot&.name.to_json) %>,
|
||||
locale: '<%= @web_widget.account.locale %>',
|
||||
websiteName: <%= raw json_escape(@web_widget.inbox.name.to_json) %>,
|
||||
websiteToken: '<%= @web_widget.website_token %>',
|
||||
welcomeTagline: <%= @web_widget.welcome_tagline.to_json.html_safe %>,
|
||||
welcomeTitle: <%= raw json_escape(@web_widget.welcome_title.to_json) %>,
|
||||
widgetColor: '<%= @web_widget.widget_color %>',
|
||||
portal: <%= @web_widget.inbox.portal.to_json.html_safe %>,
|
||||
enabledFeatures: <%= @web_widget.selected_feature_flags.to_json.html_safe %>,
|
||||
enabledLanguages: <%= available_locales_with_name.to_json.html_safe %>,
|
||||
replyTime: '<%= @web_widget.reply_time %>',
|
||||
preChatFormEnabled: <%= @web_widget.pre_chat_form_enabled %>,
|
||||
preChatFormOptions: <%= @web_widget.pre_chat_form_options.to_json.html_safe %>,
|
||||
workingHoursEnabled: <%= @web_widget.inbox.working_hours_enabled %>,
|
||||
csatSurveyEnabled: <%= @web_widget.inbox.csat_survey_enabled %>,
|
||||
workingHours: <%= @web_widget.inbox.working_hours.to_json.html_safe %>,
|
||||
outOfOfficeMessage: <%= @web_widget.inbox.out_of_office_message.to_json.html_safe %>,
|
||||
utcOffset: '<%= ActiveSupport::TimeZone[@web_widget.inbox.timezone].now.formatted_offset %>',
|
||||
timezone: '<%= @web_widget.inbox.timezone %>',
|
||||
allowMessagesAfterResolved: <%= @web_widget.inbox.allow_messages_after_resolved %>,
|
||||
disableBranding: <%= !native_hn_widget || @web_widget.inbox.account.feature_enabled?('disable_branding') %>,
|
||||
}
|
||||
window.chatwootPubsubToken = '<%= @contact_inbox.pubsub_token %>'
|
||||
window.authToken = '<%= @token %>'
|
||||
window.globalConfig = <%= raw @global_config.to_json %>
|
||||
<% unless native_hn_widget %>
|
||||
// Fetch published help articles on each widget load instead of reusing
|
||||
// Chatwoot's 24-hour article cache. Leave contact/conversation storage intact.
|
||||
try {
|
||||
const slug = window.chatwootWebChannel.portal?.slug;
|
||||
if (slug) {
|
||||
const prefix = `chatwoot_most_read_articles_${slug}_`;
|
||||
Object.keys(window.localStorage).filter(key => key.startsWith(prefix))
|
||||
.forEach(key => window.localStorage.removeItem(key));
|
||||
}
|
||||
const agentsKey = `chatwoot_available_agents_${window.chatwootWebChannel.websiteToken}`;
|
||||
window.localStorage.removeItem(agentsKey);
|
||||
window.localStorage.removeItem(`${agentsKey}:ts`);
|
||||
} catch (_) { /* Storage may be unavailable in a restricted browser. */ }
|
||||
<% end %>
|
||||
</script>
|
||||
<% unless native_hn_widget %>
|
||||
<script>
|
||||
window.xbParentOrigins = <%= raw json_escape(([primary_origin] + extra_origins).to_json) %>.flatMap(value => {
|
||||
try { const url = new URL(value); return ['https:', 'http:'].includes(url.protocol) ? [url.origin] : []; }
|
||||
catch { return []; }
|
||||
});
|
||||
</script>
|
||||
<script defer src="/xb-offline.js?v=<%= File.mtime(Rails.root.join('public', 'xb-offline.js')).to_i %>"></script>
|
||||
<% end %>
|
||||
<%= vite_client_tag %>
|
||||
<%= vite_javascript_tag 'widget' %>
|
||||
<% unless native_hn_widget %>
|
||||
<style>
|
||||
/* Upstream Branding's disabled branch leaves an empty padded footer. */
|
||||
#app .relative.flex.flex-col.h-full > .p-3:empty { display: none; }
|
||||
/* Match the chat composer's existing 20px horizontal inset. */
|
||||
#app footer:has(#chat-input) { margin-bottom: 20px; }
|
||||
</style>
|
||||
<% end %>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" class="h-full"></div>
|
||||
<%= yield %>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,35 @@
|
||||
import {readFileSync} from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = readFileSync(new URL('../../public/customer-service/widget.mjs', import.meta.url), 'utf8');
|
||||
function page(config, protocol='http:') {
|
||||
if(config?.base_url)config={enabled:true,...config};
|
||||
const scripts=[], calls=[];
|
||||
const context = {URL, MutationObserver:class{observe(){}}, location:{protocol,origin:'http://xb.loc'}, console, window:{addEventListener(){},
|
||||
xbCustomerService:config, chatwootSDK:{run:args=>calls.push(args)},
|
||||
// An XB session exists; the widget must never forward it.
|
||||
fucSettings:{auth_data:'PRIVATE-XB-SESSION',email:'[email protected]'},
|
||||
}, document:{body:{},getElementById:()=>null,createElement:()=>({events:{},addEventListener(name,fn){this.events[name]=fn;}}),
|
||||
head:{append:script=>scripts.push(script)}}};
|
||||
return {context,scripts,calls,run(){vm.runInNewContext(`(()=>{${source}\n})()`,context);}};
|
||||
}
|
||||
test('unconfigured instances and unsafe origins make no SDK request',()=>{
|
||||
for(const config of [undefined,{}, {base_url:'javascript:alert(1)',website_token:'public'},
|
||||
{base_url:'http://user:[email protected]:8596',website_token:'public'},
|
||||
{base_url:'http://xb.loc:8596/redirect?secret=x',website_token:'public'}]){
|
||||
const p=page(config);p.run();assert.equal(p.scripts.length,0);
|
||||
}
|
||||
const secure=page({base_url:'http://xb.loc:8596',website_token:'public'},'https:');
|
||||
secure.run();assert.equal(secure.scripts.length,0);
|
||||
});
|
||||
test('SDK initializes once and receives only public widget configuration',()=>{
|
||||
const p=page({base_url:'http://xb.loc:8596',website_token:'public'});
|
||||
p.run();assert.equal(p.scripts.length,1);assert.equal(p.scripts[0].src,'http://xb.loc:8596/packs/js/sdk.js');
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(p.context.window.chatwootSettings)), {
|
||||
locale: 'zh_CN', type: 'expanded_bubble', launcherTitle: '联系客服',
|
||||
});
|
||||
p.scripts[0].events.load();
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(p.calls)),[{websiteToken:'public',baseUrl:'http://xb.loc:8596'}]);
|
||||
p.run();assert.equal(p.scripts.length,1);
|
||||
});
|
||||
Vendored
+140
@@ -0,0 +1,140 @@
|
||||
// XB supplies only display settings. No login identity or secrets cross the frame.
|
||||
let config;
|
||||
const trustedParents = new Set(window.xbParentOrigins || [window.xbParentOrigin].filter(Boolean));
|
||||
const fromTrustedParent = event => event.source === parent && trustedParents.has(event.origin);
|
||||
const brandedTitles = new WeakMap();
|
||||
|
||||
function renderSiteTitle(header) {
|
||||
const title = header.querySelector('.text-base.font-medium');
|
||||
if (!title) return;
|
||||
const base = '客服系统';
|
||||
const label = title.querySelector(':scope > span') || title;
|
||||
const node = Array.from(label.childNodes).find(child =>
|
||||
child.nodeType === Node.TEXT_NODE &&
|
||||
(child.data.trim() === base || child.data === brandedTitles.get(child)));
|
||||
if (!node) return;
|
||||
const text = config?.site_name ? config.site_name + base : base;
|
||||
if (node.data !== text) node.data = text;
|
||||
brandedTitles.set(node, text);
|
||||
}
|
||||
function actionIcon(kind){
|
||||
const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');
|
||||
for(const[k,v]of Object.entries({width:'16',height:'16',viewBox:'0 0 24 24',fill:'none',stroke:'currentColor','stroke-width':'1.8','stroke-linecap':'round','stroke-linejoin':'round','aria-hidden':'true'}))svg.setAttribute(k,v);
|
||||
const path=document.createElementNS(svg.namespaceURI,'path');
|
||||
path.setAttribute('d',kind==='jump'?'M15 3h6v6M10 14 21 3M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5':'m9 5 7 7-7 7');
|
||||
svg.append(path);svg.style.cssText='flex:none;vertical-align:middle';return svg;
|
||||
}
|
||||
function render(){
|
||||
if(!window.document)return;
|
||||
for(const header of document.querySelectorAll('header')){
|
||||
renderSiteTitle(header);
|
||||
const availability=header.querySelector('[has-online-agents]');
|
||||
if(!availability)continue;
|
||||
const online=availability.getAttribute('has-online-agents')==='true';
|
||||
for(const dot of header.querySelectorAll('.h-2.w-2.rounded-full'))dot.style.display='none';
|
||||
const actions=header.querySelector('.actions');
|
||||
if(actions){
|
||||
let badge=header.querySelector('[data-xb-presence]');
|
||||
if(!badge){badge=document.createElement('span');badge.setAttribute('role','status');}
|
||||
if(badge.parentElement!==actions)actions.prepend(badge);
|
||||
let label=badge.querySelector('[data-xb-presence-label]');
|
||||
if(!label){
|
||||
label=document.createElement('span');
|
||||
label.dataset.xbPresenceLabel='';
|
||||
badge.replaceChildren(label);
|
||||
}
|
||||
const text=online?'人工在线中':'客服已离线';
|
||||
badge.dataset.xbPresence = online ? 'online' : 'offline';
|
||||
if(label.textContent!==text)label.textContent=text;
|
||||
badge.style.cssText=`font-size:11px;line-height:20px;white-space:nowrap;font-weight:500;padding:2px 7px;border-radius:6px;align-self:center;color:${online?'#087f72':'#68707d'};background:${online?'#e5f6f1':'#f0f1f3'}`;
|
||||
}
|
||||
}
|
||||
for(const subtitle of document.querySelectorAll('header [has-online-agents]'))subtitle.hidden=true;
|
||||
for(const heading of document.querySelectorAll('h3')){
|
||||
if(!['最受欢迎文章','常见问题'].includes(heading.textContent.trim()))continue;
|
||||
if(heading.textContent!=='常见问题')heading.textContent='常见问题';
|
||||
const block=heading.parentElement;
|
||||
for(const button of block.querySelectorAll('button')){
|
||||
if(button.textContent.trim()==='查看所有文章')button.parentElement.style.display='none';
|
||||
}
|
||||
}
|
||||
const buttons=[...document.querySelectorAll('button')].filter(n=>n.dataset.xbLeaveMessage||['继续对话','开始会话'].includes(n.textContent.trim()));
|
||||
for(const button of buttons){
|
||||
const card=button.parentElement;
|
||||
if (!card.hasAttribute('data-xb-support-card')) card.setAttribute('data-xb-support-card', '');
|
||||
for(const label of card.querySelectorAll('div')){
|
||||
if(label.children.length===0&&['在线','客服在线中'].includes(label.textContent.trim()))label.textContent='人工客服在线中';
|
||||
}
|
||||
const title=[...card.querySelectorAll('div')].find(n=>n.children.length===0&&['当前已离线','当前没有在线客服',config?.offline_title].includes(n.textContent.trim()));
|
||||
const old=card.querySelector('[data-xb-offline]');
|
||||
const ticketOld=card.querySelector('[data-xb-ticket]');
|
||||
const span=button.querySelector('span');
|
||||
const icon=button.querySelector('i');
|
||||
if(!title||!config){
|
||||
old?.remove();ticketOld?.remove();
|
||||
if(button.dataset.xbLeaveMessage){
|
||||
if(span)span.textContent=button.dataset.xbLeaveMessage;
|
||||
delete button.dataset.xbLeaveMessage;
|
||||
if(icon)icon.style.display='';
|
||||
button.querySelector('[data-xb-message-icon]')?.remove();
|
||||
}
|
||||
for(const hint of card.querySelectorAll('[data-xb-hidden-hint]')){hint.hidden=false;delete hint.dataset.xbHiddenHint;}
|
||||
continue;
|
||||
}
|
||||
if(title.textContent!==config.offline_title)title.textContent=config.offline_title;
|
||||
const hint=title.nextElementSibling;if(hint){hint.hidden=true;hint.dataset.xbHiddenHint='1';}
|
||||
if(!button.dataset.xbLeaveMessage)button.dataset.xbLeaveMessage=span?.textContent.trim()||button.textContent.trim();
|
||||
if(span&&span.textContent!=='给客服留言')span.textContent='给客服留言';
|
||||
button.querySelector('[data-xb-message-icon]')?.remove();
|
||||
if(icon)icon.style.display='';
|
||||
const section=old||document.createElement('div');section.dataset.xbOffline='1';
|
||||
const signature=JSON.stringify(config);if(section.dataset.signature===signature)continue;
|
||||
section.dataset.signature=signature;section.style.cssText='font-weight:400';section.replaceChildren();
|
||||
if(config.working_hours){const hours=document.createElement('p');hours.className=hint?.className||'text-n-slate-11';hours.style.margin='0';if(hint){const native=getComputedStyle(hint);hours.style.fontSize=native.fontSize;hours.style.lineHeight=native.lineHeight;}hours.textContent='客服在线时间:'+config.working_hours;section.append(hours);}
|
||||
if(!old)card.insertBefore(section,button);
|
||||
const ticket=ticketOld||document.createElement('a');ticket.dataset.xbTicket='1';ticket.href=config.ticket_url;ticket.target='_top';ticket.textContent='到用户中心提交工单';ticket.append(actionIcon('jump'));ticket.style.cssText='color:var(--widget-color,#1f93ff);font-weight:500;line-height:24px;display:inline-flex;align-items:center;gap:6px;width:fit-content';if(!ticketOld)card.append(ticket);
|
||||
}
|
||||
}
|
||||
function isHexColor(value) {
|
||||
return typeof value === 'string' && /^#[\da-f]{6}$/i.test(value);
|
||||
}
|
||||
|
||||
function loadPanelStyle(origin) {
|
||||
if (document.getElementById('xb-support-panel-css')) return;
|
||||
const root = document.documentElement;
|
||||
root.dataset.xbSupportSkin = 'default';
|
||||
const inboxColor = window.chatwootWebChannel?.widgetColor;
|
||||
if (isHexColor(inboxColor)) root.style.setProperty('--xb-support-inbox-color', inboxColor);
|
||||
const link = document.createElement('link');
|
||||
link.id = 'xb-support-panel-css';
|
||||
link.rel = 'stylesheet';
|
||||
link.href = new URL('/customer-service/panel.css?v=1', origin).href;
|
||||
document.head.append(link);
|
||||
}
|
||||
|
||||
window.addEventListener('message',event=>{
|
||||
if(!fromTrustedParent(event)||event.data?.type!=='xb-customer-service')return;
|
||||
const c=event.data;
|
||||
try{const u=new URL(c.ticket_url);if(u.origin!==event.origin)return;}catch{return;}
|
||||
loadPanelStyle(event.origin);
|
||||
let site_icon='';try{const icon=new URL(c.site_icon);if(icon.origin===event.origin&&['http:','https:'].includes(icon.protocol))site_icon=icon.href;}catch{}
|
||||
const site_name = typeof c.site_name === 'string' ? c.site_name.trim().slice(0,60) : '';
|
||||
config={site_name,working_hours:String(c.working_hours||'').slice(0,200),offline_title:String(c.offline_title||'当前没有在线客服').slice(0,100),offline_message:String(c.offline_message||'').slice(0,500),ticket_url:c.ticket_url,site_icon,online_count:Math.max(0,Math.min(3,Number(c.online_count)||0))};render();
|
||||
});
|
||||
new MutationObserver(render).observe(document.documentElement,{childList:true,subtree:true,characterData:true,attributes:true,attributeFilter:['has-online-agents']});
|
||||
|
||||
window.addEventListener('message', event => {
|
||||
if (!fromTrustedParent(event) || event.data?.type !== 'xb-support-theme') return;
|
||||
const { accent, solid, headerTint, dark } = event.data;
|
||||
const root = document.documentElement;
|
||||
if (typeof dark === 'boolean') root.dataset.xbSupportMode = dark ? 'dark' : 'light';
|
||||
if (isHexColor(accent)) {
|
||||
root.dataset.xbSupportCustomColor = '';
|
||||
root.style.setProperty('--xb-support-accent-override', accent);
|
||||
root.style.setProperty('--xb-support-solid-override', isHexColor(solid) ? solid : accent);
|
||||
}
|
||||
if (isHexColor(headerTint)) root.style.setProperty('--xb-support-header-tint', headerTint);
|
||||
});
|
||||
if (parent !== window) {
|
||||
for (const origin of trustedParents) parent.postMessage('xb-support-ready', origin);
|
||||
}
|
||||
+3
-1
@@ -1,2 +1,4 @@
|
||||
*
|
||||
!.gitignore
|
||||
!.gitignore
|
||||
!VipLoyalty/
|
||||
!VipLoyalty/**
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
namespace Plugin\VipLoyalty\Commands;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Plugin\VipLoyalty\Service;
|
||||
final class ImportOpening extends Command {
|
||||
protected $signature='vip:import-opening {file : Private JSONL opening file} {--reference= : Snapshot SHA256}';
|
||||
protected $description='导入已核定VIP期初,不导入旧订单、不改变钱包或套餐';
|
||||
public function handle(Service $service): int {
|
||||
$file=$this->argument('file');$reference=(string)$this->option('reference');
|
||||
if(!is_file($file)||!is_readable($file)||!preg_match('/^[a-f0-9]{64}$/D',$reference)){$this->error('期初文件或快照摘要无效');return self::FAILURE;}
|
||||
$count=0;
|
||||
DB::transaction(function()use($file,$reference,$service,&$count){
|
||||
$f=fopen($file,'r');$seen=[];
|
||||
try {while(($line=fgets($f))!==false){
|
||||
$v=json_decode($line,true,512,JSON_THROW_ON_ERROR);
|
||||
if(!isset($v['user_id'],$v['uuid'],$v['opening_cumulative_cents']) || !is_int($v['user_id']) || !is_int($v['opening_cumulative_cents']) || isset($seen[$v['user_id']]))throw new \RuntimeException('期初字段或用户唯一性检查失败');
|
||||
$seen[$v['user_id']]=true;$service->opening($v['user_id'],$v['uuid'],$v['opening_cumulative_cents'],$reference);++$count;
|
||||
}}finally{fclose($f);}
|
||||
});
|
||||
$this->info('已核对VIP期初 '.$count.' 人;钱包、套餐和历史订单未改变。');return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
namespace Plugin\VipLoyalty\Commands;
|
||||
use Illuminate\Console\Command;
|
||||
use Plugin\VipLoyalty\Service;
|
||||
final class ReverseConsumption extends Command {
|
||||
protected $signature='vip:reverse-consumption {order_id} {amount_cents} {reference}';
|
||||
protected $description='仅登记已完成退款的VIP消费冲回,不执行退款、不动钱包';
|
||||
public function handle(Service $service): int {
|
||||
if(!ctype_digit($this->argument('order_id')) || !ctype_digit($this->argument('amount_cents'))) {$this->error('订单及金额须为正整数');return self::FAILURE;}
|
||||
$service->reverse((int)$this->argument('order_id'),(int)$this->argument('amount_cents'),$this->argument('reference'));
|
||||
$this->info('VIP消费已核对冲回;未执行付款或钱包退款。');return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
namespace Plugin\VipLoyalty\Controllers;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Order;
|
||||
use App\Models\Plugin;
|
||||
use App\Services\Plugin\PluginConfigService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\{DB,Schema};
|
||||
use Plugin\VipLoyalty\{Service,Settings};
|
||||
final class VipController extends Controller {
|
||||
public function show(Request $request,Service $service) {return $this->success($service->summary($request->user()->id));}
|
||||
public function orderDiscount(Request $request)
|
||||
{
|
||||
$validated = $request->validate(['trade_no' => 'required|string|max:64']);
|
||||
$order = Order::where('user_id', $request->user()->id)
|
||||
->where('trade_no', $validated['trade_no'])->firstOrFail(['id']);
|
||||
if (!Schema::hasTable('fuc_order_discounts')) {
|
||||
return $this->success(null);
|
||||
}
|
||||
$columns = ['original_amount', 'member_amount', 'coupon_amount', 'member_percent', 'coupon_code'];
|
||||
if (Schema::hasColumn('fuc_order_discounts', 'coupon_type')) {
|
||||
$columns[] = 'coupon_type';
|
||||
}
|
||||
$breakdown = DB::table('fuc_order_discounts')->where('order_id', $order->id)->first($columns);
|
||||
return $this->success($breakdown);
|
||||
}
|
||||
public function settings(Settings $settings) {return $this->success($settings->values());}
|
||||
public function save(Request $request,Settings $settings,Service $service) {
|
||||
$current=json_decode(Plugin::where('code','vip_loyalty')->value('config')??'{}',true)?:[];
|
||||
$values=$settings->validate(array_replace($current,$request->only(array_keys(Settings::DEFAULTS))));
|
||||
app(PluginConfigService::class)->updateConfig('vip_loyalty',$values);
|
||||
if(!$values['enabled'])$service->suspend();
|
||||
return $this->success($settings->values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace Plugin\VipLoyalty;
|
||||
|
||||
use App\Models\Coupon;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Support\Facades\{DB,Schema};
|
||||
|
||||
final class OrderDiscounts
|
||||
{
|
||||
public function record(Order $order): void
|
||||
{
|
||||
$total = (float) $order->discount_amount;
|
||||
if ($total <= 0 && !$order->coupon_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
$price = $order->plan()->first()?->prices[$order->period] ?? null;
|
||||
$percent = (int) $order->user()->value('discount');
|
||||
$coupon = $order->coupon_id ? Coupon::find($order->coupon_id) : null;
|
||||
if ($price === null || ($order->coupon_id && !$coupon)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$original = (int) ($price * 100);
|
||||
$couponAmount = match ((int) $coupon?->type) {
|
||||
1 => (float) $coupon->value,
|
||||
2 => $original * ((float) $coupon->value / 100),
|
||||
default => 0,
|
||||
};
|
||||
$couponAmount = min($original, $couponAmount);
|
||||
$memberAmount = $original * ($percent / 100);
|
||||
// Capture only a breakdown that reconciles to this creation's XB values.
|
||||
if ($couponAmount < 0 || $percent < 0 || $percent > 100 ||
|
||||
abs($total - $couponAmount - $memberAmount) > 0.000001) {
|
||||
return;
|
||||
}
|
||||
|
||||
$savedTotal = (int) round((float) $order->fresh()->discount_amount);
|
||||
$couponCents = (int) round($couponAmount);
|
||||
if ($savedTotal < $couponCents) {
|
||||
return;
|
||||
}
|
||||
$breakdown = [
|
||||
'order_id' => $order->id,
|
||||
'original_amount' => $original,
|
||||
'member_amount' => $savedTotal - $couponCents,
|
||||
'coupon_amount' => $couponCents,
|
||||
'member_percent' => $percent,
|
||||
'coupon_code' => $coupon?->code,
|
||||
];
|
||||
if ($coupon && Schema::hasColumn('fuc_order_discounts', 'coupon_type')) {
|
||||
$breakdown['coupon_type'] = (int) $coupon->type;
|
||||
}
|
||||
DB::table('fuc_order_discounts')->insertOrIgnore($breakdown);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
namespace Plugin\VipLoyalty;
|
||||
use App\Services\Plugin\AbstractPlugin;
|
||||
use Illuminate\Support\Facades\{Log,Schema};
|
||||
use Illuminate\Validation\ValidationException;
|
||||
final class Plugin extends AbstractPlugin {
|
||||
public function boot(): void {
|
||||
if(!Schema::hasTable('fuc_vip_accounts'))return;
|
||||
$service=app(Service::class);
|
||||
try {$enabled=$service->enabled();}
|
||||
catch(ValidationException $e) {
|
||||
// An enabled but corrupt policy must not silently lose paid consumption.
|
||||
// Hooks below reject new creation/opening until an administrator repairs it.
|
||||
Log::warning('vip_loyalty_invalid_configuration');$enabled=true;
|
||||
}
|
||||
if(!$enabled){$service->suspend();return;}
|
||||
$this->listen('order.create.before',static function($payload)use($service){$service->sync($payload[0]->id);});
|
||||
if (Schema::hasTable('fuc_order_discounts')) {
|
||||
$this->listen('order.create.after', [app(OrderDiscounts::class), 'record']);
|
||||
}
|
||||
$this->listen('order.open.before',[$service,'openingOrder']);
|
||||
$this->listen('admin.user.update.after',[$service,'manualChanged']);
|
||||
}
|
||||
public function cleanup(): void {
|
||||
if(Schema::hasTable('fuc_vip_accounts'))app(Service::class)->suspend();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
namespace Plugin\VipLoyalty\Providers;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use App\Services\Plugin\PluginConfigService;
|
||||
use Plugin\VipLoyalty\ValidatedConfigService;
|
||||
final class PluginServiceProvider extends ServiceProvider {
|
||||
public function register(): void {
|
||||
$this->app->bind(PluginConfigService::class,ValidatedConfigService::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# VIP 自动升级
|
||||
|
||||
默认关闭,安装后还需明确开启插件及“开启 VIP 自动升级”。只影响当前实例。
|
||||
|
||||
默认满100/200/360元,分别享9.2/8.8/8.5折;可修改门槛和优惠。套餐实际付款在开通成功后累计,升级用于下一单。充值、佣金转余额、取消和流量重置不计。原生人工优惠保留,关闭VIP恢复人工优惠、保留累计。
|
||||
|
||||
用户中心显示原版会员名称、累计和升级差额。保存配置验证门槛/优惠有效,不改变XB支付、钱包、折抵或返佣算法。
|
||||
|
||||
迁移期初导入、消费冲回、实例隔离、本地验证和恢复见仓库维护文档 `docs/maintenance/FUC_VIP.md`。冲回命令只登记已实际退款后的VIP消费扣减,不执行钱包退款。
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
namespace Plugin\VipLoyalty;
|
||||
use App\Models\{User,Order,Plan};
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
final class Service {
|
||||
public function __construct(private Settings $settings) {}
|
||||
public function enabled(): bool { return $this->settings->values()['enabled']; }
|
||||
private function account(User $user): object {
|
||||
DB::table('fuc_vip_accounts')->insertOrIgnore(['user_id'=>$user->id,'opening_cents'=>0,'cumulative_cents'=>0,'manual_discount'=>$user->discount,
|
||||
'created_at'=>time(),'updated_at'=>time()]);
|
||||
return DB::table('fuc_vip_accounts')->where('user_id',$user->id)->lockForUpdate()->first();
|
||||
}
|
||||
private function apply(User $user,object $account): object {
|
||||
$manual=$account->manual_discount;
|
||||
// Respect a native admin discount edit since our last write.
|
||||
if($account->applied_discount!==null && (int)$user->discount!==(int)$account->applied_discount)$manual=$user->discount;
|
||||
$vip=0;foreach($this->settings->levels() as $tier)if($account->cumulative_cents >= $tier['threshold_cents'])$vip=$tier['discount'];
|
||||
$effective=max((int)$manual,$vip);
|
||||
$user->discount=$effective;$user->save();
|
||||
DB::table('fuc_vip_accounts')->where('user_id',$user->id)->update(['manual_discount'=>$manual,'applied_discount'=>$effective,'updated_at'=>time()]);
|
||||
$account->manual_discount=$manual;$account->applied_discount=$effective;
|
||||
return $account;
|
||||
}
|
||||
public function sync(int $userId): ?object {
|
||||
if(!$this->enabled())return null;
|
||||
return DB::transaction(function()use($userId){
|
||||
$user=User::whereKey($userId)->lockForUpdate()->firstOrFail();
|
||||
return $this->apply($user,$this->account($user));
|
||||
});
|
||||
}
|
||||
public function opening(int $userId,string $uuid,int $cents,string $reference): void {
|
||||
if(!$this->enabled())throw new \RuntimeException('VIP未在当前实例启用');
|
||||
if($cents<0 || !preg_match('/^[a-f0-9]{64}$/D',$reference))throw new \InvalidArgumentException('Invalid opening');
|
||||
DB::transaction(function()use($userId,$uuid,$cents,$reference){
|
||||
$user=User::whereKey($userId)->lockForUpdate()->firstOrFail();
|
||||
if(!hash_equals($user->uuid,$uuid))throw new \RuntimeException('迁移用户UUID不一致');
|
||||
$account=$this->account($user);
|
||||
if($account->opening_reference!==null) {
|
||||
if($account->opening_reference!==$reference || (int)$account->opening_cents!==$cents)throw new \RuntimeException('期初已存在且不同,禁止覆盖');
|
||||
return;
|
||||
}
|
||||
if(DB::table('fuc_vip_entries')->where('user_id',$userId)->where('kind','!=','opening')->exists())throw new \RuntimeException('用户已有新消费,禁止补写期初');
|
||||
DB::table('fuc_vip_entries')->insert(['user_id'=>$userId,'entry_key'=>'opening:'.$userId,'kind'=>'opening','amount_cents'=>$cents,'created_at'=>time()]);
|
||||
// Migrated discount is old VIP, not an unrelated native manual discount.
|
||||
DB::table('fuc_vip_accounts')->where('user_id',$userId)->update(['opening_cents'=>$cents,'cumulative_cents'=>$cents,'manual_discount'=>null,'applied_discount'=>$user->discount,'opening_reference'=>$reference]);
|
||||
$account=DB::table('fuc_vip_accounts')->where('user_id',$userId)->first();$this->apply($user,$account);
|
||||
});
|
||||
}
|
||||
public function openingOrder(Order $order): void {
|
||||
if(!$this->enabled())return;
|
||||
if(DB::transactionLevel()<1)throw new \RuntimeException('VIP累计必须与开通同事务');
|
||||
if((int)$order->status!==Order::STATUS_PROCESSING || !in_array($order->period,[Plan::PERIOD_MONTHLY,Plan::PERIOD_QUARTERLY,Plan::PERIOD_HALF_YEARLY,Plan::PERIOD_YEARLY,Plan::PERIOD_TWO_YEARLY,Plan::PERIOD_THREE_YEARLY,Plan::PERIOD_ONETIME],true))return;
|
||||
$user=User::whereKey($order->user_id)->lockForUpdate()->firstOrFail();$account=$this->account($user);
|
||||
$key='purchase:'.$order->id;
|
||||
if(DB::table('fuc_vip_entries')->where('entry_key',$key)->exists())return;
|
||||
$amount=(int)$order->total_amount+(int)$order->balance_amount;
|
||||
if($amount<0)throw new \RuntimeException('套餐消费金额不能为负');
|
||||
DB::table('fuc_vip_entries')->insert(['user_id'=>$user->id,'order_id'=>$order->id,'entry_key'=>$key,'kind'=>'purchase','amount_cents'=>$amount,'created_at'=>time()]);
|
||||
$account->cumulative_cents+=(int)$amount;
|
||||
DB::table('fuc_vip_accounts')->where('user_id',$user->id)->update(['cumulative_cents'=>$account->cumulative_cents]);
|
||||
$this->apply($user,$account);
|
||||
}
|
||||
public function reverse(int $orderId,int $cents,string $reference): void {
|
||||
if(!$this->enabled())throw new \RuntimeException('VIP未启用');
|
||||
if($cents<=0 || !preg_match('/^[A-Za-z0-9_-]{1,80}$/D',$reference))throw new \InvalidArgumentException('Invalid reversal');
|
||||
DB::transaction(function()use($orderId,$cents,$reference){
|
||||
$order=Order::whereKey($orderId)->lockForUpdate()->firstOrFail();
|
||||
$user=User::whereKey($order->user_id)->lockForUpdate()->firstOrFail();$account=$this->account($user);
|
||||
$key='refund:'.$reference;
|
||||
$existing=DB::table('fuc_vip_entries')->where('entry_key',$key)->first();
|
||||
if($existing) {
|
||||
if((int)$existing->order_id!==$orderId || -(int)$existing->amount_cents!==$cents)throw new \RuntimeException('退款凭证已用于其他金额或订单');
|
||||
return;
|
||||
}
|
||||
$paid=DB::table('fuc_vip_entries')->where('entry_key','purchase:'.$orderId)->value('amount_cents');
|
||||
$reversed=-(int)DB::table('fuc_vip_entries')->where('order_id',$orderId)->where('kind','refund')->sum('amount_cents');
|
||||
if($paid===null || $cents>(int)$paid-$reversed)throw ValidationException::withMessages(['amount'=>'VIP冲回超过已计入且未冲回的消费']);
|
||||
DB::table('fuc_vip_entries')->insert(['user_id'=>$user->id,'order_id'=>$orderId,'entry_key'=>$key,'kind'=>'refund','amount_cents'=>-$cents,'created_at'=>time()]);
|
||||
$account->cumulative_cents=max(0,(int)$account->cumulative_cents-$cents);
|
||||
DB::table('fuc_vip_accounts')->where('user_id',$user->id)->update(['cumulative_cents'=>$account->cumulative_cents]);
|
||||
$this->apply($user,$account);
|
||||
});
|
||||
}
|
||||
public function suspend(): void {
|
||||
// Disable changes discounts only; keep the independent consumption audit intact.
|
||||
DB::table('fuc_vip_accounts')->whereNotNull('applied_discount')->orderBy('user_id')->chunkById(200,function($rows){
|
||||
foreach($rows as $row)DB::transaction(function()use($row){
|
||||
$user=User::whereKey($row->user_id)->lockForUpdate()->first();
|
||||
$account=DB::table('fuc_vip_accounts')->where('user_id',$row->user_id)->lockForUpdate()->first();
|
||||
if(!$user || $account->applied_discount===null)return;
|
||||
if((int)$user->discount===(int)$account->applied_discount){$user->discount=$account->manual_discount;$user->save();}
|
||||
DB::table('fuc_vip_accounts')->where('user_id',$row->user_id)->update(['applied_discount'=>null]);
|
||||
});
|
||||
},'user_id');
|
||||
}
|
||||
public function manualChanged(array $payload): void {
|
||||
if(!$this->enabled() || !array_key_exists('discount',$payload['params']??[]))return;
|
||||
$id=$payload['user']->id;
|
||||
DB::transaction(function()use($id,$payload){
|
||||
$user=User::whereKey($id)->lockForUpdate()->firstOrFail();$account=$this->account($user);
|
||||
DB::table('fuc_vip_accounts')->where('user_id',$id)->update(['manual_discount'=>$payload['params']['discount'],'applied_discount'=>$user->discount]);
|
||||
$account->manual_discount=$payload['params']['discount'];$account->applied_discount=$user->discount;
|
||||
$this->apply($user,$account);
|
||||
});
|
||||
}
|
||||
public function summary(int $userId): array {
|
||||
if(!$this->enabled())return ['enabled'=>false];
|
||||
$a=$this->sync($userId);$levels=$this->settings->levels();$current=0;$next=null;
|
||||
foreach($levels as $tier) {if($a->cumulative_cents >= $tier['threshold_cents'])$current=$tier['level'];elseif($next===null)$next=$tier;}
|
||||
return ['enabled'=>true,'cumulative_cents'=>(int)$a->cumulative_cents,'level'=>$current,'name'=>$current?$levels[$current-1]['name']:'普通用户','discount_percent'=>(int)$a->applied_discount,
|
||||
'next_level'=>$next,'remaining_cents'=>$next?max(0,$next['threshold_cents']-(int)$a->cumulative_cents):0,'levels'=>$levels];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
namespace Plugin\VipLoyalty;
|
||||
use App\Models\Plugin;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
final class Settings {
|
||||
public const DEFAULTS=['enabled'=>false,'tier1_amount'=>100,'tier1_discount'=>8,'tier2_amount'=>200,'tier2_discount'=>12,'tier3_amount'=>360,'tier3_discount'=>15];
|
||||
public function values(): array {
|
||||
$plugin=Plugin::where('code','vip_loyalty')->first();
|
||||
$values=array_replace(self::DEFAULTS,json_decode($plugin?->config??'{}',true)?:[]);
|
||||
$values['enabled']=(bool)($plugin?->is_enabled) && filter_var($values['enabled'],FILTER_VALIDATE_BOOL);
|
||||
return $values['enabled']?$this->validate($values):$values;
|
||||
}
|
||||
public function validate(array $values): array {
|
||||
$values=array_replace(self::DEFAULTS,$values);
|
||||
$rules=['enabled'=>'required|boolean'];
|
||||
for($i=1;$i<=3;$i++) {
|
||||
$rules['tier'.$i.'_amount']='required|numeric|min:0.01|max:100000000|decimal:0,2';
|
||||
$rules['tier'.$i.'_discount']='required|integer|min:0|max:100';
|
||||
}
|
||||
Validator::make($values,$rules)->after(function($validator)use($values){
|
||||
if($validator->errors()->isNotEmpty())return;
|
||||
for($i=2;$i<=3;$i++)if((float)$values['tier'.$i.'_amount']<=(float)$values['tier'.($i-1).'_amount'] || (int)$values['tier'.$i.'_discount']<(int)$values['tier'.($i-1).'_discount'])$validator->errors()->add('tiers','VIP门槛须递增,优惠不能降低');
|
||||
})->validate();
|
||||
return array_intersect_key($values,self::DEFAULTS);
|
||||
}
|
||||
public function levels(?array $values=null): array {
|
||||
$values??=$this->values();$levels=[];
|
||||
for($i=1;$i<=3;$i++)$levels[]=['level'=>$i,'name'=>[1=>'小福',2=>'中福',3=>'大福'][$i],'threshold_cents'=>(int)round((float)$values['tier'.$i.'_amount']*100),'discount'=>(int)$values['tier'.$i.'_discount']];
|
||||
return $levels;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
namespace Plugin\VipLoyalty;
|
||||
use App\Services\Plugin\PluginConfigService;
|
||||
// Keep the native administrator plugin editor; validate only this plugin's payload.
|
||||
final class ValidatedConfigService extends PluginConfigService {
|
||||
public function updateConfig(string $pluginCode,array $config): bool {
|
||||
if($pluginCode!=='vip_loyalty')return parent::updateConfig($pluginCode,$config);
|
||||
$values=app(Settings::class)->validate(array_replace($this->getDbConfig($pluginCode),$config));
|
||||
$saved=parent::updateConfig($pluginCode,$values);
|
||||
if(!$values['enabled'])app(Service::class)->suspend();
|
||||
return $saved;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "VIP 自动升级",
|
||||
"code": "vip_loyalty",
|
||||
"version": "1.0.2",
|
||||
"description": "按实际套餐消费自动升级;独立实例开关,默认关闭。",
|
||||
"author": "XB",
|
||||
"type": "feature",
|
||||
"config": {
|
||||
"enabled": {"type":"boolean","default":false,"label":"开启 VIP 自动升级","description":"仅对当前实例生效;其他实例默认关闭。"},
|
||||
"tier1_amount": {"type":"number","default":100,"label":"VIP 1 累计门槛(元)"},
|
||||
"tier1_discount": {"type":"number","default":8,"label":"VIP 1 优惠百分比","description":"8 表示减 8%,即 9.2 折"},
|
||||
"tier2_amount": {"type":"number","default":200,"label":"VIP 2 累计门槛(元)"},
|
||||
"tier2_discount": {"type":"number","default":12,"label":"VIP 2 优惠百分比"},
|
||||
"tier3_amount": {"type":"number","default":360,"label":"VIP 3 累计门槛(元)"},
|
||||
"tier3_discount": {"type":"number","default":15,"label":"VIP 3 优惠百分比"}
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
<?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::create('fuc_vip_accounts', function(Blueprint $t) {
|
||||
$t->unsignedBigInteger('user_id')->primary();
|
||||
$t->bigInteger('opening_cents')->default(0);
|
||||
$t->bigInteger('cumulative_cents')->default(0);
|
||||
$t->unsignedTinyInteger('manual_discount')->nullable();
|
||||
$t->unsignedTinyInteger('applied_discount')->nullable();
|
||||
$t->string('opening_reference',64)->nullable();
|
||||
$t->bigInteger('created_at');$t->bigInteger('updated_at');
|
||||
});
|
||||
Schema::create('fuc_vip_entries', function(Blueprint $t) {
|
||||
$t->id();$t->unsignedBigInteger('user_id')->index();
|
||||
$t->unsignedBigInteger('order_id')->nullable()->index();
|
||||
$t->string('entry_key',191)->unique();
|
||||
$t->string('kind',16);$t->bigInteger('amount_cents');
|
||||
$t->bigInteger('created_at');
|
||||
});
|
||||
}
|
||||
public function down(): void {
|
||||
Schema::dropIfExists('fuc_vip_entries');Schema::dropIfExists('fuc_vip_accounts');
|
||||
}
|
||||
};
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
<?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::create('fuc_order_discounts', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('order_id')->primary();
|
||||
$table->unsignedBigInteger('original_amount');
|
||||
$table->unsignedBigInteger('member_amount');
|
||||
$table->unsignedBigInteger('coupon_amount');
|
||||
$table->unsignedTinyInteger('member_percent');
|
||||
$table->string('coupon_code')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('fuc_order_discounts');
|
||||
}
|
||||
};
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
<?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('fuc_order_discounts', function (Blueprint $table) {
|
||||
$table->unsignedTinyInteger('coupon_type')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('fuc_order_discounts', function (Blueprint $table) {
|
||||
$table->dropColumn('coupon_type');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Plugin\VipLoyalty\Controllers\VipController;
|
||||
Route::middleware('user')->get('/api/v1/user/vip',[VipController::class,'show']);
|
||||
Route::middleware('user')->get('/api/v1/user/vip/order-discount',[VipController::class,'orderDiscount']);
|
||||
$secure=admin_setting('secure_path',admin_setting('frontend_admin_path',hash('crc32b',config('app.key'))));
|
||||
Route::middleware('admin')->prefix('/api/v2/'.$secure.'/vip')->group(function(){
|
||||
Route::get('/',[VipController::class,'settings']);Route::post('/',[VipController::class,'save']);
|
||||
});
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
const form=document.getElementById('support-settings');
|
||||
async function api(payload){let token;try{token=JSON.parse(localStorage.getItem('XBOARD_ACCESS_TOKEN')||'null');}catch{}if(!token?.value)throw Error('请先登录XB后台,再打开客服系统。');const r=await fetch('/api/v2/'+encodeURIComponent(window.settings.secure_path)+'/config/customerService',{method:payload?'POST':'GET',headers:{Authorization:token.value,'Content-Type':'application/json'},...(payload?{body:JSON.stringify(payload)}:{})});const j=await r.json();if(!r.ok)throw Error(j.message||'保存失败');return j.data;}
|
||||
const fields=[['enabled','启用在线客服','checkbox'],['base_url','客服服务地址','url'],['website_token','网站标识','text'],['working_hours','客服在线时间','text'],['offline_title','离线标题','text'],['offline_message','离线留言提示','textarea'],['ticket_url','用户中心工单入口','text'],['telegram_enabled','启用 Telegram 接待','checkbox'],['telegram_bot_code','TeleHub 机器人代号','text'],['telegram_target_code','TeleHub 接收目标代号','text']];
|
||||
try{const data=await api();form.replaceChildren();const controls={};for(const[key,title,type]of fields){const label=document.createElement('label');label.textContent=title;const input=document.createElement(type==='textarea'?'textarea':'input');if(type!=='textarea')input.type=type;input.name=key;if(type==='checkbox')input.checked=!!data[key];else input.value=data[key]??'';label.append(input);form.append(label);controls[key]=input;}const save=document.createElement('button');save.type='submit';save.textContent='保存客服设置';const message=document.createElement('p');message.setAttribute('role','status');form.append(save,message);form.addEventListener('submit',async e=>{e.preventDefault();save.disabled=true;try{const payload={};for(const[k,,t]of fields)payload[k]=t==='checkbox'?controls[k].checked:controls[k].value;await api(payload);message.textContent='已保存';}catch(err){message.textContent=err.message;}finally{save.disabled=false;}});}catch(err){form.textContent=err.message;}
|
||||
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
/* Shared layout for the Chatwoot launcher. Colors are supplied by the widget or theme. */
|
||||
:root {
|
||||
--xb-support-button-height: 48px;
|
||||
--xb-support-bottom-gap: 24px;
|
||||
--xb-support-panel-gap: 12px;
|
||||
}
|
||||
|
||||
#cw-bubble-holder > button.woot-widget-bubble {
|
||||
box-shadow: 0 8px 24px color-mix(in srgb, var(--xb-support-launcher-shadow-color, #0f172a) 32%, transparent);
|
||||
}
|
||||
|
||||
#cw-bubble-holder > .woot--close {
|
||||
width: var(--xb-support-button-height) !important;
|
||||
height: var(--xb-support-button-height) !important;
|
||||
}
|
||||
|
||||
/* Center the SDK's native 24px strokes in the smaller circle. */
|
||||
#cw-bubble-holder > .woot--close::before,
|
||||
#cw-bubble-holder > .woot--close::after {
|
||||
left: 50%;
|
||||
top: calc(50% - 12px);
|
||||
}
|
||||
|
||||
@media (min-width: 668px) {
|
||||
#cw-bubble-holder > .woot-widget-bubble:not(.woot--hide) {
|
||||
bottom: var(--xb-support-bottom-gap);
|
||||
}
|
||||
|
||||
body > .woot-widget-holder.woot-elements--right:not(.woot--hide) {
|
||||
bottom: calc(var(--xb-support-bottom-gap) + var(--xb-support-button-height) + var(--xb-support-panel-gap));
|
||||
}
|
||||
}
|
||||
|
||||
#cw-bubble-holder .woot-widget--expanded #woot-widget-bubble-icon {
|
||||
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M20.8 11.2a7.4 7.4 0 0 1-7.4 7.4H8.8l-5.6 2.2 1.5-4.7a7.4 7.4 0 0 1 5.9-12.3h2.8a7.4 7.4 0 0 1 7.4 7.4Z' transform='translate(24 0) scale(-1 1)' fill='none' stroke='white' stroke-width='1.8' stroke-linejoin='round'/%3E%3Cg fill='white'%3E%3Ccircle cx='8' cy='11.2' r='1.1'/%3E%3Ccircle cx='12' cy='11.2' r='1.1'/%3E%3Ccircle cx='16' cy='11.2' r='1.1'/%3E%3C/g%3E%3C/svg%3E") center / contain no-repeat;
|
||||
}
|
||||
|
||||
#cw-bubble-holder .woot-widget--expanded #woot-widget-bubble-icon > path {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
#cw-bubble-holder #woot-widget--expanded__text {
|
||||
font-family: "Nunito", "Segoe UI", arial;
|
||||
font-size: 15.4px;
|
||||
font-weight: 400;
|
||||
line-height: 1.45;
|
||||
letter-spacing: .01rem;
|
||||
}
|
||||
Vendored
+151
@@ -0,0 +1,151 @@
|
||||
/* Shared XB chat panel. The inbox supplies the default brand color. */
|
||||
:root[data-xb-support-skin] {
|
||||
--xb-support-brand: var(--xb-support-inbox-color, var(--widget-color, #1f93ff));
|
||||
--xb-support-accent: var(--xb-support-accent-override, var(--xb-support-brand));
|
||||
--xb-support-solid: var(--xb-support-solid-override, var(--xb-support-brand));
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin][data-xb-support-custom-color] {
|
||||
--widget-color: var(--xb-support-accent-override) !important;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin]:is([data-xb-support-mode='dark'], .dark:not([data-xb-support-mode='light'])) {
|
||||
--xb-support-surface: 40 48 70;
|
||||
--xb-support-paper: 22 29 49;
|
||||
--xb-support-line: 59 66 83;
|
||||
--xb-support-ink: 237 239 245;
|
||||
--xb-support-tint: var(--xb-support-header-tint, #303754);
|
||||
--background-color: var(--xb-support-surface);
|
||||
--solid-1: var(--xb-support-paper);
|
||||
--solid-2: var(--xb-support-surface);
|
||||
--solid-3: var(--xb-support-surface);
|
||||
--slate-2: var(--xb-support-paper);
|
||||
--slate-3: var(--xb-support-line);
|
||||
--slate-4: var(--xb-support-line);
|
||||
--slate-6: var(--xb-support-line);
|
||||
--slate-9: 151 161 182;
|
||||
--slate-10: 180 188 205;
|
||||
--slate-11: 180 188 205;
|
||||
--slate-12: var(--xb-support-ink);
|
||||
--border-container: var(--xb-support-line);
|
||||
--border-strong: var(--xb-support-line);
|
||||
--border-weak: var(--xb-support-line);
|
||||
color: rgb(var(--xb-support-ink));
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin]:is([data-xb-support-mode='dark'], .dark:not([data-xb-support-mode='light'])) #app header {
|
||||
color: rgb(var(--xb-support-ink));
|
||||
background: linear-gradient(120deg, var(--xb-support-tint), rgb(var(--xb-support-surface)));
|
||||
border-bottom: 1px solid rgb(var(--xb-support-line));
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin]:is([data-xb-support-mode='dark'], .dark:not([data-xb-support-mode='light'])) #app .shadow.outline-n-container {
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 14px rgb(15 23 42 / 9%);
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] #app .justify-end:has(> .outline-n-container) {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] [data-xb-presence] {
|
||||
color: rgb(var(--slate-11)) !important;
|
||||
background: rgb(var(--solid-2)) !important;
|
||||
border: 1px solid rgb(var(--border-container));
|
||||
border-radius: 999px !important;
|
||||
padding-inline: 9px !important;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] [data-xb-presence='online'] {
|
||||
--xb-presence-surface: #f4f5f7;
|
||||
--xb-presence-dot: #16a35f;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: #384150 !important;
|
||||
background: var(--xb-presence-surface) !important;
|
||||
border-color: #dfe3e9;
|
||||
font-weight: 600 !important;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] [data-xb-presence='online']::before {
|
||||
content: '';
|
||||
inline-size: 6px;
|
||||
block-size: 6px;
|
||||
flex: none;
|
||||
border-radius: 50%;
|
||||
color: var(--xb-presence-dot);
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin]:is([data-xb-support-mode='dark'], .dark:not([data-xb-support-mode='light'])) [data-xb-presence='online'] {
|
||||
--xb-presence-surface: #262b36;
|
||||
--xb-presence-dot: #70e6aa;
|
||||
color: #e1e5ec !important;
|
||||
border-color: #3c4452;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] #app .chat-bubble.user {
|
||||
background: var(--xb-support-solid) !important;
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] #app .chat-bubble.agent a.link {
|
||||
color: var(--xb-support-accent);
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] #app .chat-bubble.user a.link {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] #app footer > div:has(.user-message-input) {
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 0 0 1px rgb(var(--border-container)) !important;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] #app footer > div:has(.user-message-input):focus-within {
|
||||
box-shadow: 0 0 0 1px var(--xb-support-accent),
|
||||
0 0 0 3px color-mix(in srgb, var(--xb-support-accent) 20%, transparent) !important;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] #app .user-message-input::placeholder {
|
||||
color: rgb(var(--slate-9));
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] #app [data-xb-support-card] :is(button, a) {
|
||||
color: var(--xb-support-accent) !important;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] .unread-wrap .row--agent-block > .company--name {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] .unread-wrap .close-unread-wrap {
|
||||
margin-block-end: 12px;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] .unread-wrap .unread-messages {
|
||||
/* Keep the shadow inside the scrollable list without adding to the gap. */
|
||||
padding-block-end: 12px;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] .unread-wrap .unread-messages > .chat-bubble-wrap:last-child,
|
||||
:root[data-xb-support-skin] .unread-wrap .unread-messages > .chat-bubble-wrap:last-child > .chat-bubble,
|
||||
:root[data-xb-support-skin] .unread-wrap .close-unread-button {
|
||||
margin-block-end: 0;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] .unread-wrap :is(.close-unread-wrap, .open-read-view-wrap, .unread-messages > .chat-bubble-wrap:last-child) {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] .unread-wrap .open-read-view-wrap .clear-button {
|
||||
display: flex;
|
||||
margin-inline-start: 0;
|
||||
padding-inline-end: 0;
|
||||
}
|
||||
|
||||
:root[data-xb-support-skin] .unread-wrap .open-read-view-wrap .clear-button > span {
|
||||
color: var(--xb-support-accent) !important;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
const c = window.xbCustomerService;
|
||||
if (c?.enabled && c.base_url && c.website_token && !window.__xbCustomerServiceLoaded) {
|
||||
let origin;
|
||||
try {
|
||||
const u=new URL(c.base_url);
|
||||
if(!['http:','https:'].includes(u.protocol)||u.username||u.password||u.pathname!=='/'||u.search||u.hash||(location.protocol==='https:'&&u.protocol!=='https:'))throw Error();
|
||||
origin=u.origin;
|
||||
} catch {}
|
||||
if(origin){
|
||||
window.__xbCustomerServiceLoaded=true;
|
||||
window.chatwootSettings = {
|
||||
locale: 'zh_CN',
|
||||
type: 'expanded_bubble',
|
||||
launcherTitle: '联系客服',
|
||||
};
|
||||
function configure() {
|
||||
const frame = document.getElementById('chatwoot_live_chat_widget');
|
||||
frame?.contentWindow?.postMessage({
|
||||
type: 'xb-customer-service',
|
||||
site_name: window.settings?.title,
|
||||
online_count: c.online_count,
|
||||
working_hours: c.working_hours,
|
||||
offline_title: c.offline_title,
|
||||
offline_message: c.offline_message,
|
||||
site_icon: document.querySelector?.('link[rel~="icon"]')?.href || '',
|
||||
ticket_url: new URL(c.ticket_url, location.origin).href,
|
||||
}, origin);
|
||||
}
|
||||
window.addEventListener('message',e=>{if(e.origin===origin&&e.source===document.getElementById('chatwoot_live_chat_widget')?.contentWindow)configure();});
|
||||
const script=document.createElement('script');script.src=origin+'/packs/js/sdk.js';script.async=true;script.referrerPolicy='origin';
|
||||
script.addEventListener('load',()=>{window.chatwootSDK?.run({websiteToken:c.website_token,baseUrl:origin});const observer=new MutationObserver(configure);observer.observe(document.body,{childList:true,subtree:true});configure();window.setInterval?.(async()=>{if(document.visibilityState==='hidden')return;try{const r=await fetch('/customer-service/status',{cache:'no-store',credentials:'omit'});if(!r.ok)return;const s=await r.json();if(Number.isInteger(s.online_count)&&s.online_count>=0&&s.online_count<=3&&c.online_count!==s.online_count){c.online_count=s.online_count;configure();}}catch{}},15000);});
|
||||
script.addEventListener('error',()=>{window.__xbCustomerServiceLoaded=false;});document.head.append(script);
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,7 @@
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<nav style="padding:8px 20px;text-align:right"><a href="/{{ $secure_path }}/customer-service">客服系统</a></nav>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/admin-custom/plan-device-display.js?v={{ filemtime(public_path('admin-custom/plan-device-display.js')) }}"></script>
|
||||
<script type="module" src="/admin-custom/mail-flow.js?v={{ filemtime(public_path('admin-custom/mail-flow.js')) }}"></script>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>客服系统 · {{ config('app.name') }}</title><style>body{font:15px system-ui;background:#f5f6f8;color:#222;margin:0}main{max-width:760px;margin:32px auto;padding:28px;background:white;border-radius:12px}label{display:block;margin:18px 0}input:not([type=checkbox]),textarea{display:block;box-sizing:border-box;width:100%;padding:10px;margin-top:6px;border:1px solid #ccc;border-radius:6px;font:inherit}button{padding:10px 24px;cursor:pointer}p{line-height:1.6;color:#555}</style><script>window.settings={secure_path:@json(admin_setting('secure_path', 'dove'))};</script></head><body><main><a href="/{{ admin_setting('secure_path','dove') }}">返回后台</a><h1>客服系统</h1><p>配置当前站点的在线客服、离线提示和 Telegram 接待。</p><form id="support-settings"><p>正在读取配置…</p></form></main><script type="module" src="/admin-custom/customer-service.js?v=1"></script></body></html>
|
||||
+17
-1
@@ -19,6 +19,12 @@ use Illuminate\Support\Facades\File;
|
||||
*/
|
||||
|
||||
|
||||
Route::get('/customer-service/status', function () {
|
||||
$config=app(\App\Services\CustomerService\Settings::class)->publicConfig();
|
||||
return response()->json(['online_count'=>$config['enabled']?$config['online_count']:0])
|
||||
->header('Cache-Control','no-store');
|
||||
});
|
||||
|
||||
$renderFrontend = function (Request $request) {
|
||||
if (admin_setting('app_url') && admin_setting('safe_mode_enable', 0)) {
|
||||
$requestHost = $request->getHost();
|
||||
@@ -71,7 +77,15 @@ $renderFrontend = function (Request $request) {
|
||||
if ($theme === 'Stellar') {
|
||||
$html = \App\Support\StellarDevAssets::apply($request, $html);
|
||||
}
|
||||
return response(str_replace('</head>', $brandScript . '</head>', $html));
|
||||
$support = app(\App\Services\CustomerService\Settings::class)->publicConfig();
|
||||
$supportScript = '';
|
||||
if ($support['enabled']) {
|
||||
$encoded = json_encode($support, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
|
||||
$supportScript = '<link rel="stylesheet" href="/customer-service/launcher.css?v=2">'
|
||||
. '<script>window.xbCustomerService=' . $encoded . ';</script>'
|
||||
. '<script type="module" src="/customer-service/widget.mjs?v=3"></script>';
|
||||
}
|
||||
return response(str_replace('</head>', $brandScript . $supportScript . '</head>', $html));
|
||||
} catch (Exception $e) {
|
||||
Log::error('Theme rendering failed', [
|
||||
'theme' => $theme,
|
||||
@@ -90,6 +104,8 @@ Route::get('/tutorials/{platform}/{client}.html', function (string $platform, st
|
||||
|
||||
Route::get('/', $renderFrontend);
|
||||
|
||||
Route::get('/' . admin_setting('secure_path', admin_setting('frontend_admin_path', hash('crc32b', config('app.key')))) . '/customer-service', fn () => view('customer-service-admin'));
|
||||
|
||||
//TODO:: 兼容
|
||||
Route::get('/' . admin_setting('secure_path', admin_setting('frontend_admin_path', hash('crc32b', config('app.key')))), function () {
|
||||
return view('admin', [
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# FUC-XB 外部联调验收
|
||||
|
||||
仅适用于已登记隔离测试站,不切正式站,不适用于DPL/HN。按精确Git版本执行;输出、凭据及临时状态只在测试站private,失败或结果未知先回读,不重发。
|
||||
|
||||
2026-11-04用户要求继续真实邮件/节点/客户端验收;随后明确不实际付款,但尽量验证不扣款的支付链路。收件地址指定mukaitao(既定mukaitao@proton.me)。
|
||||
|
||||
mail.php 从同宿主旧FUC只读取得原邮件传输配置;密钥只交给同一服务认证组件,不输出、不传到本机。在当前PHP进程的MySQL事务内临时配置原生邮件流程和同步任务连接及进程内缓存(不测试常驻Redis队列),调用真实HTTP内核验证码接口及原生MailService通知,只发指定收件人两封,验证同消息键不重发。不启动常驻worker或自动群发、不改FPM环境;回滚配置/日志并清理本次验证码。区分provider提交/投递、SMTP提交与收件箱实收。
|
||||
|
||||
节点使用专用QA组、独立端口及进程,原节点不切换。客户端应使用原生订阅、严格TLS、预先登记的预期出口并核对上报。额外访问门保持;仅环回受限桥可携带既有访问Cookie,XB原生节点令牌仍须验证。
|
||||
|
||||
本轮最终结果与未通过项唯一见[外部联调验收](../../docs/maintenance/FUC_XB_EXTERNAL_ACCEPTANCE.md)。`payment.php`的原生受控用例通过不等于真实收银台通过;`gateway_entry_reachable`只表示第一跳可达,须继续检查`cashier.py`的实际下游。`client.py revoked`只检查订阅403,不代表保存配置已经断网。本轮独立的保存配置实测发现禁用后仍可新建连接,未将该项标为通过。
|
||||
|
||||
停止临时节点后按`ss -ltn`核对监听,不能用普通bind把TIME_WAIT误判为仍有监听。先停止节点/API桥、排空本次traffic_fetch/stat队列,再按node-state精确清理;保留原服务PID/配置摘要,不全局flush Redis。
|
||||
@@ -0,0 +1,31 @@
|
||||
import pathlib,json,urllib.request,urllib.parse,urllib.error,ssl,socket,ipaddress,re
|
||||
from html.parser import HTMLParser
|
||||
root=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104')
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self,*a,**kw):return None
|
||||
class Title(HTMLParser):
|
||||
def __init__(self):super().__init__();self.on=False;self.parts=[]
|
||||
def handle_starttag(self,t,a):
|
||||
if t=='title':self.on=True
|
||||
def handle_endtag(self,t):
|
||||
if t=='title':self.on=False
|
||||
def handle_data(self,s):
|
||||
if self.on:self.parts.append(s.strip())
|
||||
op=urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl.create_default_context()),NoRedirect());out=[]
|
||||
for kind in ['alipay','wxpay']:
|
||||
v=json.loads((root/('mapi-'+kind+'.response')).read_text());assert v.get('code')==1 and v.get('payurl')
|
||||
url=v['payurl'];chain=[];body=b''
|
||||
for hop in range(4):
|
||||
p=urllib.parse.urlsplit(url);assert p.scheme=='https' and p.hostname and not p.username and not p.password and (p.port is None or p.port==443)
|
||||
assert p.hostname not in ['fuc-xb-test.gemcook.net','fuc-xb-test.tomtojapan.online'],'Do not follow merchant return'
|
||||
ips={x[4][0] for x in socket.getaddrinfo(p.hostname,443,type=socket.SOCK_STREAM)};assert ips and all(ipaddress.ip_address(ip).is_global for ip in ips)
|
||||
req=urllib.request.Request(url,headers={'User-Agent':'Mozilla/5.0','Referer':'https://pay.airspay.top/','Accept':'text/html'})
|
||||
try:res=op.open(req,timeout=25)
|
||||
except urllib.error.HTTPError as e:res=e
|
||||
with res:
|
||||
code=res.status;body=res.read(2097152);location=res.headers.get('Location');chain.append({'host':p.hostname,'status':code})
|
||||
if code in [301,302,303,307,308] and location:url=urllib.parse.urljoin(url,location);continue
|
||||
break
|
||||
(root/('mapi-cashier-'+kind+'.html')).write_bytes(body);parser=Title();parser.feed(body.decode(errors='replace'));title=' '.join(parser.parts)
|
||||
out.append({'type':kind,'chain':chain,'final_status':code,'title':re.sub(r'[A-Za-z0-9_-]{8,}','<id>',title)[:100],'response_bytes':len(body),'has_qr_markup':bool(re.search(b'qrcode|qr-code|qr_code|erweima',body,re.I)),'real_money_paid':0})
|
||||
print(json.dumps({'unpaid_cashier_pages_only':True,'cases':out},ensure_ascii=False))
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Follow only the observed gateway's unpaid auto-POST. Never authorize payment."""
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
from decimal import Decimal
|
||||
import hashlib,json,ssl,urllib.parse,urllib.request,urllib.error
|
||||
ROOT=Path('/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104')
|
||||
class Form(HTMLParser):
|
||||
def __init__(self):super().__init__();self.forms=[];self.title=False;self.titles=[]
|
||||
def handle_starttag(self,t,a):
|
||||
a=dict(a)
|
||||
if t=='form':self.forms.append({'action':a.get('action'),'method':a.get('method','get').lower(),'fields':{}})
|
||||
if t=='input' and self.forms and a.get('name'):self.forms[-1]['fields'][a['name']]=a.get('value','')
|
||||
if t=='title':self.title=True
|
||||
def handle_endtag(self,t):
|
||||
if t=='title':self.title=False
|
||||
def handle_data(self,s):
|
||||
if self.title:self.titles.append(s.strip())
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self,*a,**kw):return None
|
||||
def run(root=ROOT,opener=None):
|
||||
if opener is None:opener=urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl.create_default_context()),NoRedirect())
|
||||
out=[]
|
||||
for kind in ['alipay','wxpay']:
|
||||
p=Form();p.feed((root/('cashier-'+kind+'.html')).read_text());assert len(p.forms)==1
|
||||
f=p.forms[0];v=f['fields'];assert f['action']=='https://api.shangri-la.vc/submit.php' and f['method']=='post'
|
||||
assert set(v).issubset({'pid','type','notify_url','return_url','out_trade_no','name','money','sign','sign_type'})
|
||||
assert v['type']==kind and Decimal(v['money'])==Decimal('1') and v['sign_type']=='MD5'
|
||||
# The processor serves an unrelated 404 page unless HTML content negotiation is explicit.
|
||||
# Match a browser's navigation semantics; this does not authorize payment.
|
||||
req=urllib.request.Request(f['action'],data=urllib.parse.urlencode(v).encode(),headers={'Content-Type':'application/x-www-form-urlencoded','User-Agent':'FUC-XB-Isolated-Acceptance/1.0','Accept':'text/html'},method='POST')
|
||||
try:res=opener.open(req,timeout=25)
|
||||
except urllib.error.HTTPError as e:res=e
|
||||
with res:
|
||||
status=res.status;b=res.read(2097152);location=res.headers.get('Location','')
|
||||
(root/('cashier-final-'+kind+'.html')).write_bytes(b)
|
||||
parsed=Form();parsed.feed(b.decode('utf-8',errors='replace'))
|
||||
failures=[x for x in ['签名验证失败','商户不存在','商户已被封禁','商户未开启','支付金额不能','参数错误','订单已过期','订单不存在','支付参数有变化'] if x in b.decode('utf-8',errors='replace')]
|
||||
out.append({'type':kind,'observed_processor_host':'api.shangri-la.vc','http_status':status,'tls_verified':True,'title':' '.join(parsed.titles)[:120],'redirect_host':urllib.parse.urlsplit(location).hostname,'error_indicators':failures,'response_bytes':len(b),'body_sha256':hashlib.sha256(b).hexdigest(),'payment_authorization_attempted':False})
|
||||
result={'processor_unpaid_auto_post_only':True,'real_money_paid':0,'cases':out,'actual_paid_callback_not_tested':True}
|
||||
(root/'cashier-final-result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2))
|
||||
return result
|
||||
if __name__=='__main__':print(json.dumps(run(),ensure_ascii=False))
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real native subscription import and SOCKS traffic; no local desktop/TUN changes."""
|
||||
import argparse,copy,gzip,hashlib,json,os,pathlib,socket,ssl,subprocess,time,urllib.error,urllib.parse,urllib.request
|
||||
DIR=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104')
|
||||
BIN=DIR/'bin/sing-box'
|
||||
SHA='768d31fa7f68debc067bb4626539498a1e8751d36a7b99e1a54bee6a23815f93'
|
||||
PANEL='/var/www/wwwroot/fuc-xb-test/acceptance/5a75c839b94709cac1be34d6b12a7e295b5833b0/scripts/fuc-xb-acceptance/node-panel.php'
|
||||
def run(a,timeout=30):return subprocess.run(a,capture_output=True,timeout=timeout)
|
||||
def context():
|
||||
p=run(['php',PANEL,'export']);assert p.returncode==0
|
||||
return json.loads(p.stdout)
|
||||
def redact(s,c):
|
||||
for k in ['server_token','gate_cookie','subscribe_token','qa_uuid']:s=s.replace(str(c[k]),'<redacted>')
|
||||
return s[:1200]
|
||||
def fetch(c,flag,token=None):
|
||||
url=c['alias']+'/api/v1/client/subscribe?'+urllib.parse.urlencode({'token':token if token is not None else c['subscribe_token'],'flag':flag})
|
||||
r=urllib.request.Request(url,headers={'Cookie':'fuc_stage_access='+c['gate_cookie'],'User-Agent':'sing-box/1.14.3' if flag=='sing-box' else 'clash.meta/1.19.0'})
|
||||
try:
|
||||
with urllib.request.urlopen(r,timeout=25)as o:
|
||||
b=o.read(4194304);h=o.headers
|
||||
if h.get('Content-Encoding')=='gzip':b=gzip.decompress(b)
|
||||
return o.status,b
|
||||
except urllib.error.HTTPError as e:return e.code,e.read(1024)
|
||||
def prepare(c):
|
||||
assert hashlib.sha256(BIN.read_bytes()).hexdigest()==SHA,'Client artifact changed'
|
||||
status,raw=fetch(c,'sing-box');assert status==200,'Native subscription request failed'
|
||||
cfg=json.loads(raw);nodes=[o for o in cfg['outbounds'] if o.get('type')=='vmess']
|
||||
assert len(nodes)==1,'Expected exact QA-only VMess subscription'
|
||||
n=nodes[0];assert n['server']==c['expected_exit'] and n['server_port']==c['port'] and n['uuid']==c['qa_uuid'],'Native subscription identity mismatch'
|
||||
assert n['tls']['enabled'] and n['tls'].get('insecure') is False and n['tls']['server_name']==c['sni'],'Strict subscription TLS mismatch'
|
||||
(DIR/'subscription-singbox.json').write_bytes(raw)
|
||||
status,clash=fetch(c,'meta');assert status==200 and b'vmess' in clash and c['qa_uuid'].encode() in clash,'Native Clash subscription missing QA node'
|
||||
(DIR/'subscription-clash.yaml').write_bytes(clash)
|
||||
assert fetch(c,'sing-box','invalid-qa-token')[0]==403,'Invalid subscription token accepted'
|
||||
cfg['inbounds']=[{'type':'mixed','tag':'qa-local','listen':'127.0.0.1','listen_port':19876}]
|
||||
(DIR/'client-full.json').write_text(json.dumps(cfg))
|
||||
check=run([str(BIN),'check','-c',str(DIR/'client-full.json')])
|
||||
result={'native_subscription_downloaded':True,'exact_qa_node_and_uuid':True,'strict_tls_in_subscription':True,'invalid_token_rejected':True,'clash_native_format_present':True,'only_inbounds_replaced':True,'native_full_config_check_passed':check.returncode==0}
|
||||
if check.returncode:result['check_error']=redact(check.stderr.decode(errors='replace'),c)
|
||||
(DIR/'client-prepare-result.json').write_text(json.dumps(result,indent=2))
|
||||
return result,cfg
|
||||
def main():
|
||||
os.umask(0o077);p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','run','revoked']);args=p.parse_args();c=context()
|
||||
if args.action=='revoked':
|
||||
status,_=fetch(c,'sing-box');print(json.dumps({'disabled_qa_subscription_status':status,'revoked':status==403}));return
|
||||
result,cfg=prepare(c)
|
||||
if args.action=='prepare' or not result['native_full_config_check_passed']:print(json.dumps(result));return
|
||||
assert c['expected_exit']=='193.111.31.52'
|
||||
# A positive TLS handshake is independently verified before starting the application client.
|
||||
ctx=ssl.create_default_context()
|
||||
with socket.create_connection((c['expected_exit'],c['port']),timeout=8)as raw:
|
||||
with ctx.wrap_socket(raw,server_hostname=c['sni'])as tls:result['node_certificate_verified']=True;result['node_tls_version']=tls.version()
|
||||
s=socket.socket()
|
||||
try:s.bind(('127.0.0.1',19876))
|
||||
finally:s.close()
|
||||
cmd=['systemd-run','--quiet','--collect','--unit=fuc-xb-qa-client','--property=RuntimeMaxSec=600','--property=MemoryMax=384M','--property=CPUQuota=30%','--working-directory='+str(DIR),str(BIN),'run','-D',str(DIR),'-c',str(DIR/'client-full.json')]
|
||||
started=run(cmd);assert started.returncode==0,'QA client unit failed'
|
||||
try:
|
||||
ready=False
|
||||
for _ in range(50):
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1',19876),timeout=.2):ready=True;break
|
||||
except OSError:time.sleep(.2)
|
||||
if not ready:
|
||||
log=run(['journalctl','-u','fuc-xb-qa-client','-n','8','--no-pager'])
|
||||
result['client_start_error']=redact(log.stdout.decode(errors='replace'),c)
|
||||
raise RuntimeError('Native full client did not start')
|
||||
base=['curl','-sS','--proxy','socks5h://127.0.0.1:19876','--connect-timeout','8','--max-time','25']
|
||||
ip=run(base+['https://api.ipify.org?format=json'],timeout=30)
|
||||
assert ip.returncode==0 and json.loads(ip.stdout)['ip']==c['expected_exit'],'Wrong real proxy exit'
|
||||
result['actual_proxy_exit_matches']=True;result['expected_exit']=c['expected_exit']
|
||||
down=run(base+['https://speed.cloudflare.com/__down?bytes=65536'],timeout=30)
|
||||
assert down.returncode==0 and len(down.stdout)==65536,'Real download payload mismatch'
|
||||
result['download_payload_bytes']=len(down.stdout)
|
||||
(DIR/'upload-qa.bin').write_bytes(b'FUC-XB-QA-ONLY\n'*2048)
|
||||
up=run(base+['-H','Content-Type: application/octet-stream','--data-binary','@'+str(DIR/'upload-qa.bin'),'https://httpbin.org/post'],timeout=30)
|
||||
assert up.returncode==0 and len(json.loads(up.stdout).get('data',''))==len((DIR/'upload-qa.bin').read_bytes()),'Real upload echo mismatch'
|
||||
result['upload_payload_bytes']=len((DIR/'upload-qa.bin').read_bytes())
|
||||
result['real_client_network_passed']=True
|
||||
finally:
|
||||
run(['systemctl','stop','fuc-xb-qa-client'])
|
||||
result['temporary_client_stopped']=True
|
||||
(DIR/'client-run-result.json').write_text(json.dumps(result,indent=2))
|
||||
print(json.dumps(result))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
umask(0077);error_reporting(E_ALL);ini_set('display_errors','0');
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';
|
||||
$private='/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104';
|
||||
if(!is_dir($private))throw new RuntimeException('Preflight directory missing');
|
||||
$out=$private.'/mail-result.json';
|
||||
if(is_file($out))throw new RuntimeException('Refuse second delivery; inspect receipt');
|
||||
function legacyMailConfig(): array {
|
||||
$cwd=getcwd();chdir('/www/wwwroot/fuuuu.cloud');require 'config/.config.php';
|
||||
$dsn=!empty($_ENV['db_socket'])?'mysql:unix_socket='.$_ENV['db_socket']:'mysql:host='.$_ENV['db_host'].';port='.$_ENV['db_port'];
|
||||
$p=new PDO($dsn.';dbname='.$_ENV['db_database'].';charset=utf8mb4',$_ENV['db_username'],$_ENV['db_password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
|
||||
$p->exec('SET TRANSACTION READ ONLY');$p->beginTransaction();
|
||||
$s=$p->query("SELECT item,value FROM config WHERE item IN ('smtp_host','smtp_port','smtp_username','smtp_password','smtp_sender','smtp_ssl')")->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||
$v=$p->query("SELECT apikey,auther FROM mail_must WHERE client='resend' AND status=1 LIMIT 1")->fetch();
|
||||
$p->rollBack();chdir($cwd);
|
||||
if(($s['smtp_host']??'')!=='mail.privateemail.com'||($s['smtp_sender']??'')!=='[email protected]'||empty($s['smtp_password'])||empty($v['apikey']))throw new RuntimeException('Registered FUC transports changed');
|
||||
return ['smtp'=>$s,'resend'=>$v];
|
||||
}
|
||||
$legacy=legacyMailConfig();
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\{DB,Cache};
|
||||
use App\Models\MailMessage;
|
||||
if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
|
||||
// Isolate settings cache too: never publish uncommitted secrets/settings to shared Redis.
|
||||
config(['cache.stores.redis'=>['driver'=>'array'],'cache.default'=>'redis']);
|
||||
Cache::purge('redis');$app->forgetInstance(App\Support\Setting::class);
|
||||
$recipient='[email protected]';$key='fuc-xb-live-mail-20261104';
|
||||
if(MailMessage::count()!==0)throw new RuntimeException('Unexpected existing mail; stop before sending');
|
||||
$result=['recipient'=>$recipient,'sender'=>'[email protected]','real_deliveries'=>[],'simulated'=>false,'native_http_kernel'=>true,'production_site_changed'=>false];
|
||||
$baseline=['users'=>App\Models\User::count(),'orders'=>App\Models\Order::count(),'balance'=>(int)App\Models\User::sum('balance'),'settings_hash'=>hash('sha256',DB::table('v2_settings')->orderBy('id')->get()->toJson())];
|
||||
$db=DB::connection();$db->beginTransaction();
|
||||
try {
|
||||
$flow=array_replace((array)admin_setting('mail_flow',[]),['enabled'=>true,'resend_enabled'=>true,'resend_key'=>$legacy['resend']['apikey'],'resend_from'=>$legacy['resend']['auther'],'reply_to'=>'[email protected]','inbound_enabled'=>false,'auto_reply_enabled'=>false,'report_enabled'=>false,'logo_path'=>'','daily_limit'=>100,'monthly_limit'=>3000]);
|
||||
// Uncommitted settings remain invisible to other PHP/FPM requests.
|
||||
app(App\Support\Setting::class)->save(['mail_flow'=>$flow,'automatic_mail_policy'=>['level'=>3,'since'=>null]]);
|
||||
config(['queue.default'=>'sync','mail.driver'=>'smtp','mail.host'=>$legacy['smtp']['smtp_host'],'mail.port'=>(int)$legacy['smtp']['smtp_port'],'mail.username'=>$legacy['smtp']['smtp_username'],'mail.password'=>$legacy['smtp']['smtp_password'],'mail.encryption'=>'ssl','mail.from.address'=>'[email protected]','mail.from.name'=>'FUC-XB_TEST','mailflow.logo_path'=>'']);
|
||||
$r=Illuminate\Http\Request::create('https://fuc-xb-test.gemcook.net/api/v1/passport/comm/sendEmailVerify','POST',['email'=>$recipient],[],[],['HTTP_ACCEPT'=>'application/json','REMOTE_ADDR'=>'127.0.0.1']);
|
||||
app()->instance('request',$r);$response=app(Illuminate\Contracts\Http\Kernel::class)->handle($r);
|
||||
if($response->getStatusCode()!==200)throw new RuntimeException('Native verification request failed');
|
||||
$first=MailMessage::where('email',$recipient)->where('purpose','verification')->firstOrFail();
|
||||
if(!in_array($first->status,['submitted','delivered'],true)||!in_array($first->channel,['resend','conventional'],true))throw new RuntimeException('Verification not submitted');
|
||||
$code=Cache::get(App\Utils\CacheKey::get('EMAIL_VERIFY_CODE',$recipient));
|
||||
if(!preg_match('/^\d{6}$/',(string)$code))throw new RuntimeException('Verification cache contract failed');
|
||||
$result['verification_http_status']=200;$result['verification_code_cached_in_isolated_process']=true;
|
||||
$before=$first->attempts;
|
||||
(new App\Jobs\SendEmailJob(['email'=>$recipient,'subject'=>'FUC-XB verification idempotency check','template_name'=>'verify','purpose'=>'verification','message_key'=>$first->message_key,'template_value'=>['name'=>'FUC-XB_TEST','code'=>$code,'url'=>'https://fuc-xb-test.tomtojapan.online']]))->handle();
|
||||
$first->refresh();if($first->attempts!==$before)throw new RuntimeException('Mail duplicate submitted again');
|
||||
$result['same_message_key_does_not_resend']=true;
|
||||
$second=App\Services\MailService::sendEmail(['email'=>$recipient,'subject'=>'[FUC-XB隔离验收 20261104] 通知邮件','template_name'=>'notify','purpose'=>'admin_test','message_key'=>$key.'-notification','template_value'=>['name'=>'FUC-XB_TEST','content'=>'隔离测试站真实通知邮件,仅用于验收。不涉及正式切换、扣款或原用户通知。','url'=>'https://fuc-xb-test.tomtojapan.online']]);
|
||||
if(!in_array($second['status']??null,['submitted','delivered'],true))throw new RuntimeException('Notification not submitted');
|
||||
foreach(MailMessage::where('email',$recipient)->get()as$m){
|
||||
$event=null;
|
||||
if($m->channel==='resend'){
|
||||
try{$detail=app(App\Services\MailFlow\ResendClient::class)->retrieve($m->provider_id);$event=$detail['last_event']??null;}catch(Throwable){$event='provider_status_unavailable';}
|
||||
}
|
||||
$result['real_deliveries'][]=['purpose'=>$m->purpose,'channel'=>$m->channel,'status'=>$m->status,'provider_event'=>$event,'fallback_reason'=>$m->fallback_reason,'attempts'=>$m->attempts,'provider_id'=>$m->provider_id];
|
||||
}
|
||||
$result['both_messages_submitted']=count($result['real_deliveries'])===2;
|
||||
file_put_contents($out,json_encode($result,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));chmod($out,0600);
|
||||
} catch(Throwable $e) {
|
||||
$result['failed']=get_class($e);$result['failure_stage']=$e->getMessage();
|
||||
file_put_contents($out,json_encode($result,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));chmod($out,0600);
|
||||
throw $e;
|
||||
} finally {
|
||||
while($db->transactionLevel()>0)$db->rollBack();
|
||||
Cache::store('redis')->forget(App\Support\Setting::CACHE_KEY);
|
||||
Cache::forget(App\Utils\CacheKey::get('EMAIL_VERIFY_CODE',$recipient));
|
||||
Cache::forget(App\Utils\CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP',$recipient));
|
||||
Cache::forget('mailflow:resend:usage');
|
||||
}
|
||||
$after=['users'=>App\Models\User::count(),'orders'=>App\Models\Order::count(),'balance'=>(int)App\Models\User::sum('balance'),'settings_hash'=>hash('sha256',DB::table('v2_settings')->orderBy('id')->get()->toJson())];
|
||||
$result['temporary_settings_and_database_rows_rolled_back']=$baseline===$after&&MailMessage::count()===0;
|
||||
$result['verification_code_cleared']=true;$result['passed']=($result['both_messages_submitted']??false)&&$result['temporary_settings_and_database_rows_rolled_back'];
|
||||
file_put_contents($out,json_encode($result,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));echo json_encode($result,JSON_UNESCAPED_UNICODE).PHP_EOL;
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
ini_set('display_errors','0');umask(0077);$private='/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104';chdir('/www/wwwroot/fuuuu.cloud');require 'config/.config.php';$dsn=!empty($_ENV['db_socket'])?'mysql:unix_socket='.$_ENV['db_socket']:'mysql:host='.$_ENV['db_host'].';port='.$_ENV['db_port'];$p=new PDO($dsn.';dbname='.$_ENV['db_database'].';charset=utf8mb4',$_ENV['db_username'],$_ENV['db_password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$p->exec('SET TRANSACTION READ ONLY');$p->beginTransaction();$v=$p->query("SELECT item,value FROM config WHERE item IN ('epay_pid','epay_key','epay_url')")->fetchAll(PDO::FETCH_KEY_PAIR);$p->rollBack();
|
||||
$old= file_get_contents('/www/wwwroot/fuuuu.cloud/src/Services/Gateway/Epay.php');
|
||||
if(!str_contains($old,"'mapi.php'"))throw new RuntimeException('Old API contract not confirmed');
|
||||
$k=$v['epay_key'];$out=[];
|
||||
foreach(['alipay','wxpay']as$type){
|
||||
$html=file_get_contents($private.'/cashier-'.$type.'.html');$doc=new DOMDocument();@$doc->loadHTML($html);$args=[];foreach($doc->getElementsByTagName('input')as$input)if($input->hasAttribute('name'))$args[$input->getAttribute('name')]=$input->getAttribute('value');
|
||||
if((float)($args['money']??0)!==1.0||($args['type']??'')!==$type)throw new RuntimeException('Observed fixture mismatch');
|
||||
unset($args['sign'],$args['sign_type']);$args['pid']=$v['epay_pid'];$args['out_trade_no']='QA-MAPI-20261104-'.$type.'-'.bin2hex(random_bytes(4));$args['sitename']='FUC-XB-TEST';$args['clientip']='45.8.112.190';ksort($args);$pairs=[];foreach($args as$a=>$b)if($b!==''&&$b!==null)$pairs[]=$a.'='.$b;$args['sign']=md5(implode('&',$pairs).$k);$args['sign_type']='MD5';
|
||||
$curl=curl_init(rtrim($v['epay_url'],'/').'/mapi.php');curl_setopt_array($curl,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($args),CURLOPT_RETURNTRANSFER=>true,CURLOPT_FOLLOWLOCATION=>false,CURLOPT_TIMEOUT=>25,CURLOPT_SSL_VERIFYPEER=>true,CURLOPT_SSL_VERIFYHOST=>2]);$body=curl_exec($curl);$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);$tls=curl_getinfo($curl,CURLINFO_SSL_VERIFYRESULT);curl_close($curl);$j=is_string($body)?json_decode($body,true):null;
|
||||
file_put_contents($private.'/mapi-'.$type.'.response',is_string($body)?$body:'');
|
||||
$out[]=['type'=>$type,'http_status'=>$status,'tls_verify_result'=>$tls,'json_response'=>is_array($j),'code'=>is_array($j)&&is_scalar($j['code']??null)?$j['code']:null,'has_payurl'=>is_array($j)&&!empty($j['payurl']),'has_qrcode'=>is_array($j)&&!empty($j['qrcode']),'actual_payment'=>false];
|
||||
}
|
||||
echo json_encode(['old_fuc_native_api_contract_confirmed'=>true,'unpaid_api_request_only'=>true,'real_money_paid'=>0,'cases'=>$out]);
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Loopback-only adapter for the staging gate. Native XB node auth stays required."""
|
||||
import argparse, hashlib, http.server, json, pathlib, ssl, threading, urllib.error, urllib.parse, urllib.request
|
||||
ALLOWED = {'/api/v1/server/UniProxy/'+x for x in ['config','user','push','alive','alivelist','status']}
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self,*args,**kwargs): return None
|
||||
def allowed(method,path,node,token):
|
||||
p=urllib.parse.urlsplit(path);q=urllib.parse.parse_qs(p.query,keep_blank_values=True)
|
||||
return (not p.scheme and not p.netloc and p.path in ALLOWED and method in ('GET','POST') and
|
||||
q.get('node_id')==[str(node)] and q.get('token')==[token] and
|
||||
q.get('node_type',['v2ray']) in (['v2ray'],['vmess']) and
|
||||
set(q).issubset({'node_id','token','node_type'}))
|
||||
def main():
|
||||
parser=argparse.ArgumentParser();parser.add_argument('--config',required=True);args=parser.parse_args()
|
||||
path=pathlib.Path(args.config);assert path.stat().st_mode & 0o077 == 0
|
||||
cfg=json.loads(path.read_text());assert cfg['source']=='https://fuc-xb-test.gemcook.net'
|
||||
opener=urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl.create_default_context()),NoRedirect())
|
||||
metrics={'requests':{},'user_counts':[]};lock=threading.Lock()
|
||||
def record(path,status,body):
|
||||
with lock:
|
||||
key=path+':'+str(status);metrics['requests'][key]=metrics['requests'].get(key,0)+1
|
||||
if path.endswith('/user') and status==200:
|
||||
try:metrics['user_counts']=(metrics['user_counts']+[len(json.loads(body)['users'])])[-20:]
|
||||
except Exception:pass
|
||||
(pathlib.Path(args.config).parent/'bridge-metrics.json').write_text(json.dumps(metrics))
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self,*args):pass
|
||||
def do_GET(self):self.forward()
|
||||
def do_POST(self):self.forward()
|
||||
def forward(self):
|
||||
if self.client_address[0]!='127.0.0.1' or not allowed(self.command,self.path,cfg['node_id'],cfg['server_token']):
|
||||
self.send_error(403);return
|
||||
length=int(self.headers.get('Content-Length','0'))
|
||||
if length<0 or length>2097152:self.send_error(413);return
|
||||
payload=self.rfile.read(length) if self.command=='POST' else None
|
||||
headers={'Cookie':'fuc_stage_access='+cfg['gate_cookie'],'Accept':'application/json'}
|
||||
if self.command=='POST':headers['Content-Type']='application/json'
|
||||
if self.headers.get('If-None-Match'):headers['If-None-Match']=self.headers['If-None-Match']
|
||||
p=urllib.parse.urlsplit(self.path).path
|
||||
try:
|
||||
req=urllib.request.Request(cfg['source']+self.path,data=payload,headers=headers,method=self.command)
|
||||
try:res=opener.open(req,timeout=15)
|
||||
except urllib.error.HTTPError as e:res=e
|
||||
with res:status=res.status;body=res.read();response_headers=res.headers
|
||||
if len(body)>2097152:raise ValueError('oversized upstream')
|
||||
record(p,status,body)
|
||||
self.send_response(status)
|
||||
for key in ['Content-Type','ETag']:
|
||||
if response_headers.get(key):self.send_header(key,response_headers[key])
|
||||
self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
|
||||
except Exception:
|
||||
self.send_response(502);self.send_header('Content-Length','0');self.end_headers()
|
||||
server=http.server.ThreadingHTTPServer(('127.0.0.1',28766),Handler)
|
||||
server.daemon_threads=True;server.serve_forever()
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Only temporary FUC-XB QA units; never edit existing node services/configuration."""
|
||||
import argparse, hashlib, json, os, pathlib, socket, subprocess, time
|
||||
ROOT=pathlib.Path('/var/www/wwwroot/fuc-xb-acceptance')
|
||||
PRIVATE=ROOT/'private'
|
||||
EXPECTED={'/usr/local/XrayR/XrayR':'31c3beef7afb1a167dc631d16cec881ea6d3049cb0718dd8157e51da14b5296d','/etc/XrayR/config.yml':'a123e676fbc3a52fe3912db953499e2501a67b21aeb6445c3b458ec14570c2f2','/usr/local/XrayR/config.yml':'57c0dd387ec7fd36cf730c669babdbdb65312882e2fa9db6791d55f174fb41c2'}
|
||||
def run(a):
|
||||
p=subprocess.run(a,capture_output=True,text=True,timeout=35)
|
||||
if p.returncode:raise RuntimeError('QA host command failed')
|
||||
return p.stdout.strip()
|
||||
def original_ok():
|
||||
return all(hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest()==h for p,h in EXPECTED.items()) and run(['systemctl','show','XrayR','-p','MainPID','--value'])=='107692'
|
||||
def free(port):
|
||||
# A closed listener can retain TIME_WAIT sockets; bind() would report a false collision.
|
||||
p=subprocess.run(['ss','-H','-ltn','sport = :'+str(port)],capture_output=True,text=True,timeout=10)
|
||||
assert p.returncode==0,'Cannot verify temporary listener state'
|
||||
return not p.stdout.strip()
|
||||
def main():
|
||||
os.umask(0o077);p=argparse.ArgumentParser();p.add_argument('action',choices=['start','status','stop']);args=p.parse_args();PRIVATE.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
assert original_ok(),'Original XrayR baseline changed'
|
||||
if args.action=='start':
|
||||
assert free(25443) and free(28766),'Port collision'
|
||||
c=json.loads((PRIVATE/'node-runtime.json').read_text())
|
||||
assert c['expected_exit']=='193.111.31.52' and c['port']==25443 and c['sni']=='jp02.gembox-dns.com'
|
||||
cfg={'Log':{'Level':'error','ErrorPath':str(PRIVATE/'node-error.log')},'Nodes':[{'PanelType':'NewV2board','ApiConfig':{'ApiHost':'http://127.0.0.1:28766','ApiKey':c['server_token'],'NodeID':c['node_id'],'NodeType':'V2ray','Timeout':15,'EnableVless':False,'EnableXTLS':False,'SpeedLimit':10,'DeviceLimit':1},'ControllerConfig':{'ListenIP':'0.0.0.0','SendIP':'0.0.0.0','UpdatePeriodic':10,'EnableProxyProtocol':False,'CertConfig':{'CertMode':'file','CertDomain':'jp02.gembox-dns.com','CertFile':'/etc/letsencrypt/live/jp02.gembox-dns.com/fullchain.pem','KeyFile':'/etc/letsencrypt/live/jp02.gembox-dns.com/privkey.pem'}}}]}
|
||||
(PRIVATE/'xrayr.json').write_text(json.dumps(cfg))
|
||||
run(['systemd-run','--quiet','--collect','--unit=fuc-xb-qa-api','--property=RuntimeMaxSec=1800','--property=MemoryMax=96M','--property=CPUQuota=20%','/usr/bin/python3',str(pathlib.Path(__file__).with_name('node-bridge.py')),'--config',str(PRIVATE/'node-runtime.json')])
|
||||
for _ in range(25):
|
||||
if not free(28766):break
|
||||
time.sleep(0.2)
|
||||
assert not free(28766),'QA API bridge did not start'
|
||||
run(['systemd-run','--quiet','--collect','--unit=fuc-xb-qa-node','--property=RuntimeMaxSec=1800','--property=MemoryMax=256M','--property=CPUQuota=25%','--working-directory='+str(PRIVATE),'/usr/local/XrayR/XrayR','-c',str(PRIVATE/'xrayr.json')])
|
||||
print(json.dumps({'started_temporary_qa_units':True,'runtime_limit_seconds':1800,'original_unchanged':original_ok()}))
|
||||
elif args.action=='status':
|
||||
metrics=json.loads((PRIVATE/'bridge-metrics.json').read_text()) if (PRIVATE/'bridge-metrics.json').exists() else {}
|
||||
print(json.dumps({'node_active':run(['systemctl','show','fuc-xb-qa-node','-p','ActiveState','--value']),'api_active':run(['systemctl','show','fuc-xb-qa-api','-p','ActiveState','--value']),'port_listening':not free(25443),'metrics':metrics,'original_unchanged':original_ok()}))
|
||||
else:
|
||||
for u in ['fuc-xb-qa-node','fuc-xb-qa-api']:
|
||||
subprocess.run(['systemctl','stop',u],capture_output=True,timeout=30)
|
||||
assert free(25443) and free(28766),'Temporary port remains occupied'
|
||||
for name in ['node-runtime.json','xrayr.json']:(PRIVATE/name).unlink(missing_ok=True)
|
||||
print(json.dumps({'temporary_units_stopped':True,'temporary_ports_closed':True,'copied_gate_cookie_and_api_key_removed':True,'original_unchanged':original_ok()}))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';$dir='/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104';
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\{DB,Cache};
|
||||
use App\Models\{User,Server,ServerGroup};
|
||||
if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
|
||||
$action=$argv[1]??'';$file=$dir.'/node-state.json';
|
||||
if($action==='setup'){
|
||||
if(file_exists($file)||Server::count()!==0||User::where('email','[email protected]')->exists())throw new RuntimeException('Node fixture collision');
|
||||
$state=['before'=>['users'=>User::count(),'groups'=>ServerGroup::count(),'nodes'=>0,'wallet'=>(int)User::sum('balance')],'setting_rows'=>DB::table('v2_settings')->whereIn('name',['server_token','server_push_interval','server_pull_interval'])->get()->map(fn($x)=>(array)$x)->all(),'created_at'=>time()];
|
||||
// Journal intended identity before creating any fixture.
|
||||
file_put_contents($file,json_encode($state));chmod($file,0600);
|
||||
DB::transaction(function()use(&$state,$file){
|
||||
$g=new ServerGroup();$g->name='FUC-XB isolated QA 20261104';$g->save();
|
||||
$u=User::create(['email'=>'[email protected]','password'=>password_hash(bin2hex(random_bytes(20)),PASSWORD_BCRYPT),'uuid'=>(string)Illuminate\Support\Str::uuid(),'token'=>bin2hex(random_bytes(16)),'group_id'=>$g->id,'balance'=>0,'banned'=>0,'expired_at'=>time()+3600,'transfer_enable'=>100*1024*1024,'u'=>0,'d'=>0,'speed_limit'=>10,'device_limit'=>1]);
|
||||
$n=Server::create(['type'=>'vmess','name'=>'FUC-XB QA JP02 (temporary)','group_ids'=>[(string)$g->id],'route_ids'=>[],'host'=>'193.111.31.52','port'=>25443,'server_port'=>25443,'rate'=>1,'transfer_enable'=>100*1024*1024,'u'=>0,'d'=>0,'show'=>true,'enabled'=>true,'sort'=>9999,'protocol_settings'=>['tls'=>1,'tls_settings'=>['server_name'=>'jp02.gembox-dns.com','allow_insecure'=>false],'network'=>'ws','network_settings'=>['path'=>'/fuc-xb-qa-20261104','headers'=>['Host'=>'jp02.gembox-dns.com']]]]);
|
||||
$state+=['user_id'=>$u->id,'node_id'=>$n->id,'group_id'=>$g->id,'server_token'=>bin2hex(random_bytes(32))];
|
||||
app(App\Support\Setting::class)->save(['server_token'=>$state['server_token'],'server_push_interval'=>10,'server_pull_interval'=>10]);
|
||||
file_put_contents($file,json_encode($state));chmod($file,0600);
|
||||
});
|
||||
file_put_contents($file,json_encode($state));chmod($file,0600);
|
||||
$users=App\Services\ServerService::getAvailableUsers(Server::findOrFail($state['node_id']));
|
||||
if($users->count()!==1||(int)$users[0]->id!==$state['user_id'])throw new RuntimeException('QA isolation failed');
|
||||
echo json_encode(['created'=>true,'only_qa_user_on_node'=>true,'qa_quota_mib'=>100,'qa_lifetime_seconds'=>3600,'node_type'=>'vmess','port'=>25443,'formal_users_changed'=>false]).PHP_EOL;
|
||||
exit;
|
||||
}
|
||||
$state=json_decode(file_get_contents($file),true,512,JSON_THROW_ON_ERROR);$u=User::findOrFail($state['user_id']);$n=Server::findOrFail($state['node_id']);
|
||||
if($u->email!=='[email protected]'||$n->name!=='FUC-XB QA JP02 (temporary)')throw new RuntimeException('Fixture identity changed');
|
||||
if($action==='work'){
|
||||
$before=Illuminate\Support\Facades\Queue::size('traffic_fetch')+Illuminate\Support\Facades\Queue::size('stat');
|
||||
if($before>100)throw new RuntimeException('Unexpected queue backlog');
|
||||
Illuminate\Support\Facades\Artisan::call('queue:work',['connection'=>'redis','--queue'=>'traffic_fetch,stat','--stop-when-empty'=>true,'--max-time'=>25,'--tries'=>1,'--sleep'=>1]);
|
||||
echo json_encode(['bounded_worker'=>true,'pending_before'=>$before,'traffic_pending'=>Illuminate\Support\Facades\Queue::size('traffic_fetch'),'stat_pending'=>Illuminate\Support\Facades\Queue::size('stat')]).PHP_EOL;exit;
|
||||
}
|
||||
if($action==='probe'){
|
||||
echo json_encode(['qa_upload'=>$u->u,'qa_download'=>$u->d,'node_upload'=>$n->u,'node_download'=>$n->d,'last_check_at'=>$n->last_check_at,'last_push_at'=>$n->last_push_at,'online'=>$n->online,'available_users'=>App\Services\ServerService::getAvailableUsers($n)->count(),'available_servers'=>count(App\Services\ServerService::getAvailableServers($u))]).PHP_EOL;exit;
|
||||
}
|
||||
if($action==='disable'){
|
||||
$u->update(['banned'=>1,'expired_at'=>time()-1,'transfer_enable'=>0]);
|
||||
echo json_encode(['disabled'=>true,'users_no_longer_dispatched'=>App\Services\ServerService::getAvailableUsers($n)->count()===0]).PHP_EOL;exit;
|
||||
}
|
||||
if($action==='export'){
|
||||
// Only SSH consumers receive this; never print to the chat/tool log.
|
||||
$gate=json_decode(file_get_contents('/var/www/wwwroot/fuc-xb-test/private/gate-credentials.json'),true);
|
||||
echo json_encode(['node_id'=>$n->id,'server_token'=>$state['server_token'],'gate_cookie'=>$gate['cookie_token'],'source'=>'https://fuc-xb-test.gemcook.net','alias'=>'https://fuc-xb-test.tomtojapan.online','subscribe_token'=>$u->token,'qa_uuid'=>$u->uuid,'expected_exit'=>'193.111.31.52','expected_country'=>'JP','port'=>25443,'sni'=>'jp02.gembox-dns.com','node_tag'=>$n->name]);exit;
|
||||
}
|
||||
if($action==='cleanup'){
|
||||
if(!$u->banned)throw new RuntimeException('Disable and verify revoked access before cleanup');
|
||||
$backup=['user'=>$u->getAttributes(),'node'=>$n->getAttributes(),'traffic'=>DB::table('v2_stat_user')->where('user_id',$u->id)->get()->all()];
|
||||
file_put_contents($dir.'/node-fixtures-before-cleanup.json',json_encode($backup));
|
||||
DB::transaction(function()use($state,$u,$n){
|
||||
foreach(['v2_stat_user','v2_traffic_reset_logs','fuc_vip_entries','fuc_vip_accounts']as$t)DB::table($t)->where('user_id',$u->id)->delete();
|
||||
DB::table('personal_access_tokens')->where('tokenable_id',$u->id)->delete();
|
||||
DB::table('v2_stat_server')->where('server_id',$n->id)->where('server_type','vmess')->delete();
|
||||
app(App\Services\DeviceStateService::class)->removeNodeDevices($n->id,$u->id);
|
||||
Illuminate\Support\Facades\Redis::srem('traffic:pending_check',(string)$u->id);
|
||||
$n->delete();$u->delete();ServerGroup::where('id',$state['group_id'])->where('name','FUC-XB isolated QA 20261104')->delete();
|
||||
DB::table('v2_settings')->whereIn('name',['server_token','server_push_interval','server_pull_interval'])->delete();
|
||||
foreach($state['setting_rows']as$row)DB::table('v2_settings')->insert($row);
|
||||
});
|
||||
Cache::store('redis')->forget(App\Support\Setting::CACHE_KEY);
|
||||
$after=['users'=>User::count(),'groups'=>ServerGroup::count(),'nodes'=>Server::count(),'wallet'=>(int)User::sum('balance')];
|
||||
echo json_encode(['cleanup'=>true,'baseline_counts_and_wallet_restored'=>$after===$state['before'],'temporary_master_token_removed'=>true,'formal_users_changed'=>false]).PHP_EOL;exit;
|
||||
}
|
||||
throw new RuntimeException('Unknown action');
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';$private='/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104';
|
||||
$credentials=json_decode(stream_get_contents(STDIN),true,512,JSON_THROW_ON_ERROR);
|
||||
if(!isset($credentials['merchant_id'],$credentials['api_key']))throw new RuntimeException('Missing registered merchant fields');
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\{DB,Cache,Http,Mail,Queue};
|
||||
use App\Models\{User,Plan,Order,Payment};
|
||||
if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
|
||||
config(['cache.stores.redis'=>['driver'=>'array'],'cache.default'=>'redis']);Cache::purge('redis');$app->forgetInstance(App\Support\Setting::class);
|
||||
Mail::fake();Queue::fake()->except([App\Jobs\OrderHandleJob::class]);Http::preventStrayRequests();
|
||||
$checks=[];$cashiers=[];$auth='';
|
||||
function checkPay(bool $ok,string $name):void{global $checks;if(!$ok)throw new RuntimeException($name);$checks[]=$name;}
|
||||
function apiPay(string $path,string $method='GET',array $data=[]):array{
|
||||
global $auth;$r=Illuminate\Http\Request::create('https://fuc-xb-test.gemcook.net/api/v1/'.$path,$method,$data,[],[],['HTTP_ACCEPT'=>'application/json','HTTP_AUTHORIZATION'=>$auth,'REMOTE_ADDR'=>'127.0.0.1']);
|
||||
app()->instance('request',$r);app('auth')->forgetGuards();$res=app(Illuminate\Contracts\Http\Kernel::class)->handle($r);
|
||||
return [$res->getStatusCode(),json_decode($res->getContent(),true),$res->getContent()];
|
||||
}
|
||||
function signPay(array $p):array{
|
||||
global $credentials;unset($p['sign'],$p['sign_type']);$v=array_filter($p,fn($x)=>$x!==''&&$x!==null);ksort($v,SORT_STRING);$parts=[];foreach($v as$k=>$x)$parts[]=$k.'='.$x;$p['sign']=md5(implode('&',$parts).$credentials['api_key']);$p['sign_type']='MD5';return $p;
|
||||
}
|
||||
function checkoutPay(User $u,Plan $p,Payment $channel):array {
|
||||
global $auth;$auth=(new App\Services\AuthService($u->fresh()))->generateAuthData()['auth_data'];
|
||||
[$c,$v]=apiPay('user/order/save','POST',['plan_id'=>$p->id,'period'=>'month_price']);checkPay($c===200,'native order create');
|
||||
$trade=$v['data'];[$c,$v]=apiPay('user/order/checkout','POST',['trade_no'=>$trade,'method'=>$channel->id]);checkPay($c===200&&($v['type']??null)===1,'native checkout builds EPay redirect');
|
||||
return [Order::where('trade_no',$trade)->firstOrFail(),$v['data']];
|
||||
}
|
||||
$before=['users'=>User::count(),'orders'=>Order::count(),'payments'=>Payment::count(),'wallet'=>(int)User::sum('balance'),'vip'=>DB::table('fuc_vip_entries')->count(),'plugins'=>DB::table('v2_plugins')->count()];
|
||||
$db=DB::connection();$db->beginTransaction();
|
||||
try{
|
||||
$pm=app(App\Services\Plugin\PluginManager::class);$pm->initializeEnabledPlugins();
|
||||
if(!App\Models\Plugin::where('code','epay')->exists())$pm->install('epay');$pm->enable('epay');
|
||||
checkPay(isset((new App\Services\PaymentService('temp'))->getAvailablePaymentMethods()['EPay']),'native EPay plugin enabled only in transaction');
|
||||
$u=User::create(['email'=>'[email protected]','password'=>password_hash(bin2hex(random_bytes(20)),PASSWORD_BCRYPT),'uuid'=>(string)Illuminate\Support\Str::uuid(),'token'=>bin2hex(random_bytes(16)),'balance'=>0,'expired_at'=>0,'banned'=>0]);
|
||||
$p=Plan::create(['name'=>'QA-payment-only-20261104','prices'=>['monthly'=>1],'transfer_enable'=>1,'capacity_limit'=>null,'show'=>1,'sell'=>1,'renew'=>1,'reset_traffic_method'=>2]);
|
||||
app(Plugin\VipLoyalty\Service::class)->opening($u->id,$u->uuid,9900,hash('sha256','qa-payment-opening-20261104'));
|
||||
$channels=[];
|
||||
foreach(['alipay','wxpay']as$type){
|
||||
$channel=Payment::create(['uuid'=>App\Utils\Helper::randomChar(8),'name'=>'QA-'.$type,'payment'=>'EPay','enable'=>true,'sort'=>9000,'handling_fee_fixed'=>0,'handling_fee_percent'=>0,'notify_domain'=>'https://fuc-xb-test.gemcook.net','config'=>['url'=>'https://pay.airspay.top','pid'=>$credentials['merchant_id'],'key'=>$credentials['api_key'],'type'=>$type]]);
|
||||
$channels[$type]=$channel;
|
||||
[$o,$url]=checkoutPay($u,$p,$channel);$parts=parse_url($url);parse_str($parts['query']??'',$args);
|
||||
checkPay(($parts['scheme']??'')==='https'&&($parts['host']??'')==='pay.airspay.top'&&($args['type']??'')===$type&&($args['money']??'')==='1','registered merchant redirect and exact unpaid amount '.$type);
|
||||
checkPay(str_starts_with($args['notify_url'],'https://fuc-xb-test.gemcook.net/')&&!str_contains($args['notify_url'],'fuuuu.cloud'),'callback stays on isolated site '.$type);
|
||||
checkPay($args['sign']===signPay($args)['sign'],'independent MD5 redirect signature '.$type);
|
||||
// Read the real cashier once, with no user wallet, cookies, scan, payment approval or automatic redirect.
|
||||
$curl=curl_init($url);curl_setopt_array($curl,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_FOLLOWLOCATION=>false,CURLOPT_TIMEOUT=>20,CURLOPT_CONNECTTIMEOUT=>8,CURLOPT_SSL_VERIFYPEER=>true,CURLOPT_SSL_VERIFYHOST=>2,CURLOPT_USERAGENT=>'FUC-XB-Isolated-Acceptance/1.0']);
|
||||
$html=curl_exec($curl);$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);$tls=curl_getinfo($curl,CURLINFO_SSL_VERIFYRESULT);$err=curl_errno($curl);curl_close($curl);
|
||||
$cashiers[]=['type'=>$type,'http_status'=>$status,'tls_verify_result'=>$tls,'transport_error'=>$err,'body_bytes'=>is_string($html)?strlen($html):0,'provider_rejected'=>is_string($html)&&(str_contains($html,'签名验证失败')||str_contains($html,'商户不存在')||str_contains($html,'商户已被封禁')||str_contains($html,'商户未开启'))];
|
||||
if(is_string($html))file_put_contents($private.'/cashier-'.$type.'.html',$html);
|
||||
[$c,$state]=apiPay('user/order/check','GET',['trade_no'=>$o->trade_no]);checkPay($c===200&&$state['data']===0&&$o->fresh()->status===0,'cashier visit alone never opens order '.$type);
|
||||
[$c]=apiPay('user/order/cancel','POST',['trade_no'=>$o->trade_no]);checkPay($c===200&&$o->fresh()->status===2,'unpaid order cancelled '.$type);
|
||||
}
|
||||
// Controlled signed notifications are synthetic, not actual gateway delivery or settlement.
|
||||
$channel=$channels['alipay'];$channel->update(['handling_fee_fixed'=>5,'handling_fee_percent'=>2]);
|
||||
$u->update(['balance'=>20]);[$o]=$pair=checkoutPay($u,$p,$channel);
|
||||
checkPay((int)$o->total_amount===80&&(int)$o->balance_amount===20&&(int)$o->handling_amount===7,'native mixed wallet principal and fee separation');
|
||||
$params=['pid'=>$credentials['merchant_id'],'type'=>'alipay','out_trade_no'=>$o->trade_no,'trade_no'=>'QA-CONTROLLED-20261104-'.$o->id,'trade_status'=>'TRADE_SUCCESS','money'=>'0.87'];
|
||||
$path='guest/payment/notify/EPay/'.$channel->uuid;
|
||||
$mutations=['wrong merchant'=>['pid'=>'invalid-merchant'],'wrong channel type'=>['type'=>'wxpay'],'pending trade'=>['trade_status'=>'WAIT_BUYER_PAY'],'negative amount'=>['money'=>'-0.87'],'incorrect amount'=>['money'=>'0.86'],'fee omitted'=>['money'=>'0.80'],'sub-cent amount'=>['money'=>'0.870'],'unknown order'=>['out_trade_no'=>'QA-NOT-EXIST']];
|
||||
foreach($mutations as$name=>$diff){[$c]=apiPay($path,'POST',signPay(array_replace($params,$diff)));checkPay($c!==200&&$o->fresh()->status===0,'reject signed '.$name);}
|
||||
$bad=signPay($params);$bad['sign']=str_repeat('0',32);[$c]=apiPay($path,'POST',$bad);checkPay($c!==200&&$o->fresh()->status===0,'reject invalid signature');
|
||||
$bad=signPay($params);$bad['sign_type']='RSA';[$c]=apiPay($path,'POST',$bad);checkPay($c!==200,'reject unsupported signature type');
|
||||
$bad=signPay($params);$bad['money']=['0.87'];[$c]=apiPay($path,'POST',$bad);checkPay($c!==200,'reject array payload');
|
||||
[$c,$v,$raw]=apiPay($path,'POST',signPay($params));checkPay($c===200&&$raw==='success'&&$o->fresh()->status===3,'controlled signed callback opens synchronously');
|
||||
$expiry=$u->fresh()->expired_at;$entry=DB::table('fuc_vip_entries')->where('order_id',$o->id)->get();
|
||||
checkPay($entry->count()===1&&(int)$entry[0]->amount_cents===100&&$u->fresh()->discount===8,'VIP counts package wallet plus online principal and excludes fees');
|
||||
[$c,$v,$raw]=apiPay($path,'POST',signPay($params));checkPay($c===200&&$raw==='success'&&$u->fresh()->expired_at===$expiry&&DB::table('fuc_vip_entries')->where('order_id',$o->id)->count()===1,'duplicate callback never reopens or double accrues');
|
||||
[$c]=apiPay($path,'POST',signPay(array_replace($params,['trade_no'=>'QA-WRONG-PROVIDER-ID'])));checkPay($c!==200,'reject conflicting callback transaction');
|
||||
$auth=(new App\Services\AuthService($u->fresh()))->generateAuthData()['auth_data'];[$c,$v]=apiPay('user/order/save','POST',['plan_id'=>$p->id,'period'=>'month_price']);$next=Order::where('trade_no',$v['data'])->firstOrFail();checkPay((int)$next->total_amount===92,'new discount applies to next order');
|
||||
[$c]=apiPay('user/order/cancel','POST',['trade_no'=>$next->trade_no]);checkPay($c===200,'cancel next order');
|
||||
$late=signPay(array_replace($params,['out_trade_no'=>$next->trade_no,'money'=>'0.92','trade_no'=>'QA-LATE']));[$c]=apiPay($path,'POST',$late);checkPay($c!==200&&$next->fresh()->status===2,'late callback cannot revive cancelled order');
|
||||
$db->rollBack();
|
||||
$after=['users'=>User::count(),'orders'=>Order::count(),'payments'=>Payment::count(),'wallet'=>(int)User::sum('balance'),'vip'=>DB::table('fuc_vip_entries')->count(),'plugins'=>DB::table('v2_plugins')->count()];
|
||||
checkPay($before===$after,'all test business and plugin rows rolled back');
|
||||
$cashierOk=count($cashiers)===2&&!array_filter($cashiers,fn($x)=>!in_array($x['http_status'],[200,301,302,303],true)||$x['tls_verify_result']!==0||$x['transport_error']!==0||$x['provider_rejected']);
|
||||
$result=['native_business_checks_passed'=>true,'gateway_entry_reachable'=>$cashierOk,'final_cashier_tested'=>false,'checks'=>count($checks),'cases'=>$checks,'real_cashiers'=>$cashiers,'native_http_kernel'=>true,'real_money_paid'=>0,'callbacks_are_controlled_synthetic'=>true,'actual_gateway_success_callback_tested'=>false,'external_unpaid_cashier_orders_may_expire'=>true,'rollback'=>true,'production_changed'=>false];
|
||||
file_put_contents($private.'/payment-result.json',json_encode($result,JSON_PRETTY_PRINT));echo json_encode($result).PHP_EOL;
|
||||
}finally{while($db->transactionLevel()>0)$db->rollBack();Cache::store('redis')->forget(App\Support\Setting::CACHE_KEY);}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';$dir='/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104';
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$a=require $root.'/bootstrap/app.php';$a->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
if(Illuminate\Support\Facades\DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
|
||||
$path=$root.'/scripts/node-onboarding/sing-box-template.json';
|
||||
if(hash_file('sha256',$path)!=='32168fd207632602d4f99f6c66c4d2c3e2399dc0ec3726d9e5b0be1564db3d81')throw new RuntimeException('Reviewed modern template changed');
|
||||
$modern=file_get_contents($path);$old=App\Models\SubscribeTemplate::where('name','singbox')->firstOrFail();
|
||||
$current=json_decode($old->content,true,512,JSON_THROW_ON_ERROR);$new=json_decode($modern,true,512,JSON_THROW_ON_ERROR);
|
||||
if($current===$new){echo json_encode(['already_updated'=>true,'shared_code_changed'=>false]).PHP_EOL;exit;}
|
||||
$default=json_decode(file_get_contents($root.'/resources/rules/default.sing-box.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
if($current!==$default)throw new RuntimeException('Unexpected custom template; do not overwrite');
|
||||
$backup=$dir.'/singbox-template-before.json';if(file_exists($backup))throw new RuntimeException('Existing backup; inspect current state');
|
||||
file_put_contents($backup,json_encode($old->getAttributes()));chmod($backup,0600);
|
||||
App\Models\SubscribeTemplate::setContent('singbox',$modern);
|
||||
if(App\Models\SubscribeTemplate::getContent('singbox')!==$modern)throw new RuntimeException('Template readback failed');
|
||||
echo json_encode(['updated_only_isolated_instance_template'=>true,'old_template_backed_up'=>true,'shared_code_changed'=>false,'other_instances_changed'=>false,'modern_template_sha256'=>hash('sha256',$modern)]).PHP_EOL;
|
||||
@@ -0,0 +1,11 @@
|
||||
import importlib.util,pathlib,unittest
|
||||
s=importlib.util.spec_from_file_location('bridge',pathlib.Path(__file__).with_name('node-bridge.py'));b=importlib.util.module_from_spec(s);s.loader.exec_module(b)
|
||||
class Scope(unittest.TestCase):
|
||||
def test_exact_qa_node(self):
|
||||
self.assertTrue(b.allowed('GET','/api/v1/server/UniProxy/user?node_id=7&token=test-only&node_type=v2ray',7,'test-only'))
|
||||
def test_no_other_resources(self):
|
||||
for path in ['/api/v1/user/info?node_id=7&token=test-only','/api/v1/server/UniProxy/user?node_id=8&token=test-only','/api/v1/server/UniProxy/user?node_id=7&token=wrong','/api/v1/server/UniProxy/user?node_id=7&node_id=8&token=test-only','https://other.invalid/api/v1/server/UniProxy/user?node_id=7&token=test-only','/api/v1/server/UniProxy/user?node_id=7&token=test-only&extra=1']:
|
||||
with self.subTest(path=path):self.assertFalse(b.allowed('GET',path,7,'test-only'))
|
||||
def test_no_unneeded_methods(self):
|
||||
self.assertFalse(b.allowed('DELETE','/api/v1/server/UniProxy/user?node_id=7&token=test-only',7,'test-only'))
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Regression for the observed processor's HTML negotiation and unpaid boundary."""
|
||||
import importlib.util,json,pathlib,tempfile,unittest,urllib.parse
|
||||
|
||||
spec=importlib.util.spec_from_file_location('cashier',pathlib.Path(__file__).with_name('cashier.py'))
|
||||
cashier=importlib.util.module_from_spec(spec);spec.loader.exec_module(cashier)
|
||||
|
||||
class Response:
|
||||
def __init__(self,status,body):self.status=status;self.body=body;self.headers={}
|
||||
def __enter__(self):return self
|
||||
def __exit__(self,*args):return False
|
||||
def read(self,limit):return self.body[:limit]
|
||||
|
||||
class Processor:
|
||||
def __init__(self,expired=False):self.requests=[];self.expired=expired
|
||||
def open(self,req,timeout):
|
||||
self.requests.append(req)
|
||||
if req.get_header('Accept')!='text/html':return Response(404,b'<title>404 Not Found</title>')
|
||||
if self.expired:return Response(200,'<title>支付错误</title>订单已过期'.encode())
|
||||
fields=urllib.parse.parse_qs(req.data.decode())
|
||||
return Response(200,('<title>'+fields['type'][0]+' cashier</title>').encode())
|
||||
|
||||
class Cashier(unittest.TestCase):
|
||||
def fixture(self,root):
|
||||
for kind in ['alipay','wxpay']:
|
||||
fields={'pid':'synthetic','type':kind,'out_trade_no':'QA-only','money':'1','sign':'synthetic','sign_type':'MD5'}
|
||||
html='<form action="https://api.shangri-la.vc/submit.php" method="post">'+''.join('<input name="'+k+'" value="'+v+'">' for k,v in fields.items())+'</form>'
|
||||
(root/('cashier-'+kind+'.html')).write_text(html)
|
||||
def test_html_navigation_reaches_both_cashiers_without_payment_or_new_order(self):
|
||||
with tempfile.TemporaryDirectory()as d:
|
||||
root=pathlib.Path(d);self.fixture(root);processor=Processor();result=cashier.run(root,processor)
|
||||
self.assertEqual([c['http_status']for c in result['cases']],[200,200])
|
||||
self.assertEqual(len(processor.requests),2)
|
||||
self.assertTrue(all(req.get_method()=='POST'and req.full_url=='https://api.shangri-la.vc/submit.php'for req in processor.requests))
|
||||
self.assertEqual(result['real_money_paid'],0)
|
||||
self.assertTrue(result['actual_paid_callback_not_tested'])
|
||||
self.assertEqual(json.loads((root/'cashier-final-result.json').read_text()),result)
|
||||
def test_expired_200_is_reported_as_business_error(self):
|
||||
with tempfile.TemporaryDirectory()as d:
|
||||
root=pathlib.Path(d);self.fixture(root);result=cashier.run(root,Processor(expired=True))
|
||||
self.assertTrue(all('订单已过期'in c['error_indicators']for c in result['cases']))
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
// FUC-XB cutover only. The caller owns the target transaction and checks the instance.
|
||||
function fucAnnouncementRows(PDO $source, DateTimeZone $timezone): array
|
||||
{
|
||||
$rows = $source->query(
|
||||
'SELECT id, status, sort, date, content, title, rank
|
||||
FROM announcement ORDER BY sort DESC, date DESC, id DESC'
|
||||
);
|
||||
return fucProjectAnnouncements($rows, $timezone);
|
||||
}
|
||||
|
||||
function fucProjectAnnouncements(iterable $rows, DateTimeZone $timezone): array
|
||||
{
|
||||
$notices = [];
|
||||
foreach ($rows as $row) {
|
||||
$id = (int) $row['id'];
|
||||
$date = DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $row['date'], $timezone);
|
||||
if ($id < 1 || !$date || $date->format('Y-m-d H:i:s') !== $row['date']
|
||||
|| !in_array((string) $row['status'], ['0', '1'], true) || strlen($row['content']) > 65535
|
||||
|| mb_strlen($row['title']) > 255) {
|
||||
throw new RuntimeException('Announcement cannot be represented in the XB schema');
|
||||
}
|
||||
$tags = [];
|
||||
if ((int) $row['sort'] > 0) $tags[] = '旧站置顶';
|
||||
if ($row['rank'] && $row['rank'] !== 'none') $tags[] = $row['rank'];
|
||||
$notices[] = [
|
||||
'id' => $id,
|
||||
'sort' => count($notices) + 1,
|
||||
'title' => trim($row['title']) === '' ? '旧站公告 ' . $id : $row['title'],
|
||||
'content' => $row['content'],
|
||||
'show' => (int) $row['status'],
|
||||
'tags' => $tags ? json_encode($tags, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) : null,
|
||||
'created_at' => $date->getTimestamp(),
|
||||
'updated_at' => $date->getTimestamp(),
|
||||
];
|
||||
}
|
||||
return $notices;
|
||||
}
|
||||
|
||||
function fucImportAnnouncements(PDO $target, array $notices): array
|
||||
{
|
||||
if (!$target->inTransaction()) throw new LogicException('An active cutover transaction is required');
|
||||
$select = $target->query(
|
||||
'SELECT id, sort, title, content, `show`, tags, created_at, updated_at
|
||||
FROM v2_notice ORDER BY sort, id DESC FOR UPDATE'
|
||||
);
|
||||
$existing = $select->fetchAll(PDO::FETCH_ASSOC);
|
||||
$select->closeCursor();
|
||||
$normalize = static function (array $row): array {
|
||||
foreach (['id', 'sort', 'show', 'created_at', 'updated_at'] as $key) $row[$key] = (int) $row[$key];
|
||||
if ($row['tags'] !== null) $row['tags'] = json_decode($row['tags'], true, 8, JSON_THROW_ON_ERROR);
|
||||
return $row;
|
||||
};
|
||||
$expected = array_map($normalize, $notices);
|
||||
$inserted = 0;
|
||||
if (!$existing) {
|
||||
$insert = $target->prepare(
|
||||
'INSERT INTO v2_notice (id, sort, title, content, `show`, tags, created_at, updated_at)
|
||||
VALUES (:id, :sort, :title, :content, :show, :tags, :created_at, :updated_at)'
|
||||
);
|
||||
foreach ($notices as $notice) {
|
||||
$insert->execute($notice);
|
||||
$inserted++;
|
||||
}
|
||||
$select->execute();
|
||||
$existing = $select->fetchAll(PDO::FETCH_ASSOC);
|
||||
$select->closeCursor();
|
||||
}
|
||||
if (array_map($normalize, $existing) !== $expected) {
|
||||
throw new RuntimeException('XB announcement readback differs or the target contains existing notices');
|
||||
}
|
||||
return [
|
||||
'total' => count($notices),
|
||||
'visible' => array_sum(array_column($notices, 'show')),
|
||||
'inserted' => $inserted,
|
||||
'sha256' => hash('sha256', json_encode($expected, JSON_THROW_ON_ERROR)),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create one recoverable legacy FUC database dump after the write freeze."""
|
||||
|
||||
import datetime
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
PRIVATE = Path("/var/www/wwwroot/fuc-xb-test/private")
|
||||
SOCKET = "/run/mysqld/mysqld.sock"
|
||||
SOURCE = Path("/www/wwwroot/fuuuu.cloud")
|
||||
CLIENT = ["mariadb", "--protocol=socket", "--socket=" + SOCKET, "--batch", "--skip-column-names"]
|
||||
DUMP = [
|
||||
"mariadb-dump", "--protocol=socket", "--socket=" + SOCKET, "--quick",
|
||||
"--lock-tables", "--routines", "--events", "--triggers", "--hex-blob",
|
||||
"--default-character-set=utf8mb4", "--skip-add-locks",
|
||||
]
|
||||
|
||||
|
||||
def database_inventory(database):
|
||||
result = subprocess.run(CLIENT + [database], input=(
|
||||
"SELECT TABLE_NAME, TABLE_TYPE, COALESCE(ENGINE,'') FROM information_schema.TABLES "
|
||||
"WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME;"
|
||||
), text=True, capture_output=True, check=True, timeout=30)
|
||||
return result.stdout.splitlines()
|
||||
|
||||
|
||||
def database_programs(database):
|
||||
result = subprocess.run(CLIENT + [database], input=(
|
||||
"SELECT (SELECT COUNT(*) FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA=DATABASE()),"
|
||||
"(SELECT COUNT(*) FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA=DATABASE()),"
|
||||
"(SELECT COUNT(*) FROM information_schema.EVENTS WHERE EVENT_SCHEMA=DATABASE());"
|
||||
), text=True, capture_output=True, check=True, timeout=30)
|
||||
return dict(zip(("triggers", "routines", "events"), map(int, result.stdout.split()), strict=True))
|
||||
|
||||
|
||||
def validate_dump(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as compressed:
|
||||
for block in iter(lambda: compressed.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
tail = b""
|
||||
with gzip.open(path, "rb") as dump:
|
||||
for block in iter(lambda: dump.read(1024 * 1024), b""):
|
||||
tail = (tail + block)[-256:]
|
||||
if b"-- Dump completed on " not in tail:
|
||||
raise RuntimeError("MariaDB dump completion footer is missing")
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def backup(database, directory):
|
||||
if not re.fullmatch(r"[A-Za-z0-9_]+", database) or database.startswith("fuc_xb"):
|
||||
raise RuntimeError("Expected a legacy source database")
|
||||
inventory = database_inventory(database)
|
||||
programs = database_programs(database)
|
||||
if not inventory:
|
||||
raise RuntimeError("Empty legacy database inventory")
|
||||
destination = directory / "old-fuc-full.sql.gz"
|
||||
manifest = directory / "old-fuc-full.json"
|
||||
temporary = directory / "old-fuc-full.sql.gz.part"
|
||||
if any(os.path.lexists(path) for path in (destination, manifest, temporary)):
|
||||
raise RuntimeError("A legacy backup or partial attempt already exists")
|
||||
if shutil.disk_usage(directory).free < 256 * 1024 * 1024:
|
||||
raise RuntimeError("Insufficient space for the legacy backup")
|
||||
|
||||
try:
|
||||
with temporary.open("xb") as output:
|
||||
with subprocess.Popen(DUMP + [database], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as proc:
|
||||
try:
|
||||
with gzip.GzipFile(filename="", mode="wb", fileobj=output, mtime=0) as zipped:
|
||||
shutil.copyfileobj(proc.stdout, zipped)
|
||||
if proc.wait() != 0:
|
||||
raise RuntimeError("MariaDB legacy backup failed")
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
digest = validate_dump(temporary)
|
||||
if database_inventory(database) != inventory or database_programs(database) != programs:
|
||||
raise RuntimeError("Legacy database schema changed during the backup")
|
||||
receipt = {
|
||||
"created_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
"database_sha256": hashlib.sha256(database.encode()).hexdigest(),
|
||||
"inventory": inventory,
|
||||
"programs": programs,
|
||||
"bytes": temporary.stat().st_size,
|
||||
"sha256": digest,
|
||||
}
|
||||
os.rename(temporary, destination)
|
||||
with manifest.open("x") as handle:
|
||||
json.dump(receipt, handle, indent=2)
|
||||
handle.write("\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
return receipt
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2 or not re.fullmatch(r"cutover-[0-9]{8}T[0-9]{6}Z", sys.argv[1]):
|
||||
raise RuntimeError("An exact cutover window directory is required")
|
||||
directory = PRIVATE / sys.argv[1]
|
||||
gate = directory / "freeze-verified.json"
|
||||
if directory.resolve() != directory or gate.resolve() != gate:
|
||||
raise RuntimeError("A private cutover directory and freeze receipt are required")
|
||||
for path in (directory, gate):
|
||||
info = path.stat()
|
||||
if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077:
|
||||
raise RuntimeError("Cutover evidence must be private")
|
||||
with gate.open() as handle:
|
||||
freeze = json.load(handle)
|
||||
stopped = ("old_ingress_maintenance", "old_business_writers_stopped", "old_nodes_drained")
|
||||
verified = datetime.datetime.fromisoformat(freeze["verified_utc"])
|
||||
age = datetime.datetime.now(datetime.timezone.utc) - verified
|
||||
if any(freeze.get(key) is not True for key in stopped) or not 0 <= age.total_seconds() <= 900:
|
||||
raise RuntimeError("A current verified write freeze is required")
|
||||
database = subprocess.run(
|
||||
["php", "-r", "require 'config/.config.php'; echo $_ENV['db_database'];"],
|
||||
cwd=SOURCE, capture_output=True, text=True, check=True, timeout=10,
|
||||
).stdout
|
||||
if hashlib.sha256(database.encode()).hexdigest() != freeze["database_sha256"]:
|
||||
raise RuntimeError("Freeze receipt does not identify the legacy database")
|
||||
receipt = backup(database, directory)
|
||||
print(json.dumps({key: receipt[key] for key in ("created_utc", "bytes", "sha256")}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as exc:
|
||||
sys.exit(str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__)
|
||||
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"schema": "fuc-xb.catalog.v1",
|
||||
"source": "2026-11-05 readonly public products",
|
||||
"reset_traffic_method": 2,
|
||||
"period_semantics": "XB native calendar months; whole-term quota; no monthly reset",
|
||||
"products": [
|
||||
{
|
||||
"code": "lite-30",
|
||||
"series": "lite",
|
||||
"name": "轻量套餐",
|
||||
"price_yuan": 18.0,
|
||||
"quota_gb": 200,
|
||||
"period": "monthly"
|
||||
},
|
||||
{
|
||||
"code": "normal-30",
|
||||
"series": "normal",
|
||||
"name": "标准套餐",
|
||||
"price_yuan": 42.0,
|
||||
"quota_gb": 500,
|
||||
"period": "monthly"
|
||||
},
|
||||
{
|
||||
"code": "plus-30",
|
||||
"series": "plus",
|
||||
"name": "旗舰套餐",
|
||||
"price_yuan": 95.0,
|
||||
"quota_gb": 1170,
|
||||
"period": "monthly"
|
||||
},
|
||||
{
|
||||
"code": "pro-30",
|
||||
"series": "pro",
|
||||
"name": "专业套餐",
|
||||
"price_yuan": 194.0,
|
||||
"quota_gb": 2500,
|
||||
"period": "monthly"
|
||||
},
|
||||
{
|
||||
"code": "lite-90",
|
||||
"series": "lite",
|
||||
"name": "轻量套餐",
|
||||
"price_yuan": 51.0,
|
||||
"quota_gb": 600,
|
||||
"period": "quarterly"
|
||||
},
|
||||
{
|
||||
"code": "normal-90",
|
||||
"series": "normal",
|
||||
"name": "标准套餐",
|
||||
"price_yuan": 120.0,
|
||||
"quota_gb": 1500,
|
||||
"period": "quarterly"
|
||||
},
|
||||
{
|
||||
"code": "plus-90",
|
||||
"series": "plus",
|
||||
"name": "旗舰套餐",
|
||||
"price_yuan": 270.0,
|
||||
"quota_gb": 3500,
|
||||
"period": "quarterly"
|
||||
},
|
||||
{
|
||||
"code": "pro-90",
|
||||
"series": "pro",
|
||||
"name": "专业套餐",
|
||||
"price_yuan": 540.0,
|
||||
"quota_gb": 7500,
|
||||
"period": "quarterly"
|
||||
},
|
||||
{
|
||||
"code": "normal-365",
|
||||
"series": "normal",
|
||||
"name": "标准套餐",
|
||||
"price_yuan": 453.0,
|
||||
"quota_gb": 6000,
|
||||
"period": "yearly"
|
||||
},
|
||||
{
|
||||
"code": "plus-365",
|
||||
"series": "plus",
|
||||
"name": "旗舰套餐",
|
||||
"price_yuan": 1020.0,
|
||||
"quota_gb": 14000,
|
||||
"period": "yearly"
|
||||
},
|
||||
{
|
||||
"code": "pro-365",
|
||||
"series": "pro",
|
||||
"name": "专业套餐",
|
||||
"price_yuan": 2085.0,
|
||||
"quota_gb": 30000,
|
||||
"period": "yearly"
|
||||
},
|
||||
{
|
||||
"code": "lite-365",
|
||||
"series": "lite",
|
||||
"name": "轻量套餐",
|
||||
"price_yuan": 194.0,
|
||||
"quota_gb": 2400,
|
||||
"period": "yearly"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Observe the existing certificate. Never edits shared renewal hooks or keys."""
|
||||
import fcntl,hashlib,json,os,pathlib,socket,ssl,subprocess,time
|
||||
STATE=pathlib.Path('/var/lib/fuc-xb-node')
|
||||
def run(args):
|
||||
p=subprocess.run(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True,timeout=30)
|
||||
if p.returncode:raise RuntimeError('FUC certificate check failed; original services untouched')
|
||||
return p.stdout.strip()
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
lock=open('/run/lock/fuc-xb-node.lock','a')
|
||||
try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
except BlockingIOError:return
|
||||
state=json.loads((STATE/'owner.json').read_text());assert state['owner']=='fuc-xb-launch-20261105'
|
||||
row=state['node'];cert=row['certificate']
|
||||
run(['openssl','x509','-in',cert,'-noout','-checkhost',row['sni']]);run(['openssl','x509','-in',cert,'-noout','-checkend','604800']);run(['openssl','verify','-untrusted',cert,cert])
|
||||
assert run(['openssl','x509','-in',cert,'-pubkey','-noout'])==run(['openssl','pkey','-in',row['private_key'],'-pubout']),'Renewed certificate key mismatch'
|
||||
current=run(['openssl','x509','-in',cert,'-noout','-fingerprint','-sha256'])
|
||||
changed=current!=state['certificate_fingerprint']
|
||||
if changed:
|
||||
run(['systemctl','restart','fuc-xb-node']);assert run(['systemctl','is-active','fuc-xb-node'])=='active'
|
||||
for _ in range(30):
|
||||
pid=run(['systemctl','show','fuc-xb-node','-p','MainPID','--value'])
|
||||
if 'pid='+pid+',' in run(['ss','-H','-ltnp','sport = :24445']):break
|
||||
time.sleep(1)
|
||||
else:raise RuntimeError('FUC did not own its listener after certificate refresh')
|
||||
expected=bytes.fromhex(current.split('=',1)[1].replace(':',''))
|
||||
with socket.create_connection(('127.0.0.1',24445),timeout=8)as raw:
|
||||
with ssl.create_default_context().wrap_socket(raw,server_hostname=row['sni'])as tls:
|
||||
assert hashlib.sha256(tls.getpeercert(binary_form=True)).digest()==expected,'FUC did not load renewed certificate'
|
||||
state['certificate_fingerprint']=current
|
||||
tmp=STATE/'owner.json.tmp';tmp.write_text(json.dumps(state,indent=2));tmp.replace(STATE/'owner.json')
|
||||
print(json.dumps({'valid_over_7days':True,'certificate_changed':changed,'fuc_restarted':changed,'other_services_restarted':False}))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
|
||||
// Only the server-side acceptance client consumes stdout; it contains QA secrets.
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';$dir='/var/www/wwwroot/fuc-xb-test/private/launch-ready-20261105';
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
if(Illuminate\Support\Facades\DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
|
||||
$state=json_decode(file_get_contents($dir.'/panel-state.json'),true,512,JSON_THROW_ON_ERROR);if($state['owner']!=='fuc-xb-launch-20261105')throw new RuntimeException('Wrong owner');
|
||||
$u=App\Models\User::findOrFail($state['current_user_id']);if($u->group_id!==$state['qa_group_id']||!str_ends_with($u->email,'@fuc-xb.invalid'))throw new RuntimeException('Not restricted QA');
|
||||
$gate=json_decode(file_get_contents('/var/www/wwwroot/fuc-xb-test/private/gate-credentials.json'),true,512,JSON_THROW_ON_ERROR);$nodes=[];
|
||||
foreach($state['nodes']as$key=>$row){$n=App\Models\Server::findOrFail($row['node_id']);$m=App\Models\ServerMachine::findOrFail($row['machine_id']);if($m->name!=='fuc-xb-'.$key)throw new RuntimeException('Machine owner changed');$nodes[$key]=['node_id'=>$n->id,'machine_id'=>$m->id,'machine_token'=>$m->token,'spec'=>$row['spec'],'available_users'=>App\Services\ServerService::getAvailableUsers($n)->count(),'u'=>(int)$n->u,'d'=>(int)$n->d];}
|
||||
echo json_encode(['owner'=>$state['owner'],'manifest_sha256'=>$state['manifest_sha256'],'phase'=>$state['qa_phase'],'source'=>'https://fuc-xb-test.gemcook.net','alias'=>'https://fuc-xb-test.tomtojapan.online','gate_cookie'=>$gate['cookie_token'],'qa_uuid'=>$u->uuid,'subscribe_token'=>$u->token,'user_id'=>$u->id,'u'=>(int)$u->u,'d'=>(int)$u->d,'nodes'=>$nodes,'pending_traffic'=>Illuminate\Support\Facades\Queue::size('traffic_fetch'),'pending_stat'=>Illuminate\Support\Facades\Queue::size('stat')],JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real native subscriptions, each relay/exit, and saved-client revocation."""
|
||||
import argparse,fcntl,gzip,hashlib,json,os,pathlib,secrets,socket,ssl,subprocess,time,urllib.error,urllib.parse,urllib.request
|
||||
BASE=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/launch-ready-20261105/client')
|
||||
BIN=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104/bin/sing-box')
|
||||
SHA='768d31fa7f68debc067bb4626539498a1e8751d36a7b99e1a54bee6a23815f93'
|
||||
SOCKS=19876;CONTROL=29090;UNIT='fuc-xb-launch-client'
|
||||
STARTED=False
|
||||
def digest(value):return hashlib.sha256(json.dumps(value,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest()
|
||||
def identity(c):return {'user_id':c['user_id'],'uuid_sha256':hashlib.sha256(c['qa_uuid'].encode()).hexdigest(),'phase':c['phase'],'manifest_sha256':c['manifest_sha256'],'nodes_sha256':digest({k:{'node_id':n['node_id'],'machine_id':n['machine_id'],'token_sha256':hashlib.sha256(n['machine_token'].encode()).hexdigest(),'spec':n['spec']}for k,n in c['nodes'].items()}),'binary_sha256':SHA}
|
||||
def binding(c,d):
|
||||
b=json.loads((d/'binding.json').read_text());assert b['identity']==identity(c)and time.time()-b['created_at']<3600,'Stale/foreign QA progress'
|
||||
assert hashlib.sha256(BIN.read_bytes()).hexdigest()==b['identity']['binary_sha256'],'Client binary changed since positive test'
|
||||
assert hashlib.sha256((d/'client-full.json').read_bytes()).hexdigest()==b['config_sha256']and hashlib.sha256((d/'controller.json').read_bytes()).hexdigest()==b['controller_sha256'],'Saved client configuration changed'
|
||||
return b
|
||||
def run(args,timeout=45):return subprocess.run(args,capture_output=True,timeout=timeout)
|
||||
def context():
|
||||
p=run(['php',str(pathlib.Path(__file__).with_name('client-context.php'))]);assert p.returncode==0,'Client context unavailable'
|
||||
c=json.loads(p.stdout);assert c['owner']=='fuc-xb-launch-20261105'and len(c['nodes'])==22
|
||||
return c
|
||||
def fetch(c,flag,token=None):
|
||||
# The staging gate is intentionally not embedded in subscriptions or clients.
|
||||
url=c['source']+'/api/v1/client/subscribe?'+urllib.parse.urlencode({'token':token if token is not None else c['subscribe_token'],'flag':flag})
|
||||
req=urllib.request.Request(url,headers={'Cookie':'fuc_stage_access='+c['gate_cookie'],'User-Agent':'sing-box/1.14.3'if flag=='sing-box'else'clash.meta/1.19.32','Accept':'*/*'})
|
||||
try:r=urllib.request.urlopen(req,timeout=30)
|
||||
except urllib.error.HTTPError as e:r=e
|
||||
with r:
|
||||
raw=r.read(8*1024*1024)
|
||||
if r.headers.get('Content-Encoding')=='gzip':raw=gzip.decompress(raw)
|
||||
return r.status,raw
|
||||
def api(c,path,params):
|
||||
if path.startswith('machine/'):
|
||||
req=urllib.request.Request(c['source']+'/api/v2/server/'+path,data=json.dumps(params).encode(),headers={'Accept':'application/json','Content-Type':'application/json'},method='POST')
|
||||
else:req=urllib.request.Request(c['source']+'/api/v2/server/'+path+'?'+urllib.parse.urlencode(params),headers={'Accept':'application/json'})
|
||||
try:r=urllib.request.urlopen(req,timeout=25)
|
||||
except urllib.error.HTTPError as e:r=e
|
||||
with r:return r.status,r.read(2*1024*1024)
|
||||
def auth_matrix(c,empty=False):
|
||||
receipts=[];ids={n['node_id']for n in c['nodes'].values()}
|
||||
for key,n in c['nodes'].items():
|
||||
args={'machine_id':n['machine_id'],'token':n['machine_token']}
|
||||
code,body=api(c,'machine/nodes',args);rows=json.loads(body).get('nodes',[])
|
||||
assert code==200 and [x['id']for x in rows]==[n['node_id']],'Machine binding incorrect: '+key
|
||||
code,body=api(c,'user',{**args,'node_id':n['node_id']});users=json.loads(body).get('users',[])
|
||||
assert code==200 and len(users)==(0 if empty else 1),'Unexpected native user list: '+key
|
||||
if not empty:assert int(users[0]['id'])==c['user_id'],'A migrated customer reached QA node'
|
||||
wrong=next(i for i in ids if i!=n['node_id'])
|
||||
assert api(c,'machine/nodes',{**args,'token':'deliberately-invalid'})[0]==403
|
||||
assert api(c,'config',{**args,'node_id':wrong})[0]in [400,401,403]
|
||||
receipts.append({'key':key,'exact_owned_node':True,'available_users':len(users),'wrong_token_rejected':True,'unowned_node_rejected':True,'no_web_gate_cookie_used':True})
|
||||
return receipts
|
||||
def prepare(c,d):
|
||||
assert hashlib.sha256(BIN.read_bytes()).hexdigest()==SHA,'Client binary drift'
|
||||
code,raw=fetch(c,'sing-box');assert code==200,'Native full subscription failed'
|
||||
cfg=json.loads(raw);proxies=[x for x in cfg['outbounds']if x.get('type')=='anytls'];assert len(proxies)==22,'Native node count mismatch'
|
||||
found={}
|
||||
for key,n in c['nodes'].items():
|
||||
row=n['spec'];matches=[x for x in proxies if x['server']==row['relay_host']and x['server_port']==row['relay_port']];assert len(matches)==1,'Native route mismatch: '+key
|
||||
p=matches[0];assert p['password']==c['qa_uuid']and p['tls']['enabled']and p['tls'].get('insecure')is False and p['tls']['server_name']==row['sni'],'Native TLS/identity mismatch'
|
||||
found[key]=p['tag']
|
||||
(d/'subscription-singbox.json').write_bytes(raw)
|
||||
code,clash=fetch(c,'meta');assert code==200 and b'anytls'in clash and c['qa_uuid'].encode()in clash,'Native Clash subscription failed';(d/'subscription-clash.yaml').write_bytes(clash)
|
||||
php=r"require '/var/www/wwwroot/fuc-xb-test/current/vendor/autoload.php';echo json_encode(Symfony\Component\Yaml\Yaml::parse(stream_get_contents(STDIN)));"
|
||||
parsed=subprocess.run(['php','-r',php],input=clash,capture_output=True,timeout=20);assert parsed.returncode==0,'Native Clash YAML parse failed'
|
||||
meta=json.loads(parsed.stdout);meta_nodes=[p for p in meta['proxies']if p.get('type')=='anytls'];assert len(meta_nodes)==22,'Clash Meta node count mismatch'
|
||||
for key,n in c['nodes'].items():
|
||||
spec=n['spec'];matches=[p for p in meta_nodes if p['server']==spec['relay_host']and p['port']==spec['relay_port']];assert len(matches)==1,'Clash route mismatch: '+key
|
||||
p=matches[0];assert p['password']==c['qa_uuid']and p.get('skip-cert-verify',False)is False and p.get('sni')==spec['sni'],'Clash TLS/identity mismatch: '+key
|
||||
assert fetch(c,'sing-box','deliberately-invalid-subscription')[0]==403
|
||||
if(d/'binding.json').exists():
|
||||
old=binding(c,d);assert old['native_sha256']==hashlib.sha256(raw).hexdigest(),'Native subscription changed during resumed test'
|
||||
return {'native_full_config_checked':True,'binding':old,'resumed_same_configuration':True,'clash_meta_nodes_checked':22}
|
||||
cfg['inbounds']=[{'type':'mixed','tag':'qa-local','listen':'127.0.0.1','listen_port':SOCKS}]
|
||||
control_secret=secrets.token_hex(24);cfg.setdefault('experimental',{})['clash_api']={'external_controller':'127.0.0.1:'+str(CONTROL),'secret':control_secret,'default_mode':'global'}
|
||||
(d/'client-full.json').write_text(json.dumps(cfg,ensure_ascii=False));(d/'controller.json').write_text(json.dumps({'secret':control_secret,'tags':found}))
|
||||
checked=run([str(BIN),'check','-c',str(d/'client-full.json')]);(d/'config-check.stderr').write_bytes(checked.stderr)
|
||||
assert checked.returncode==0,'Native config rejected by real client; diagnostic private'
|
||||
b={'identity':identity(c),'created_at':int(time.time()),'native_sha256':hashlib.sha256(raw).hexdigest(),'config_sha256':hashlib.sha256((d/'client-full.json').read_bytes()).hexdigest(),'controller_sha256':hashlib.sha256((d/'controller.json').read_bytes()).hexdigest()};(d/'binding.json').write_text(json.dumps(b,indent=2))
|
||||
return {'native_full_config_checked':True,'native_anytls_nodes':22,'all_tls_strict':True,'native_outbounds_dns_rules_retained':True,'only_inbounds_and_loopback_controller_changed':True,'invalid_subscription_rejected':True,'clash_meta_nodes_checked':22,'binding':b}
|
||||
def start(d):
|
||||
global STARTED
|
||||
STARTED=False
|
||||
for port in [SOCKS,CONTROL]:assert not run(['ss','-H','-ltn','sport = :'+str(port)]).stdout.strip(),'QA listener collision'
|
||||
p=run(['systemd-run','--quiet','--collect','--unit='+UNIT,'--description=FUC-XB launch restricted QA client','--property=RuntimeMaxSec=1200','--property=MemoryMax=384M','--property=CPUQuota=40%','--working-directory='+str(d),str(BIN),'run','-D',str(d),'-c',str(d/'client-full.json')]);assert p.returncode==0,'QA client did not start';STARTED=True
|
||||
for _ in range(50):
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1',CONTROL),timeout=.3):return
|
||||
except OSError:time.sleep(.2)
|
||||
raise RuntimeError('QA controller unavailable')
|
||||
def stop():
|
||||
global STARTED
|
||||
if not STARTED:return
|
||||
props=run(['systemctl','show',UNIT,'-p','Description','-p','LoadState','-p','MainPID']).stdout.decode()
|
||||
state=dict(line.split('=',1)for line in props.splitlines()if '='in line)
|
||||
gone=state.get('LoadState')=='not-found'and state.get('MainPID')=='0'
|
||||
if not gone:
|
||||
assert state.get('Description')=='FUC-XB launch restricted QA client','QA unit ownership changed'
|
||||
assert run(['systemctl','stop',UNIT]).returncode==0,'QA client stop failed'
|
||||
for port in [SOCKS,CONTROL]:assert not run(['ss','-H','-ltn','sport = :'+str(port)]).stdout.strip(),'QA listener remains active'
|
||||
STARTED=False
|
||||
def select(d,key):
|
||||
c=json.loads((d/'controller.json').read_text());request=urllib.request.Request('http://127.0.0.1:'+str(CONTROL)+'/proxies/'+urllib.parse.quote('节点选择',safe=''),data=json.dumps({'name':c['tags'][key]},ensure_ascii=False).encode(),headers={'Authorization':'Bearer '+c['secret'],'Content-Type':'application/json'},method='PUT')
|
||||
with urllib.request.urlopen(request,timeout=10)as r:assert r.status in [200,204],'Client selector failed'
|
||||
def tls_alive(spec):
|
||||
with socket.create_connection((spec['relay_host'],spec['relay_port']),timeout=8)as raw:
|
||||
with ssl.create_default_context().wrap_socket(raw,server_hostname=spec['sni'])as tls:return tls.version()
|
||||
def network(c,d,revoked=False):
|
||||
b=binding(c,d)
|
||||
progress=d/('revoked-progress.json'if revoked else'network-progress.json')
|
||||
old=json.loads(progress.read_text())if progress.exists()else{'binding':b,'nodes':{}};assert old['binding']==b,'Progress belongs to another client';result=old['nodes']
|
||||
assert set(result).issubset(c['nodes']),'Foreign progress'
|
||||
try:
|
||||
start(d)
|
||||
if revoked:
|
||||
with urllib.request.urlopen('https://api.ipify.org?format=json',timeout=12)as r:assert r.status==200 and json.loads(r.read()).get('ip'),'Public target health unavailable'
|
||||
for key,n in c['nodes'].items():
|
||||
if key in result:continue
|
||||
select(d,key);spec=n['spec'];tls=tls_alive(spec)
|
||||
base=['curl','-sS','--proxy','socks5h://127.0.0.1:'+str(SOCKS),'--connect-timeout','5','--max-time','12'if revoked else'25']
|
||||
ip=run(base+['https://api.ipify.org?format=json'],35)
|
||||
if revoked:
|
||||
(d/('rejected-'+key+'.stderr')).write_bytes(ip.stderr)
|
||||
assert ip.returncode in [35,52,56,97] and not ip.stdout,'No definite saved-client rejection: '+key
|
||||
row={'saved_config_rejected':True,'curl_exit':ip.returncode,'node_tls_still_alive':tls,'target_health_confirmed':True,'stderr_sha256':hashlib.sha256(ip.stderr).hexdigest()}
|
||||
else:
|
||||
assert ip.returncode==0 and json.loads(ip.stdout)['ip']==spec['expected_exit'],'Real exit mismatch: '+key
|
||||
down=run(base+['https://speed.cloudflare.com/__down?bytes=65536'],35);assert down.returncode==0 and len(down.stdout)==65536,'Download failed: '+key
|
||||
body=b'FUC-XB-QA-ONLY\n'*2048;(d/'upload.bin').write_bytes(body)
|
||||
up=run(base+['-H','Content-Type: application/octet-stream','--data-binary','@'+str(d/'upload.bin'),'https://httpbin.org/post'],35);assert up.returncode==0 and json.loads(up.stdout).get('data','').encode()==body,'Upload echo failed: '+key
|
||||
row={'actual_exit':spec['expected_exit'],'tls':tls,'download_bytes':len(down.stdout),'upload_bytes':len(body),'native_selector_used':True}
|
||||
result[key]=row;progress.write_text(json.dumps({'binding':b,'nodes':result},indent=2));print(json.dumps({'phase':c['phase'],'key':key,**row}),flush=True)
|
||||
finally:stop()
|
||||
return result
|
||||
def traffic(c,before):
|
||||
for _ in range(25):
|
||||
after=context();assert identity(after)==identity(c),'QA identity changed while waiting for reports'
|
||||
delta={k:{s:after['nodes'][k][s]-before['nodes'][k][s]for s in ['u','d']}for k in c['nodes']}
|
||||
user={s:after[s]-before[s]for s in ['u','d']};raw={s:sum(n[s]for n in delta.values())for s in ['u','d']}
|
||||
if not after['pending_traffic']and not after['pending_stat']and all(n['u']>0 and n['d']>0 for n in delta.values())and all(user[s]==2*raw[s]for s in ['u','d']):
|
||||
return {'all_22_nodes_reported_upload_download':True,'rate':2,'raw_bytes':raw,'rated_user_bytes':user,'native_user_and_server_counts_exact':True,'per_node_delta':delta}
|
||||
time.sleep(2)
|
||||
raise RuntimeError('Native traffic reports/rate not reconciled')
|
||||
def main():
|
||||
os.umask(0o077);BASE.mkdir(mode=0o700,parents=True,exist_ok=True);lock=(BASE/'operation.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','run','revoked','api']);args=p.parse_args();c=context();d=BASE/c['phase'];d.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
if args.action=='api':result={'phase':c['phase'],'authentication':auth_matrix(c,any(n['available_users']==0 for n in c['nodes'].values()))}
|
||||
elif args.action=='revoked':
|
||||
assert(d/'network-result.json').is_file(),'Positive test missing'
|
||||
positive=json.loads((d/'network-result.json').read_text());assert positive['binding']==binding(c,d),'Revocation configuration differs from positive test'
|
||||
code,_=fetch(c,'sing-box');assert code==(200 if c['phase']=='exhausted'else 403),'Unexpected native subscription status'
|
||||
result={'phase':c['phase'],'binding':binding(c,d),'subscription_status':code,'authentication':auth_matrix(c,True),'nodes':network(c,d,True),'temporary_client_stopped':True};(d/'revocation-result.json').write_text(json.dumps(result,indent=2))
|
||||
else:
|
||||
assert not(d/'network-result.json').exists(),'Existing completed test; inspect rather than repeat'
|
||||
result=prepare(c,d);result['authentication']=auth_matrix(c)
|
||||
if args.action=='run':
|
||||
before_file=d/'traffic-before.json'
|
||||
if before_file.exists():before=json.loads(before_file.read_text());assert before['binding']==binding(c,d),'Traffic baseline changed'
|
||||
else:
|
||||
before={'binding':binding(c,d),'user_id':c['user_id'],'u':c['u'],'d':c['d'],'nodes':{k:{'u':n['u'],'d':n['d']}for k,n in c['nodes'].items()}};before_file.write_text(json.dumps(before,indent=2))
|
||||
result.update(phase=c['phase'],nodes=network(c,d),temporary_client_stopped=True);result['traffic']=traffic(c,before);(d/'network-result.json').write_text(json.dumps(result,indent=2))
|
||||
print(json.dumps({'passed':True,'phase':c['phase'],'action':args.action,'nodes_checked':len(result.get('nodes',result.get('authentication',[])))}))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
|
||||
$dir='/var/www/wwwroot/fuc-xb-test/private/launch-ready-20261105';$root='/var/www/wwwroot/fuc-xb-test/current';
|
||||
if(is_file($dir.'/configured.json'))throw new RuntimeException('Already configured; inspect before repeating');
|
||||
$credentials=json_decode(stream_get_contents(STDIN),true,16,JSON_THROW_ON_ERROR);
|
||||
if(empty($credentials['merchant_id'])||empty($credentials['api_key']))throw new RuntimeException('Missing registered merchant');
|
||||
chdir('/www/wwwroot/fuuuu.cloud');require 'config/.config.php';
|
||||
$dsn=!empty($_ENV['db_socket'])?'mysql:unix_socket='.$_ENV['db_socket']:'mysql:host='.$_ENV['db_host'].';port='.$_ENV['db_port'];
|
||||
$pdo=new PDO($dsn.';dbname='.$_ENV['db_database'].';charset=utf8mb4',$_ENV['db_username'],$_ENV['db_password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
|
||||
$pdo->exec('SET TRANSACTION READ ONLY');$pdo->beginTransaction();
|
||||
$smtp=$pdo->query("SELECT item,value FROM config WHERE item IN ('smtp_host','smtp_port','smtp_username','smtp_password','smtp_sender','smtp_ssl')")->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||
$resend=$pdo->query("SELECT apikey,auther FROM mail_must WHERE client='resend' AND status=1 LIMIT 1")->fetch();$pdo->rollBack();unset($pdo);
|
||||
if(($smtp['smtp_host']??'')!=='mail.privateemail.com'||($smtp['smtp_sender']??'')!=='[email protected]'||(int)$smtp['smtp_port']!==465||empty($smtp['smtp_password'])||empty($resend['apikey']))throw new RuntimeException('Registered source mail settings changed');
|
||||
chdir($root);putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\{DB,Cache,Crypt};use App\Models\{Payment,Plugin};
|
||||
if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
|
||||
$lock=fopen($dir.'/panel.lock','c');if(!flock($lock,LOCK_EX|LOCK_NB))throw new RuntimeException('Another preparation is running');
|
||||
if(Payment::count())throw new RuntimeException('Unexpected existing payment channels');
|
||||
$before=DB::table('v2_settings')->orderBy('id')->get()->toJson();file_put_contents($dir.'/settings-before-mail-payment.json',$before);chmod($dir.'/settings-before-mail-payment.json',0600);
|
||||
$result=DB::transaction(function()use($dir,$smtp,$resend,$credentials){
|
||||
$flow=array_replace((array)admin_setting('mail_flow',[]),['enabled'=>true,'resend_enabled'=>true,'resend_key'=>'encrypted:'.Crypt::encryptString($resend['apikey']),'resend_from'=>$resend['auther'],'reply_to'=>'[email protected]','inbound_enabled'=>false,'auto_reply_enabled'=>false,'report_enabled'=>false,'daily_limit'=>100,'monthly_limit'=>3000]);
|
||||
app(App\Support\Setting::class)->save(['mail_flow'=>$flow,'automatic_mail_policy'=>['level'=>3,'since'=>null],'remind_mail_enable'=>0,'email_host'=>$smtp['smtp_host'],'email_port'=>(int)$smtp['smtp_port'],'email_username'=>$smtp['smtp_username'],'email_password'=>$smtp['smtp_password'],'email_encryption'=>'ssl','email_from_address'=>'[email protected]','email_verify'=>1,'stop_register'=>1,'telegram_bot_enable'=>0,'server_ws_enable'=>0]);
|
||||
$pm=app(App\Services\Plugin\PluginManager::class);if(!Plugin::where('code','epay')->exists())$pm->install('epay');$pm->enable('epay');
|
||||
$channels=[];foreach(['alipay'=>'支付宝','wxpay'=>'微信支付']as$type=>$name){$p=Payment::create(['uuid'=>App\Utils\Helper::randomChar(8),'name'=>'空中支付 · '.$name,'payment'=>'EPay','enable'=>false,'sort'=>count($channels)+1,'handling_fee_fixed'=>0,'handling_fee_percent'=>0,'notify_domain'=>'https://fuc-xb-test.gemcook.net','config'=>['url'=>'https://pay.airspay.top','pid'=>$credentials['merchant_id'],'key'=>$credentials['api_key'],'type'=>$type]]);$channels[$type]=['id'=>$p->id,'uuid'=>$p->uuid];}
|
||||
$result=['configured'=>true,'smtp_configured'=>true,'resend_configured'=>true,'real_mail_sent_by_configuration'=>0,'bulk_automatic_mail_disabled'=>true,'inbound_mail_disabled'=>true,'registration_still_disabled'=>true,'payment_channels'=>$channels,'payment_channels_disabled_until_cutover'=>true,'real_money_paid'=>0,'websocket_disabled_polling_native'=>true,'production_site_changed'=>false];
|
||||
file_put_contents($dir.'/configured.json',json_encode($result,JSON_PRETTY_PRINT));chmod($dir.'/configured.json',0600);return $result;
|
||||
});
|
||||
Cache::store('redis')->forget(App\Support\Setting::CACHE_KEY);echo json_encode($result).PHP_EOL;
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
// Exports the verified restore of the frozen legacy backup.
|
||||
ini_set('display_errors', '0');
|
||||
try {
|
||||
$database = $argv[1] ?? '';
|
||||
if (PHP_SAPI !== 'cli' || !preg_match('/\Afuc_legacy_restore_[a-f0-9]{12}\z/D', $database)) {
|
||||
throw new RuntimeException('Expected an isolated legacy restore');
|
||||
}
|
||||
$sourceRoot = '/www/wwwroot/fuuuu.cloud';
|
||||
chdir($sourceRoot);
|
||||
require $sourceRoot . '/config/.config.php';
|
||||
$connection = new PDO(
|
||||
'mysql:unix_socket=/run/mysqld/mysqld.sock;dbname=' . $database . ';charset=utf8mb4',
|
||||
'root', '',
|
||||
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
|
||||
);
|
||||
$tables = ['user', 'order', 'plan_queue', 'product', 'invoice', 'paylist', 'user_money_log',
|
||||
'payback', 'invite_up', 'link', 'user_coupon', 'vip_map', 'renewal_quote', 'announcement'];
|
||||
$omitUser = ['ga_token', 'api_token', 'usdt_addr', 'reg_ip', 'remark', 'banned_reason'];
|
||||
$write = static function (array $record): void {
|
||||
echo json_encode($record, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), "\n";
|
||||
};
|
||||
$counts = $columns = [];
|
||||
foreach ($tables as $table) {
|
||||
$columns[$table] = $connection->query('SHOW COLUMNS FROM `' . $table . '`')->fetchAll(PDO::FETCH_COLUMN);
|
||||
if ($table === 'user') $columns[$table] = array_values(array_diff($columns[$table], $omitUser));
|
||||
$counts[$table] = (int) $connection->query('SELECT COUNT(*) FROM `' . $table . '`')->fetchColumn();
|
||||
}
|
||||
$write([
|
||||
'kind' => 'header', 'format' => 'fuc-research-snapshot-v1', 'snapshot_utc' => gmdate('c'),
|
||||
'timezone' => $_ENV['timeZone'], 'database_identity_sha256' => hash('sha256', $_ENV['db_database']),
|
||||
'counts' => $counts,
|
||||
]);
|
||||
foreach ($tables as $table) {
|
||||
$fields = implode(',', array_map(static fn ($field) => '`' . $field . '`', $columns[$table]));
|
||||
$order = $table === 'announcement' ? ' ORDER BY sort DESC,date DESC,id DESC'
|
||||
: (in_array('id', $columns[$table], true) ? ' ORDER BY id' : '');
|
||||
$rows = $connection->query('SELECT ' . $fields . ' FROM `' . $table . '`' . $order);
|
||||
foreach ($rows as $row) $write(['kind' => 'row', 'table' => $table, 'row' => $row]);
|
||||
}
|
||||
$write(['kind' => 'footer', 'counts' => $counts, 'source_business_writes' => 0]);
|
||||
} catch (Throwable $failure) {
|
||||
fwrite(STDERR, get_class($failure) . ' on line ' . $failure->getLine() . "\n");
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Approved staging exception for XB native V2 machine authentication only."""
|
||||
import hashlib, json, os, pathlib, shutil, subprocess
|
||||
|
||||
BASE = pathlib.Path('/var/www/wwwroot/fuc-xb-test')
|
||||
TARGET = pathlib.Path('/etc/nginx/conf.d/fuc-xb-test.conf')
|
||||
EXPECTED = '8427a451875673b28d678e12100b306584c21f8ddc71487dac6b28e05cac1066'
|
||||
LOCATION = ''' location ^~ /api/v2/server/ {
|
||||
# Native XB machine authentication; no staging web-cookie replication.
|
||||
limit_except GET POST { deny all; }
|
||||
client_max_body_size 2m;
|
||||
include fastcgi_params;
|
||||
fastcgi_param SCRIPT_FILENAME $realpath_root/index.php;
|
||||
fastcgi_param SCRIPT_NAME /index.php;
|
||||
fastcgi_param XB_INSTANCE fuc-xb-test;
|
||||
fastcgi_pass unix:/run/php/php8.4-fuc-xb-test.sock;
|
||||
fastcgi_read_timeout 45s;
|
||||
}
|
||||
'''
|
||||
|
||||
def checked(args):
|
||||
p = subprocess.run(args, capture_output=True)
|
||||
assert p.returncode == 0, 'Gate command failed; configuration restored if needed'
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
before = TARGET.read_bytes()
|
||||
assert hashlib.sha256(before).hexdigest() == EXPECTED, 'Configuration changed; inspect before applying'
|
||||
checked(['nginx', '-t'])
|
||||
text = before.decode()
|
||||
assert text.count(' location = /stage-login {') == 2
|
||||
assert '/api/v2/server/' not in text
|
||||
backup = BASE/'private/launch-ready-20261105/gate-before.conf'
|
||||
assert not backup.exists(), 'Existing intent; inspect receipt rather than repeat'
|
||||
backup.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
backup.write_bytes(before)
|
||||
after = text.replace(' location = /stage-login {', LOCATION+' location = /stage-login {').encode()
|
||||
try:
|
||||
TARGET.write_bytes(after)
|
||||
checked(['nginx','-t'])
|
||||
checked(['systemctl','reload','nginx'])
|
||||
except BaseException:
|
||||
TARGET.write_bytes(before)
|
||||
checked(['nginx','-t'])
|
||||
checked(['systemctl','reload','nginx'])
|
||||
raise
|
||||
value = {'changed':True,'native_machine_auth_only':True,'exception':'/api/v2/server/','website_gate_retained':True,'xb_core_changed':False,'before_sha256':EXPECTED,'after_sha256':hashlib.sha256(after).hexdigest(),'rollback':str(backup)}
|
||||
(backup.parent/'gate-applied.json').write_text(json.dumps(value,indent=2))
|
||||
print(json.dumps(value))
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Give only this FUC CLI worker the process functions Horizon requires."""
|
||||
import hashlib,json,os,pathlib,pwd,subprocess
|
||||
BASE=pathlib.Path('/var/www/wwwroot/fuc-xb-test')
|
||||
UNIT=pathlib.Path('/etc/systemd/system/fuc-xb-test-horizon.service')
|
||||
DIR=BASE/'private/launch-ready-20261105/horizon-php'
|
||||
SCAN=BASE/'shared/horizon-php.d'
|
||||
EXPECTED='b3d82cb30ef7e42fcdfbc97c5b2d6eb2a70477eda4ee5dbb26f3a261b17ed67a'
|
||||
REQUIRED={'proc_open','proc_get_status','proc_close','proc_terminate'}
|
||||
def run(args,env=None):
|
||||
p=subprocess.run(args,capture_output=True,text=True,env=env,timeout=100)
|
||||
assert p.returncode==0,'FUC CLI worker operation failed'
|
||||
return p.stdout.strip()
|
||||
def main():
|
||||
os.umask(0o077);assert hashlib.sha256(UNIT.read_bytes()).hexdigest()==EXPECTED
|
||||
settings=json.loads(run(['php','-r',"echo json_encode(['scan'=>PHP_CONFIG_FILE_SCAN_DIR,'disabled'=>ini_get('disable_functions'),'ini'=>php_ini_loaded_file()]);"]))
|
||||
source=pathlib.Path(settings['scan']);assert source.is_dir() and source.is_absolute()and ':'not in str(source)
|
||||
disabled={x.strip()for x in settings['disabled'].split(',')if x.strip()};restored=sorted(disabled&REQUIRED)
|
||||
assert 'proc_open'in restored,'Unexpected CLI hardening; inspect rather than changing'
|
||||
before=UNIT.read_bytes();group=pwd.getpwnam('fucxbtest').pw_gid
|
||||
if DIR.exists()or SCAN.exists():
|
||||
assert DIR.is_dir()and SCAN.is_dir()and not DIR.is_symlink()and not SCAN.is_symlink()
|
||||
assert not(DIR/'receipt.json').exists()and (DIR/'unit-before').read_bytes()==before,'Foreign/completed override'
|
||||
assert {p.name for p in SCAN.iterdir()}=={p.name for p in source.glob('*.ini')}|{'zz-fuc-horizon-process.ini'},'Partial override changed'
|
||||
else:
|
||||
DIR.mkdir(mode=0o700);(DIR/'unit-before').write_bytes(before);SCAN.mkdir(mode=0o750)
|
||||
SCAN.chmod(0o750);os.chown(SCAN,0,group)
|
||||
sources={}
|
||||
for f in sorted(source.glob('*.ini')):
|
||||
assert f.is_file();target=SCAN/f.name
|
||||
if os.path.lexists(target):assert target.is_symlink()and target.resolve()==f.resolve(),'INI source changed'
|
||||
else:target.symlink_to(f)
|
||||
sources[str(f.resolve())]=hashlib.sha256(f.read_bytes()).hexdigest()
|
||||
override=SCAN/'zz-fuc-horizon-process.ini';content='disable_functions='+','.join(sorted(disabled-REQUIRED))+'\n'
|
||||
if override.exists():assert override.is_file()and not override.is_symlink()and override.read_text()==content,'INI override changed'
|
||||
else:override.write_text(content)
|
||||
override.chmod(0o640);os.chown(override,0,group)
|
||||
env={**os.environ,'PHP_INI_SCAN_DIR':str(SCAN),'XB_INSTANCE':'fuc-xb-test'}
|
||||
probe=json.loads(run(['runuser','-u','fucxbtest','--','env','PHP_INI_SCAN_DIR='+str(SCAN),'php','-r',"echo json_encode(array_combine(['proc_open','proc_get_status','proc_close','proc_terminate'],array_map('function_exists',['proc_open','proc_get_status','proc_close','proc_terminate'])));"],env))
|
||||
assert all(probe.values()),'Required FUC worker process functions unavailable'
|
||||
updated=before.decode().replace('Environment=XB_INSTANCE=fuc-xb-test\n','Environment=XB_INSTANCE=fuc-xb-test\nEnvironment=PHP_INI_SCAN_DIR='+str(SCAN)+'\n')
|
||||
assert updated!=before.decode()
|
||||
try:
|
||||
UNIT.write_text(updated);UNIT.chmod(0o644);run(['systemctl','daemon-reload']);run(['systemctl','restart','fuc-xb-test-horizon'])
|
||||
assert run(['systemctl','is-active','fuc-xb-test-horizon'])=='active'
|
||||
assert all(hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest()==sha for p,sha in sources.items()),'Global PHP sources changed'
|
||||
except BaseException:
|
||||
UNIT.write_bytes(before);run(['systemctl','daemon-reload']);run(['systemctl','restart','fuc-xb-test-horizon']);raise
|
||||
receipt={'configured':True,'scope':'FUC-XB CLI Horizon and its children only','restored_process_functions':restored,'global_php_and_fpm_unchanged':True,'other_disabled_functions_retained':True,'unit_sha256':hashlib.sha256(UNIT.read_bytes()).hexdigest(),'scan_directory':str(SCAN),'source_ini_sha256':sources}
|
||||
(DIR/'receipt.json').write_text(json.dumps(receipt,indent=2));print(json.dumps({k:v for k,v in receipt.items()if k!='source_ini_sha256'}))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';$dir='/var/www/wwwroot/fuc-xb-test/private/launch-ready-20261105';
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\{DB,Cache};use App\Models\MailMessage;
|
||||
if(DB::connection()->getDatabaseName()!=='fuc_xb_test'||config('queue.default')!=='redis'||config('mail.driver')!=='smtp'||App\Services\MailFlow\AutomaticMailPolicy::state()['level']!==3)throw new RuntimeException('Mail worker isolation guard failed');
|
||||
$action=$argv[1]??'';$file=$dir.'/mail-queue-intent.json';$recipient='[email protected]';$key='fuc-xb-launch-worker-20261105-notification';
|
||||
if($action==='enqueue'){
|
||||
if(is_file($file))throw new RuntimeException('Existing intent; inspect receipts rather than resend');
|
||||
$before=MailMessage::where('email',$recipient)->pluck('id')->all();file_put_contents($file,json_encode(['recipient'=>$recipient,'before_ids'=>$before,'started_at'=>time(),'expected_messages'=>2]));chmod($file,0600);
|
||||
// Exercise the native verification controller -> Redis -> persistent Horizon worker.
|
||||
$r=Illuminate\Http\Request::create('https://fuc-xb-test.gemcook.net/api/v1/passport/comm/sendEmailVerify','POST',['email'=>$recipient],[],[],['HTTP_ACCEPT'=>'application/json','REMOTE_ADDR'=>'127.0.0.1']);app()->instance('request',$r);$response=app(Illuminate\Contracts\Http\Kernel::class)->handle($r);if($response->getStatusCode()!==200)throw new RuntimeException('Native verification enqueue failed');
|
||||
App\Jobs\SendEmailJob::dispatch(['email'=>$recipient,'subject'=>'[FUC-XB 工作队列验收 20261105] 通知邮件','template_name'=>'notify','purpose'=>'admin_test','message_key'=>$key,'template_value'=>['name'=>'FUC-XB_TEST','content'=>'仅用于独立测试站真实工作队列验收;不涉及正式切换或扣款。','url'=>'https://fuc-xb-test.tomtojapan.online']]);
|
||||
echo json_encode(['queued'=>true,'recipient'=>$recipient,'expected_messages'=>2,'queue'=>'redis','worker'=>'persistent Horizon','mass_mail_sent'=>0]);exit;
|
||||
}
|
||||
if($action==='status'){
|
||||
$s=json_decode(file_get_contents($file),true,512,JSON_THROW_ON_ERROR);$rows=MailMessage::where('email',$recipient)->whereNotIn('id',$s['before_ids'])->get();if($rows->count()>2)throw new RuntimeException('Unexpected duplicate mail; stop');
|
||||
$out=[];foreach($rows as$m){$event=null;if($m->channel==='resend'&&$m->provider_id){try{$event=app(App\Services\MailFlow\ResendClient::class)->retrieve($m->provider_id)['last_event']??null;}catch(Throwable){$event='provider_status_unavailable';}}
|
||||
$out[]=['id'=>$m->id,'purpose'=>$m->purpose,'channel'=>$m->channel,'status'=>$m->status,'attempts'=>$m->attempts,'provider_event'=>$event];}
|
||||
$passed=count($out)===2&&!array_filter($out,fn($r)=>!in_array($r['status'],['submitted','delivered'],true)||$r['attempts']!==1);
|
||||
if($passed){Cache::forget(App\Utils\CacheKey::get('EMAIL_VERIFY_CODE',$recipient));Cache::forget(App\Utils\CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP',$recipient));file_put_contents($dir.'/mail-queue-receipt.json',json_encode(['passed'=>true,'messages'=>$out,'recipient'=>$recipient,'queue_worker_lifecycle_verified'=>true,'verification_cache_cleared'=>true],JSON_PRETTY_PRINT));}
|
||||
echo json_encode(['passed'=>$passed,'messages'=>$out,'pending'=>Illuminate\Support\Facades\Queue::size('send_email'),'failed_jobs'=>DB::table('failed_jobs')->count()]);exit;
|
||||
}
|
||||
throw new RuntimeException('Unsupported mail acceptance action');
|
||||
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Independent FUC-XB runtime. Never changes DPL/HN/XrayR or certificate renewals."""
|
||||
import argparse,fcntl,hashlib,json,os,pathlib,re,shutil,subprocess,time
|
||||
|
||||
OWNER='fuc-xb-launch-20261105'
|
||||
SHA='55bf71fa9d9f2048d3255ae7c0af929a41897ca7743f6ead34132a6ca4c79043'
|
||||
ETC=pathlib.Path('/etc/fuc-xb-node')
|
||||
OPT=pathlib.Path('/opt/fuc-xb-node')
|
||||
STATE=pathlib.Path('/var/lib/fuc-xb-node')
|
||||
UNIT=pathlib.Path('/etc/systemd/system/fuc-xb-node.service')
|
||||
REFRESH=pathlib.Path('/etc/systemd/system/fuc-xb-certificate-refresh.service')
|
||||
TIMER=pathlib.Path('/etc/systemd/system/fuc-xb-certificate-refresh.timer')
|
||||
JOURNAL=None
|
||||
|
||||
def same_protected(actual,expected):
|
||||
# ExecStart serializes transient pid/start/exit metadata which daemon-reload
|
||||
# may reset. Unit bytes, executable, config, MainPID/start time/NRestarts
|
||||
# remain the authoritative protection checks.
|
||||
def stable(value):return {k:stable(v)for k,v in value.items()if k!='execstart_sha256'}if isinstance(value,dict)else value
|
||||
return stable(actual)==stable(expected)
|
||||
|
||||
def run(args):
|
||||
p=subprocess.run(args,capture_output=True,text=True,timeout=45)
|
||||
assert p.returncode==0,'FUC node operation failed; no credentials logged'
|
||||
return p.stdout.strip()
|
||||
def digest(path):return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest()
|
||||
def protected():
|
||||
result={}
|
||||
for name in ['XrayR','dpl-node']:
|
||||
props=dict(x.split('=',1)for x in run(['systemctl','show',name,'-p','MainPID','-p','ActiveState','-p','NRestarts','-p','ExecMainStartTimestampMonotonic','-p','ExecStart']).splitlines()if '='in x)
|
||||
cmd=props.pop('ExecStart','');m=re.search(r'path=([^ ;]+)',cmd);binary=m.group(1)if m else None
|
||||
paths=['/etc/'+name+'/config.yml']
|
||||
if name=='XrayR':paths+=['/usr/local/XrayR/config.yml']
|
||||
result[name]={'properties':props,'binary':binary,'binary_sha256':digest(binary)if binary and pathlib.Path(binary).is_file()else None,'execstart_sha256':hashlib.sha256(cmd.encode()).hexdigest(),'config_sha256':{p:digest(p)for p in paths if pathlib.Path(p).is_file()},'unit_sha256':hashlib.sha256(run(['systemctl','cat',name]).encode()).hexdigest()}
|
||||
return result
|
||||
def persist():
|
||||
tmp=STATE/'owner.json.tmp';tmp.write_text(json.dumps(JOURNAL,indent=2));tmp.chmod(0o600);tmp.replace(STATE/'owner.json')
|
||||
def write(path,text,mode=0o600):
|
||||
assert not os.path.lexists(str(path)),'FUC path already exists; inspect ownership'
|
||||
try:
|
||||
with path.open('xb')as f:f.write(text.encode()if isinstance(text,str)else text)
|
||||
path.chmod(mode)
|
||||
finally:
|
||||
if path.is_file():JOURNAL['files'][str(path)]=digest(path);persist()
|
||||
def validate_cert(row):
|
||||
cert=row['certificate'];key=row['private_key'];domain=row['sni']
|
||||
run(['openssl','x509','-in',cert,'-noout','-checkhost',domain]);run(['openssl','x509','-in',cert,'-noout','-checkend','604800']);run(['openssl','verify','-untrusted',cert,cert])
|
||||
assert run(['openssl','x509','-in',cert,'-pubkey','-noout'])==run(['openssl','pkey','-in',key,'-pubout']),'Certificate key mismatch'
|
||||
return run(['openssl','x509','-in',cert,'-noout','-fingerprint','-sha256'])
|
||||
def owned_units():
|
||||
for p in [UNIT,REFRESH,TIMER]:
|
||||
assert not os.path.lexists('/etc/systemd/system/'+p.name+'.d'),'Unexpected FUC systemd override'
|
||||
props=dict(x.split('=',1)for x in run(['systemctl','show',p.name,'-p','FragmentPath','-p','DropInPaths']).splitlines()if '='in x)
|
||||
assert props.get('FragmentPath')==str(p) and not props.get('DropInPaths'),'Parsed FUC unit changed'
|
||||
def verify():
|
||||
state=json.loads((STATE/'owner.json').read_text());assert state['owner']==OWNER
|
||||
assert same_protected(protected(),state['protected']),'Unrelated original service drift; stop for review'
|
||||
assert digest(OPT/'xboard-node')==SHA
|
||||
owned_units()
|
||||
assert all(pathlib.Path(p).is_file()and digest(p)==sha for p,sha in state['files'].items()),'FUC owned files drift'
|
||||
status=run(['systemctl','show','fuc-xb-node','-p','ActiveState','--value'])
|
||||
pid=run(['systemctl','show','fuc-xb-node','-p','MainPID','--value']);listener=run(['ss','-H','-ltnp','sport = :24445'])
|
||||
return {'owner':OWNER,'active':status=='active','original_services_unchanged':True,'binary_sha256':SHA,'port_listening':('pid='+pid+',')in listener,'owned_files_unchanged':True,'cert_timer_enabled':run(['systemctl','is-enabled','fuc-xb-certificate-refresh.timer'])=='enabled','cert_timer_active':run(['systemctl','is-active','fuc-xb-certificate-refresh.timer'])=='active'}
|
||||
def install(context):
|
||||
global JOURNAL
|
||||
row=context['node'];assert context['owner']==OWNER and row['listen_port']==24445
|
||||
assert context['source']=='https://fuc-xb-test.gemcook.net'
|
||||
assert isinstance(context['machine_id'],int)and context['machine_id']>0
|
||||
token=context['machine_token'];assert len(token)>=32 and token.isalnum(),'Unexpected machine token encoding'
|
||||
assert digest('/opt/dpl-node/xboard-node')==SHA
|
||||
assert not run(['ss','-H','-ltn','sport = :24445']),'Port in use'
|
||||
assert all(not os.path.lexists(str(p))for p in [ETC,OPT,STATE,UNIT,REFRESH,TIMER]),'FUC namespace collision'
|
||||
for name in ['fuc-xb-node.service','fuc-xb-certificate-refresh.service','fuc-xb-certificate-refresh.timer']:
|
||||
assert not os.path.lexists('/etc/systemd/system/'+name+'.d'),'Existing systemd override'
|
||||
props=dict(x.split('=',1)for x in run(['systemctl','show',name,'-p','LoadState','-p','FragmentPath','-p','DropInPaths']).splitlines()if '='in x)
|
||||
assert props.get('LoadState')=='not-found' and not props.get('FragmentPath') and not props.get('DropInPaths'),'Existing parsed systemd unit'
|
||||
total=int(pathlib.Path('/proc/meminfo').read_text().splitlines()[0].split()[1])*1024
|
||||
assert total>=1000000000,'Candidate below physical-memory requirement'
|
||||
cert=validate_cert(row);before=protected();assert same_protected(before,context['expected_units']),'Preflight old-service baseline changed'
|
||||
STATE.mkdir(mode=0o700)
|
||||
JOURNAL={'owner':OWNER,'node':row,'machine_id':context['machine_id'],'protected':before,'certificate_fingerprint':cert,'files':{},'created_directories':[str(STATE)],'phase':'installing'};persist()
|
||||
try:return install_files(context,token)
|
||||
except BaseException:
|
||||
cleanup=[]
|
||||
for command in [['systemctl','disable','--now','fuc-xb-certificate-refresh.timer','fuc-xb-node'],['systemctl','stop','fuc-xb-certificate-refresh.service']]:
|
||||
try:cleanup.append({'operation':command[1],'returncode':subprocess.run(command,capture_output=True,timeout=45).returncode})
|
||||
except subprocess.TimeoutExpired:cleanup.append({'operation':command[1],'timed_out':True})
|
||||
JOURNAL['failure_cleanup']=cleanup
|
||||
JOURNAL['phase']='failed';persist()
|
||||
raise
|
||||
def install_files(context,token):
|
||||
for p in [ETC,OPT]:p.mkdir(mode=0o700);JOURNAL['created_directories'].append(str(p));persist()
|
||||
write(OPT/'xboard-node',pathlib.Path('/opt/dpl-node/xboard-node').read_bytes(),0o700)
|
||||
assert digest(OPT/'xboard-node')==SHA,'Copied binary hash differs before execution'
|
||||
cfg={'panel':{'url':context['source']},'machine':{'machine_id':context['machine_id'],'token_env':'FUC_XB_MACHINE_TOKEN'},'kernel':{'type':'singbox','config_dir':str(STATE/'kernel')},'log':{'level':'warn'},'runtime':{'gomemlimit':'128MiB','gogc':75},'node':{'push_interval':5,'pull_interval':5}}
|
||||
write(ETC/'config.json',json.dumps(cfg));write(ETC/'secret.env','FUC_XB_MACHINE_TOKEN='+token+'\n')
|
||||
unit='''[Unit]
|
||||
Description=FUC-XB independent native V2 node
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
[Service]
|
||||
Type=simple
|
||||
EnvironmentFile=/etc/fuc-xb-node/secret.env
|
||||
WorkingDirectory=/var/lib/fuc-xb-node
|
||||
ExecStart=/opt/fuc-xb-node/xboard-node -c /etc/fuc-xb-node/config.json
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
MemoryMax=256M
|
||||
CPUQuota=50%
|
||||
LimitNOFILE=1048576
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
'''
|
||||
write(UNIT,unit,0o644)
|
||||
helper=pathlib.Path(__file__).with_name('certificate-refresh.py');write(OPT/helper.name,helper.read_bytes(),0o700)
|
||||
write(REFRESH,'''[Unit]
|
||||
Description=Reload only FUC-XB after its existing certificate changes
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/python3 /opt/fuc-xb-node/certificate-refresh.py
|
||||
''',0o644)
|
||||
write(TIMER,'''[Unit]
|
||||
Description=Check FUC-XB certificate every five minutes
|
||||
[Timer]
|
||||
OnBootSec=3min
|
||||
OnUnitActiveSec=5min
|
||||
Persistent=true
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
''',0o644)
|
||||
run(['systemctl','daemon-reload']);run(['systemctl','enable','--now','fuc-xb-node','fuc-xb-certificate-refresh.timer'])
|
||||
for _ in range(45):
|
||||
if run(['ss','-H','-ltn','sport = :24445']):break
|
||||
time.sleep(1)
|
||||
value=verify();assert value['active']and value['port_listening'],'Node not ready'
|
||||
JOURNAL['phase']='installed';persist();(STATE/'installed.json').write_text(json.dumps(value,indent=2));return value
|
||||
def rollback():
|
||||
state=json.loads((STATE/'owner.json').read_text());assert state['owner']==OWNER and same_protected(protected(),state['protected'])
|
||||
assert all(pathlib.Path(p).is_file()and digest(p)==sha for p,sha in state['files'].items()),'Owned files changed; no automatic removal'
|
||||
if str(TIMER)in state['files']:run(['systemctl','disable','--now','fuc-xb-certificate-refresh.timer'])
|
||||
services=[p.stem for p in [REFRESH,UNIT]if str(p)in state['files']]
|
||||
if services:run(['systemctl','stop',*services])
|
||||
if str(UNIT)in state['files']:run(['systemctl','disable','fuc-xb-node'])
|
||||
for service in services:
|
||||
assert run(['systemctl','show',service,'-p','MainPID','--value'])=='0','Owned process still running; retain files'
|
||||
assert run(['systemctl','show',service,'-p','ActiveState','--value']) in ['inactive','failed'],'Owned service not stopped'
|
||||
if str(TIMER)in state['files']:
|
||||
assert run(['systemctl','show','fuc-xb-certificate-refresh.timer','-p','ActiveState','--value'])=='inactive','Timer still running'
|
||||
enabled=subprocess.run(['systemctl','is-enabled','fuc-xb-certificate-refresh.timer'],capture_output=True,text=True,timeout=30)
|
||||
assert enabled.stdout.strip()=='disabled','Timer still enabled'
|
||||
for p in [UNIT,REFRESH,TIMER]:
|
||||
if str(p)in state['files']:p.unlink()
|
||||
# Exact independent namespaces only. Secrets are removed with the FUC configuration.
|
||||
for p in reversed(state['created_directories']):shutil.rmtree(p)
|
||||
run(['systemctl','daemon-reload']);assert same_protected(protected(),state['protected'])
|
||||
return {'rollback':True,'original_services_unchanged':True}
|
||||
def resume(context):
|
||||
global JOURNAL
|
||||
JOURNAL=json.loads((STATE/'owner.json').read_text())
|
||||
assert JOURNAL['owner']==OWNER and JOURNAL['machine_id']==context['machine_id'] and JOURNAL['node']==context['node']
|
||||
assert JOURNAL['phase']in ['failed','installed'],'Unknown partial phase; inspect'
|
||||
assert same_protected(protected(),JOURNAL['protected']) and same_protected(protected(),context['expected_units'])
|
||||
assert all(pathlib.Path(p).is_file()and digest(p)==sha for p,sha in JOURNAL['files'].items()),'Partial runtime files changed'
|
||||
assert (ETC/'secret.env').read_text()=='FUC_XB_MACHINE_TOKEN='+context['machine_token']+'\n'
|
||||
owned_units()
|
||||
validate_cert(context['node'])
|
||||
try:
|
||||
run(['systemctl','enable','--now','fuc-xb-node','fuc-xb-certificate-refresh.timer'])
|
||||
for _ in range(45):
|
||||
if run(['ss','-H','-ltn','sport = :24445']):break
|
||||
time.sleep(1)
|
||||
value=verify();assert value['active']and value['port_listening'],'Resumed node not ready'
|
||||
JOURNAL['phase']='installed';persist();return value
|
||||
except BaseException:
|
||||
cleanup=subprocess.run(['systemctl','disable','--now','fuc-xb-node','fuc-xb-certificate-refresh.timer'],capture_output=True,timeout=45)
|
||||
JOURNAL['phase']='failed';JOURNAL['resume_cleanup_returncode']=cleanup.returncode;persist();raise
|
||||
if __name__=='__main__':
|
||||
import sys
|
||||
os.umask(0o077);p=argparse.ArgumentParser();p.add_argument('action',choices=['install','verify','rollback','resume']);args=p.parse_args()
|
||||
lock=open('/run/lock/fuc-xb-node.lock','a');fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
if args.action=='install':value=install(json.load(sys.stdin))
|
||||
elif args.action=='resume':value=resume(json.load(sys.stdin))
|
||||
elif args.action=='verify':value=verify()
|
||||
else:value=rollback()
|
||||
print(json.dumps(value))
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';$dir='/var/www/wwwroot/fuc-xb-test/private/launch-ready-20261105';
|
||||
$stateFile=$dir.'/panel-state.json';$manifestFile=$dir.'/node-manifest.json';
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\{DB,Cache};use App\Models\{User,Plan,Server,ServerMachine,ServerGroup};
|
||||
if(DB::connection()->getDatabaseName()!=='fuc_xb_test'||!is_link('/var/www/wwwroot/fuc-xb-test/current'))throw new RuntimeException('Wrong staging instance');
|
||||
$lock=fopen($dir.'/panel.lock','c');if(!flock($lock,LOCK_EX|LOCK_NB))throw new RuntimeException('Another FUC preparation is running');
|
||||
$action=$argv[1]??'';
|
||||
function saveState(array $s):void{global $stateFile;$p=$stateFile.'.tmp';file_put_contents($p,json_encode($s,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));chmod($p,0600);rename($p,$stateFile);}
|
||||
function newQA(int $gid,string $phase):User{return User::create(['email'=>'qa-launch-'.$phase.'[email protected]','password'=>password_hash(bin2hex(random_bytes(20)),PASSWORD_BCRYPT),'uuid'=>(string)Illuminate\Support\Str::uuid(),'token'=>bin2hex(random_bytes(16)),'group_id'=>$gid,'transfer_enable'=>104857600,'expired_at'=>time()+3600,'balance'=>0,'banned'=>0,'u'=>0,'d'=>0,'speed_limit'=>30,'device_limit'=>2,'remind_expire'=>0,'remind_traffic'=>0]);}
|
||||
if($action==='prepare'){
|
||||
if(is_file($stateFile)||Server::count()||ServerMachine::count())throw new RuntimeException('Existing preparation; inspect before retry');
|
||||
$manifest=json_decode(file_get_contents($manifestFile),true,512,JSON_THROW_ON_ERROR);
|
||||
if($manifest['owner']!=='fuc-xb-launch-20261105'||count($manifest['nodes'])!==22)throw new RuntimeException('Wrong frozen batch');
|
||||
$catalog=json_decode(file_get_contents(__DIR__.'/catalog.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
if(count($catalog['products'])!==12||$catalog['reset_traffic_method']!==2)throw new RuntimeException('Wrong catalog');
|
||||
$qa=json_decode(file_get_contents('/var/www/wwwroot/fuc-xb-test/private/qa-credentials.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
$state=['owner'=>$manifest['owner'],'manifest_sha256'=>$manifest['manifest_sha256'],'before'=>['users'=>User::count(),'wallet'=>(int)User::sum('balance'),'plans'=>Plan::count(),'groups'=>ServerGroup::count()],'nodes'=>[],'plans'=>[],'users'=>[],'phase'=>'preparing'];
|
||||
file_put_contents($dir.'/plans-before.json',DB::table('v2_plan')->orderBy('id')->get()->toJson());chmod($dir.'/plans-before.json',0600);
|
||||
DB::transaction(function()use(&$state,$catalog,$manifest,$qa){
|
||||
$g=new ServerGroup();$g->name='FUC-XB launch restricted QA';$g->save();$state['qa_group_id']=$g->id;
|
||||
$sales=new ServerGroup();$sales->name='FUC-XB 正式销售权限';$sales->save();$state['sales_group_id']=$sales->id;
|
||||
Plan::whereKey($qa['plan_id'])->update(['show'=>false]);
|
||||
foreach($catalog['products']as$i=>$p){$plan=Plan::create(['name'=>$p['name'],'group_id'=>$sales->id,'transfer_enable'=>$p['quota_gb'],'speed_limit'=>null,'device_limit'=>null,'display_device_limit'=>null,'capacity_limit'=>null,'show'=>true,'sell'=>true,'renew'=>true,'prices'=>[$p['period']=>$p['price_yuan']],'sort'=>$i+1,'reset_traffic_method'=>2,'tags'=>['fuc-series:'.$p['series']],'content'=>'']);$state['plans'][$p['code']]=$plan->id;}
|
||||
foreach($manifest['nodes']as$i=>$row){
|
||||
$machine=ServerMachine::create(['name'=>'fuc-xb-'.$row['key'],'token'=>ServerMachine::generateToken(),'is_active'=>true,'notes'=>$state['owner'].'; isolated QA until cutover']);
|
||||
$node=Server::create(['name'=>$row['name'],'type'=>'anytls','host'=>$row['relay_host'],'port'=>(string)$row['relay_port'],'server_port'=>'24445','group_ids'=>[(string)$g->id],'route_ids'=>[],'tags'=>[$state['owner']],'rate'=>$row['rate'],'show'=>true,'enabled'=>true,'machine_id'=>$machine->id,'sort'=>$i+1,'protocol_settings'=>['tls'=>['server_name'=>$row['sni'],'allow_insecure'=>false]],'cert_config'=>['cert_mode'=>'file','domain'=>$row['sni'],'cert_file'=>$row['certificate'],'key_file'=>$row['private_key']]]);
|
||||
$state['nodes'][$row['key']]=['node_id'=>$node->id,'machine_id'=>$machine->id,'spec'=>$row];
|
||||
}
|
||||
$user=newQA($g->id,'banned');$state['users'][]=$user->id;$state['current_user_id']=$user->id;$state['qa_phase']='banned';
|
||||
$state['settings_before']=DB::table('v2_settings')->whereIn('name',['server_pull_interval','server_push_interval'])->get()->map(fn($r)=>(array)$r)->all();
|
||||
app(App\Support\Setting::class)->save(['server_pull_interval'=>5,'server_push_interval'=>5]);
|
||||
$state['phase']='prepared';saveState($state);
|
||||
});
|
||||
echo json_encode(['prepared'=>true,'sales_plans'=>count($state['plans']),'nodes'=>count($state['nodes']),'old_users_on_new_nodes'=>0,'qa_group_isolated'=>true,'manifest_sha256'=>$state['manifest_sha256']]).PHP_EOL;exit;
|
||||
}
|
||||
$state=json_decode(file_get_contents($stateFile),true,512,JSON_THROW_ON_ERROR);if($state['owner']!=='fuc-xb-launch-20261105')throw new RuntimeException('Foreign state');
|
||||
if($action==='export-machine'){
|
||||
$key=$argv[2]??'';$row=$state['nodes'][$key]??null;if(!$row)throw new RuntimeException('Unknown node');$m=ServerMachine::findOrFail($row['machine_id']);
|
||||
if($m->name!=='fuc-xb-'.$key)throw new RuntimeException('Machine ownership changed');
|
||||
// Dedicated SSH consumer only; never print this action in the tool UI.
|
||||
echo json_encode(['owner'=>$state['owner'],'source'=>'https://fuc-xb-test.gemcook.net','machine_id'=>$m->id,'machine_token'=>$m->token,'node'=>$row['spec']]);exit;
|
||||
}
|
||||
if($action==='status'){
|
||||
$nodes=[];foreach($state['nodes']as$key=>$row){$n=Server::findOrFail($row['node_id']);$m=ServerMachine::findOrFail($row['machine_id']);$nodes[$key]=['id'=>$n->id,'group_ids'=>$n->group_ids,'available_users'=>App\Services\ServerService::getAvailableUsers($n)->count(),'upload'=>$n->u,'download'=>$n->d,'last_check_at'=>$n->last_check_at,'last_push_at'=>$n->last_push_at,'machine_last_seen'=>$m->last_seen_at];}
|
||||
echo json_encode(['phase'=>$state['phase'],'qa_phase'=>$state['qa_phase'],'nodes'=>$nodes,'users'=>User::count(),'native_orders'=>App\Models\Order::count(),'sales_plans'=>Plan::where('show',true)->where('sell',true)->count(),'automatic_mail_policy'=>App\Services\MailFlow\AutomaticMailPolicy::state()]);exit;
|
||||
}
|
||||
if($action==='qa-revoke'){
|
||||
$u=User::findOrFail($state['current_user_id']);if($u->group_id!==$state['qa_group_id'])throw new RuntimeException('QA identity changed');
|
||||
if($state['qa_phase']==='banned')$u->update(['banned'=>1]);elseif($state['qa_phase']==='expired')$u->update(['expired_at'=>time()-1]);elseif($state['qa_phase']==='exhausted')$u->update(['u'=>$u->transfer_enable]);else throw new RuntimeException('Invalid phase');
|
||||
echo json_encode(['revoked'=>true,'phase'=>$state['qa_phase']]);exit;
|
||||
}
|
||||
if($action==='qa-bound'){
|
||||
$u=User::findOrFail($state['current_user_id']);if($u->group_id!==$state['qa_group_id']||!str_ends_with($u->email,'@fuc-xb.invalid')||$u->balance!==0)throw new RuntimeException('Not this QA');
|
||||
$u->update(['transfer_enable'=>104857600,'expired_at'=>min((int)$u->expired_at,time()+3600)]);echo json_encode(['restricted'=>true,'quota_bytes'=>104857600,'maximum_seconds'=>3600]);exit;
|
||||
}
|
||||
if($action==='qa-next'){
|
||||
$u=User::findOrFail($state['current_user_id']);foreach($state['nodes']as$row)if(App\Services\ServerService::getAvailableUsers(Server::findOrFail($row['node_id']))->count())throw new RuntimeException('Revoke all QA access first');
|
||||
$phase=match($state['qa_phase']){'banned'=>'expired','expired'=>'exhausted',default=>throw new RuntimeException('No remaining phase')};
|
||||
$u->update(['banned'=>1]);$new=newQA($state['qa_group_id'],$phase);$state['users'][]=$new->id;$state['current_user_id']=$new->id;$state['qa_phase']=$phase;saveState($state);echo json_encode(['new_identity'=>true,'phase'=>$phase]);exit;
|
||||
}
|
||||
throw new RuntimeException('Unsupported operation');
|
||||
@@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate and restore a frozen FUC backup, then seal the final import input."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import gzip
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
PRIVATE = Path("/var/www/wwwroot/fuc-xb-test/private")
|
||||
BASELINE = PRIVATE / "refresh-20261105"
|
||||
TARGET = "fuc_xb_test"
|
||||
|
||||
|
||||
def load_tool(name, path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def checked(condition, reason):
|
||||
if not condition:
|
||||
raise RuntimeError(reason)
|
||||
|
||||
|
||||
def private(path):
|
||||
checked(path.resolve() == path and path.stat().st_uid == 0
|
||||
and path.stat().st_mode & 0o077 == 0, "Private root-owned input required")
|
||||
return path
|
||||
|
||||
|
||||
def read(path):
|
||||
return json.loads(private(path).read_text())
|
||||
|
||||
|
||||
def sha(path):
|
||||
with private(path).open("rb") as handle:
|
||||
return hashlib.file_digest(handle, "sha256").hexdigest()
|
||||
|
||||
|
||||
def write(path, value):
|
||||
with path.open("x") as handle:
|
||||
json.dump(value, handle, indent=2)
|
||||
handle.write("\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
|
||||
|
||||
def validate_snapshot(path, identity):
|
||||
counts = {}
|
||||
with gzip.open(path, "rt", encoding="utf-8") as stream:
|
||||
header = json.loads(next(stream))
|
||||
checked(header["kind"] == "header" and header["database_identity_sha256"] == identity,
|
||||
"Wrong source identity in snapshot")
|
||||
counts = dict.fromkeys(header["counts"], 0)
|
||||
for line in stream:
|
||||
entry = json.loads(line)
|
||||
if entry["kind"] == "footer":
|
||||
checked(not stream.readline() and counts == entry["counts"] == header["counts"]
|
||||
and entry["source_business_writes"] == 0, "Snapshot counts do not reconcile")
|
||||
return {"complete": True, "sha256": sha(path), "counts": counts,
|
||||
"snapshot_utc": header["snapshot_utc"], "source_business_writes": 0}
|
||||
checked(entry["kind"] == "row", "Unrecognized snapshot record")
|
||||
counts[entry["table"]] += 1
|
||||
raise RuntimeError("Incomplete snapshot")
|
||||
|
||||
|
||||
def prepare(directory, backup, manifest):
|
||||
source = "fuc_legacy_restore_" + secrets.token_hex(6)
|
||||
client = backup.CLIENT
|
||||
def run_sql(sql):
|
||||
subprocess.run(client, input=sql, text=True, capture_output=True, check=True, timeout=30)
|
||||
|
||||
snapshot = directory / "snapshot.jsonl.gz"
|
||||
partial = directory / "snapshot.jsonl.gz.part"
|
||||
checked(not snapshot.exists() and not partial.exists(), "An earlier snapshot exists")
|
||||
run_sql("CREATE DATABASE " + source + " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
|
||||
try:
|
||||
with gzip.open(directory / "old-fuc-full.sql.gz", "rb") as dump:
|
||||
with subprocess.Popen(client + [source], stdin=subprocess.PIPE,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as loader:
|
||||
try:
|
||||
shutil.copyfileobj(dump, loader.stdin)
|
||||
loader.stdin.close()
|
||||
checked(loader.wait(timeout=60) == 0, "Legacy backup restore failed")
|
||||
finally:
|
||||
if loader.poll() is None:
|
||||
loader.kill()
|
||||
checked(backup.database_inventory(source) == manifest["inventory"], "Restored table inventory differs")
|
||||
with partial.open("xb") as compressed:
|
||||
with subprocess.Popen(["php", str(HERE / "export-final-snapshot.php"), source],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as exporter:
|
||||
try:
|
||||
with gzip.GzipFile(filename="", fileobj=compressed, mode="wb", mtime=0) as stream:
|
||||
shutil.copyfileobj(exporter.stdout, stream)
|
||||
checked(exporter.wait(timeout=60) == 0, "Restored snapshot export failed")
|
||||
finally:
|
||||
if exporter.poll() is None:
|
||||
exporter.kill()
|
||||
result = validate_snapshot(partial, manifest["database_sha256"])
|
||||
partial.rename(snapshot)
|
||||
write(directory / "snapshot-manifest.json", result)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
run_sql("DROP DATABASE " + source)
|
||||
|
||||
|
||||
def main():
|
||||
checked(os.geteuid() == 0 and len(sys.argv) == 2
|
||||
and re.fullmatch(r"cutover-[0-9]{8}T[0-9]{6}Z", sys.argv[1]), "Expected a cutover window")
|
||||
directory = private(PRIVATE / sys.argv[1])
|
||||
freeze = read(directory / "freeze-verified.json")
|
||||
manifest = read(directory / "old-fuc-full.json")
|
||||
target = read(directory / "target-verified.json")
|
||||
now = datetime.now(timezone.utc)
|
||||
frozen_at = datetime.fromisoformat(freeze["verified_utc"])
|
||||
backed_up = datetime.fromisoformat(manifest["created_utc"])
|
||||
checked(frozen_at <= backed_up <= now and (now - frozen_at).total_seconds() <= 1800
|
||||
and all(freeze.get(key) is True for key in
|
||||
("old_ingress_maintenance", "old_business_writers_stopped", "old_nodes_drained", "payments_drained"))
|
||||
and freeze["database_sha256"] == manifest["database_sha256"], "Verified source freeze and backup required")
|
||||
checked(target["database"] == TARGET and target["public_writes_blocked"] is True
|
||||
and target["writers_stopped"] is True and re.fullmatch(r"[0-9a-f]{40}", target["release"]),
|
||||
"Verified XB target gate required")
|
||||
backup = load_tool("fuc_legacy_backup", HERE / "backup-legacy.py")
|
||||
dump = private(directory / "old-fuc-full.sql.gz")
|
||||
checked(dump.stat().st_size == manifest["bytes"] and backup.validate_dump(dump) == manifest["sha256"],
|
||||
"Frozen full backup fails verification")
|
||||
checked(not any(manifest["programs"].values()) and all(
|
||||
"\tBASE TABLE\t" in table for table in manifest["inventory"]), "Legacy stored programs or views require reviewed restore")
|
||||
checked(not any((directory / file).exists() for file in
|
||||
("import-ready.json", "snapshot-manifest.json", "projection.json", "identity-overrides.json")),
|
||||
"Existing cutover inputs require inspection")
|
||||
prepare(directory, backup, manifest)
|
||||
write(directory / "identity-overrides.json", read(BASELINE / "identity-overrides.json"))
|
||||
project = load_tool("fuc_final_projection", HERE.parent / "fuc-xb-refresh" / "project.py")
|
||||
project.main(directory, BASELINE)
|
||||
write(directory / "import-ready.json", {
|
||||
"target": TARGET, "release": target["release"], "freeze_sha256": sha(directory / "freeze-verified.json"),
|
||||
"target_gate_sha256": sha(directory / "target-verified.json"),
|
||||
"backup_sha256": manifest["sha256"], "snapshot_sha256": sha(directory / "snapshot.jsonl.gz"),
|
||||
"projection_sha256": sha(directory / "projection.json"),
|
||||
})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, RuntimeError, AssertionError, subprocess.SubprocessError) as failure:
|
||||
sys.exit(str(failure) if isinstance(failure, RuntimeError) else type(failure).__name__)
|
||||
@@ -0,0 +1,460 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
// FUC-XB final-refresh planning and isolated rehearsal.
|
||||
umask(0077);
|
||||
ini_set('display_errors', '0');
|
||||
$root = '/var/www/wwwroot/fuc-xb-test/current';
|
||||
$private = '/var/www/wwwroot/fuc-xb-test/private';
|
||||
$stateDirectory = $private . '/launch-ready-20261105';
|
||||
|
||||
final class RefreshRejected extends RuntimeException {}
|
||||
|
||||
function must(bool $ok, string $reason): void
|
||||
{
|
||||
if (!$ok) throw new RefreshRejected($reason);
|
||||
}
|
||||
function readJson(string $file): array
|
||||
{
|
||||
must(is_file($file) && !is_link($file) && (fileperms($file) & 0077) === 0, 'A private regular input is required');
|
||||
return json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
function finalInputs(string $directory, array $summary, bool $formal): array
|
||||
{
|
||||
require_once __DIR__ . '/announcements.php';
|
||||
if ($formal) {
|
||||
$ready = readJson($directory . '/import-ready.json');
|
||||
$freeze = readJson($directory . '/freeze-verified.json');
|
||||
$target = readJson($directory . '/target-verified.json');
|
||||
$backup = readJson($directory . '/old-fuc-full.json');
|
||||
$age = time() - strtotime($freeze['verified_utc']);
|
||||
must(posix_geteuid() === 0 && fileowner($directory) === 0 && (fileperms($directory) & 0077) === 0
|
||||
&& $age >= 0 && $age <= 2100
|
||||
&& $freeze['old_ingress_maintenance'] === true && $freeze['old_business_writers_stopped'] === true
|
||||
&& $freeze['old_nodes_drained'] === true && $freeze['payments_drained'] === true
|
||||
&& $target['public_writes_blocked'] === true && $target['writers_stopped'] === true,
|
||||
'Current verified freeze of both sites required');
|
||||
must($ready['target'] === 'fuc_xb_test' && $target['database'] === $ready['target']
|
||||
&& $ready['freeze_sha256'] === hash_file('sha256', $directory . '/freeze-verified.json')
|
||||
&& $ready['target_gate_sha256'] === hash_file('sha256', $directory . '/target-verified.json')
|
||||
&& $ready['backup_sha256'] === $backup['sha256']
|
||||
&& $ready['backup_sha256'] === hash_file('sha256', $directory . '/old-fuc-full.sql.gz')
|
||||
&& $ready['snapshot_sha256'] === $summary['snapshot_sha256']
|
||||
&& $ready['projection_sha256'] === $summary['projection_sha256']
|
||||
&& $ready['release'] === $target['release']
|
||||
&& basename(realpath(dirname(__DIR__, 2))) === $target['release'],
|
||||
'Final source, target or release changed');
|
||||
}
|
||||
$handle = gzopen($directory . '/snapshot.jsonl.gz', 'rb');
|
||||
must($handle !== false, 'Cannot open final snapshot');
|
||||
$rows = [];
|
||||
try {
|
||||
$header = json_decode(gzgets($handle), true, 512, JSON_THROW_ON_ERROR);
|
||||
while (($line = gzgets($handle)) !== false) {
|
||||
$record = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
|
||||
if ($record['kind'] === 'row' && $record['table'] === 'announcement') $rows[] = $record['row'];
|
||||
}
|
||||
} finally {
|
||||
gzclose($handle);
|
||||
}
|
||||
must(isset($header['counts']['announcement']) && count($rows) === $header['counts']['announcement'],
|
||||
'Final snapshot does not contain its full announcement table');
|
||||
return fucProjectAnnouncements($rows, new DateTimeZone($header['timezone']));
|
||||
}
|
||||
function groupCohorts(string $directory, array $project): array
|
||||
{
|
||||
$manifest = readJson($directory . '/snapshot-manifest.json');
|
||||
$path = $directory . '/snapshot.jsonl.gz';
|
||||
must(is_file($path) && !is_link($path) && (fileperms($path) & 0077) === 0, 'Private source snapshot required');
|
||||
must($manifest['complete'] && $manifest['source_business_writes'] === 0 && hash_file('sha256', $path) === $project['snapshot_sha256'] && $manifest['sha256'] === $project['snapshot_sha256'], 'Snapshot provenance mismatch');
|
||||
$users = array_column($project['users'], 'group_id', 'id');
|
||||
$handle = gzopen($path, 'rb');
|
||||
must($handle !== false, 'Cannot open snapshot');
|
||||
$mapping = $reverse = [];
|
||||
$count = 0;
|
||||
try {
|
||||
while (($line = gzgets($handle)) !== false) {
|
||||
$item = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
|
||||
if ($item['kind'] !== 'row' || $item['table'] !== 'user') continue;
|
||||
$user = $item['row'];
|
||||
$id = (int) $user['id'];
|
||||
$class = (int) $user['class'];
|
||||
must(array_key_exists($id, $users), 'Source user not present in projection');
|
||||
$group = $users[$id];
|
||||
unset($users[$id]);
|
||||
$count++;
|
||||
if ($class <= 0) {
|
||||
must($group === null, 'Inactive source user received a projected group');
|
||||
continue;
|
||||
}
|
||||
$cohort = $class . ':' . (int) $user['node_group'];
|
||||
must(is_int($group) && (!isset($mapping[$cohort]) || $mapping[$cohort] === $group) && (!isset($reverse[$group]) || $reverse[$group] === $cohort), 'Cohort mapping is not one-to-one');
|
||||
$mapping[$cohort] = $group;
|
||||
$reverse[$group] = $cohort;
|
||||
}
|
||||
} finally {
|
||||
gzclose($handle);
|
||||
}
|
||||
$projectedIds = array_column($project['groups'], 'id');
|
||||
$observedIds = array_values($mapping);
|
||||
sort($projectedIds);
|
||||
sort($observedIds);
|
||||
must(!$users && $count === $manifest['counts']['user'] && $projectedIds === $observedIds, 'Snapshot/projection users or groups differ');
|
||||
ksort($mapping);
|
||||
return $mapping;
|
||||
}
|
||||
function validateProjection(string $directory): array
|
||||
{
|
||||
$summary = readJson($directory . '/projection-summary.json');
|
||||
$p = readJson($directory . '/projection.json');
|
||||
must(hash_file('sha256', $directory . '/projection.json') === $summary['projection_sha256'] && $p['snapshot_sha256'] === $summary['snapshot_sha256'], 'Projection content drift');
|
||||
must(count($p['users']) === $summary['users'] && count($p['vip_openings']) === $summary['users'] && count($p['plans']) === $summary['hidden_legacy_plans'] && count($p['groups']) === $summary['groups'], 'Projection counts drift');
|
||||
must(array_sum(array_column($p['users'], 'balance')) === $summary['wallet_cents'] && array_sum(array_column($p['users'], 'commission_balance')) === $summary['commission_cents'] && array_sum(array_column($p['refunds'], 'amount_cents')) === $summary['prepaid_refund_cents'], 'Projection balances drift');
|
||||
return [$summary, $p];
|
||||
}
|
||||
function legacyPlanAssignments(string $directory, array $users, array $groups, array $plans, array $products): array
|
||||
{
|
||||
$stream = gzopen($directory . '/snapshot.jsonl.gz', 'rb');
|
||||
must($stream !== false, 'Cannot read source orders');
|
||||
$orders = $invoices = [];
|
||||
try {
|
||||
while (($line = gzgets($stream)) !== false) {
|
||||
$item = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
|
||||
if ($item['kind'] !== 'row') continue;
|
||||
$row = $item['row'];
|
||||
if ($item['table'] === 'order' && $row['status'] === 'activated') {
|
||||
$orders[(int) $row['user_id']][] = [(int) $row['id'], $row['product_code']];
|
||||
} elseif ($item['table'] === 'invoice' && in_array($row['status'], ['paid_gateway', 'paid_balance', 'paid_admin'], true)) {
|
||||
$invoices[(int) $row['order_id']][] = (int) $row['user_id'];
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
gzclose($stream);
|
||||
}
|
||||
|
||||
$assignments = [];
|
||||
foreach ($users as $id => $user) {
|
||||
if ($user['plan_id'] === null) continue;
|
||||
$group = $user['group_id'];
|
||||
if ($group === $groups['1:1']) {
|
||||
must(empty($orders[$id]), 'Trial user has an activated order');
|
||||
$assignments[$id] = $plans['legacy-trial'];
|
||||
} elseif ($group === $groups['2:99']) {
|
||||
$assignments[$id] = $plans['legacy-restricted'];
|
||||
} else {
|
||||
must($group === $groups['2:1'] && count($orders[$id] ?? []) === 1, 'An ordinary legacy entitlement needs reconciliation');
|
||||
[$order, $product] = $orders[$id][0];
|
||||
must(($invoices[$order] ?? []) === [$id], 'An activated order needs payment reconciliation');
|
||||
if (in_array($product, ['3th-a', '3th-b'], true)) {
|
||||
$assignments[$id] = $plans['legacy-promotion'];
|
||||
} else {
|
||||
must(($products[$product]['series'] ?? null) === 'lite', 'An activated paid product has no approved hidden mapping');
|
||||
$assignments[$id] = $plans['legacy-lite'];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $assignments;
|
||||
}
|
||||
|
||||
function canonical($value)
|
||||
{
|
||||
if (!is_array($value)) return $value;
|
||||
if (!array_is_list($value)) ksort($value);
|
||||
return array_map('canonical', $value);
|
||||
}
|
||||
function digest(array $value): string
|
||||
{
|
||||
return hash('sha256', json_encode(canonical($value), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
function sameRow(array $expected, array $actual, string $fieldScope): void
|
||||
{
|
||||
foreach ($expected as $key => $value) {
|
||||
must(array_key_exists($key, $actual) && ($actual[$key] === null ? null : (string) $actual[$key]) === ($value === null ? null : (string) $value), 'Field mismatch in ' . $fieldScope . '.' . $key);
|
||||
}
|
||||
}
|
||||
|
||||
function streamDigest($db, array $tables): string
|
||||
{
|
||||
$hash = hash_init('sha256');
|
||||
foreach ($tables as $table => $key) {
|
||||
hash_update($hash, $table . "\n");
|
||||
foreach ($db->table($table)->orderBy($key)->cursor() as $row) hash_update($hash, json_encode(canonical((array) $row), JSON_THROW_ON_ERROR) . "\n");
|
||||
}
|
||||
return hash_final($hash);
|
||||
}
|
||||
|
||||
try {
|
||||
$mode = $argv[2] ?? 'preview';
|
||||
$formal = in_array($mode, ['cutover-commit', 'cutover-verify'], true);
|
||||
$finalDrill = in_array($mode, ['rehearse-final-commit', 'rehearse-final-verify'], true);
|
||||
$final = $formal || $finalDrill;
|
||||
$commitMode = $final || in_array($mode, ['rehearse-commit','verify-commit'], true);
|
||||
$verifyOnly = in_array($mode, ['verify-commit', 'cutover-verify', 'rehearse-final-verify'], true);
|
||||
$directoryPattern = $formal ? '/\Acutover-[0-9]{8}T[0-9]{6}Z\z/D' : '/\Arefresh-20[0-9]{6}(?:-[a-z0-9-]{1,32})?\z/D';
|
||||
must(PHP_SAPI === 'cli' && ($commitMode || in_array($mode, ['preview','rehearse-rollback'], true))
|
||||
&& preg_match($directoryPattern, $argv[1] ?? '') === 1, 'Invalid refresh operation');
|
||||
if ($commitMode && !$formal) {
|
||||
$expectedDirectory = $finalDrill ? 'refresh-20261105-final-import-rehearsal' : 'refresh-20261105-launch-rehearsal';
|
||||
must($argv[1] === $expectedDirectory && preg_match('/\Afuc_xb_cutover_qa_[a-f0-9]{8}\z/D', getenv('DB_DATABASE') ?: '') === 1,
|
||||
'Rehearsal commit is limited to a disposable database');
|
||||
}
|
||||
$targetDirectory = $private . '/' . $argv[1];
|
||||
must(realpath($targetDirectory) === $targetDirectory, 'Unsafe projection directory');
|
||||
$active = readJson($private . '/active-migration.json');
|
||||
$activeDirectory = $private . '/refresh-20261105';
|
||||
// Validate the deployed projection rather than treating mutable staging rows as source facts.
|
||||
[$oldSummary, $old] = validateProjection($activeDirectory);
|
||||
must($active['private_dir'] === $activeDirectory && $active['snapshot_sha256'] === $old['snapshot_sha256'], 'Active migration does not reference the expected baseline');
|
||||
[$summary, $fresh] = validateProjection($targetDirectory);
|
||||
$notices = $final ? finalInputs($targetDirectory, $summary, $formal) : [];
|
||||
$oldCohorts = groupCohorts($activeDirectory, $old);
|
||||
$freshCohorts = groupCohorts($targetDirectory, $fresh);
|
||||
must(array_keys($oldCohorts) === ['1:1', '2:1', '2:99'] && array_keys($freshCohorts) === array_keys($oldCohorts), 'A legacy cohort changed; review access explicitly');
|
||||
$groups = [];
|
||||
foreach ($freshCohorts as $cohort => $id) $groups[$id] = $oldCohorts[$cohort];
|
||||
|
||||
putenv('XB_INSTANCE=fuc-xb-test');
|
||||
$_SERVER['XB_INSTANCE'] = $_ENV['XB_INSTANCE'] = 'fuc-xb-test';
|
||||
require $root . '/vendor/autoload.php';
|
||||
$app = require $root . '/bootstrap/app.php';
|
||||
if ($commitMode) {
|
||||
$runtime = getenv('FUC_CUTOVER_RUNTIME') ?: '';
|
||||
must(preg_match('~\A/tmp/fuc-xb-cutover-[a-f0-9]{8}\z~D', $runtime) === 1 && realpath($runtime) === $runtime && (fileperms($runtime) & 0077) === 0, 'A private cutover runtime is required');
|
||||
$app->useStoragePath($runtime . '/storage');
|
||||
foreach (['CONFIG','ROUTES','EVENTS','SERVICES','PACKAGES'] as $cache) {
|
||||
$key = 'APP_' . $cache . '_CACHE';
|
||||
$path = $runtime . '/' . strtolower($cache) . '.php';
|
||||
$_SERVER[$key] = $_ENV[$key] = $path;
|
||||
putenv($key . '=' . $path);
|
||||
}
|
||||
}
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
if ($commitMode) config(['cache.default' => 'array', 'cache.stores.redis' => ['driver' => 'array']]);
|
||||
$db = Illuminate\Support\Facades\DB::connection();
|
||||
$expectedDatabase = $commitMode && !$formal ? getenv('DB_DATABASE') : 'fuc_xb_test';
|
||||
must($db->getDatabaseName() === $expectedDatabase && $db->selectOne('SELECT DATABASE() AS active_db')->active_db === $expectedDatabase, 'Wrong isolated database');
|
||||
if ($formal) {
|
||||
$server = $db->selectOne('SELECT @@hostname AS host, @@socket AS local_socket');
|
||||
must(realpath($root) === realpath(dirname(__DIR__, 2))
|
||||
&& $server->host === gethostname() && $server->local_socket === '/run/mysqld/mysqld.sock',
|
||||
'Formal import must use the deployed release and its local database');
|
||||
}
|
||||
$verifiedTables = ['v2_user'=>'id','v2_plan'=>'id','fuc_vip_accounts'=>'user_id','fuc_vip_entries'=>'id','v2_order'=>'id'];
|
||||
if ($final) $verifiedTables += ['v2_notice'=>'id','personal_access_tokens'=>'id','v2_traffic_reset_logs'=>'id'];
|
||||
$receiptTable = $final ? 'fuc_cutover_receipt' : 'fuc_cutover_drill';
|
||||
if ($commitMode) {
|
||||
$lock = fopen(($formal ? $stateDirectory : $runtime) . '/panel.lock', 'c');
|
||||
must($lock && flock($lock, LOCK_EX | LOCK_NB), 'An isolated import is already running');
|
||||
if ($final && !$verifyOnly) {
|
||||
$db->statement('CREATE TABLE IF NOT EXISTS fuc_cutover_receipt (snapshot_sha256 char(64) PRIMARY KEY, projection_sha256 char(64) NOT NULL, rows_sha256 char(64) NOT NULL) ENGINE=InnoDB');
|
||||
}
|
||||
if ($final) {
|
||||
$tables = array_unique(array_merge(array_keys($verifiedTables), ['v2_traffic_reset_logs', $receiptTable]));
|
||||
$transactional = $db->table('information_schema.TABLES')->whereRaw('TABLE_SCHEMA = DATABASE()')
|
||||
->whereIn('TABLE_NAME', $tables)->where('ENGINE', 'InnoDB')->count();
|
||||
must($transactional === count($tables), 'All cutover tables must use InnoDB');
|
||||
}
|
||||
$receipt = $db->table($receiptTable)->where('snapshot_sha256', $summary['snapshot_sha256'])->first();
|
||||
if ($receipt) {
|
||||
must($receipt->projection_sha256 === $summary['projection_sha256'] && $receipt->rows_sha256 === streamDigest($db, $verifiedTables), 'Committed database readback differs');
|
||||
must($db->table('v2_user')->count() === $summary['users'] + (int) !$final && $db->table('fuc_vip_accounts')->count() === $summary['users'] && $db->table('fuc_vip_entries')->count() === $summary['users'] && !$db->table('v2_order')->exists(), 'Committed row counts differ');
|
||||
$verified = ['passed'=>true,'mode'=>$mode,'users'=>(int)$summary['users'],'vip_openings'=>(int)$summary['users'],'refund_orders'=>(int)$summary['prepaid_orders'],'refund_cents'=>(int)$summary['prepaid_refund_cents'],'wallet_cents'=>(int)$summary['wallet_cents'],'readback_sha256'=>$receipt->rows_sha256,'duplicate_writes'=>false];
|
||||
if ($final) {
|
||||
must($db->table('v2_notice')->count() === count($notices) && !$db->table('personal_access_tokens')->exists(), 'Final notices or session counts differ');
|
||||
$verified['announcements'] = count($notices);
|
||||
}
|
||||
echo json_encode($verified, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit;
|
||||
}
|
||||
must(!$verifyOnly && !$db->table($receiptTable)->exists(), 'Expected committed snapshot receipt is missing or conflicts');
|
||||
Illuminate\Support\Facades\Queue::fake();
|
||||
Illuminate\Support\Facades\Mail::fake();
|
||||
Illuminate\Support\Facades\Http::preventStrayRequests();
|
||||
}
|
||||
$state = readJson($stateDirectory . '/panel-state.json');
|
||||
$qa = readJson($private . '/qa-credentials.json');
|
||||
must($state['owner'] === 'fuc-xb-launch-20261105' && count($state['plans']) === 12 && count($state['nodes']) === 22, 'Owned operations baseline changed');
|
||||
must(!$db->table('v2_order')->exists() && !$db->table('v2_commission_log')->exists() && !$db->table('fuc_vip_entries')->where('kind', '!=', 'opening')->exists(), 'Native business exists; prelaunch replacement is unsafe');
|
||||
|
||||
$protected = [];
|
||||
$catalog = readJson($private . '/catalog-rebuild-20261105/applied.json');
|
||||
$sales = array_slice($catalog['destinations'], 0, 4, true);
|
||||
$hidden = array_slice($catalog['destinations'], 4, null, true);
|
||||
must(array_keys($sales) === ['lite','normal','plus','pro'] && array_keys($hidden) === ['legacy-trial','legacy-promotion','legacy-restricted'], 'Unexpected catalog receipt');
|
||||
$plans = $db->table('v2_plan')->orderBy('id')->get()->map(fn($r) => (array) $r)->all();
|
||||
$byId = array_column($plans, null, 'id');
|
||||
$legacyLite = array_values(array_filter($plans, fn($plan) => $plan['name'] === '旧站轻量套餐'));
|
||||
must(count($legacyLite) === 1, 'The protected legacy-lite plan is missing or ambiguous');
|
||||
$hidden['legacy-lite'] = (int) $legacyLite[0]['id'];
|
||||
$expectedPlanIds = array_merge(array_values($sales), array_values($hidden));
|
||||
sort($expectedPlanIds);
|
||||
must(array_map('intval', array_keys($byId)) === $expectedPlanIds, 'The current four sales and four hidden plans do not match');
|
||||
$expectedHiddenGroups = ['legacy-trial'=>$oldCohorts['1:1'], 'legacy-promotion'=>$oldCohorts['2:1'], 'legacy-restricted'=>$oldCohorts['2:99'], 'legacy-lite'=>$oldCohorts['2:1']];
|
||||
foreach ($hidden as $kind => $id) {
|
||||
$plan = $byId[$id];
|
||||
must(!$plan['show'] && !$plan['sell'] && !$plan['renew'] && !json_decode($plan['prices'] ?? '[]', true, 32, JSON_THROW_ON_ERROR) && (int) $plan['reset_traffic_method'] === 2 && (int) $plan['group_id'] === $expectedHiddenGroups[$kind], 'A legacy plan has lost entitlement protections');
|
||||
}
|
||||
foreach ($catalog['result']['formal_plans'] as $entry) {
|
||||
$plan = $byId[$entry['id']];
|
||||
$price = array_map('floatval', $entry['prices']);
|
||||
$current = array_map('floatval', json_decode($plan['prices'], true, 32, JSON_THROW_ON_ERROR));
|
||||
must(in_array($entry['id'], $sales, true) && $plan['show'] && $plan['sell'] && $plan['renew'] && (int) $plan['transfer_enable'] === $entry['monthly_quota_gb'] && (int) $plan['group_id'] === (int) $state['sales_group_id'] && (int) $plan['reset_traffic_method'] === 1 && $current === $price + ['reset_traffic'=>$price['monthly']], 'A sales plan changed');
|
||||
}
|
||||
$protected['catalog'] = digest($plans);
|
||||
$products = array_column(json_decode(file_get_contents($root . '/scripts/fuc-xb-launch/catalog.json'), true, 32, JSON_THROW_ON_ERROR)['products'], null, 'code');
|
||||
|
||||
$legacyGroupIds = array_values($oldCohorts);
|
||||
$opsGroups = [$state['qa_group_id'], $state['sales_group_id']];
|
||||
$groupIds = array_merge($legacyGroupIds, $opsGroups);
|
||||
sort($groupIds);
|
||||
must($db->table('v2_server_group')->orderBy('id')->pluck('id')->map(fn($id) => (int) $id)->all() === $groupIds, 'Unowned group exists');
|
||||
$protected['groups'] = digest($db->table('v2_server_group')->orderBy('id')->get()->map(fn($r) => (array) $r)->all());
|
||||
$nodeIds = array_column(array_values($state['nodes']), 'node_id');
|
||||
$machineIds = array_column(array_values($state['nodes']), 'machine_id');
|
||||
sort($nodeIds);
|
||||
sort($machineIds);
|
||||
$nodes = $db->table('v2_server')->orderBy('id')->get()->map(fn($r) => (array) $r)->all();
|
||||
must(array_map('intval', array_column($nodes, 'id')) === $nodeIds, 'Unowned node exists');
|
||||
$expectedMachines = array_column(array_values($state['nodes']), 'machine_id', 'node_id');
|
||||
foreach ($nodes as $node) {
|
||||
must(array_map('intval', json_decode($node['group_ids'], true, 8, JSON_THROW_ON_ERROR)) === [$state['qa_group_id']] && (int) $node['machine_id'] === $expectedMachines[$node['id']], 'Node has lost QA isolation or machine identity');
|
||||
}
|
||||
// Only stable fields contribute to the plan; live traffic and heartbeats can advance.
|
||||
$protected['nodes'] = digest(array_map(fn($n) => array_diff_key($n, array_flip(['u','d','updated_at'])), $nodes));
|
||||
$machines = $db->table('v2_server_machine')->orderBy('id')->get()->map(fn($r) => array_diff_key((array) $r, array_flip(['last_seen_at','load_status','updated_at'])))->all();
|
||||
must(array_map('intval', array_column($machines, 'id')) === $machineIds, 'Unowned machine exists');
|
||||
$protected['machines_hash_only'] = digest($machines);
|
||||
|
||||
$freshUsers = array_column($fresh['users'], null, 'id');
|
||||
$oldUsers = array_column($old['users'], null, 'id');
|
||||
must(count($freshUsers) === $summary['users'] && count($oldUsers) === $oldSummary['users'], 'User IDs are not unique');
|
||||
$assignments = legacyPlanAssignments($targetDirectory, $freshUsers, $freshCohorts, $hidden, $products);
|
||||
$assignedCounts = array_count_values($assignments);
|
||||
$cohortCounts = array_map(fn($id) => $assignedCounts[$id] ?? 0, $hidden);
|
||||
$existing = $db->table('v2_user')->select(['id','email','uuid','is_admin','is_staff'])->orderBy('id')->get();
|
||||
$knownQA = array_map('intval', array_merge([$qa['user_id']], $state['users']));
|
||||
$owned = $admins = 0;
|
||||
foreach ($existing as $row) {
|
||||
$id = (int) $row->id;
|
||||
if (isset($oldUsers[$id])) {
|
||||
$want = $oldUsers[$id];
|
||||
must($row->email === $want['email'] && $row->uuid === $want['uuid'], 'A migrated identity was replaced');
|
||||
if ($row->is_admin) {
|
||||
must($row->email === '[email protected]' && isset($freshUsers[$id]) && $freshUsers[$id]['email'] === $row->email && $freshUsers[$id]['uuid'] === $row->uuid, 'Administrator identity changed');
|
||||
$admins++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$isFixture = $final && $row->email === '[email protected]';
|
||||
must(($isFixture || in_array($id, $knownQA, true)) && str_ends_with($row->email, '@fuc-xb.invalid') && !$row->is_admin && !$row->is_staff, 'An unowned staging user exists');
|
||||
$owned++;
|
||||
}
|
||||
must($admins === 1 && count($existing) === count($oldUsers) + $owned, 'Missing migrated identity or administrator');
|
||||
$qaCollision = isset($freshUsers[$qa['user_id']]);
|
||||
$collisions = count(array_intersect(array_keys($freshUsers), $knownQA));
|
||||
$nextQaId = $qaCollision ? max(max(array_keys($freshUsers)), (int) $existing->max('id')) + 1 : $qa['user_id'];
|
||||
$usersWithChangedSourceUUID = 0;
|
||||
$freshPlanGroups = array_column($fresh['plans'], 'group_id', 'id');
|
||||
foreach ($freshUsers as $id => $row) {
|
||||
if (isset($oldUsers[$id]) && $oldUsers[$id]['uuid'] !== $row['uuid']) $usersWithChangedSourceUUID++;
|
||||
if ($row['plan_id'] === null) must($row['group_id'] === null, 'Unentitled user has a group');
|
||||
else must(isset($assignments[$id], $groups[$row['group_id']]) && $freshPlanGroups[$row['plan_id']] === $row['group_id'] && (int) $byId[$assignments[$id]]['group_id'] === $groups[$row['group_id']], 'Entitlement points outside its remapped group');
|
||||
}
|
||||
$result = ['read_only'=>true,'source_snapshot_sha256'=>$fresh['snapshot_sha256'],'projection_sha256'=>$summary['projection_sha256'],'users'=>$summary['users'],'hidden_plans'=>count($hidden),'hidden_plan_assignments'=>$cohortCounts,'wallet_cents'=>$summary['wallet_cents'],'commission_cents'=>$summary['commission_cents'],'refund_orders'=>$summary['prepaid_orders'],'refund_cents'=>$summary['prepaid_refund_cents'],'operating_plans_preserved'=>count($sales),'operating_nodes_preserved'=>count($nodes),'operating_machines_preserved'=>count($machines),'known_qa_user_id_collisions'=>$collisions,'gui_qa_requires_id_change'=>$qaCollision,'new_source_uuid_count'=>$usersWithChangedSourceUUID,'eligible_legacy_groups'=>[$oldCohorts['1:1'],$oldCohorts['2:1']],'excluded_legacy_group'=>$oldCohorts['2:99'],'protected_digests'=>$protected,'plan_sha256'=>digest(['source'=>$summary['projection_sha256'],'assignments'=>$assignments,'group_ids'=>$groups,'protected'=>$protected,'gui_qa_id'=>$nextQaId])];
|
||||
if ($final || in_array($mode, ['rehearse-rollback','rehearse-commit'], true)) {
|
||||
must($final || $targetDirectory === $private . '/refresh-20261105-launch-rehearsal', 'Rollback rehearsal is limited to the isolated rehearsal snapshot');
|
||||
if (!$commitMode) {
|
||||
$lock = fopen($stateDirectory . '/panel.lock', 'c');
|
||||
must($lock && flock($lock, LOCK_EX | LOCK_NB), 'FUC panel operations are busy');
|
||||
}
|
||||
$closed = readJson($stateDirectory . '/qa-cleanup.json');
|
||||
$registrationClosed = $commitMode
|
||||
? (int) $db->table('v2_settings')->where('name', 'stop_register')->value('value') === 1
|
||||
: (int) admin_setting('stop_register') === 1;
|
||||
must($closed['passed'] && ($final || $owned === 1) && !$db->table('v2_payment')->where('enable', 1)->exists() && $registrationClosed, 'Finish isolated QA and keep payment/registration disabled');
|
||||
must(!$db->table('v2_order')->exists() && !$db->table('v2_commission_log')->exists() && !$db->table('v2_stat_user')->exists(), 'New business or user statistics exist');
|
||||
$qaRow = (array) $db->table('v2_user')->where('id', $qa['user_id'])->first();
|
||||
must($final || ($qaRow['email'] === '[email protected]' && !$qaRow['is_admin'] && !$qaRow['is_staff'] && $qaRow['group_id'] === null), 'GUI QA ownership changed');
|
||||
$rollbackTables = ['v2_user'=>'id','v2_plan'=>'id','fuc_vip_accounts'=>'user_id','fuc_vip_entries'=>'id','personal_access_tokens'=>'id','v2_traffic_reset_logs'=>'id'];
|
||||
$baseline = streamDigest($db, $rollbackTables);
|
||||
app(App\Services\Plugin\PluginManager::class)->initializeEnabledPlugins();
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
foreach (['v2_traffic_reset_logs','fuc_vip_entries','fuc_vip_accounts'] as $table) $db->table($table)->delete();
|
||||
if ($final) $db->table('personal_access_tokens')->delete();
|
||||
$db->table('v2_user')->delete();
|
||||
foreach ($freshUsers as $id => &$user) {
|
||||
if ($user['group_id'] !== null) $user['group_id'] = $groups[$user['group_id']];
|
||||
$user['plan_id'] = $assignments[$id] ?? null;
|
||||
$user['next_reset_at'] = null;
|
||||
if ($user['email'] === '[email protected]') $user['is_admin'] = 1;
|
||||
}
|
||||
unset($user);
|
||||
foreach (array_chunk($freshUsers, 150) as $batch) $db->table('v2_user')->insert($batch);
|
||||
if (!$final) {
|
||||
$qaRow['id'] = $nextQaId;
|
||||
$db->table('v2_user')->insert($qaRow);
|
||||
}
|
||||
$vip = app(Plugin\VipLoyalty\Service::class);
|
||||
App\Models\User::withoutTimestamps(function () use ($fresh, $vip) {
|
||||
foreach ($fresh['vip_openings'] as $entry) $vip->opening($entry['user_id'], $entry['uuid'], $entry['opening_cumulative_cents'], $fresh['snapshot_sha256']);
|
||||
});
|
||||
$fullReadback = 0;
|
||||
foreach ($db->table('v2_user')->orderBy('id')->cursor() as $row) {
|
||||
$id = (int) $row->id;
|
||||
must(isset($freshUsers[$id]) || (!$final && $id === $nextQaId), 'Unexpected imported identity');
|
||||
sameRow($freshUsers[$id] ?? $qaRow, (array) $row, 'user');
|
||||
$fullReadback++;
|
||||
}
|
||||
must($fullReadback === $summary['users'] + (int) !$final, 'Incomplete user readback');
|
||||
$openings = array_column($fresh['vip_openings'], null, 'user_id');
|
||||
$vipReadback = 0;
|
||||
foreach ($db->table('fuc_vip_accounts')->orderBy('user_id')->cursor() as $account) {
|
||||
$id = (int) $account->user_id;
|
||||
must(isset($openings[$id]) && (int) $account->opening_cents === $openings[$id]['opening_cumulative_cents'] && (int) $account->cumulative_cents === $openings[$id]['opening_cumulative_cents'] && $account->opening_reference === $fresh['snapshot_sha256'], 'VIP opening readback mismatch');
|
||||
$vipReadback++;
|
||||
}
|
||||
must($vipReadback === $summary['users'] && !$db->table('v2_order')->exists(), 'VIP count or order boundary mismatch');
|
||||
if ($commitMode) {
|
||||
$entryCount = 0;
|
||||
foreach ($db->table('fuc_vip_entries')->orderBy('id')->cursor() as $entry) {
|
||||
$id = (int) $entry->user_id;
|
||||
must(isset($openings[$id]) && $entry->entry_key === 'opening:' . $id && $entry->kind === 'opening' && (int) $entry->amount_cents === $openings[$id]['opening_cumulative_cents'], 'VIP opening ledger differs');
|
||||
$entryCount++;
|
||||
}
|
||||
must($entryCount === $summary['users'], 'VIP opening ledger count differs');
|
||||
}
|
||||
$billingUsers = $db->table('v2_user');
|
||||
if (!$final) $billingUsers->where('id', '!=', $nextQaId);
|
||||
must((int) $billingUsers->sum('balance') === $summary['wallet_cents'] && (int) $billingUsers->sum('commission_balance') === $summary['commission_cents'], 'Wallet or commission mismatch');
|
||||
must(digest($db->table('v2_plan')->orderBy('id')->get()->map(fn($r)=>(array)$r)->all()) === $protected['catalog'], 'Current sales or hidden plans changed');
|
||||
must(digest($db->table('v2_server')->orderBy('id')->get()->map(fn($r)=>array_diff_key((array)$r,array_flip(['u','d','updated_at'])))->all()) === $protected['nodes'] && digest($db->table('v2_server_machine')->orderBy('id')->get()->map(fn($r)=>array_diff_key((array)$r,array_flip(['last_seen_at','load_status','updated_at'])))->all()) === $protected['machines_hash_only'], 'Nodes or machines changed');
|
||||
if ($final) $result['announcements'] = fucImportAnnouncements($db->getPdo(), $notices);
|
||||
if ($commitMode) {
|
||||
$result['committed_sha256'] = streamDigest($db, $verifiedTables);
|
||||
$db->table($receiptTable)->insert(['snapshot_sha256'=>$summary['snapshot_sha256'],'projection_sha256'=>$summary['projection_sha256'],'rows_sha256'=>$result['committed_sha256']]);
|
||||
$db->commit();
|
||||
}
|
||||
} finally {
|
||||
while ($db->transactionLevel()) $db->rollBack();
|
||||
}
|
||||
if (!$commitMode) {
|
||||
must(streamDigest($db, $rollbackTables) === $baseline, 'Rollback did not restore the original rows');
|
||||
}
|
||||
$result['read_only'] = false;
|
||||
$result['committed_database_writes'] = $commitMode;
|
||||
$result[$final ? 'import_readback' : 'rehearsal'] = ['rolled_back'=>!$commitMode,'original_rows_restored'=>!$commitMode,'full_user_readback'=>$fullReadback,'vip_opening_readback'=>$vipReadback,'gui_qa_collision_handled'=>$qaCollision];
|
||||
}
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
|
||||
} catch (Throwable $e) {
|
||||
// Do not expose framework arguments or snapshots to the invoking terminal.
|
||||
$reason = $e instanceof RefreshRejected ? $e->getMessage() : get_class($e);
|
||||
if ($e instanceof ErrorException) {
|
||||
$reason .= ' at line ' . $e->getLine();
|
||||
if (preg_match('/\AUndefined (array key|variable) ["$a-zA-Z0-9_]+\z/D', $e->getMessage())) {
|
||||
$reason .= ' ' . $e->getMessage();
|
||||
}
|
||||
}
|
||||
fwrite(STDERR, $reason . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Run on white jump only. JSON auth/request on stdin; default is read-only probe."""
|
||||
import fcntl,hashlib,ipaddress,json,os,re,sys,tempfile,time,urllib.request
|
||||
from pathlib import Path
|
||||
os.umask(0o077)
|
||||
FIELDS=['id','name','tunnelId','inPort','inIp','remoteAddr','strategy','speedId','ipMaxConn','ipSpeedId','maxConn','proxyProtocol','proxyProtocolReceive','proxyProtocolSend','status','userId']
|
||||
class Blocked(RuntimeError):pass
|
||||
def digest(value):return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
|
||||
def require(value,reason):
|
||||
if not value:raise Blocked(reason)
|
||||
def atomic(path,value):
|
||||
fd,tmp=tempfile.mkstemp(prefix='.relay-',dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd,'w') as f:os.fchmod(f.fileno(),0o600);json.dump(value,f,sort_keys=True);f.flush();os.fsync(f.fileno())
|
||||
os.replace(tmp,path)
|
||||
finally:
|
||||
if os.path.exists(tmp):os.unlink(tmp)
|
||||
def normalized(data):
|
||||
if isinstance(data,dict):
|
||||
rows=data.get('forwards',data.get('list',data.get('records')))
|
||||
total=data.get('total',data.get('count'))
|
||||
require(isinstance(total,int) and isinstance(rows,list) and total==len(rows),'incomplete_forward_inventory')
|
||||
require(not data.get('hasMore') and not data.get('nextPage'),'paginated_inventory_requires_review')
|
||||
else:rows=data
|
||||
require(isinstance(rows,list),'forward_inventory_unknown')
|
||||
result=[{k:item.get(k) for k in FIELDS} for item in rows]
|
||||
require(all(type(x['id']) is int and x['id']>0 for x in result),'invalid_forward_identity')
|
||||
require(len({x['id'] for x in result})==len(result),'duplicate_forward_identity')
|
||||
return sorted(result,key=lambda x:x['id'])
|
||||
def captcha_contract(source):
|
||||
match=re.search(r'const checkCaptcha\s*=.*?network_default\.(post|get)\("([^"\n]+)"',source)
|
||||
require(match is not None,'captcha_contract_unknown')
|
||||
return match[1].upper(),'/'+match[2].lstrip('/')
|
||||
def validate_request(request):
|
||||
require(set(request)=={'batch_id','backup_root','relay_host','tunnel_id','expected_user_id','expected_before_count','expected_before_sha256','rules'},'request_fields_unknown')
|
||||
require(re.fullmatch(r'[a-z0-9-]+',request['batch_id'] or ''),'batch_identity_unknown')
|
||||
require(re.fullmatch(r'/root/codex-backups/fuc-xb/[a-z0-9-]+/relay',request['backup_root'] or ''),'unsafe_backup_path')
|
||||
require(re.fullmatch(r'[a-z0-9.-]+',request['relay_host'] or ''),'unsafe_relay_host')
|
||||
for key in ['tunnel_id','expected_user_id','expected_before_count']:require(type(request[key]) is int and request[key]>0,'invalid_request_identity')
|
||||
require(re.fullmatch(r'[0-9a-f]{64}',request['expected_before_sha256'] or ''),'frozen_inventory_digest_required')
|
||||
rules=request['rules'];require(isinstance(rules,list) and rules,'empty_rule_request')
|
||||
for rule in rules:
|
||||
require(set(rule)=={'name','port','address','listen_port','old_port'},'rule_fields_unknown')
|
||||
require(re.fullmatch(r'fuc-xb-[a-z0-9-]+-anytls',rule['name'] or ''),'unsafe_rule_name')
|
||||
require(ipaddress.ip_address(rule['address']).version==4,'ipv4_target_required')
|
||||
for key in ['port','listen_port']:require(type(rule[key]) is int and 1024<=rule[key]<=65535,'unsafe_rule_port')
|
||||
if rule['old_port'] is not None:require(type(rule['old_port']) is int and 1024<=rule['old_port']<=65535,'unsafe_rule_port')
|
||||
require(rule['port']!=rule['old_port'] and rule['listen_port']!=443,'old_port_collision')
|
||||
for key in ['name','port','address']:require(len({x[key] for x in rules})==len(rules),'duplicate_candidate_rule')
|
||||
def target(rule):return rule['address']+':'+str(rule['listen_port'])
|
||||
def matches(row,rule,request):
|
||||
expected=dict(name=rule['name'],tunnelId=request['tunnel_id'],inPort=rule['port'],inIp=request['relay_host']+':'+str(rule['port']),remoteAddr=target(rule),strategy='fifo',speedId=None,ipMaxConn=0,ipSpeedId=None,maxConn=0,proxyProtocol=0,proxyProtocolReceive=0,proxyProtocolSend=0,status=1,userId=request['expected_user_id'])
|
||||
return all(row.get(k)==value for k,value in expected.items())
|
||||
class RelayBatch:
|
||||
def __init__(self,request,api,root):validate_request(request);self.request=request;self.api=api;self.root=Path(root)
|
||||
def rows(self):
|
||||
result=self.api('/forward/list',None);require(result.get('code')==0,'forward_list_failed');return normalized(result.get('data'))
|
||||
def inspect(self,rows,journal):
|
||||
request=self.request;rules=request['rules'];by_name={}
|
||||
if journal:
|
||||
require(journal['request_sha256']==digest(request) and journal['request']==request,'different_task_ownership')
|
||||
baseline=journal['before']
|
||||
require(len(baseline)==request['expected_before_count']and digest(baseline)==request['expected_before_sha256'],'frozen_journal_baseline_changed')
|
||||
else:
|
||||
require(len(rows)==request['expected_before_count'],'unexpected_initial_rule_count');require(digest(rows)==request['expected_before_sha256'],'frozen_original_inventory_changed');baseline=rows
|
||||
for rule in rules:
|
||||
collisions=[x for x in rows if x['name']==rule['name'] or str(x['inPort'])==str(rule['port']) or x['remoteAddr']==target(rule)]
|
||||
if collisions:
|
||||
require(len(collisions)==1 and matches(collisions[0],rule,request),'candidate_rule_conflict')
|
||||
require(journal and rule['name'] in journal['intents'],'matching_rule_without_task_intent')
|
||||
observed=journal['added'].get(rule['name'])
|
||||
require(observed is None or observed==collisions[0],'owned_rule_changed')
|
||||
by_name[rule['name']]=collisions[0]
|
||||
elif journal:
|
||||
require(rule['name'] not in journal['added'],'owned_rule_disappeared')
|
||||
require(rule['name'] not in journal['intents'],'unknown_create_outcome_requires_explicit_review')
|
||||
if rule['old_port'] is None:
|
||||
# Explicit absence is an ownership assertion, not an optional check.
|
||||
# Check every rule, including other users/tunnels, in both snapshots.
|
||||
for inventory in (baseline,rows):
|
||||
require(not any(x['remoteAddr']==rule['address']+':443' for x in inventory),'unexpected_original_443_rule')
|
||||
else:
|
||||
original=[x for x in baseline if str(x['inPort'])==str(rule['old_port']) and x['remoteAddr']==rule['address']+':443' and x['tunnelId']==request['tunnel_id'] and x['userId']==request['expected_user_id']]
|
||||
require(len(original)==1,'original_443_rule_missing')
|
||||
added_ids={x['id'] for x in by_name.values()}
|
||||
require(normalized([x for x in rows if x['id'] not in added_ids])==baseline,'original_rule_inventory_changed')
|
||||
return by_name
|
||||
def run(self,apply=False):
|
||||
path=self.root/'journal.json';require(not path.is_symlink(),'private_journal_required')
|
||||
if self.root.exists():require(not self.root.is_symlink() and not self.root.stat().st_mode&0o077,'private_backup_required')
|
||||
if path.exists():require(path.is_file() and not path.stat().st_mode&0o077,'private_journal_required')
|
||||
journal=json.loads(path.read_text()) if path.exists() else None
|
||||
current=self.rows();found=self.inspect(current,journal)
|
||||
if not apply:return {'state':'ready' if len(found)==len(self.request['rules']) else 'absent','captured_at':int(time.time()),'new':list(found.values()),'before_count':len(journal['before']) if journal else len(current),'after_count':len(current),'writes':False,'request_sha256':digest(self.request)}
|
||||
if journal is None:
|
||||
require(digest(current)==self.request['expected_before_sha256'],'frozen_original_inventory_changed')
|
||||
journal={'version':1,'request':self.request,'request_sha256':digest(self.request),'before':current,'intents':{},'added':{}}
|
||||
atomic(path,journal) # Immutable initial before: never recaptured on recovery.
|
||||
for rule in self.request['rules']:
|
||||
current=self.rows();found=self.inspect(current,journal)
|
||||
if rule['name'] in found:
|
||||
journal['added'][rule['name']]=found[rule['name']];atomic(path,journal);continue
|
||||
journal['intents'][rule['name']]={'payload':rule,'attempt':journal['intents'].get(rule['name'],{}).get('attempt',0)+1,'at':int(time.time())}
|
||||
atomic(path,journal)
|
||||
payload=dict(name=rule['name'],tunnelId=self.request['tunnel_id'],inPort=rule['port'],remoteAddr=target(rule),strategy='fifo',speedId=None,ipMaxConn=0,maxConn=0,proxyProtocol=0,proxyProtocolReceive=0,proxyProtocolSend=0)
|
||||
result=self.api('/forward/create',payload) # Exactly once per observed-absent attempt; no network retry.
|
||||
require(result.get('code')==0,'create_outcome_requires_probe')
|
||||
found=self.inspect(self.rows(),journal);require(rule['name'] in found,'create_outcome_requires_probe')
|
||||
journal['added'][rule['name']]=found[rule['name']];atomic(path,journal)
|
||||
final=self.rows();found=self.inspect(final,journal)
|
||||
require(len(found)==len(self.request['rules']),'incomplete_batch')
|
||||
journal['state']='applied';journal['added']=found;atomic(path,journal)
|
||||
return {'state':'applied','captured_at':int(time.time()),'request_sha256':digest(self.request),'before_count':len(journal['before']),'after_count':len(final),'old_rules_unchanged':True,'new':list(found.values())}
|
||||
def pause_owned(self):
|
||||
path=self.root/'journal.json';require(path.is_file()and not path.is_symlink(),'owned_journal_required')
|
||||
journal=json.loads(path.read_text());request=self.request
|
||||
require(journal['request']==request and journal['request_sha256']==digest(request),'different_task_ownership')
|
||||
require(len(journal['before'])==request['expected_before_count']and digest(journal['before'])==request['expected_before_sha256'],'frozen_journal_baseline_changed')
|
||||
require(journal.get('state')in ['applied','pausing','paused']and len(journal['added'])==len(request['rules']),'complete_owned_batch_required')
|
||||
expected={x['id']:x for x in journal['added'].values()}
|
||||
require(len(expected)==len(request['rules']),'owned_ids_not_unique')
|
||||
def check(rows):
|
||||
by_id={x['id']:x for x in rows}
|
||||
require(normalized([x for x in rows if x['id']not in expected])==journal['before'],'original_rule_inventory_changed')
|
||||
for ident,before in expected.items():
|
||||
current=by_id.get(ident);require(current is not None,'owned_rule_disappeared')
|
||||
require(current.get('status')in [0,1]and dict(current,status=1)==before,'owned_rule_changed')
|
||||
return by_id
|
||||
check(self.rows());journal['state']='pausing';atomic(path,journal)
|
||||
for ident in expected:
|
||||
current=check(self.rows())[ident]
|
||||
if current['status']==0:continue
|
||||
# Current frontend contract: POST /forward/pause {id}; never delete/reset.
|
||||
journal.setdefault('pause_intents',{})[str(ident)]=int(time.time());atomic(path,journal)
|
||||
result=self.api('/forward/pause',{'id':ident});require(result.get('code')==0,'pause_outcome_requires_probe')
|
||||
require(check(self.rows())[ident]['status']==0,'pause_not_confirmed')
|
||||
after=check(self.rows());require(all(after[i]['status']==0 for i in expected),'pause_incomplete')
|
||||
journal['state']='paused';atomic(path,journal)
|
||||
return {'state':'paused','owned_ids':sorted(expected),'old_rules_unchanged':True,'new_rules_only':True}
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self,*args,**kwargs):raise Blocked('redirect_requires_review')
|
||||
class API:
|
||||
def __init__(self):self.base='https://hw.lshan.eu.org';self.token=None;self.opener=urllib.request.build_opener(NoRedirect())
|
||||
def call(self,path,data=None,method='POST'):
|
||||
require(re.fullmatch(r'/[A-Za-z0-9/_-]+',path),'unexpected_api_path')
|
||||
headers={'Content-Type':'application/json','Accept':'application/json'}
|
||||
if self.token:headers['Authorization']=self.token
|
||||
raw=json.dumps(data or {}).encode() if method=='POST' else None
|
||||
with self.opener.open(urllib.request.Request(self.base+'/api/v1'+path,data=raw,headers=headers,method=method),timeout=40) as response:return json.load(response)
|
||||
def login(self,auth):
|
||||
with self.opener.open(self.base+'/assets/index-C6H-F141-v186.js',timeout=30) as response:source=response.read().decode()
|
||||
method,path=captcha_contract(source)
|
||||
check=self.call(path,method=method);require(check.get('code')==0 and check.get('data')==0,'mandatory_captcha_requires_user')
|
||||
result=self.call('/user/login',dict(username=auth['username'],password=auth['password'],captchaId=''));auth.clear()
|
||||
require(result.get('code')==0,'normal_login_failed');require(not result['data'].get('requirePasswordChange'),'password_change_required')
|
||||
self.token=result['data'].get('token');require(isinstance(self.token,str) and self.token,'login_token_missing')
|
||||
def main():
|
||||
data=json.load(sys.stdin);request=data.pop('request');apply=data.pop('apply',False);operation=data.pop('operation','apply'if apply else'probe');require(type(apply) is bool and operation in ['probe','apply','pause'],'explicit_operation_required');require(set(data)=={'username','password'},'authentication_fields_unknown');validate_request(request)
|
||||
require(apply==(operation in ['apply','pause']),'operation_apply_flag_conflict')
|
||||
api=API();api.login(data);root=Path(request['backup_root'])
|
||||
# Applying owns a task-private lock and journal. A pure probe creates no files.
|
||||
if apply:
|
||||
root.mkdir(parents=True,mode=0o700,exist_ok=True);require(not root.is_symlink() and not root.stat().st_mode&0o077,'private_backup_required')
|
||||
lock=root/'operation.lock';require(not lock.is_symlink(),'unsafe_lock')
|
||||
with lock.open('a') as handle:
|
||||
os.chmod(lock,0o600);fcntl.flock(handle,fcntl.LOCK_EX);batch=RelayBatch(request,api.call,root);result=batch.pause_owned()if operation=='pause'else batch.run(True)
|
||||
else:result=RelayBatch(request,api.call,root).run(False)
|
||||
print(json.dumps(result))
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
except Exception as error:
|
||||
print(json.dumps({'state':'blocked','reason':str(error) if type(error) is Blocked else 'Remote outcome unknown; inspect protected journal and probe, never blindly replay','error_type':type(error).__name__}));raise SystemExit(2)
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Back up, import and independently verify one sealed production cutover."""
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
PRIVATE = Path("/var/www/wwwroot/fuc-xb-test/private")
|
||||
CURRENT = Path("/var/www/wwwroot/fuc-xb-test/current")
|
||||
|
||||
|
||||
def command(args, environment, timeout):
|
||||
result = subprocess.run(args, env=environment, capture_output=True, text=True, timeout=timeout)
|
||||
if result.returncode:
|
||||
diagnostic = result.stderr.strip().splitlines()
|
||||
if diagnostic and len(diagnostic[-1]) <= 140:
|
||||
raise RuntimeError(diagnostic[-1])
|
||||
raise RuntimeError("A cutover command failed")
|
||||
return json.loads(result.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() != 0 or len(sys.argv) != 2 or not re.fullmatch(r"cutover-[0-9]{8}T[0-9]{6}Z", sys.argv[1]):
|
||||
raise RuntimeError("Expected an exact root-owned cutover window")
|
||||
window = sys.argv[1]
|
||||
directory = PRIVATE / window
|
||||
release = HERE.parents[1]
|
||||
if directory.resolve() != directory or directory.stat().st_uid != 0 or directory.stat().st_mode & 0o077:
|
||||
raise RuntimeError("Cutover directory is not private")
|
||||
if release != CURRENT.resolve() or not re.fullmatch(r"[a-f0-9]{40}", release.name):
|
||||
raise RuntimeError("Run the deployed cutover release")
|
||||
env = {key: value for key, value in os.environ.items() if key in ("PATH", "LANG", "LC_ALL", "TZ")}
|
||||
with (directory / "final-import.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
if not (directory / "old-fuc-full.json").exists():
|
||||
command(["python3", str(HERE / "backup-legacy.py"), window], env, 100)
|
||||
if not (directory / "import-ready.json").exists():
|
||||
command(["python3", str(HERE / "prepare-final-import.py"), window], env, 160)
|
||||
runtime = Path("/tmp/fuc-xb-cutover-" + secrets.token_hex(4))
|
||||
runtime.mkdir(mode=0o700)
|
||||
try:
|
||||
for relative in ("storage/framework/cache/data", "storage/framework/sessions",
|
||||
"storage/framework/views", "storage/logs"):
|
||||
(runtime / relative).mkdir(parents=True)
|
||||
env["FUC_CUTOVER_RUNTIME"] = str(runtime)
|
||||
importer = ["php", str(HERE / "refresh-plan.php"), window]
|
||||
committed = command(importer + ["cutover-commit"], env, 240)
|
||||
verified = command(importer + ["cutover-verify"], env, 40)
|
||||
if committed.get("committed_sha256", committed.get("readback_sha256")) != verified["readback_sha256"]:
|
||||
raise RuntimeError("Independent target readback differs")
|
||||
receipt = directory / "target-import-verified.json"
|
||||
if receipt.exists():
|
||||
if json.loads(receipt.read_text()) != verified:
|
||||
raise RuntimeError("Final verification receipt changed")
|
||||
else:
|
||||
with receipt.open("x") as handle:
|
||||
json.dump(verified, handle, indent=2)
|
||||
handle.write("\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
print(json.dumps(verified))
|
||||
finally:
|
||||
shutil.rmtree(runtime)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as failure:
|
||||
sys.exit(str(failure) if isinstance(failure, RuntimeError) else type(failure).__name__)
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Enable only this staging instance's native workers and minute scheduler."""
|
||||
import hashlib,json,os,pathlib,re,shutil,subprocess
|
||||
BASE=pathlib.Path('/var/www/wwwroot/fuc-xb-test')
|
||||
DIR=BASE/'private/launch-ready-20261105/runtime'
|
||||
UNIT=pathlib.Path('/etc/systemd/system/fuc-xb-test-horizon.service')
|
||||
CRON=pathlib.Path('/etc/cron.d/fuc-xb-test')
|
||||
def run(args):
|
||||
p=subprocess.run(args,capture_output=True,text=True,timeout=60)
|
||||
assert p.returncode==0,'FUC runtime operation failed; inspect private diagnostic'
|
||||
return p.stdout.strip()
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
assert not DIR.exists()and not os.path.lexists(UNIT)and not os.path.lexists(CRON),'Existing runtime; inspect instead of overwriting'
|
||||
for name in [str(UNIT)+'.d']:assert not os.path.lexists(name),'Existing worker override'
|
||||
ready=json.loads((BASE/'private/launch-ready-20261105/configured.json').read_text())
|
||||
assert ready['bulk_automatic_mail_disabled']and ready['payment_channels_disabled_until_cutover']
|
||||
php=r'''putenv('XB_INSTANCE=fuc-xb-test');require $argv[1].'/vendor/autoload.php';$a=require $argv[1].'/bootstrap/app.php';$a->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();if(Illuminate\Support\Facades\DB::connection()->getDatabaseName()!=='fuc_xb_test'||App\Services\MailFlow\AutomaticMailPolicy::state()['level']!==3||admin_setting('remind_mail_enable')||!admin_setting('stop_register')||App\Models\Payment::where('enable',true)->exists())throw new RuntimeException('Isolation guard failed');foreach(['send_email','send_email_mass','send_telegram','default','order_handle']as$q)if(Illuminate\Support\Facades\Queue::size($q))throw new RuntimeException('Unexpected notification/business backlog');echo json_encode(['guarded'=>true]);'''
|
||||
assert json.loads(run(['runuser','-u','fucxbtest','--','php','-r',php,str(BASE/'current')]))['guarded']
|
||||
DIR.mkdir(mode=0o700)
|
||||
envfile=BASE/'shared/.env';before=envfile.read_bytes();shutil.copy2(envfile,DIR/'environment-before');(DIR/'environment-before').chmod(0o600)
|
||||
text=before.decode();changes={'APP_ENV':'production','MAIL_DRIVER':'smtp','MAIL_MAILER':'smtp','HORIZON_PREFIX':'fuc_xb_test_horizon_','HORIZON_DATA_PIPELINE_MAX':'2','HORIZON_BUSINESS_MAX':'1','HORIZON_NOTIFICATION_MAX':'1','HORIZON_WORKER_MEMORY_MB':'128'}
|
||||
for k,v in changes.items():
|
||||
pattern=r'^'+re.escape(k)+r'=.*$'
|
||||
text=re.sub(pattern,k+'='+v,text,flags=re.M)if re.search(pattern,text,re.M)else text.rstrip()+'\n'+k+'='+v+'\n'
|
||||
journal={'owner':'fuc-xb-launch-20261105','changed_env_keys':list(changes),'before_env_sha256':hashlib.sha256(before).hexdigest(),'phase':'preparing'}
|
||||
(DIR/'intent.json').write_text(json.dumps(journal,indent=2));envfile.write_text(text)
|
||||
unit='''[Unit]
|
||||
Description=FUC-XB isolated Horizon
|
||||
After=network-online.target fuc-xb-test-redis.service
|
||||
Requires=fuc-xb-test-redis.service
|
||||
[Service]
|
||||
Type=simple
|
||||
User=fucxbtest
|
||||
Group=fucxbtest
|
||||
Environment=XB_INSTANCE=fuc-xb-test
|
||||
WorkingDirectory=/var/www/wwwroot/fuc-xb-test/current
|
||||
ExecStart=/usr/bin/php artisan horizon
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
KillSignal=SIGTERM
|
||||
TimeoutStopSec=90
|
||||
MemoryMax=768M
|
||||
CPUQuota=100%
|
||||
UMask=0027
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
'''
|
||||
cron='''SHELL=/bin/sh
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
* * * * * fucxbtest cd /var/www/wwwroot/fuc-xb-test/current && XB_INSTANCE=fuc-xb-test /usr/bin/php artisan schedule:run >> /var/www/wwwroot/fuc-xb-test/shared/storage/logs/schedule.log 2>&1
|
||||
'''
|
||||
try:
|
||||
run(['runuser','-u','fucxbtest','--','env','XB_INSTANCE=fuc-xb-test','php',str(BASE/'current/artisan'),'config:clear'])
|
||||
UNIT.write_text(unit);UNIT.chmod(0o644);CRON.write_text(cron);CRON.chmod(0o644)
|
||||
run(['systemctl','daemon-reload']);run(['systemctl','enable','--now','fuc-xb-test-horizon'])
|
||||
assert run(['systemctl','is-active','fuc-xb-test-horizon'])=='active'
|
||||
run(['runuser','-u','fucxbtest','--','env','XB_INSTANCE=fuc-xb-test','php',str(BASE/'current/artisan'),'schedule:run'])
|
||||
except BaseException:
|
||||
CRON.unlink(missing_ok=True)
|
||||
stopped=subprocess.run(['systemctl','disable','--now','fuc-xb-test-horizon'],capture_output=True,timeout=100)
|
||||
journal['phase']='failed';journal['cleanup_returncode']=stopped.returncode;(DIR/'intent.json').write_text(json.dumps(journal,indent=2));raise
|
||||
journal.update(phase='active',mail_driver='smtp',queue='redis',automatic_mail_policy=3,payment_channels_enabled=0,worker_unit_sha256=hashlib.sha256(UNIT.read_bytes()).hexdigest(),cron_sha256=hashlib.sha256(CRON.read_bytes()).hexdigest(),after_env_sha256=hashlib.sha256(envfile.read_bytes()).hexdigest())
|
||||
(DIR/'receipt.json').write_text(json.dumps(journal,indent=2));print(json.dumps(journal))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,369 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline fault tests: temporary paths, synthetic secrets, no network/systemd."""
|
||||
import builtins
|
||||
import copy
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import pathlib
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
HERE = pathlib.Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def load(filename):
|
||||
spec = importlib.util.spec_from_file_location(filename.replace('-', '_'), HERE / filename)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class HostTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = pathlib.Path(self.temp.name)
|
||||
self.host = load('node-host.py')
|
||||
self.source = self.root / 'source-binary'
|
||||
self.source.write_bytes(b'offline synthetic binary')
|
||||
self.memory = self.root / 'meminfo'
|
||||
self.memory.write_text('MemTotal: 2000000 kB\n')
|
||||
for name, suffix in [('ETC', 'etc'), ('OPT', 'opt'), ('STATE', 'state'),
|
||||
('UNIT', 'systemd/fuc-xb-node.service'),
|
||||
('REFRESH', 'systemd/fuc-xb-certificate-refresh.service'),
|
||||
('TIMER', 'systemd/fuc-xb-certificate-refresh.timer')]:
|
||||
setattr(self.host, name, self.root / suffix)
|
||||
self.host.UNIT.parent.mkdir()
|
||||
self.baseline = {'original': 'unchanged'}
|
||||
self.host.protected = Mock(return_value=self.baseline)
|
||||
self.host.SHA = hashlib.sha256(self.source.read_bytes()).hexdigest()
|
||||
self.host.pathlib = types.SimpleNamespace(Path=self.path)
|
||||
self.host.os = types.SimpleNamespace(path=types.SimpleNamespace(lexists=lambda p: self.path(p).is_symlink() or self.path(p).exists()))
|
||||
self.host.validate_cert = Mock(return_value='SHA256 Fingerprint=AA')
|
||||
self.commands = []
|
||||
self.cleanup_commands = []
|
||||
self.host.run = self.command_run
|
||||
self.host.subprocess = types.SimpleNamespace(run=self.cleanup_run)
|
||||
self.host.time = types.SimpleNamespace(sleep=lambda _: None)
|
||||
self.context = {'owner': self.host.OWNER, 'source': 'https://fuc-xb-test.gemcook.net',
|
||||
'machine_id': 101, 'machine_token': 'syntheticOnly' * 4,
|
||||
'expected_units': self.baseline,
|
||||
'node': {'listen_port': 24445, 'sni': 'offline.invalid',
|
||||
'certificate': '/synthetic/cert', 'private_key': '/synthetic/key'}}
|
||||
self.fail_enable = False
|
||||
self.listener = True
|
||||
self.fail_stop = False
|
||||
self.stopped = set()
|
||||
|
||||
def path(self, value):
|
||||
value = str(value)
|
||||
if value == '/opt/dpl-node/xboard-node':
|
||||
return self.source
|
||||
if value == '/proc/meminfo':
|
||||
return self.memory
|
||||
if value.startswith('/etc/systemd/system/'):
|
||||
return self.root / 'systemd-checks' / value.rsplit('/', 1)[1]
|
||||
return pathlib.Path(value)
|
||||
|
||||
def command_run(self, args):
|
||||
self.commands.append(args)
|
||||
if args[:2] == ['systemctl', 'stop']:
|
||||
if self.fail_stop:
|
||||
raise RuntimeError('synthetic systemctl stop failure')
|
||||
self.stopped.update(args[2:])
|
||||
if args[:3] == ['systemctl', 'disable', '--now']:
|
||||
self.stopped.update(args[3:])
|
||||
if args[:2] == ['systemctl', 'show']:
|
||||
if 'LoadState' in args:
|
||||
return 'LoadState=not-found\nFragmentPath=\nDropInPaths='
|
||||
if 'FragmentPath' in args:
|
||||
units = {p.name: p for p in (self.host.UNIT, self.host.REFRESH, self.host.TIMER)}
|
||||
return 'FragmentPath=' + str(units[args[2]]) + '\nDropInPaths='
|
||||
if 'MainPID' in args:
|
||||
return '0' if args[2] in self.stopped else '444'
|
||||
return 'inactive' if args[2] in self.stopped else 'active'
|
||||
if args[:2] == ['systemctl', 'enable'] and self.fail_enable:
|
||||
raise RuntimeError('synthetic enable failure')
|
||||
if args[:2] == ['systemctl', 'is-enabled']:
|
||||
return 'enabled'
|
||||
if args[:2] == ['systemctl', 'is-active']:
|
||||
return 'inactive' if args[2] in self.stopped else 'active'
|
||||
if args[0] == 'ss':
|
||||
started = any(x[:2] == ['systemctl', 'enable'] for x in self.commands)
|
||||
return 'LISTEN users:(("synthetic",pid=444,fd=3))' if started and self.listener else ''
|
||||
return ''
|
||||
|
||||
def cleanup_run(self, args, **kwargs):
|
||||
self.cleanup_commands.append(args)
|
||||
if args[:2] == ['systemctl', 'is-enabled']:
|
||||
return types.SimpleNamespace(returncode=1, stdout='disabled\n', stderr='')
|
||||
if args[:2] == ['systemctl', 'stop']:
|
||||
if self.fail_stop:
|
||||
return types.SimpleNamespace(returncode=1, stdout='', stderr='synthetic failure')
|
||||
self.stopped.update(args[2:])
|
||||
if args[:3] == ['systemctl', 'disable', '--now']:
|
||||
self.stopped.update(args[3:])
|
||||
return types.SimpleNamespace(returncode=0, stdout='', stderr='')
|
||||
|
||||
def install(self):
|
||||
return self.host.install(self.context)
|
||||
|
||||
def test_success_isolated_install_and_exact_rollback(self):
|
||||
result = self.install()
|
||||
self.assertTrue(result['port_listening'])
|
||||
state = json.loads((self.host.STATE / 'owner.json').read_text())
|
||||
self.assertEqual(state['phase'], 'installed')
|
||||
self.assertNotIn(self.context['machine_token'], json.dumps(state))
|
||||
self.assertIn(str(self.host.ETC / 'secret.env'), state['files'])
|
||||
self.assertEqual((self.host.ETC / 'secret.env').stat().st_mode & 0o777, 0o600)
|
||||
self.host.rollback()
|
||||
self.assertFalse(self.host.STATE.exists())
|
||||
self.assertTrue(self.source.exists())
|
||||
self.assertFalse(any('XrayR' in a or 'dpl-node' in a for a in self.cleanup_commands))
|
||||
|
||||
def test_existing_refresh_unit_rejected_before_mutation(self):
|
||||
self.host.REFRESH.write_text('unrelated')
|
||||
with self.assertRaises(AssertionError):
|
||||
self.install()
|
||||
self.assertFalse(self.host.STATE.exists())
|
||||
self.assertEqual(self.host.REFRESH.read_text(), 'unrelated')
|
||||
|
||||
def test_broken_symlink_rejected_before_mutation(self):
|
||||
self.host.TIMER.symlink_to(self.root / 'missing')
|
||||
with self.assertRaises(AssertionError):
|
||||
self.install()
|
||||
self.assertFalse(self.host.STATE.exists())
|
||||
|
||||
def test_systemd_dropin_rejected(self):
|
||||
p = self.path('/etc/systemd/system/fuc-xb-node.service.d')
|
||||
p.mkdir(parents=True)
|
||||
with self.assertRaises(AssertionError):
|
||||
self.install()
|
||||
self.assertFalse(self.host.STATE.exists())
|
||||
|
||||
def test_frozen_original_baseline_drift_rejected(self):
|
||||
self.context['expected_units'] = {'original': 'different'}
|
||||
with self.assertRaises(AssertionError):
|
||||
self.install()
|
||||
self.assertFalse(self.host.STATE.exists())
|
||||
|
||||
def test_failure_after_secret_is_journaled_and_disabled(self):
|
||||
original = self.host.write
|
||||
def fail(path, value, mode=0o600):
|
||||
original(path, value, mode)
|
||||
if path.name == 'secret.env':
|
||||
raise RuntimeError('synthetic after-secret failure')
|
||||
self.host.write = fail
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.install()
|
||||
state = json.loads((self.host.STATE / 'owner.json').read_text())
|
||||
self.assertEqual(state['phase'], 'failed')
|
||||
self.assertIn(str(self.host.ETC / 'secret.env'), state['files'])
|
||||
self.assertTrue(any(a[:3] == ['systemctl', 'disable', '--now'] for a in self.cleanup_commands))
|
||||
self.host.rollback()
|
||||
self.assertFalse(self.host.ETC.exists())
|
||||
|
||||
def test_enable_failure_disables_and_stops_refresh(self):
|
||||
self.fail_enable = True
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.install()
|
||||
self.assertTrue(any(a[:3] == ['systemctl', 'disable', '--now'] for a in self.cleanup_commands))
|
||||
self.assertIn(['systemctl', 'stop', 'fuc-xb-certificate-refresh.service'], self.cleanup_commands)
|
||||
|
||||
def test_verify_and_rollback_reject_owned_file_drift(self):
|
||||
self.install()
|
||||
(self.host.ETC / 'config.json').write_text('changed')
|
||||
with self.assertRaises(AssertionError):
|
||||
self.host.verify()
|
||||
with self.assertRaises(AssertionError):
|
||||
self.host.rollback()
|
||||
self.assertTrue(self.host.ETC.exists())
|
||||
|
||||
def test_copied_hash_checked_before_enable(self):
|
||||
original = self.host.write
|
||||
def corrupt(path, value, mode=0o600):
|
||||
original(path, b'corrupted' if path.name == 'xboard-node' else value, mode)
|
||||
self.host.write = corrupt
|
||||
with self.assertRaises(AssertionError):
|
||||
self.install()
|
||||
self.assertFalse(any(a[:2] == ['systemctl', 'enable'] for a in self.commands))
|
||||
|
||||
def test_missing_or_foreign_listener_fails_closed(self):
|
||||
self.listener = False
|
||||
with self.assertRaises(AssertionError):
|
||||
self.install()
|
||||
self.assertEqual(json.loads((self.host.STATE / 'owner.json').read_text())['phase'], 'failed')
|
||||
|
||||
def test_rollback_stop_failure_keeps_owned_files_for_recovery(self):
|
||||
self.install()
|
||||
self.fail_stop = True
|
||||
with self.assertRaises((AssertionError, RuntimeError)):
|
||||
self.host.rollback()
|
||||
self.assertTrue(self.host.STATE.exists())
|
||||
self.assertTrue((self.host.OPT / 'xboard-node').exists())
|
||||
|
||||
def protection_snapshot(self):
|
||||
return {'dpl-node': {'execstart_sha256': 'transient-before',
|
||||
'properties': {'MainPID': '123', 'NRestarts': '0',
|
||||
'ExecMainStartTimestampMonotonic': '456', 'ActiveState': 'active'},
|
||||
'unit_sha256': 'unit-bytes', 'binary': '/synthetic/original',
|
||||
'binary_sha256': 'binary-bytes', 'config_sha256': {'/synthetic/config': 'config-bytes'}}}
|
||||
|
||||
def test_transient_execstart_metadata_change_is_accepted(self):
|
||||
expected = self.protection_snapshot()
|
||||
actual = copy.deepcopy(expected)
|
||||
actual['dpl-node']['execstart_sha256'] = 'transient-after'
|
||||
self.assertTrue(self.host.same_protected(actual, expected))
|
||||
|
||||
def test_all_stable_original_service_fields_still_reject_drift(self):
|
||||
expected = self.protection_snapshot()
|
||||
for field in ('unit_sha256', 'binary', 'binary_sha256', 'config_sha256',
|
||||
'MainPID', 'NRestarts', 'ExecMainStartTimestampMonotonic', 'ActiveState'):
|
||||
with self.subTest(field=field):
|
||||
actual = copy.deepcopy(expected)
|
||||
row = actual['dpl-node']
|
||||
if field in row['properties']:
|
||||
row['properties'][field] = 'changed'
|
||||
elif field == 'config_sha256':
|
||||
row[field]['/synthetic/config'] = 'changed'
|
||||
else:
|
||||
row[field] = 'changed'
|
||||
self.assertFalse(self.host.same_protected(actual, expected))
|
||||
|
||||
def test_resume_success_does_not_rewrite_owned_runtime(self):
|
||||
self.install()
|
||||
before = json.loads((self.host.STATE / 'owner.json').read_text())['files']
|
||||
self.commands.clear()
|
||||
self.assertTrue(self.host.resume(self.context)['port_listening'])
|
||||
self.assertEqual(json.loads((self.host.STATE / 'owner.json').read_text())['files'], before)
|
||||
|
||||
def test_resume_rejects_owned_file_drift_before_enable(self):
|
||||
self.install()
|
||||
(self.host.ETC / 'config.json').write_text('changed')
|
||||
self.commands.clear()
|
||||
with self.assertRaises(AssertionError):
|
||||
self.host.resume(self.context)
|
||||
self.assertFalse(any(a[:2] == ['systemctl', 'enable'] for a in self.commands))
|
||||
|
||||
def test_resume_rejects_context_secret_drift_before_enable(self):
|
||||
self.install()
|
||||
changed = copy.deepcopy(self.context)
|
||||
changed['machine_token'] = 'differentSyntheticSecret' * 3
|
||||
self.commands.clear()
|
||||
with self.assertRaises(AssertionError):
|
||||
self.host.resume(changed)
|
||||
self.assertFalse(any(a[:2] == ['systemctl', 'enable'] for a in self.commands))
|
||||
|
||||
def test_resume_rejects_secret_file_drift_before_enable(self):
|
||||
self.install()
|
||||
(self.host.ETC / 'secret.env').write_text('FUC_XB_MACHINE_TOKEN=changed\n')
|
||||
self.commands.clear()
|
||||
with self.assertRaises(AssertionError):
|
||||
self.host.resume(self.context)
|
||||
self.assertFalse(any(a[:2] == ['systemctl', 'enable'] for a in self.commands))
|
||||
|
||||
def test_resume_rejects_new_unowned_systemd_override_before_enable(self):
|
||||
self.install()
|
||||
self.path('/etc/systemd/system/fuc-xb-node.service.d').mkdir(parents=True)
|
||||
self.commands.clear()
|
||||
with self.assertRaises(AssertionError):
|
||||
self.host.resume(self.context)
|
||||
self.assertFalse(any(a[:2] == ['systemctl', 'enable'] for a in self.commands))
|
||||
|
||||
|
||||
class RefreshTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = pathlib.Path(self.temp.name)
|
||||
self.refresh = load('certificate-refresh.py')
|
||||
self.refresh.STATE = self.root
|
||||
self.old = 'SHA256 Fingerprint=' + '00' * 32
|
||||
self.new = 'SHA256 Fingerprint=' + hashlib.sha256(b'new leaf').hexdigest()
|
||||
self.state = {'owner': 'fuc-xb-launch-20261105', 'certificate_fingerprint': self.old,
|
||||
'node': {'certificate': '/synthetic/cert', 'private_key': '/synthetic/key', 'sni': 'offline.invalid'}}
|
||||
(self.root / 'owner.json').write_text(json.dumps(self.state))
|
||||
self.refresh.open = lambda path, *a, **kw: builtins.open(self.root / 'lock', *a, **kw)
|
||||
self.refresh.fcntl = types.SimpleNamespace(flock=Mock(), LOCK_EX=2, LOCK_NB=4)
|
||||
self.refresh.os = types.SimpleNamespace(umask=lambda _: None)
|
||||
self.refresh.time = types.SimpleNamespace(sleep=lambda _: None)
|
||||
self.commands = []
|
||||
self.bad_key = False
|
||||
self.listener = True
|
||||
self.refresh.run = self.command_run
|
||||
|
||||
def command_run(self, args):
|
||||
self.commands.append(args)
|
||||
if args[0] == 'openssl':
|
||||
if '-pubkey' in args:
|
||||
return 'PUBLIC'
|
||||
if '-pubout' in args:
|
||||
return 'WRONG' if self.bad_key else 'PUBLIC'
|
||||
if '-fingerprint' in args:
|
||||
return self.new
|
||||
return ''
|
||||
if args[:2] == ['systemctl', 'is-active']:
|
||||
return 'active'
|
||||
if args[:2] == ['systemctl', 'show']:
|
||||
return '444'
|
||||
if args[0] == 'ss':
|
||||
return 'LISTEN pid=444,' if self.listener else ''
|
||||
return ''
|
||||
|
||||
def fingerprint(self):
|
||||
return json.loads((self.root / 'owner.json').read_text())['certificate_fingerprint']
|
||||
|
||||
def test_wrong_key_does_not_restart_or_advance(self):
|
||||
self.bad_key = True
|
||||
with self.assertRaises(AssertionError):
|
||||
self.refresh.main()
|
||||
self.assertEqual(self.fingerprint(), self.old)
|
||||
self.assertNotIn(['systemctl', 'restart', 'fuc-xb-node'], self.commands)
|
||||
|
||||
def test_no_listener_does_not_advance(self):
|
||||
self.listener = False
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.refresh.main()
|
||||
self.assertEqual(self.fingerprint(), self.old)
|
||||
|
||||
def test_lock_contention_returns_without_commands(self):
|
||||
self.refresh.fcntl.flock.side_effect = BlockingIOError
|
||||
self.refresh.main()
|
||||
self.assertEqual(self.commands, [])
|
||||
self.assertEqual(self.fingerprint(), self.old)
|
||||
|
||||
def test_tls_wrong_certificate_does_not_advance(self):
|
||||
raw = Mock()
|
||||
raw.__enter__ = Mock(return_value=raw)
|
||||
raw.__exit__ = Mock(return_value=False)
|
||||
tls = Mock()
|
||||
tls.__enter__ = Mock(return_value=tls)
|
||||
tls.__exit__ = Mock(return_value=False)
|
||||
tls.getpeercert.return_value = b'wrong leaf'
|
||||
self.refresh.socket = types.SimpleNamespace(create_connection=Mock(return_value=raw))
|
||||
self.refresh.ssl = types.SimpleNamespace(create_default_context=Mock(return_value=types.SimpleNamespace(wrap_socket=Mock(return_value=tls))))
|
||||
with self.assertRaises(AssertionError):
|
||||
self.refresh.main()
|
||||
self.assertEqual(self.fingerprint(), self.old)
|
||||
|
||||
def test_success_advances_only_after_verified_tls(self):
|
||||
raw = Mock()
|
||||
raw.__enter__ = Mock(return_value=raw)
|
||||
raw.__exit__ = Mock(return_value=False)
|
||||
tls = Mock()
|
||||
tls.__enter__ = Mock(return_value=tls)
|
||||
tls.__exit__ = Mock(return_value=False)
|
||||
tls.getpeercert.return_value = b'new leaf'
|
||||
self.refresh.socket = types.SimpleNamespace(create_connection=Mock(return_value=raw))
|
||||
context = types.SimpleNamespace(wrap_socket=Mock(return_value=tls))
|
||||
self.refresh.ssl = types.SimpleNamespace(create_default_context=Mock(return_value=context))
|
||||
self.refresh.main()
|
||||
self.assertEqual(self.fingerprint(), self.new)
|
||||
context.wrap_socket.assert_called_once_with(raw, server_hostname='offline.invalid')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline relay lifecycle/fault tests. All API responses and writes are local."""
|
||||
import copy
|
||||
import json
|
||||
import pathlib
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
|
||||
HERE = pathlib.Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def load_relay():
|
||||
module = types.ModuleType('fuc_relay_offline_test')
|
||||
source = HERE / 'relay.py'
|
||||
exec(compile(source.read_text(), str(source), 'exec'), module.__dict__)
|
||||
return module
|
||||
|
||||
|
||||
def row(identity, name, port, target):
|
||||
return dict(id=identity, name=name, tunnelId=48, inPort=port,
|
||||
inIp='relay.invalid:' + str(port), remoteAddr=target,
|
||||
strategy='fifo', speedId=None, ipMaxConn=0, ipSpeedId=None,
|
||||
maxConn=0, proxyProtocol=0, proxyProtocolReceive=0,
|
||||
proxyProtocolSend=0, status=1, userId=49)
|
||||
|
||||
|
||||
class RelayTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.module = load_relay()
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = pathlib.Path(self.temp.name)
|
||||
self.baseline = [row(1, 'old-us', 46101, '198.51.100.1:443'),
|
||||
row(2, 'old-jp', 46202, '198.51.100.2:443')]
|
||||
self.rows = copy.deepcopy(self.baseline)
|
||||
self.rules = [dict(name='fuc-xb-us-anytls', port=48101, address='198.51.100.1', listen_port=24445, old_port=46101),
|
||||
dict(name='fuc-xb-jp-anytls', port=48202, address='198.51.100.2', listen_port=24445, old_port=46202)]
|
||||
self.request = dict(batch_id='fuc-xb-launch-offline',
|
||||
backup_root='/root/codex-backups/fuc-xb/fuc-xb-launch-offline/relay',
|
||||
relay_host='relay.invalid', tunnel_id=48, expected_user_id=49,
|
||||
expected_before_count=2, expected_before_sha256=self.module.digest(self.baseline),
|
||||
rules=self.rules)
|
||||
self.creates = []
|
||||
self.pauses = []
|
||||
self.failure = None
|
||||
self.batch = self.module.RelayBatch(self.request, self.api, self.root)
|
||||
|
||||
def api(self, path, payload):
|
||||
if path == '/forward/list':
|
||||
return {'code': 0, 'data': copy.deepcopy(self.rows)}
|
||||
if path == '/forward/pause':
|
||||
self.pauses.append(payload['id'])
|
||||
matches = [r for r in self.rows if r['id'] == payload['id']]
|
||||
self.assertEqual(len(matches), 1)
|
||||
matches[0]['status'] = 0
|
||||
return {'code': 0}
|
||||
self.assertEqual(path, '/forward/create')
|
||||
self.creates.append(copy.deepcopy(payload))
|
||||
if self.failure == 'before-create':
|
||||
raise TimeoutError('synthetic unknown create outcome')
|
||||
self.rows.append(row(100 + len(self.creates), payload['name'], payload['inPort'], payload['remoteAddr']))
|
||||
if self.failure == 'after-create':
|
||||
raise TimeoutError('synthetic lost create response')
|
||||
if self.failure == 'old-drift-after-create':
|
||||
self.rows[0]['remoteAddr'] = '203.0.113.99:443'
|
||||
return {'code': 0}
|
||||
|
||||
def journal(self, **changes):
|
||||
value = dict(version=1, request=self.request, request_sha256=self.module.digest(self.request),
|
||||
before=copy.deepcopy(self.baseline), intents={}, added={})
|
||||
value.update(changes)
|
||||
self.module.atomic(self.root / 'journal.json', value)
|
||||
return value
|
||||
|
||||
def test_probe_is_read_only_and_checks_frozen_inventory(self):
|
||||
result = self.batch.run(False)
|
||||
self.assertEqual(result['state'], 'absent')
|
||||
self.assertFalse(result['writes'])
|
||||
self.assertEqual(self.creates, [])
|
||||
self.assertFalse((self.root / 'journal.json').exists())
|
||||
|
||||
def test_normal_append_preserves_originals_and_resume_does_not_duplicate(self):
|
||||
result = self.batch.run(True)
|
||||
self.assertEqual(result['state'], 'applied')
|
||||
self.assertTrue(result['old_rules_unchanged'])
|
||||
self.assertEqual(self.rows[:2], self.baseline)
|
||||
self.assertEqual(len(self.creates), 2)
|
||||
self.assertEqual(self.batch.run(True)['state'], 'applied')
|
||||
self.assertEqual(len(self.creates), 2)
|
||||
self.assertEqual(self.batch.run(False)['state'], 'ready')
|
||||
saved = json.loads((self.root / 'journal.json').read_text())
|
||||
self.assertEqual(saved['before'], self.baseline)
|
||||
self.assertEqual((self.root / 'journal.json').stat().st_mode & 0o777, 0o600)
|
||||
|
||||
def test_same_count_old_row_drift_blocks_probe_and_apply(self):
|
||||
self.rows[0]['status'] = 0
|
||||
for apply in (False, True):
|
||||
with self.subTest(apply=apply), self.assertRaisesRegex(self.module.Blocked, 'frozen_original_inventory_changed'):
|
||||
self.batch.run(apply)
|
||||
self.assertEqual(self.creates, [])
|
||||
self.assertFalse((self.root / 'journal.json').exists())
|
||||
|
||||
def test_candidate_name_port_or_target_conflict_blocks_without_write(self):
|
||||
for field, value in [('name', self.rules[0]['name']), ('inPort', self.rules[0]['port']),
|
||||
('remoteAddr', '198.51.100.1:24445')]:
|
||||
with self.subTest(field=field):
|
||||
self.rows = copy.deepcopy(self.baseline)
|
||||
self.rows[0][field] = value
|
||||
self.request['expected_before_sha256'] = self.module.digest(self.rows)
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'candidate_rule_conflict'):
|
||||
self.batch.run(True)
|
||||
self.assertEqual(self.creates, [])
|
||||
|
||||
def test_unknown_absent_intent_blocks_probe_and_apply(self):
|
||||
self.journal(intents={self.rules[0]['name']: {'attempt': 1, 'at': 1, 'payload': self.rules[0]}})
|
||||
for apply in (False, True):
|
||||
with self.subTest(apply=apply), self.assertRaisesRegex(self.module.Blocked, 'unknown_create_outcome_requires_explicit_review'):
|
||||
self.batch.run(apply)
|
||||
self.assertEqual(self.creates, [])
|
||||
|
||||
def test_timeout_before_create_is_never_replayed(self):
|
||||
self.failure = 'before-create'
|
||||
with self.assertRaises(TimeoutError):
|
||||
self.batch.run(True)
|
||||
self.failure = None
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'unknown_create_outcome_requires_explicit_review'):
|
||||
self.batch.run(True)
|
||||
self.assertEqual(len(self.creates), 1)
|
||||
self.assertEqual(self.rows, self.baseline)
|
||||
|
||||
def test_lost_response_after_create_is_reconciled_without_duplicate(self):
|
||||
self.failure = 'after-create'
|
||||
with self.assertRaises(TimeoutError):
|
||||
self.batch.run(True)
|
||||
self.failure = None
|
||||
self.assertEqual(self.batch.run(True)['state'], 'applied')
|
||||
self.assertEqual(len(self.creates), 2)
|
||||
self.assertEqual(len(self.rows), 4)
|
||||
|
||||
def test_journal_baseline_same_count_corruption_blocks(self):
|
||||
corrupt = copy.deepcopy(self.baseline)
|
||||
corrupt[0]['proxyProtocolSend'] = 1
|
||||
self.journal(before=corrupt)
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'frozen_journal_baseline_changed'):
|
||||
self.batch.run(True)
|
||||
self.assertEqual(self.creates, [])
|
||||
|
||||
def test_journal_baseline_count_corruption_blocks(self):
|
||||
self.journal(before=self.baseline[:1])
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'frozen_journal_baseline_changed'):
|
||||
self.batch.run(True)
|
||||
self.assertEqual(self.creates, [])
|
||||
|
||||
def test_matching_rule_without_ownership_intent_is_not_adopted(self):
|
||||
self.journal()
|
||||
self.rows.append(row(90, self.rules[0]['name'], self.rules[0]['port'], '198.51.100.1:24445'))
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'matching_rule_without_task_intent'):
|
||||
self.batch.run(True)
|
||||
self.assertEqual(self.creates, [])
|
||||
|
||||
def test_old_row_drift_after_creation_blocks_remaining_candidates(self):
|
||||
self.failure = 'old-drift-after-create'
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'original_rule_inventory_changed'):
|
||||
self.batch.run(True)
|
||||
self.assertEqual(len(self.creates), 1)
|
||||
saved = json.loads((self.root / 'journal.json').read_text())
|
||||
self.assertEqual(saved['before'], self.baseline)
|
||||
self.assertNotEqual(saved.get('state'), 'applied')
|
||||
|
||||
def test_invalid_frozen_digest_rejected_before_api(self):
|
||||
self.request['expected_before_sha256'] = 'not-a-digest'
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'frozen_inventory_digest_required'):
|
||||
self.module.RelayBatch(self.request, self.api, self.root)
|
||||
self.assertEqual(self.creates, [])
|
||||
|
||||
def test_pause_changes_only_owned_ids_and_preserves_originals(self):
|
||||
applied = self.batch.run(True)
|
||||
owned = {r['id'] for r in applied['new']}
|
||||
result = self.batch.pause_owned()
|
||||
self.assertEqual(result['state'], 'paused')
|
||||
self.assertEqual(set(self.pauses), owned)
|
||||
self.assertEqual(self.rows[:2], self.baseline)
|
||||
self.assertTrue(all(r['status'] == 0 for r in self.rows if r['id'] in owned))
|
||||
self.assertEqual(result['owned_ids'], sorted(owned))
|
||||
|
||||
def test_repeated_pause_does_not_repeat_api_mutations(self):
|
||||
self.batch.run(True)
|
||||
self.batch.pause_owned()
|
||||
calls = list(self.pauses)
|
||||
self.assertEqual(self.batch.pause_owned()['state'], 'paused')
|
||||
self.assertEqual(self.pauses, calls)
|
||||
self.assertEqual(len(self.creates), 2)
|
||||
|
||||
def test_pause_rejects_owned_field_drift_before_mutation(self):
|
||||
self.batch.run(True)
|
||||
self.rows[2]['remoteAddr'] = '203.0.113.99:24445'
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'owned_rule_changed'):
|
||||
self.batch.pause_owned()
|
||||
self.assertEqual(self.pauses, [])
|
||||
self.assertEqual(self.rows[:2], self.baseline)
|
||||
|
||||
def test_pause_rejects_original_field_drift_before_mutation(self):
|
||||
self.batch.run(True)
|
||||
self.rows[0]['proxyProtocolSend'] = 1
|
||||
with self.assertRaisesRegex(self.module.Blocked, 'original_rule_inventory_changed'):
|
||||
self.batch.pause_owned()
|
||||
self.assertEqual(self.pauses, [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,7 @@
|
||||
# FUC-XB 2026-11-05隔离刷新
|
||||
|
||||
仅适用用户明确授权的旧FUC→现有独立测试站重新迁移;源正式站只读、不切正式、不改DPL/HN。project.py只消费同宿主private一致性快照,动态计算人数、权益、完整预购退款及VIP期初,不使用旧11542人/13笔常数。refresh.php只允许fuc_xb_test,要求精确投影SHA、完整备份和恢复核验;拒绝目标存在真实订单、节点、会话或非期初VIP。一次事务替换用户/历史套餐/组和期初,全字段及资金回读通过再提交;保留原合成QA认证,ID按新数据最大值调整,旧账不进入新业务订单。
|
||||
|
||||
程序文件不包含凭据/用户行,运行私有数据不提交Git。失败先查refresh-intent及数据库实际状态,不删除日志盲重跑。数据库提交与私有QA文件更新为两阶段;未知状态按备份/日志恢复,不能再次给钱包返款。测试节点按Xboard-Node和原生V2机器接口验收,不沿用旧XrayR。
|
||||
|
||||
本轮已完成原生V2机器接口与AnyTLS独立节点实测,禁用/过期/耗尽后三类保存配置均拒绝。耗尽账号的订阅200可刷新是XB原生设计,实际联网必须拒绝;不为测试改核心。客户端本地SOCKS空闲检查采用ss监听,不把TIME_WAIT当监听。最终三种节点QA及机器/组/节点、复制的机器令牌/Cookie均清理,原合成网页QA仍保留。当前完整证据见[验收报告](../../docs/maintenance/FUC_XB_V2_REACCEPTANCE.md)。
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real native subscription import and SOCKS traffic; no local desktop/TUN changes."""
|
||||
import argparse,copy,gzip,hashlib,json,os,pathlib,socket,ssl,subprocess,time,urllib.error,urllib.parse,urllib.request
|
||||
DIR=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/refresh-20261105/client')
|
||||
BIN=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104/bin/sing-box')
|
||||
SHA='768d31fa7f68debc067bb4626539498a1e8751d36a7b99e1a54bee6a23815f93'
|
||||
PANEL=str(pathlib.Path(__file__).with_name('node-panel.php'))
|
||||
def run(a,timeout=30):return subprocess.run(a,capture_output=True,timeout=timeout)
|
||||
def context():
|
||||
p=run(['php',PANEL,'export']);assert p.returncode==0
|
||||
return json.loads(p.stdout)
|
||||
def redact(s,c):
|
||||
for k in ['machine_token','gate_cookie','subscribe_token','qa_uuid']:s=s.replace(str(c[k]),'<redacted>')
|
||||
return s[:1200]
|
||||
def fetch(c,flag,token=None):
|
||||
url=c['alias']+'/api/v1/client/subscribe?'+urllib.parse.urlencode({'token':token if token is not None else c['subscribe_token'],'flag':flag})
|
||||
r=urllib.request.Request(url,headers={'Cookie':'fuc_stage_access='+c['gate_cookie'],'User-Agent':'sing-box/1.14.3' if flag=='sing-box' else 'clash.meta/1.19.0'})
|
||||
try:
|
||||
with urllib.request.urlopen(r,timeout=25)as o:
|
||||
b=o.read(4194304);h=o.headers
|
||||
if h.get('Content-Encoding')=='gzip':b=gzip.decompress(b)
|
||||
return o.status,b
|
||||
except urllib.error.HTTPError as e:return e.code,e.read(1024)
|
||||
def prepare(c):
|
||||
assert hashlib.sha256(BIN.read_bytes()).hexdigest()==SHA,'Client artifact changed'
|
||||
status,raw=fetch(c,'sing-box');assert status==200,'Native subscription request failed'
|
||||
cfg=json.loads(raw);nodes=[o for o in cfg['outbounds'] if o.get('type')=='anytls']
|
||||
assert len(nodes)==1,'Expected exact QA-only AnyTLS subscription'
|
||||
n=nodes[0];assert n['server']==c['expected_exit'] and n['server_port']==c['port'] and n['password']==c['qa_uuid'],'Native subscription identity mismatch'
|
||||
assert n['tls']['enabled'] and n['tls'].get('insecure') is False and n['tls']['server_name']==c['sni'],'Strict subscription TLS mismatch'
|
||||
(DIR/'subscription-singbox.json').write_bytes(raw)
|
||||
status,clash=fetch(c,'meta');assert status==200 and b'anytls' in clash and c['qa_uuid'].encode() in clash,'Native Clash subscription missing QA node'
|
||||
(DIR/'subscription-clash.yaml').write_bytes(clash)
|
||||
assert fetch(c,'sing-box','invalid-qa-token')[0]==403,'Invalid subscription token accepted'
|
||||
cfg['inbounds']=[{'type':'mixed','tag':'qa-local','listen':'127.0.0.1','listen_port':19876}]
|
||||
(DIR/'client-full.json').write_text(json.dumps(cfg))
|
||||
check=run([str(BIN),'check','-c',str(DIR/'client-full.json')])
|
||||
result={'native_subscription_downloaded':True,'exact_qa_node_and_uuid':True,'strict_tls_in_subscription':True,'invalid_token_rejected':True,'clash_native_format_present':True,'only_inbounds_replaced':True,'native_full_config_check_passed':check.returncode==0}
|
||||
if check.returncode:result['check_error']=redact(check.stderr.decode(errors='replace'),c)
|
||||
(DIR/'client-prepare-result.json').write_text(json.dumps(result,indent=2))
|
||||
return result,cfg
|
||||
def saved_rejection(c):
|
||||
assert (DIR/'client-full.json').exists(),'No saved positive client configuration'
|
||||
ctx=ssl.create_default_context();result={}
|
||||
def alive():
|
||||
with socket.create_connection((c['expected_exit'],c['port']),timeout=8)as raw:
|
||||
with ctx.wrap_socket(raw,server_hostname=c['sni'])as tls:return tls.version()
|
||||
result['node_tls_before']=alive()
|
||||
cmd=['systemd-run','--quiet','--collect','--unit=fuc-xb-qa-client','--property=RuntimeMaxSec=90','--property=MemoryMax=384M','--working-directory='+str(DIR),str(BIN),'run','-D',str(DIR),'-c',str(DIR/'client-full.json')]
|
||||
assert run(cmd).returncode==0,'Saved client unit failed'
|
||||
try:
|
||||
ready=False
|
||||
for _ in range(50):
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1',19876),timeout=.2):ready=True;break
|
||||
except OSError:time.sleep(.2)
|
||||
assert ready,'Saved client failed to start'
|
||||
p=run(['curl','-sS','--proxy','socks5h://127.0.0.1:19876','--connect-timeout','5','--max-time','12','https://api.ipify.org?format=json'],timeout=20)
|
||||
result['saved_config_rejected']=p.returncode!=0 and not p.stdout
|
||||
result['node_tls_after']=alive();assert result['saved_config_rejected'],'Revoked credential still connects'
|
||||
finally:
|
||||
run(['systemctl','stop','fuc-xb-qa-client']);result['temporary_client_stopped']=True
|
||||
(DIR/('revocation-'+c['phase']+'.json')).write_text(json.dumps(result,indent=2))
|
||||
return result
|
||||
def main():
|
||||
os.umask(0o077);DIR.mkdir(mode=0o700,parents=True,exist_ok=True);p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','run','revoked']);args=p.parse_args();c=context()
|
||||
if args.action=='revoked':
|
||||
status,_=fetch(c,'sing-box');assert status==(200 if c['phase']=='exhausted' else 403),'Unexpected native subscription status';result=saved_rejection(c);result.update(native_subscription_status=status,phase=c['phase']);print(json.dumps(result));return
|
||||
result,cfg=prepare(c)
|
||||
if args.action=='prepare' or not result['native_full_config_check_passed']:print(json.dumps(result));return
|
||||
assert c['expected_exit']=='193.111.31.52'
|
||||
# A positive TLS handshake is independently verified before starting the application client.
|
||||
ctx=ssl.create_default_context()
|
||||
with socket.create_connection((c['expected_exit'],c['port']),timeout=8)as raw:
|
||||
with ctx.wrap_socket(raw,server_hostname=c['sni'])as tls:result['node_certificate_verified']=True;result['node_tls_version']=tls.version()
|
||||
check_port=run(['ss','-H','-ltn','sport = :19876'])
|
||||
assert check_port.returncode==0 and not check_port.stdout.strip(),'QA SOCKS listener already exists'
|
||||
cmd=['systemd-run','--quiet','--collect','--unit=fuc-xb-qa-client','--property=RuntimeMaxSec=600','--property=MemoryMax=384M','--property=CPUQuota=30%','--working-directory='+str(DIR),str(BIN),'run','-D',str(DIR),'-c',str(DIR/'client-full.json')]
|
||||
started=run(cmd);assert started.returncode==0,'QA client unit failed'
|
||||
try:
|
||||
ready=False
|
||||
for _ in range(50):
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1',19876),timeout=.2):ready=True;break
|
||||
except OSError:time.sleep(.2)
|
||||
if not ready:
|
||||
log=run(['journalctl','-u','fuc-xb-qa-client','-n','8','--no-pager'])
|
||||
result['client_start_error']=redact(log.stdout.decode(errors='replace'),c)
|
||||
raise RuntimeError('Native full client did not start')
|
||||
base=['curl','-sS','--proxy','socks5h://127.0.0.1:19876','--connect-timeout','8','--max-time','25']
|
||||
ip=run(base+['https://api.ipify.org?format=json'],timeout=30)
|
||||
assert ip.returncode==0 and json.loads(ip.stdout)['ip']==c['expected_exit'],'Wrong real proxy exit'
|
||||
result['actual_proxy_exit_matches']=True;result['expected_exit']=c['expected_exit']
|
||||
down=run(base+['https://speed.cloudflare.com/__down?bytes=65536'],timeout=30)
|
||||
assert down.returncode==0 and len(down.stdout)==65536,'Real download payload mismatch'
|
||||
result['download_payload_bytes']=len(down.stdout)
|
||||
(DIR/'upload-qa.bin').write_bytes(b'FUC-XB-QA-ONLY\n'*2048)
|
||||
up=run(base+['-H','Content-Type: application/octet-stream','--data-binary','@'+str(DIR/'upload-qa.bin'),'https://httpbin.org/post'],timeout=30)
|
||||
assert up.returncode==0 and len(json.loads(up.stdout).get('data',''))==len((DIR/'upload-qa.bin').read_bytes()),'Real upload echo mismatch'
|
||||
result['upload_payload_bytes']=len((DIR/'upload-qa.bin').read_bytes())
|
||||
result['real_client_network_passed']=True
|
||||
finally:
|
||||
run(['systemctl','stop','fuc-xb-qa-client'])
|
||||
result['temporary_client_stopped']=True
|
||||
(DIR/'client-run-result.json').write_text(json.dumps(result,indent=2))
|
||||
print(json.dumps(result))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Loopback staging gate transport; retains native V2 machine-token authentication."""
|
||||
import http.server,json,pathlib,ssl,threading,urllib.request,urllib.error,urllib.parse
|
||||
DIR=pathlib.Path('/var/www/wwwroot/fuc-xb-acceptance/private/v2-20261105')
|
||||
ALLOWED={'/api/v2/server/'+x for x in ['handshake','config','user','report','push','alive','alivelist','status','machine/nodes','machine/status']}
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self,*a,**kw):return None
|
||||
def allowed(method,path,payload,content_type,cfg):
|
||||
p=urllib.parse.urlsplit(path)
|
||||
if p.scheme or p.netloc or p.path not in ALLOWED or method not in ['GET','POST']:return False
|
||||
try:
|
||||
q=urllib.parse.parse_qs(p.query,keep_blank_values=True)
|
||||
body=json.loads(payload)if payload and content_type.startswith('application/json')else urllib.parse.parse_qs(payload.decode())if payload else{}
|
||||
def value(key):
|
||||
vals=[]
|
||||
for d in [q,body]:
|
||||
if key in d:vals+=d[key]if isinstance(d[key],list)else[d[key]]
|
||||
return [str(x)for x in vals]
|
||||
if value('machine_id')!=[str(cfg['machine_id'])]or value('token')!=[cfg['machine_token']]:return False
|
||||
node=value('node_id')
|
||||
return node==[str(cfg['node_id'])]or(not node and p.path in ['/api/v2/server/handshake','/api/v2/server/machine/nodes','/api/v2/server/machine/status'])
|
||||
except(ValueError,TypeError,UnicodeError):return False
|
||||
def main():
|
||||
cfg=json.loads((DIR/'context.json').read_text());assert cfg['source']=='https://fuc-xb-test.gemcook.net'
|
||||
op=urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl.create_default_context()),NoRedirect());metrics={'requests':{},'user_counts':[]};lock=threading.Lock()
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self,*a):pass
|
||||
def do_GET(self):self.forward()
|
||||
def do_POST(self):self.forward()
|
||||
def forward(self):
|
||||
length=int(self.headers.get('Content-Length','0'))
|
||||
if self.client_address[0]!='127.0.0.1'or length<0 or length>2097152:self.send_error(403);return
|
||||
b=self.rfile.read(length)if length else b'';content=self.headers.get('Content-Type','')
|
||||
if not allowed(self.command,self.path,b,content,cfg):
|
||||
with lock:metrics['scope_rejections']=metrics.get('scope_rejections',0)+1;(DIR/'bridge-metrics.json').write_text(json.dumps(metrics))
|
||||
self.send_error(403);return
|
||||
headers={'Cookie':'fuc_stage_access='+cfg['gate_cookie'],'Accept':'application/json'}
|
||||
if content:headers['Content-Type']=content
|
||||
if self.headers.get('If-None-Match'):headers['If-None-Match']=self.headers['If-None-Match']
|
||||
try:
|
||||
req=urllib.request.Request(cfg['source']+self.path,data=b if self.command=='POST'else None,headers=headers,method=self.command)
|
||||
try:res=op.open(req,timeout=15)
|
||||
except urllib.error.HTTPError as e:res=e
|
||||
with res:status=res.status;body=res.read(2097153);rh=res.headers
|
||||
if len(body)>2097152:raise ValueError('Oversized response')
|
||||
path=urllib.parse.urlsplit(self.path).path
|
||||
with lock:
|
||||
key=path+':'+str(status);metrics['requests'][key]=metrics['requests'].get(key,0)+1
|
||||
if path.endswith('/user')and status==200:metrics['user_counts']=(metrics['user_counts']+[len(json.loads(body)['users'])])[-20:]
|
||||
(DIR/'bridge-metrics.json').write_text(json.dumps(metrics))
|
||||
self.send_response(status)
|
||||
for k in ['Content-Type','ETag']:
|
||||
if rh.get(k):self.send_header(k,rh[k])
|
||||
self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
|
||||
except Exception:self.send_response(502);self.send_header('Content-Length','0');self.end_headers()
|
||||
http.server.ThreadingHTTPServer(('127.0.0.1',28766),H).serve_forever()
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib,subprocess,json,os,hashlib,time,argparse
|
||||
BASE=pathlib.Path('/var/www/wwwroot/fuc-xb-acceptance');DIR=BASE/'private/v2-20261105';BIN='/opt/dpl-node/xboard-node'
|
||||
SHA='55bf71fa9d9f2048d3255ae7c0af929a41897ca7743f6ead34132a6ca4c79043'
|
||||
def run(a):
|
||||
p=subprocess.run(a,capture_output=True,text=True,timeout=40);assert p.returncode==0,'QA command failed';return p.stdout.strip()
|
||||
def free(port):return not run(['ss','-H','-ltn','sport = :'+str(port)])
|
||||
def baseline():
|
||||
return {'dpl_pid':run(['systemctl','show','dpl-node','-p','MainPID','--value']),'xrayr_pid':run(['systemctl','show','XrayR','-p','MainPID','--value']),'binary_sha256':hashlib.sha256(pathlib.Path(BIN).read_bytes()).hexdigest(),'unit_sha256':hashlib.sha256(run(['systemctl','cat','dpl-node']).encode()).hexdigest()}
|
||||
def main():
|
||||
os.umask(0o077);p=argparse.ArgumentParser();p.add_argument('action',choices=['start','status','stop']);args=p.parse_args();DIR.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
if args.action=='start':
|
||||
assert free(25443)and free(28766);assert not(DIR/'before.json').exists(),'Already started; inspect before retry'
|
||||
before=baseline();assert before['binary_sha256']==SHA and before['dpl_pid']=='110612'and before['xrayr_pid']=='107692';(DIR/'before.json').write_text(json.dumps(before))
|
||||
c=json.loads((DIR/'context.json').read_text());assert c['expected_exit']=='193.111.31.52'and c['port']==25443
|
||||
cfg={'panel':{'url':'http://127.0.0.1:28766'},'machine':{'machine_id':c['machine_id'],'token_env':'FUC_XB_TEST_MACHINE_TOKEN'},'kernel':{'type':'singbox','config_dir':str(DIR/'kernel')},'log':{'level':'info'},'runtime':{'gomemlimit':'256MiB','gogc':75},'node':{'push_interval':5,'pull_interval':5}}
|
||||
(DIR/'config.json').write_text(json.dumps(cfg));(DIR/'node-secret.env').write_text('FUC_XB_TEST_MACHINE_TOKEN='+c['machine_token']+'\n')
|
||||
run(['systemd-run','--quiet','--collect','--unit=fuc-xb-v2-qa-api','--property=RuntimeMaxSec=1800','--property=MemoryMax=96M','/usr/bin/python3',str(pathlib.Path(__file__).with_name('node-bridge.py'))])
|
||||
for _ in range(30):
|
||||
if not free(28766):break
|
||||
time.sleep(.2)
|
||||
assert not free(28766)
|
||||
run(['systemd-run','--quiet','--collect','--unit=fuc-xb-v2-qa-node','--property=RuntimeMaxSec=1800','--property=MemoryMax=384M','--property=CPUQuota=30%','--property=EnvironmentFile='+str(DIR/'node-secret.env'),'--working-directory='+str(DIR),BIN,'-c',str(DIR/'config.json')])
|
||||
print(json.dumps({'started':True,'program':'Xboard-Node','native_v2_machine_interface':True,'binary_matches_dpl_hn':True,'original_unchanged':baseline()==before}))
|
||||
elif args.action=='status':
|
||||
before=json.loads((DIR/'before.json').read_text());print(json.dumps({'node_active':run(['systemctl','show','fuc-xb-v2-qa-node','-p','ActiveState','--value']),'api_active':run(['systemctl','show','fuc-xb-v2-qa-api','-p','ActiveState','--value']),'node_listening':not free(25443),'metrics':json.loads((DIR/'bridge-metrics.json').read_text())if(DIR/'bridge-metrics.json').exists()else{},'original_unchanged':before==baseline()}))
|
||||
else:
|
||||
for unit in ['fuc-xb-v2-qa-node','fuc-xb-v2-qa-api']:subprocess.run(['systemctl','stop',unit],capture_output=True,timeout=40)
|
||||
assert free(25443)and free(28766);before=json.loads((DIR/'before.json').read_text());assert before==baseline()
|
||||
for name in ['context.json','node-secret.env','config.json']:(DIR/name).unlink(missing_ok=True)
|
||||
# Generated kernel configs contain only synthetic QA credentials; remove them as well.
|
||||
import shutil
|
||||
shutil.rmtree(DIR/'kernel',ignore_errors=True)
|
||||
print(json.dumps({'stopped':True,'temporary_listeners_absent':True,'copied_credentials_removed':True,'original_unchanged':True}))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';$dir='/var/www/wwwroot/fuc-xb-test/private/refresh-20261105';$stateFile=$dir.'/node-v2-state.json';
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';require $root.'/vendor/autoload.php';$a=require $root.'/bootstrap/app.php';$a->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\{DB,Cache};use App\Models\{User,Server,ServerMachine,ServerGroup};
|
||||
if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
|
||||
$action=$argv[1]??'';
|
||||
function qaV2($group,$phase):User{return User::create(['email'=>'qa-v2-'.$phase.'[email protected]','password'=>password_hash(bin2hex(random_bytes(20)),PASSWORD_BCRYPT),'uuid'=>(string)Illuminate\Support\Str::uuid(),'token'=>bin2hex(random_bytes(16)),'group_id'=>$group,'transfer_enable'=>104857600,'expired_at'=>time()+3600,'banned'=>0,'balance'=>0,'u'=>0,'d'=>0,'device_limit'=>1,'speed_limit'=>10,'remind_expire'=>0,'remind_traffic'=>0]);}
|
||||
if($action==='setup'){
|
||||
if(file_exists($stateFile)||Server::count()||ServerMachine::count())throw new RuntimeException('Fixture collision');
|
||||
$before=['users'=>User::count(),'groups'=>ServerGroup::count(),'nodes'=>Server::count(),'machines'=>ServerMachine::count(),'wallet'=>(int)User::sum('balance')];
|
||||
$state=['before'=>$before,'settings'=>DB::table('v2_settings')->whereIn('name',['server_push_interval','server_pull_interval'])->get()->map(fn($x)=>(array)$x)->all(),'users'=>[]];
|
||||
DB::transaction(function()use(&$state,$stateFile){
|
||||
$g=new ServerGroup();$g->name='FUC-XB V2 QA 20261105';$g->save();$m=ServerMachine::create(['name'=>'fuc-xb-v2-qa-20261105','token'=>ServerMachine::generateToken(),'is_active'=>true,'notes'=>'Isolated QA only; no production users']);
|
||||
$n=Server::create(['name'=>'FUC-XB V2 QA JP02 (temporary)','type'=>'anytls','host'=>'193.111.31.52','port'=>'25443','server_port'=>'25443','group_ids'=>[(string)$g->id],'route_ids'=>[],'tags'=>[],'rate'=>1,'show'=>true,'enabled'=>true,'machine_id'=>$m->id,'sort'=>9999,'protocol_settings'=>['tls'=>['server_name'=>'jp02.gembox-dns.com','allow_insecure'=>false]],'cert_config'=>['cert_mode'=>'file','domain'=>'jp02.gembox-dns.com','cert_file'=>'/etc/letsencrypt/live/jp02.gembox-dns.com/fullchain.pem','key_file'=>'/etc/letsencrypt/live/jp02.gembox-dns.com/privkey.pem']]);
|
||||
$u=qaV2($g->id,'banned');$state+=['group_id'=>$g->id,'machine_id'=>$m->id,'node_id'=>$n->id,'current_user_id'=>$u->id,'phase'=>'banned'];$state['users'][]=$u->id;
|
||||
app(App\Support\Setting::class)->save(['server_pull_interval'=>5,'server_push_interval'=>5]);file_put_contents($stateFile,json_encode($state));
|
||||
});
|
||||
echo json_encode(['isolated_setup'=>true,'native_interface'=>'api/v2/server','machine_auth'=>true,'node_type'=>'anytls','production_users_on_node'=>0]).PHP_EOL;exit;
|
||||
}
|
||||
$s=json_decode(file_get_contents($stateFile),true,512,JSON_THROW_ON_ERROR);$n=Server::findOrFail($s['node_id']);$m=ServerMachine::findOrFail($s['machine_id']);$u=User::findOrFail($s['current_user_id']);
|
||||
if($n->name!=='FUC-XB V2 QA JP02 (temporary)'||$m->name!=='fuc-xb-v2-qa-20261105')throw new RuntimeException('Fixture identity changed');
|
||||
if($action==='probe'){echo json_encode(['phase'=>$s['phase'],'available_users'=>App\Services\ServerService::getAvailableUsers($n)->count(),'qa_upload'=>$u->u,'qa_download'=>$u->d,'node_upload'=>$n->u,'node_download'=>$n->d,'last_check_at'=>$n->last_check_at,'last_push_at'=>$n->last_push_at,'machine_last_seen'=>$m->last_seen_at,'online'=>$n->online]).PHP_EOL;exit;}
|
||||
if($action==='revoke'){
|
||||
if($s['phase']==='banned')$u->update(['banned'=>1]);elseif($s['phase']==='expired')$u->update(['expired_at'=>time()-1]);elseif($s['phase']==='exhausted')$u->update(['u'=>$u->transfer_enable]);else throw new RuntimeException('Unknown phase');
|
||||
echo json_encode(['phase'=>$s['phase'],'available_users'=>App\Services\ServerService::getAvailableUsers($n)->count(),'empty_list'=>App\Services\ServerService::getAvailableUsers($n)->isEmpty()]).PHP_EOL;exit;
|
||||
}
|
||||
if($action==='next'){
|
||||
if(App\Services\ServerService::getAvailableUsers($n)->count())throw new RuntimeException('Revoke first');$phase=($s['phase']==='banned'?'expired':($s['phase']==='expired'?'exhausted':null));if(!$phase)throw new RuntimeException('No next phase');
|
||||
$u->update(['banned'=>1]);$new=qaV2($s['group_id'],$phase);$s['phase']=$phase;$s['current_user_id']=$new->id;$s['users'][]=$new->id;file_put_contents($stateFile,json_encode($s));echo json_encode(['phase'=>$phase,'new_identity'=>true,'old_qa_remains_disabled'=>true]).PHP_EOL;exit;
|
||||
}
|
||||
if($action==='work'){ $before=Illuminate\Support\Facades\Queue::size('traffic_fetch')+Illuminate\Support\Facades\Queue::size('stat');if($before>100)throw new RuntimeException('Unexpected backlog');Illuminate\Support\Facades\Artisan::call('queue:work',['connection'=>'redis','--queue'=>'traffic_fetch,stat','--stop-when-empty'=>true,'--max-time'=>25,'--tries'=>1,'--sleep'=>1]);echo json_encode(['traffic_pending'=>Illuminate\Support\Facades\Queue::size('traffic_fetch'),'stat_pending'=>Illuminate\Support\Facades\Queue::size('stat')]).PHP_EOL;exit;}
|
||||
if($action==='export'){$g=json_decode(file_get_contents('/var/www/wwwroot/fuc-xb-test/private/gate-credentials.json'),true);echo json_encode(['machine_id'=>$m->id,'machine_token'=>$m->token,'node_id'=>$n->id,'gate_cookie'=>$g['cookie_token'],'qa_uuid'=>$u->uuid,'subscribe_token'=>$u->token,'source'=>'https://fuc-xb-test.gemcook.net','alias'=>'https://fuc-xb-test.tomtojapan.online','port'=>25443,'sni'=>'jp02.gembox-dns.com','node_tag'=>$n->name,'phase'=>$s['phase'],'expected_exit'=>'193.111.31.52']);exit;}
|
||||
if($action==='cleanup'){
|
||||
if(App\Services\ServerService::getAvailableUsers($n)->count())throw new RuntimeException('Revoke first');
|
||||
DB::transaction(function()use($s,$n,$m){foreach($s['users']as$id){foreach(['v2_stat_user','v2_traffic_reset_logs','fuc_vip_entries','fuc_vip_accounts']as$t)DB::table($t)->where('user_id',$id)->delete();DB::table('personal_access_tokens')->where('tokenable_id',$id)->delete();app(App\Services\DeviceStateService::class)->removeNodeDevices($n->id,$id);Illuminate\Support\Facades\Redis::srem('traffic:pending_check',(string)$id);User::whereKey($id)->delete();}DB::table('v2_stat_server')->where('server_id',$n->id)->where('server_type','anytls')->delete();DB::table('v2_server_machine_load_history')->where('machine_id',$m->id)->delete();$n->delete();$m->delete();ServerGroup::whereKey($s['group_id'])->delete();DB::table('v2_settings')->whereIn('name',['server_pull_interval','server_push_interval'])->delete();foreach($s['settings']as$row)DB::table('v2_settings')->insert($row);});Cache::store('redis')->forget(App\Support\Setting::CACHE_KEY);
|
||||
$after=['users'=>User::count(),'groups'=>ServerGroup::count(),'nodes'=>Server::count(),'machines'=>ServerMachine::count(),'wallet'=>(int)User::sum('balance')];echo json_encode(['cleanup'=>true,'baseline_restored'=>$after===$s['before']]).PHP_EOL;exit;
|
||||
}
|
||||
throw new RuntimeException('Unknown action');
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Project a fresh, server-private FUC snapshot; never connects to either database."""
|
||||
from pathlib import Path
|
||||
from collections import defaultdict,Counter
|
||||
from decimal import Decimal
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
import gzip,json,hashlib,os,re
|
||||
os.umask(0o077)
|
||||
ROOT=Path('/var/www/wwwroot/fuc-xb-test/private/refresh-20261105')
|
||||
def main(ROOT=ROOT, previous=None):
|
||||
manifest=json.loads((ROOT/'snapshot-manifest.json').read_text());source=ROOT/'snapshot.jsonl.gz'
|
||||
assert hashlib.sha256(source.read_bytes()).hexdigest()==manifest['sha256']
|
||||
target=ROOT/'projection.json';assert not target.exists(),'Existing projection: verify before replacing'
|
||||
tables=defaultdict(list);head=foot=None
|
||||
with gzip.open(source,'rt')as f:
|
||||
for line in f:
|
||||
v=json.loads(line)
|
||||
if v['kind']=='header':head=v
|
||||
elif v['kind']=='footer':foot=v
|
||||
else:tables[v['table']].append(v['row'])
|
||||
assert head and foot and head['counts']==foot['counts']=={k:len(tables[k])for k in head['counts']}
|
||||
def integer(v):return int(v or 0)
|
||||
def cents(v):
|
||||
n=Decimal(str(v or 0))*100;assert n==n.to_integral_value(),'Fractional cents';return int(n)
|
||||
def timestamp(v):
|
||||
try:return int(datetime.strptime(v,'%Y-%m-%d %H:%M:%S').replace(tzinfo=ZoneInfo('Asia/Shanghai')).timestamp())
|
||||
except(ValueError,TypeError):return 0
|
||||
users={integer(u['id']):u for u in tables['user']};assert len(users)==len(tables['user'])
|
||||
# Only explicitly confirmed original identities receive these overrides.
|
||||
mapping=json.loads((ROOT/'identity-overrides.json').read_text())['users']
|
||||
old={}
|
||||
if previous:
|
||||
old_bytes=(previous/'projection.json').read_bytes()
|
||||
old_summary=json.loads((previous/'projection-summary.json').read_text())
|
||||
assert hashlib.sha256(old_bytes).hexdigest()==old_summary['projection_sha256']
|
||||
old={row['id']:row for row in json.loads(old_bytes)['users']}
|
||||
links={}
|
||||
for link in tables['link']:
|
||||
uid=integer(link['userid'])
|
||||
if uid in users:assert uid not in links;links[uid]=link['token']
|
||||
invoices=defaultdict(list)
|
||||
for inv in tables['invoice']:invoices[integer(inv['order_id'])].append(inv)
|
||||
refunds=[];refunded=Counter()
|
||||
for o in tables['order']:
|
||||
if o['status']!='pending' or integer(o['user_id'])not in users:continue
|
||||
inv=invoices[integer(o['id'])];assert len(inv)==1,'Prepaid invoice cardinality changed';i=inv[0]
|
||||
assert integer(i['user_id'])==integer(o['user_id'])and i['status']in ['paid_gateway','paid_balance','paid_admin']
|
||||
amount=cents(i['price'])+(cents(i['money_use'])if i['status']=='paid_gateway'else 0);assert amount>=0
|
||||
v={'order_id':integer(o['id']),'user_id':integer(o['user_id']),'invoice_id':integer(i['id']),'amount_cents':amount};refunds.append(v);refunded[v['user_id']]+=amount
|
||||
cohorts=sorted({(integer(u['class']),integer(u['node_group']))for u in users.values()if integer(u['class'])>0})
|
||||
groups={c:i+1 for i,c in enumerate(cohorts)}
|
||||
keys=sorted({((integer(u['class']),integer(u['node_group'])),integer(u['transfer_enable']),integer(u['node_speedlimit']))for u in users.values()if integer(u['class'])>0})
|
||||
plans={c:i+1 for i,c in enumerate(keys)};clock=int(datetime.fromisoformat(head['snapshot_utc']).timestamp())
|
||||
thresholds=sorted((cents(v['amount']),integer(v['rate']))for v in tables['vip_map'])
|
||||
def discount(n):return max([rate for amount,rate in thresholds if n>=amount]or[0])
|
||||
rows=[];openings=[];generated=0
|
||||
for uid,u in sorted(users.items()):
|
||||
email=mapping.get(str(uid),{}).get('target_email',str(u['email']or'').strip().lower());assert re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+',email),'Unapproved invalid email in new snapshot'
|
||||
assert re.fullmatch(r'\$2[aby]\$\d\d\$[./A-Za-z0-9]{53}',u['pass']),'Unsupported password'
|
||||
assert re.fullmatch(r'[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}',u['uuid'])
|
||||
cohort=(integer(u['class']),integer(u['node_group']));quota=integer(u['transfer_enable']);speed=integer(u['node_speedlimit']);opening=max(0,cents(u['total_pay'])-refunded[uid]);token=links.get(uid)
|
||||
if not token:
|
||||
previous_user=old.get(uid)
|
||||
if previous_user and previous_user['email']==email and previous_user['uuid']==u['uuid']:
|
||||
token=previous_user['token']
|
||||
else:
|
||||
token=os.urandom(16).hex()
|
||||
generated+=1
|
||||
row={'id':uid,'email':email,'password':u['pass'],'password_algo':None,'password_salt':None,'uuid':u['uuid'],'token':token,'invite_user_id':integer(u['ref_by'])or None,'transfer_enable':quota,'u':integer(u['u']),'d':integer(u['d']),'expired_at':timestamp(u['class_expire']),'balance':cents(u['money'])+refunded[uid],'commission_balance':cents(u['money_aff']),'banned':int(bool(integer(u['is_banned'])or integer(u['is_shadow_banned']))),'is_admin':0,'is_staff':0,'group_id':groups.get(cohort),'plan_id':plans.get((cohort,quota,speed)),'speed_limit':speed or None,'device_limit':None,'created_at':timestamp(u['reg_date'])or None,'updated_at':clock,'next_reset_at':None,'discount':discount(opening),'remind_expire':0,'remind_traffic':0}
|
||||
rows.append(row);openings.append({'user_id':uid,'uuid':u['uuid'],'source_cumulative_cents':cents(u['total_pay']),'returned_prepaid_cents':refunded[uid],'opening_cumulative_cents':opening})
|
||||
assert len({r['email']for r in rows})==len(rows)and len({r['uuid']for r in rows})==len(rows)and len({r['token']for r in rows})==len(rows)
|
||||
assert all(not r['invite_user_id']or r['invite_user_id']in users for r in rows),'Orphan referral requires review'
|
||||
group_rows=[{'id':i,'name':'历史权限组 '+str(i),'created_at':clock,'updated_at':clock}for key,i in groups.items()]
|
||||
plan_rows=[]
|
||||
for (cohort,quota,speed),i in plans.items():plan_rows.append({'id':i,'group_id':groups[cohort],'name':'历史权益 '+str(i),'transfer_enable':(quota+1073741823)//1073741824,'speed_limit':speed or None,'show':0,'sell':0,'renew':0,'prices':'{}','reset_traffic_method':2,'content':'迁移保留原始字节额度和到期;禁止直接续售或自动重置','created_at':clock,'updated_at':clock})
|
||||
value={'snapshot_sha256':manifest['sha256'],'groups':group_rows,'plans':plan_rows,'users':rows,'vip_openings':openings,'refunds':refunds}
|
||||
target.write_text(json.dumps(value,ensure_ascii=False,separators=(',',':')));target.chmod(0o600)
|
||||
summary={'users':len(rows),'groups':len(groups),'hidden_legacy_plans':len(plans),'prepaid_orders':len(refunds),'prepaid_refund_cents':sum(refunded.values()),'wallet_cents':sum(r['balance']for r in rows),'commission_cents':sum(r['commission_balance']for r in rows),'vip_openings':len(openings),'vip_negative_floored':sum(v['source_cumulative_cents']<v['returned_prepaid_cents']for v in openings),'new_tokens_for_missing_links':generated,'old_orders_in_native_business':0,'source_writes':0,'target_database_writes':0,'projection_sha256':hashlib.sha256(target.read_bytes()).hexdigest(),'snapshot_sha256':manifest['sha256']}
|
||||
(ROOT/'projection-summary.json').write_text(json.dumps(summary,indent=2));print(json.dumps(summary))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
declare(strict_types=1);umask(0077);ini_set('display_errors','0');
|
||||
$root='/var/www/wwwroot/fuc-xb-test/current';$private='/var/www/wwwroot/fuc-xb-test/private';$dir=$private.'/refresh-20261105';
|
||||
$options=getopt('',['apply:']);if(!isset($options['apply'])){echo "Requires --apply=exact-projection-sha256; only isolated fuc_xb_test.\n";exit;}
|
||||
$secrets=json_decode(stream_get_contents(STDIN),true,512,JSON_THROW_ON_ERROR);
|
||||
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
|
||||
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\DB;use App\Models\{User,Plan,Server,ServerMachine};
|
||||
if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong target database');
|
||||
$summary=json_decode(file_get_contents($dir.'/projection-summary.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
if(!hash_equals($summary['projection_sha256'],$options['apply'])||!hash_equals($options['apply'],hash_file('sha256',$dir.'/projection.json')))throw new RuntimeException('Projection checksum changed');
|
||||
$backup=json_decode(file_get_contents($private.'/refresh-20261105-before/receipt.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
if(!$backup['passed']||!$backup['all_table_rows_and_content_hashes_equal']||!hash_equals($backup['backup_sha256'],hash_file('sha256',$private.'/refresh-20261105-before/fuc_xb_test.sql.gz')))throw new RuntimeException('Verified backup required');
|
||||
$marker=$dir.'/refresh-applied.json';if(file_exists($marker))throw new RuntimeException('Refresh already journaled; verify before retry');
|
||||
$data=json_decode(file_get_contents($dir.'/projection.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
if(count($data['users'])!==$summary['users']||count($data['vip_openings'])!==$summary['users'])throw new RuntimeException('Projection count mismatch');
|
||||
foreach(['v2_order','v2_commission_log','personal_access_tokens','v2_stat_user','v2_stat_server']as$table)if(DB::table($table)->exists())throw new RuntimeException('Unexpected target business rows: '.$table);
|
||||
if(Server::count()||ServerMachine::count()||DB::table('fuc_vip_entries')->where('kind','!=','opening')->exists())throw new RuntimeException('Unexpected test node or VIP activity');
|
||||
$qaFile=$private.'/qa-credentials.json';$qa=json_decode(file_get_contents($qaFile),true,512,JSON_THROW_ON_ERROR);$qaUser=User::findOrFail($qa['user_id']);$qaPlan=Plan::findOrFail($qa['plan_id']);
|
||||
if($qaUser->email!=='[email protected]'||$qaUser->is_admin||$qaUser->is_staff)throw new RuntimeException('QA identity mismatch');
|
||||
$adminRows=array_values(array_filter($data['users'],fn($r)=>$r['email']===$secrets['username']));if(count($adminRows)!==1)throw new RuntimeException('Default admin missing or duplicated');$admin=$adminRows[0];
|
||||
if(!App\Utils\Helper::multiPasswordVerify($admin['password_algo'],$admin['password_salt'],$secrets['password'],$admin['password']))throw new RuntimeException('Source default admin credential changed; not overwritten');
|
||||
$qaRow=$qaUser->getAttributes();$qaPlanRow=$qaPlan->getAttributes();$qaRow['id']=max(array_column($data['users'],'id'))+1;$qaRow['plan_id']=null;$qaRow['group_id']=null;$qaPlanRow['id']=max(array_column($data['plans'],'id'))+1;
|
||||
$qaRow['balance']=100000;$qaRow['u']=$qaRow['d']=0;$qaRow['transfer_enable']=0;$qaRow['expired_at']=0;$qaRow['discount']=null;
|
||||
$qa['user_id']=$qaRow['id'];$qa['plan_id']=$qaPlanRow['id'];
|
||||
app(App\Services\Plugin\PluginManager::class)->initializeEnabledPlugins();
|
||||
$before=['users'=>User::count(),'plans'=>Plan::count(),'groups'=>DB::table('v2_server_group')->count()];
|
||||
file_put_contents($dir.'/refresh-intent.json',json_encode(['projection_sha256'=>$options['apply'],'before'=>$before,'backup_sha256'=>$backup['backup_sha256']]));
|
||||
function normalizeRefresh($r):array{return array_map(fn($v)=>$v===null?null:(string)$v,(array)$r);}
|
||||
DB::transaction(function()use($data,$summary,$qaRow,$qaPlanRow,$admin){
|
||||
foreach(['v2_traffic_reset_logs','fuc_vip_entries','fuc_vip_accounts','v2_user','v2_plan','v2_server_group']as$t)DB::table($t)->delete();
|
||||
foreach(['v2_server_group'=>'groups','v2_plan'=>'plans','v2_user'=>'users']as$t=>$key){
|
||||
foreach($data[$key]as$row)DB::table($t)->insert($row);
|
||||
foreach($data[$key]as$row){$actual=DB::table($t)->where('id',$row['id'])->first();foreach($row as$k=>$v)if(normalizeRefresh([$v])!==normalizeRefresh([$actual->$k]))throw new RuntimeException('Full-field refresh mismatch: '.$t.'.'.$k);}
|
||||
}
|
||||
foreach($data['vip_openings']as$v)app(Plugin\VipLoyalty\Service::class)->opening($v['user_id'],$v['uuid'],$v['opening_cumulative_cents'],$data['snapshot_sha256']);
|
||||
if((int)User::sum('balance')!==$summary['wallet_cents']||(int)User::sum('commission_balance')!==$summary['commission_cents']||DB::table('fuc_vip_accounts')->count()!==$summary['users'])throw new RuntimeException('Refresh money or VIP mismatch');
|
||||
DB::table('v2_user')->where('id',$admin['id'])->update(['is_admin'=>1]);DB::table('v2_user')->insert($qaRow);DB::table('v2_plan')->insert($qaPlanRow);
|
||||
});
|
||||
$temp=$qaFile.'.refresh';file_put_contents($temp,json_encode($qa));chmod($temp,0600);rename($temp,$qaFile);
|
||||
$result=['passed'=>true,'snapshot_sha256'=>$data['snapshot_sha256'],'migrated_users'=>$summary['users'],'hidden_plans'=>$summary['hidden_legacy_plans'],'groups'=>$summary['groups'],'wallet_cents'=>$summary['wallet_cents'],'commission_cents'=>$summary['commission_cents'],'prepaid_refund_orders'=>$summary['prepaid_orders'],'prepaid_refund_cents'=>$summary['prepaid_refund_cents'],'vip_openings'=>DB::table('fuc_vip_accounts')->count(),'total_users'=>User::count(),'admins'=>User::where('is_admin',1)->count(),'full_field_readback'=>true,'qa_credentials_preserved'=>true,'native_orders'=>DB::table('v2_order')->count(),'source_writes'=>0,'shared_core_changed'=>false];
|
||||
file_put_contents($marker,json_encode($result,JSON_PRETTY_PRINT));chmod($marker,0600);echo json_encode($result).PHP_EOL;
|
||||
@@ -0,0 +1,12 @@
|
||||
import importlib.util,pathlib,json,unittest
|
||||
s=importlib.util.spec_from_file_location('v2bridge',pathlib.Path(__file__).with_name('node-bridge.py'));b=importlib.util.module_from_spec(s);s.loader.exec_module(b)
|
||||
class Scope(unittest.TestCase):
|
||||
def setUp(self):self.c={'machine_id':7,'node_id':9,'machine_token':'synthetic'}
|
||||
def test_machine_discovery(self):self.assertTrue(b.allowed('POST','/api/v2/server/machine/nodes',json.dumps({'machine_id':7,'token':'synthetic'}).encode(),'application/json',self.c))
|
||||
def test_exact_node(self):self.assertTrue(b.allowed('GET','/api/v2/server/user?machine_id=7&node_id=9&token=synthetic',b'','',self.c))
|
||||
def test_reject_other_machine_node_token_and_duplicates(self):
|
||||
for q in ['machine_id=8&node_id=9&token=synthetic','machine_id=7&node_id=8&token=synthetic','machine_id=7&node_id=9&token=wrong','machine_id=7&machine_id=7&node_id=9&token=synthetic','machine_id=7&token=synthetic']:
|
||||
self.assertFalse(b.allowed('GET','/api/v2/server/user?'+q,b'','',self.c))
|
||||
def test_reject_other_paths_and_methods(self):
|
||||
for method,path in [('DELETE','/api/v2/server/user'),('GET','/api/v2/admin/user'),('POST','https://other.invalid/api/v2/server/machine/nodes')]:self.assertFalse(b.allowed(method,path,json.dumps({'machine_id':7,'token':'synthetic'}).encode(),'application/json',self.c))
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,234 @@
|
||||
// Run the theme's real event handlers against a static DOM and delayed API doubles.
|
||||
// This checks races and business payloads; it is not browser/provider acceptance.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import {JSDOM,VirtualConsole} from '../../codex/output/fuc-theme/test-tools/node_modules/jsdom/lib/api.js';
|
||||
const jsErrors=[],consoleCapture=new VirtualConsole();consoleCapture.on('jsdomError',error=>jsErrors.push(error));
|
||||
const dom=new JSDOM('<html><head><style>.modal.fade .modal-dialog{transition:transform .3s ease-out}.modal-backdrop.fade{transition:opacity .15s linear}</style></head><body><div id="app"></div></body></html>',{url:'http://xb.loc/#/login',runScripts:'outside-only',pretendToBeVisual:true,virtualConsole:consoleCapture});
|
||||
for(const key of ['window','document','DOMParser','localStorage','sessionStorage','location','history','FormData'])globalThis[key]=dom.window[key];
|
||||
globalThis.innerWidth=1280;globalThis.matchMedia=()=>({matches:false,addEventListener(){}});
|
||||
globalThis.requestAnimationFrame=window.requestAnimationFrame.bind(window);globalThis.cancelAnimationFrame=window.cancelAnimationFrame.bind(window);
|
||||
window.scrollTo=()=>{};window.ApexCharts=class{render(){return Promise.resolve()}destroy(){}};
|
||||
const plans=[{id:1,name:'Paid',month_price:1200,transfer_enable:100},{id:2,name:'Free',month_price:0,transfer_enable:10}];
|
||||
const calls=[];let delayedLogin,delayedCoupon,checkoutAmount=0,checkoutStatus=0,failOrderCheck=false,orders=[];
|
||||
const payload=(data,status=200)=>({ok:status<400,status,json:async()=>({data})});
|
||||
globalThis.fetch=async(url,options={})=>{
|
||||
if(String(url).startsWith('file:'))return {ok:true,text:()=>fs.readFile(new URL(url),'utf8'),json:async()=>JSON.parse(await fs.readFile(new URL(url),'utf8'))};
|
||||
const path=String(url).replace('/api/v1/','');calls.push({path,body:options.body?JSON.parse(options.body):null});
|
||||
if(path==='guest/comm/config')return payload({is_captcha:0});
|
||||
if(path==='passport/auth/login')return new Promise(resolve=>delayedLogin=()=>resolve(payload({auth_data:'Bearer synthetic'})));
|
||||
if(path==='user/info')return payload({email:'[email protected]',plan_id:2});
|
||||
if(path==='user/getSubscribe')return payload({plan_id:2,plan:plans[1],transfer_enable:1000,u:0,d:0,subscribe_url:'http://xb.loc/s/synthetic'});
|
||||
if(path==='user/comm/config')return payload({withdraw_methods:[]});
|
||||
if(path.startsWith('user/notice/fetch?current=')){
|
||||
const offset=(Number(new URLSearchParams(path.split('?')[1]).get('current'))-1)*5;
|
||||
const notices=Array.from({length:18},(_,i)=>({id:i+1,title:'归档公告 '+(i+1),content:'归档正文',created_at:1793836800}));
|
||||
return {ok:true,status:200,json:async()=>({data:notices.slice(offset,offset+5),total:notices.length})};
|
||||
}
|
||||
if(path==='user/plan/fetch')return payload([plans[0]]);
|
||||
if(path==='user/plan/fetch?id=2')return payload({...plans[1],show:false,sell:false,renew:true,capacity_limit:'Sold out'});
|
||||
if(path==='user/coupon/check')return new Promise(resolve=>delayedCoupon=()=>resolve(payload({name:'QA'})));
|
||||
if(path==='user/order/save')return payload('synthetic-order');
|
||||
if(path==='user/order/fetch')return payload(orders);
|
||||
if(path==='user/order/detail?trade_no=synthetic-order')return payload({trade_no:'synthetic-order',plan:plans[1],period:'month_price',status:checkoutStatus,total_amount:checkoutAmount});
|
||||
if(path==='user/order/check?trade_no=synthetic-order')return payload(checkoutStatus,failOrderCheck?503:200);
|
||||
if(path==='user/order/getPaymentMethod')return payload([{id:17,name:'空中支付 · 微信支付',payment:'Epay'},{id:21,name:'空中支付 · 支付宝',payment:'Epay'}]);
|
||||
if(path==='user/order/checkout')return payload({type:1,data:'https://pay.example.test/synthetic-only'});
|
||||
if(path==='user/order/cancel'){
|
||||
const order=orders.find(order=>order.trade_no===JSON.parse(options.body).trade_no);
|
||||
if(!order||Number(order.status)!==0)return payload(null,422);
|
||||
order.status=2;
|
||||
return payload(true);
|
||||
}
|
||||
return payload([]);
|
||||
};
|
||||
const append=document.head.append.bind(document.head);
|
||||
document.head.append=node=>{append(node);if(node.tagName==='SCRIPT')queueMicrotask(()=>{try{window.eval(requireFile(node.src));node.onload?.();}catch(error){node.onerror?.(error);}});if(node.tagName==='LINK')queueMicrotask(()=>node.onload?.());};
|
||||
const insertBefore=document.head.insertBefore.bind(document.head);
|
||||
document.head.insertBefore=(node,before)=>{const result=insertBefore(node,before);if(node.tagName==='LINK')queueMicrotask(()=>node.onload?.());return result;};
|
||||
const {readFileSync}=await import('node:fs');const requireFile=url=>readFileSync(new URL(url),'utf8');
|
||||
const until=async predicate=>{for(let n=0;n<200;n++){if(predicate())return;await new Promise(resolve=>setTimeout(resolve,10));}throw Error('DOM state did not settle');};
|
||||
const go=async route=>{location.hash='/'+route;await until(()=>document.body.dataset.nativePage===route);};
|
||||
await import('../../theme/Fuc/assets/app.mjs');
|
||||
test('login uses original pending text and waits for success confirmation before routing',async()=>{
|
||||
await until(()=>document.querySelector('[data-form=login]'));const form=document.querySelector('[data-form=login]'),button=form.querySelector('[type=submit]');
|
||||
form.querySelector('[name=email]').value='[email protected]';form.querySelector('[name=password]').value='synthetic-password';
|
||||
form.dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
assert.equal(button.textContent,'正在登录');assert.equal(button.disabled,true);await until(()=>delayedLogin);delayedLogin();
|
||||
await until(()=>document.querySelector('.swal2-confirm'));assert.equal(location.hash,'#/login');
|
||||
document.querySelector('.swal2-confirm').click();await until(()=>document.body.dataset.nativePage==='dashboard');
|
||||
assert.equal(calls.find(c=>c.path==='passport/auth/login').body.password,'synthetic-password');
|
||||
});
|
||||
test('a delayed coupon response cannot reopen a purchase modal on a different page',async()=>{
|
||||
await go('plans');document.querySelector('[data-action=buy]').click();await until(()=>document.querySelector('#coupon_modal.show'));
|
||||
const form=document.querySelector('[data-form=purchase-coupon]');form.querySelector('[name=coupon_code]').value='QA';
|
||||
form.dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));await until(()=>delayedCoupon);
|
||||
await go('profile');delayedCoupon();await new Promise(resolve=>setTimeout(resolve,50));
|
||||
assert.equal(document.querySelector('#order_modal.show'),null);assert.equal(document.body.dataset.nativePage,'profile');
|
||||
assert.equal(calls.filter(c=>c.path==='user/order/save').length,0);
|
||||
});
|
||||
test('canceling the source-style subscription reset never calls the reset API',async()=>{
|
||||
document.querySelector('[data-target="#sublink-modal"]').click();await until(()=>document.querySelector('#sublink-modal.show'));
|
||||
document.querySelector('[data-action=reset-security]').click();await until(()=>document.querySelector('.swal2-cancel'));
|
||||
document.querySelector('.swal2-cancel').click();await new Promise(resolve=>setTimeout(resolve,20));
|
||||
assert.equal(calls.some(c=>c.path==='user/resetSecurity'),false);
|
||||
});
|
||||
test('leaving during the original modal transition leaves no late component errors',async()=>{
|
||||
await go('plans');document.querySelector('[data-action=buy]').click();
|
||||
await go('profile');await new Promise(resolve=>setTimeout(resolve,700));
|
||||
assert.deepEqual(jsErrors.map(e=>e.message),[]);
|
||||
});
|
||||
test('manual renewal of an off-sale owned plan keeps the actual XB plan and period',async()=>{
|
||||
await go('plans');
|
||||
const renewal=document.querySelector('[data-action=buy][data-id="2"][data-period="month_price"]');assert.ok(renewal);
|
||||
renewal.click();await until(()=>document.querySelector('#coupon_modal.show'));
|
||||
document.querySelector('#coupon_modal [data-form=purchase-coupon]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
await until(()=>document.querySelector('#order_modal.show'));
|
||||
document.querySelector('#order_modal [data-form=purchase]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
await until(()=>document.body.dataset.nativePage==='checkout');
|
||||
assert.deepEqual(calls.filter(c=>c.path==='user/order/save').at(-1).body,{plan_id:2,period:'month_price'});
|
||||
const modal=document.querySelector('#fuc-checkout-modal');
|
||||
assert.ok(document.querySelector('[data-action=buy][data-id="2"]'));
|
||||
assert.ok(modal.querySelector('[data-form=checkout]'));
|
||||
await until(()=>modal.classList.contains('show'));
|
||||
modal.querySelector('[aria-label="关闭订单详情"]').click();
|
||||
await until(()=>document.body.dataset.nativePage==='plans');
|
||||
assert.equal(location.hash,'#/plans');
|
||||
location.hash='/checkout/synthetic-order';
|
||||
await until(()=>document.body.dataset.nativePage==='checkout');
|
||||
assert.equal(document.querySelector('#fuc-checkout-modal'),null);
|
||||
assert.ok(document.querySelector('[data-form=checkout]'));
|
||||
});
|
||||
test('the old plan URL opens the order list, with an unpaid order accessible on its page',async()=>{
|
||||
orders=Array.from({length:20},(_,i)=>({trade_no:'paid-'+i,status:3}));
|
||||
orders.push({trade_no:'synthetic-order',status:0});
|
||||
try{
|
||||
location.hash='/myplan';
|
||||
await until(()=>document.body.dataset.nativePage==='orders');
|
||||
assert.equal(location.hash,'#/orders');
|
||||
const menu=document.querySelector('.navigation-main a[href="#/orders"]');
|
||||
assert.equal(menu.querySelector('.menu-title').textContent,'套餐订单');
|
||||
assert.ok(menu.querySelector('.icon-hard-drive'));
|
||||
assert.equal(menu.closest('li').nextElementSibling.querySelector('a').getAttribute('href'),'#/wallet');
|
||||
assert.equal(document.querySelector('[data-pending-order]'),null);
|
||||
assert.doesNotMatch(document.querySelector('tbody').textContent,/synthetic-order/);
|
||||
document.querySelector('[data-action=next]').click();
|
||||
const unpaidLink=()=>document.querySelector('tbody a[href="#/checkout/synthetic-order?from=orders"]');
|
||||
await until(unpaidLink);
|
||||
assert.equal(unpaidLink().textContent,'继续支付');
|
||||
unpaidLink().click();
|
||||
await until(()=>document.querySelector('#fuc-checkout-modal.show'));
|
||||
assert.equal(location.hash,'#/checkout/synthetic-order?from=orders');
|
||||
document.querySelector('#fuc-checkout-modal [data-action=native-dismiss]').click();
|
||||
await until(()=>document.body.dataset.nativePage==='orders');
|
||||
assert.equal(location.hash,'#/orders');
|
||||
orders.pop();
|
||||
location.hash='/subscribe';
|
||||
await until(()=>location.hash==='#/orders'&&document.querySelector('tbody tr'));
|
||||
}finally{orders=[];}
|
||||
});
|
||||
test('pending orders can be canceled from their rows after confirmation',async()=>{
|
||||
await go('plans');
|
||||
orders=[{trade_no:'first-order',status:0},{trade_no:'row-order',status:'0'},{trade_no:'paid-order',status:3}];
|
||||
try{
|
||||
await go('orders');
|
||||
const sent=()=>calls.filter(call=>call.path==='user/order/cancel').map(call=>call.body.trade_no);
|
||||
const row=()=>document.querySelector('tbody button[data-trade-no="row-order"]');
|
||||
const first=()=>document.querySelector('tbody button[data-trade-no="first-order"]');
|
||||
assert.equal(document.querySelector('[data-pending-order]'),null);
|
||||
assert.equal(document.querySelector('tbody button[data-trade-no="paid-order"]'),null);
|
||||
assert.equal(document.querySelector('tbody a[href="#/checkout/paid-order?from=orders"]').textContent,'查看');
|
||||
row().click();
|
||||
assert.equal(row().textContent,'再次点击确认取消');
|
||||
assert.deepEqual(sent(),[]);
|
||||
row().click();
|
||||
await until(()=>!row());
|
||||
first().click();
|
||||
assert.deepEqual(sent(),['row-order']);
|
||||
first().click();
|
||||
await until(()=>!first());
|
||||
assert.deepEqual(sent(),['row-order','first-order']);
|
||||
assert.equal(location.hash,'#/orders');
|
||||
assert.equal(document.querySelectorAll('tbody button[data-trade-no]').length,0);
|
||||
}finally{orders=[];}
|
||||
});
|
||||
test('a shop order opens checkout over the shop and closes back to it',async()=>{
|
||||
await go('plans');
|
||||
document.querySelector('[data-action=buy]').click();
|
||||
await until(()=>document.querySelector('#coupon_modal.show'));
|
||||
document.querySelector('[data-form=purchase-coupon]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
await until(()=>document.querySelector('#order_modal.show'));
|
||||
document.querySelector('#order_modal [data-form=purchase]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
await until(()=>document.querySelector('#fuc-checkout-modal.show'));
|
||||
assert.equal(location.hash,'#/checkout/synthetic-order?from=plans');
|
||||
assert.ok(document.querySelector('[data-action=buy]'));
|
||||
document.querySelector('#fuc-checkout-modal [data-action=native-dismiss]').click();
|
||||
await until(()=>document.body.dataset.nativePage==='plans');
|
||||
assert.equal(location.hash,'#/plans');
|
||||
});
|
||||
test('payment cards show short labels and open the selected native cashier directly',async t=>{
|
||||
const opened=[];
|
||||
t.mock.method(window.HTMLAnchorElement.prototype,'click',function(){opened.push([this.href,this.target]);});
|
||||
checkoutAmount=1200;location.hash='/checkout/synthetic-order?from=plans';
|
||||
await until(()=>document.querySelector('#fuc-checkout-modal input[name=method]'));
|
||||
const form=document.querySelector('#fuc-checkout-modal [data-form=checkout]');
|
||||
const first=form.querySelector('input[value="17"]'),second=form.querySelector('input[value="21"]');
|
||||
assert.deepEqual([...form.querySelectorAll('.nav-text')].map(node=>node.textContent),['微信','支付宝']);
|
||||
assert.equal(first.checked,true);assert.equal(document.querySelector('#fuc-checkout-modal details'),null);
|
||||
second.click();
|
||||
assert.equal(second.checked,true);assert.equal(first.nextElementSibling.classList.contains('active'),false);
|
||||
assert.equal(second.nextElementSibling.classList.contains('active'),true);
|
||||
form.dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
await until(()=>calls.some(c=>c.path==='user/order/checkout'));
|
||||
assert.deepEqual(calls.find(c=>c.path==='user/order/checkout').body,{trade_no:'synthetic-order',method:'21'});
|
||||
await until(()=>opened.length>0);
|
||||
assert.deepEqual(opened,[['https://pay.example.test/synthetic-only','_self']]);
|
||||
assert.equal(document.querySelector('#payment-result').textContent,'');
|
||||
checkoutAmount=0;await go('plans');
|
||||
});
|
||||
test('payment refresh is a fallback for failed or slow checks and clears when the order advances',async t=>{
|
||||
t.mock.method(window.HTMLAnchorElement.prototype,'click',()=>{});
|
||||
const realSetTimeout=globalThis.setTimeout;
|
||||
const start=Date.now();
|
||||
let now=start,nextCheck;
|
||||
t.mock.method(Date,'now',()=>now);
|
||||
t.mock.method(globalThis,'setTimeout',(callback,delay,...args)=>{
|
||||
if(delay!==5000)return realSetTimeout(callback,delay,...args);
|
||||
const timer=realSetTimeout(callback,delay,...args);
|
||||
nextCheck=async()=>{clearTimeout(timer);await callback(...args);};
|
||||
return timer;
|
||||
});
|
||||
const refresh=()=>document.querySelector('[data-action=refresh-payment]');
|
||||
const check=async()=>{assert.ok(nextCheck);const run=nextCheck;nextCheck=null;await run();};
|
||||
checkoutAmount=1200;
|
||||
try{
|
||||
location.hash='/checkout/synthetic-order?from=orders';
|
||||
await until(()=>refresh());
|
||||
assert.equal(refresh().hidden,true);
|
||||
document.querySelector('[data-form=checkout]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
await until(()=>nextCheck);
|
||||
now=start+5000;await check();
|
||||
assert.equal(refresh().hidden,true);
|
||||
failOrderCheck=true;await check();
|
||||
assert.equal(refresh().hidden,false);
|
||||
failOrderCheck=false;now=start+60000;await check();
|
||||
assert.equal(refresh().hidden,false);
|
||||
checkoutStatus=1;await check();
|
||||
assert.match(document.querySelector('#fuc-checkout-modal .fuc-checkout-product').textContent,/开通中/);
|
||||
assert.equal(refresh().hidden,true);
|
||||
checkoutStatus=3;await check();
|
||||
assert.match(document.querySelector('#fuc-checkout-modal .fuc-checkout-product').textContent,/已完成/);
|
||||
assert.equal(refresh(),null);
|
||||
}finally{
|
||||
checkoutAmount=0;checkoutStatus=0;failOrderCheck=false;await go('plans');
|
||||
}
|
||||
});
|
||||
test('the announcement page shows all four native XB pages in order',async()=>{
|
||||
calls.length=0;
|
||||
await go('notices');
|
||||
assert.deepEqual(calls.filter(c=>c.path.startsWith('user/notice/fetch?current=')).map(c=>c.path.split('=')[1]),['1','2','3','4']);
|
||||
const headings=[...document.querySelectorAll('h5')].map(node=>node.textContent.trim()).filter(title=>title.startsWith('归档公告 '));
|
||||
assert.deepEqual(headings,Array.from({length:18},(_,i)=>'归档公告 '+(i+1)));
|
||||
});
|
||||
test.after(()=>{window.Pace.stop();dom.window.close();});
|
||||
@@ -0,0 +1,21 @@
|
||||
// Run only when updating the Fuc runtime bundles. Never modifies shared dependencies.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {createRequire} from 'node:module';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {createHash} from 'node:crypto';
|
||||
const root=fileURLToPath(new URL('../../',import.meta.url));
|
||||
const require=createRequire(path.join(root,'theme/package.json'));
|
||||
const versions={esbuild:'0.25.12',qrcode:'1.5.4',marked:'15.0.12',dompurify:'3.4.17'};
|
||||
for(const [name,version] of Object.entries(versions)){
|
||||
const actual=JSON.parse(fs.readFileSync(path.join(root,'theme/node_modules',name,'package.json'),'utf8')).version;
|
||||
if(actual!==version)throw Error(`${name}: expected ${version}, found ${actual}; review dependency update first`);
|
||||
}
|
||||
const {build}=require('esbuild');const output=path.join(root,'theme/Fuc/assets/vendor');fs.mkdirSync(output,{recursive:true});
|
||||
for(const [name,contents] of Object.entries({qrcode:"export {default} from 'qrcode/lib/browser.js';",richtext:"export {marked} from 'marked'; export {default as DOMPurify} from 'dompurify';"})){
|
||||
await build({stdin:{contents,resolveDir:path.join(root,'theme')},bundle:true,format:'esm',platform:'browser',minify:true,outfile:path.join(output,name+'.mjs')});
|
||||
}
|
||||
for(const [name,file] of [['qrcode','license'],['marked','LICENSE.md'],['dompurify','LICENSE']])fs.copyFileSync(path.join(root,'theme/node_modules',name,file),path.join(output,name+'.LICENSE'));
|
||||
const hashes=Object.fromEntries(['qrcode.mjs','richtext.mjs'].map(name=>[name,createHash('sha256').update(fs.readFileSync(path.join(output,name))).digest('hex')]));
|
||||
fs.writeFileSync(path.join(output,'manifest.json'),JSON.stringify({versions,sha256:hashes},null,2)+'\n');
|
||||
console.log('Fuc vendor bundles and license provenance updated');
|
||||
@@ -1,7 +1,39 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createApi, soldOut, safeUrl, bytes, money} from '../../theme/Fuc/assets/core.mjs';
|
||||
import {createApi, soldOut, safeUrl, bytes, money, paymentResult, routeFromHash,trafficSummary,canPurchase} from '../../theme/Fuc/assets/core.mjs';
|
||||
import {subscriptionUrl,importUrl} from '../../theme/Fuc/assets/subscription.mjs';
|
||||
const response = (body,status=200) => ({ok:status<400,status,json:async()=>body});
|
||||
test('owned renewal is not blocked by new-sale capacity, and reset requires ownership',()=>{
|
||||
const plan={id:7,show:false,sell:false,renew:true,capacity_limit:'Sold out',month_price:1200,reset_price:100};
|
||||
assert.equal(canPurchase(plan,{plan_id:7},'month_price'),true);
|
||||
assert.equal(canPurchase(plan,{plan_id:8},'month_price'),false);
|
||||
assert.equal(canPurchase({...plan,renew:false},{plan_id:7},'month_price'),false);
|
||||
assert.equal(canPurchase(plan,{plan_id:7},'reset_price'),true);
|
||||
assert.equal(canPurchase(plan,{plan_id:8},'reset_price'),false);
|
||||
});
|
||||
test('an expired response from a previous token cannot discard a newer login',async()=>{
|
||||
let token='Bearer old',resolve,cleared=false;
|
||||
const api=createApi({getToken:()=>token,onUnauthorized:()=>cleared=true,fetcher:()=>new Promise(done=>resolve=done)});
|
||||
const pending=api('user/info');token='Bearer new';resolve(response({message:'未登录'},401));
|
||||
await assert.rejects(pending);assert.equal(cleared,false);
|
||||
});
|
||||
test('today traffic uses rated XB bytes once and keeps donut slices consistent',()=>{
|
||||
const now=new Date(2026,10,2,12),today=new Date(2026,10,2).getTime()/1000,yesterday=today-86400;
|
||||
const summary=trafficSummary({transfer_enable:1000,u:100,d:300},[{record_at:today,u:20,d:30,server_rate:2},{record_at:yesterday,u:50,d:100}],now);
|
||||
assert.equal(summary.today,50);assert.equal(summary.history,350);assert.equal(summary.remaining,600);assert.deepEqual(summary.series,[60,35,5]);
|
||||
assert.deepEqual(trafficSummary({transfer_enable:0},[],now).series,[0,0,0]);
|
||||
assert.equal(trafficSummary({},null,now).today,null,'failed stats are unknown, not fake zero');
|
||||
assert.equal(trafficSummary({transfer_enable:100,u:150},[{record_at:today,u:150,d:0}],now).series.reduce((a,b)=>a+b),100);
|
||||
});
|
||||
test('each subscription control uses XB flags and Trojan uses the supported type filter',()=>{
|
||||
const raw='https://subscription.example.test/s/synthetic?token=local&custom=kept';
|
||||
const trojan=new URL(subscriptionUrl(raw,'trojan'));assert.equal(trojan.searchParams.get('flag'),'general');assert.equal(trojan.searchParams.get('types'),'trojan');assert.equal(trojan.searchParams.get('custom'),'kept');
|
||||
for(const client of ['general','meta','hiddify','sing-box','shadowsocks'])assert.equal(new URL(subscriptionUrl(raw,client)).searchParams.get('flag'),client);
|
||||
assert.equal(new URL(subscriptionUrl(raw,'shadowrocket')).searchParams.get('flag'),'general');
|
||||
const clash=new URL(importUrl(raw,'meta','验收站'));assert.equal(new URL(clash.searchParams.get('url')).searchParams.get('flag'),'meta');assert.equal(clash.searchParams.get('name'),'验收站');
|
||||
const rocket=importUrl(raw,'shadowrocket');assert.equal(atob(rocket.slice('shadowrocket://add/sub://'.length)),subscriptionUrl(raw,'shadowrocket'));
|
||||
assert.throws(()=>subscriptionUrl('javascript:alert(1)','meta'));assert.throws(()=>subscriptionUrl(raw,'unsupported'));
|
||||
});
|
||||
test('uses auth_data verbatim, sends writes as JSON, unwraps Resource data',async()=>{
|
||||
let call; const api=createApi({getToken:()=> 'Bearer synthetic',fetcher:async(...args)=>{call=args;return response({status:'success',data:{id:7}});}});
|
||||
assert.deepEqual(await api('user/update',{remind_expire:1}),{id:7});
|
||||
@@ -25,7 +57,30 @@ test('stock null and positive are available, zero and localized sold-out are not
|
||||
assert.equal(soldOut({capacity_limit:100,capacity_remaining:0}),true);
|
||||
});
|
||||
test('rejects script URLs and embedded credentials; formats actual XB money and bytes',()=>{
|
||||
assert.equal(safeUrl(''), '');
|
||||
assert.equal(safeUrl('javascript:alert(1)'), ''); assert.equal(safeUrl('https://user:[email protected]'), '');
|
||||
assert.equal(safeUrl('https://example.test/sub'), 'https://example.test/sub');
|
||||
assert.equal(money(1200),'¥12.00'); assert.equal(bytes(1024**3),'1.00 GB'); assert.equal(bytes(1024**2),'1.00 MB'); assert.equal(bytes(-1),'0 B');
|
||||
});
|
||||
test('XB expired session 403 clears auth but permission denial does not',async()=>{
|
||||
for(const [message,expected] of [['未登录或登陆已过期',true],['没有权限',false]]){
|
||||
let cleared=false;
|
||||
await assert.rejects(createApi({onUnauthorized:()=>cleared=true,fetcher:async()=>response({message},403)})('user/info'));
|
||||
assert.equal(cleared,expected);
|
||||
}
|
||||
});
|
||||
test('payment contracts distinguish QR, redirects, form and successful settlement',()=>{
|
||||
assert.deepEqual(paymentResult({type:0,data:'alipay://pay/test'}),{kind:'qr',value:'alipay://pay/test'});
|
||||
assert.equal(paymentResult({type:1,data:'https://example.test/pay'}).kind,'url');
|
||||
assert.equal(paymentResult({type:1,data:'<form action="https://example.test/pay"></form>'}).kind,'form');
|
||||
assert.equal(paymentResult({type:-1,data:true}).kind,'complete');
|
||||
for(const result of [{type:-1,data:false},{type:0,data:''},{type:1,data:'javascript:alert(1)'},{type:1,data:'https://u:[email protected]/'},{type:9,data:true}])assert.throws(()=>paymentResult(result));
|
||||
});
|
||||
test('detail routes survive legacy aliases and email-login query parsing',()=>{
|
||||
assert.equal(routeFromHash('#/ticket/123').name,'ticket');
|
||||
assert.equal(routeFromHash('#/ticket').name,'tickets');
|
||||
assert.equal(routeFromHash('#/order/no').name,'checkout');
|
||||
assert.equal(routeFromHash('#/order').name,'orders');
|
||||
assert.equal(routeFromHash('#/shop').name,'plans');
|
||||
assert.equal(routeFromHash('#/login?verify=abc&redirect=dashboard').query.get('verify'),'abc');
|
||||
});
|
||||
@@ -0,0 +1,233 @@
|
||||
// Static DOM contract tests, not a substitute for browser or provider acceptance.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import {JSDOM} from '../../codex/output/fuc-theme/test-tools/node_modules/jsdom/lib/api.js';
|
||||
const dom=new JSDOM('<!doctype html><html><head></head><body></body></html>',{url:'http://xb.loc/'});
|
||||
for(const key of ['window','document','DOMParser','localStorage'])globalThis[key]=dom.window[key];
|
||||
globalThis.fetch=async url=>({ok:true,text:()=>fs.readFile(new URL(url),'utf8'),json:async()=>JSON.parse(await fs.readFile(new URL(url),'utf8'))});
|
||||
const {paymentForm,showPayment}=await import('../../theme/Fuc/assets/payments.mjs');
|
||||
const {richText}=await import('../../theme/Fuc/assets/content.mjs');
|
||||
const {copyText}=await import('../../theme/Fuc/assets/clipboard.mjs');
|
||||
const native=await import('../../theme/Fuc/assets/native.mjs');await native.nativeReady;
|
||||
test('touch login waits for a tap while desktop keeps keyboard autofocus',()=>{
|
||||
const original=window.matchMedia;
|
||||
try {
|
||||
window.matchMedia=()=>({matches:true});
|
||||
const touch=new DOMParser().parseFromString(native.nativeLogin('富蕴'),'text/html');
|
||||
assert.equal(touch.querySelector('[autofocus]'),null);
|
||||
window.matchMedia=()=>({matches:false});
|
||||
const desktop=new DOMParser().parseFromString(native.nativeLogin('富蕴'),'text/html');
|
||||
assert.equal(desktop.querySelector('[autofocus]').name,'email');
|
||||
}finally{window.matchMedia=original;}
|
||||
});
|
||||
test('user navigation keeps active shared CSS and its dark/bridge overrides attached',async()=>{
|
||||
const append=document.head.append.bind(document.head),insert=document.head.insertBefore.bind(document.head),moved=[];
|
||||
document.head.append=node=>{if(node.isConnected&&node.tagName==='LINK')moved.push(node);append(node);if(node.tagName==='LINK')queueMicrotask(()=>node.onload?.());};
|
||||
document.head.insertBefore=(node,before)=>{if(node.isConnected&&node.tagName==='LINK')moved.push(node);const result=insert(node,before);if(node.tagName==='LINK')queueMicrotask(()=>node.onload?.());return result;};
|
||||
globalThis.innerWidth=1280;
|
||||
try {
|
||||
await native.prepareNativeMode('user','plans');native.nativeMode('user','plans');
|
||||
const common=[...document.querySelectorAll('[data-fuc-native]')].filter(n=>!n.href.includes('/page/shop.css'));
|
||||
const dark=document.getElementById('native-dark'),bridge=document.getElementById('native-bridge');moved.length=0;
|
||||
await native.prepareNativeMode('user','wallet');native.nativeMode('user','wallet');
|
||||
assert.ok(common.length>5);assert.ok(common.every(n=>n.isConnected&&n.media==='all'));
|
||||
assert.equal(document.getElementById('native-dark'),dark);assert.equal(document.getElementById('native-bridge'),bridge);
|
||||
assert.deepEqual(moved,[],'reparenting loaded LINKs can unload CSS and flash an unstyled page');
|
||||
const before=[...document.querySelectorAll('[data-fuc-native]')];
|
||||
const changing=native.prepareNativeMode('auth','login');assert.ok(before.every(n=>n.isConnected&&n.media==='all'));
|
||||
await changing;native.nativeMode('auth','login');
|
||||
assert.ok(before.every(n=>!n.isConnected));
|
||||
const styles=JSON.parse(await fs.readFile(new URL('../../theme/Fuc/assets/native/styles.json',import.meta.url),'utf8'));
|
||||
assert.deepEqual([...document.querySelectorAll('[data-fuc-native]')].map(n=>n.href.split('/native/')[1].split('?')[0]),styles.login.map(p=>p.split('?')[0]));
|
||||
assert.equal([...document.querySelectorAll('link[rel=stylesheet]')].at(-1),bridge,'overrides keep their position after the native CSS');
|
||||
}finally{document.head.append=append;document.head.insertBefore=insert;}
|
||||
});
|
||||
test('wallet-funded checkout and history show package value instead of zero online remainder',()=>{
|
||||
const order={trade_no:'synthetic-wallet-order',status:3,total_amount:0,balance_amount:10000,surplus_amount:0,surplus_credit:0,period:'month_price',plan:{name:'Synthetic plan'},created_at:1};
|
||||
const context={user:{},sub:{},data:order,methods:[],config:{}};
|
||||
const detail=new DOMParser().parseFromString(native.nativeSecondary('checkout',context),'text/html');
|
||||
assert.match(detail.querySelector('[data-order-settlement]').textContent,/套餐价格:.*100\.00/);
|
||||
assert.match(detail.querySelector('[data-order-settlement]').textContent,/钱包抵扣:.*100\.00/);
|
||||
const history=new DOMParser().parseFromString(native.nativeSecondary('orders',{...context,data:[order]}),'text/html');
|
||||
assert.match(history.querySelector('tbody tr').textContent,/100\.00/);
|
||||
|
||||
});
|
||||
test('purchase preview keeps list price but leaves final VIP/coupon/balance settlement to native order',()=>{
|
||||
const html=native.nativeSecondary('purchase',{user:{vip:{enabled:true,name:'小福',discount_percent:8}},sub:{},data:{id:167,name:'Synthetic',month_price:10000},period:'month_price',config:{}});
|
||||
const view=new DOMParser().parseFromString(html,'text/html');
|
||||
assert.equal(view.querySelector('#product-buy-total').textContent,'下单后确认');
|
||||
assert.match(view.body.textContent,/100\.00/);assert.doesNotMatch(view.body.textContent,/小福|9\.2 折/);
|
||||
assert.match(view.querySelector('[data-order-price-notice]').textContent,/取消未支付订单可退回已抵扣余额/);
|
||||
});
|
||||
test('zero online remainder needs no channel and cancelled wallet deduction is labelled returned',()=>{
|
||||
const context={user:{},sub:{},data:{trade_no:'synthetic',status:0,total_amount:0,balance_amount:9200,plan:{name:'Synthetic'},period:'month_price'},methods:[],config:{}};
|
||||
let view=new DOMParser().parseFromString(native.nativeSecondary('checkout',context),'text/html');
|
||||
assert.equal(view.querySelector('select[name=method]'),null);
|
||||
assert.equal(view.querySelector('[data-form=checkout] button[type=submit]').textContent,'确认开通');
|
||||
assert.equal(view.querySelector('[data-form=checkout] button[type=submit]').disabled,false);
|
||||
view=new DOMParser().parseFromString(native.nativeSecondary('checkout',{...context,data:{...context.data,status:2}}),'text/html');
|
||||
assert.match(view.querySelector('[data-order-settlement]').textContent,/原钱包抵扣(已退回)/);
|
||||
});
|
||||
test('discounted checkout formats fixed and percentage coupons without changing the native amount due',()=>{
|
||||
const context={user:{vip:{levels:[{name:'小福',discount:8}]}},sub:{},asModal:true,data:{trade_no:'synthetic-discount',status:0,period:'month_price',total_amount:404,balance_amount:500,discount_amount:296,coupon_id:1,plan:{name:'Synthetic'}},discountBreakdown:{original_amount:1200,member_amount:96,coupon_amount:200,member_percent:8,coupon_code:'FUCUI2',coupon_type:1},methods:[{id:17,name:"微信",payment:"Epay"},{id:21,name:"支付宝",payment:"Epay"}],config:{}};
|
||||
const view=new DOMParser().parseFromString(native.nativeSecondary('checkout',context),'text/html');
|
||||
const text=view.querySelector('[data-order-settlement]').textContent;
|
||||
assert.match(text,/套餐价格:.*12\.00/);
|
||||
assert.match(text,/小福:-8%优惠码:-¥2\.00优惠合计:-¥2\.96/);
|
||||
assert.equal(view.querySelector('[data-order-settlement] > [data-settlement-divider]').textContent,'优惠合计:-¥2.96');
|
||||
assert.match(text,/钱包抵扣:.*5\.00/);assert.match(text,/还需支付:.*4\.04/);
|
||||
assert.equal(view.querySelector('#fuc-checkout-modal details'),null);
|
||||
const pay=view.querySelector('[data-form=checkout] button[type=submit]');
|
||||
assert.equal(pay.textContent,'在线支付');
|
||||
assert.equal(pay.disabled,false);
|
||||
assert.equal(view.querySelectorAll('input[name=method]').length,2);
|
||||
const checkout=coupon_type=>native.nativeSecondary('checkout',{...context,discountBreakdown:{...context.discountBreakdown,coupon_type}});
|
||||
assert.match(new DOMParser().parseFromString(checkout(2),'text/html').querySelector('[data-order-settlement]').textContent,/优惠码:-16\.67%/);
|
||||
assert.match(new DOMParser().parseFromString(checkout(null),'text/html').querySelector('[data-order-settlement]').textContent,/优惠码:-¥2\.00/);
|
||||
});
|
||||
test('package amount uses only consumed old-plan credit and displays channel fees separately',()=>{
|
||||
const context={user:{},sub:{},data:{trade_no:'synthetic',status:3,total_amount:2500,balance_amount:1000,surplus_amount:3000,surplus_credit:1500,handling_amount:125,plan:{name:'Synthetic'},period:'month_price'},methods:[],config:{}};
|
||||
const view=new DOMParser().parseFromString(native.nativeSecondary('checkout',context),'text/html');
|
||||
assert.match(view.querySelector('[data-order-settlement]').textContent,/套餐价格:.*50\.00/);
|
||||
const settlement=view.querySelector('[data-order-settlement]').textContent;
|
||||
assert.match(settlement,/旧套餐折抵:.*15\.00/);assert.match(settlement,/渠道手续费:.*1\.25/);assert.match(settlement,/折抵返余:.*15\.00/);
|
||||
});
|
||||
test('VIP uses the original dashboard card without the removed upgrade hint',()=>{
|
||||
const user={email:'[email protected]',vip:{enabled:true,name:'小福',cumulative_cents:10000,discount_percent:8,next_level:{name:'中福'},remaining_cents:10000}};
|
||||
const host=document.createElement('div');host.innerHTML=native.nativeDashboard(user,{plan_id:1,plan:{name:'套餐'},transfer_enable:100,u:0,d:0,expired_at:2000000000},[],'福云',v=>v);
|
||||
const card=host.querySelector('.card-stats .col');assert.equal(card.querySelector('span.h3').textContent,'小福');assert.match(card.textContent,/累计支付:¥ 100.00/);assert.equal(card.querySelector('[data-vip-progress]'),null);
|
||||
const off=document.createElement('div');off.innerHTML=native.nativeDashboard({email:'[email protected]'},{plan:{name:'套餐'}},[],'福云',v=>v);assert.equal(off.querySelector('[data-vip-progress]'),null);
|
||||
});
|
||||
test('payment HTML rebuild excludes scripts, handlers and unsafe actions',()=>{
|
||||
const form=paymentForm('<form action="https://pay.example.test/checkout" method="post" onsubmit="bad()"><input name="signature" value="signed"><input name="bad" type="file"><script>bad()</script></form>');
|
||||
assert.equal(form.method,'post');assert.equal(form.target,'_self');assert.equal(form.querySelector('[name=signature]').value,'signed');
|
||||
assert.equal(form.querySelector('script,[onsubmit],input[type=file]'),null);
|
||||
assert.throws(()=>paymentForm('<form action="javascript:bad()"></form>'));
|
||||
assert.throws(()=>paymentForm('<form action="https://u:[email protected]/"></form>'));
|
||||
});
|
||||
test('checkout submits a rebuilt provider form directly without running response HTML',async t=>{
|
||||
const container=document.createElement('div');
|
||||
const sent=[];
|
||||
t.mock.method(window.HTMLFormElement.prototype,'submit',function(){
|
||||
assert.ok(this.isConnected);
|
||||
sent.push([this.action,this.method,this.target,this.querySelector('[name=signature]').value]);
|
||||
});
|
||||
assert.equal(await showPayment({type:1,data:'<form action="https://pay.example.test/checkout" method="post"><input name="signature" value="signed"><script>bad()</script></form>'},container),false);
|
||||
assert.deepEqual(sent,[['https://pay.example.test/checkout','post','_self','signed']]);
|
||||
assert.equal(container.childElementCount,0);
|
||||
assert.equal(await showPayment({type:-1,data:true},container),true);
|
||||
});
|
||||
test('copy succeeds with original HTTP fallback, cleans selection field and prefers modern clipboard',async()=>{
|
||||
let copied='';document.execCommand=action=>{assert.equal(action,'copy');copied=document.activeElement.value;return true;};
|
||||
await copyText('synthetic local link',{clipboard:undefined,document});
|
||||
assert.equal(copied,'synthetic local link');assert.equal(document.querySelector('textarea'),null);
|
||||
await copyText('modern local link',{clipboard:{writeText:async value=>copied=value},document});
|
||||
assert.equal(copied,'modern local link');delete document.execCommand;
|
||||
});
|
||||
test('knowledge Markdown renders tables and safe links after native template binding',()=>{
|
||||
const html=native.nativeSecondary('article',{user:{},sub:{},data:{title:'Guide',body:'## Guide\n\n[Documentation](https://docs.example.test/)\n\n| A | B |\n| - | - |\n| 1 | 2 |\n\n<img src="https://img.example.test/a.png" onerror="bad()"><script>bad()</script>'},richText,config:{}});
|
||||
const view=new DOMParser().parseFromString(html,'text/html');
|
||||
assert.equal(view.querySelector('[data-fuc-richtext] a').href,'https://docs.example.test/');
|
||||
assert.ok(view.querySelector('[data-fuc-richtext] table'));
|
||||
assert.equal(view.querySelector('script,[onerror]'),null);
|
||||
assert.equal(view.querySelector('[data-fuc-richtext] img').src,'https://img.example.test/a.png');
|
||||
});
|
||||
test('home shows only actual plans, with real available period and zero price',()=>{
|
||||
const html=native.nativeHome([{name:'Annual',year_price:12000,transfer_enable:10},{name:'Free',month_price:0,transfer_enable:1}],'QA');
|
||||
const view=new DOMParser().parseFromString(html,'text/html');
|
||||
assert.equal(view.querySelectorAll('#pricing .pricing').length,2);
|
||||
assert.match(view.querySelectorAll('.pricing-price')[0].textContent,/120.00.*年付/s);
|
||||
assert.match(view.querySelectorAll('.pricing-price')[1].textContent,/0.00.*月付/s);
|
||||
assert.equal(new DOMParser().parseFromString(native.nativeHome([],'QA'),'text/html').querySelectorAll('#pricing .pricing').length,0);
|
||||
const loggedIn=new DOMParser().parseFromString(native.nativeHome([],'QA',true),'text/html');assert.equal(loggedIn.querySelector('.nav-btn').getAttribute('href'),'#/dashboard');assert.match(loggedIn.querySelector('.nav-btn').textContent,/用户中心/);
|
||||
});
|
||||
test('community link comes from XB config and never inherits the FUC channel',()=>{
|
||||
const parse=config=>new DOMParser().parseFromString(native.nativeHeader({},'QA','dashboard',config),'text/html');
|
||||
const link=doc=>[...doc.querySelectorAll('a')].find(n=>n.textContent.includes('加入 Telegram'));
|
||||
assert.equal(link(parse({})).hasAttribute('href'),false);
|
||||
const configured=link(parse({telegram_discuss_link:'https://t.me/example_test_channel'}));
|
||||
assert.equal(configured.href,'https://t.me/example_test_channel');assert.equal(configured.hasAttribute('data-action'),false);
|
||||
assert.equal(link(parse({telegram_discuss_link:'javascript:alert(1)'})).hasAttribute('href'),false);
|
||||
});
|
||||
test('panel settings retain saved palette, mode and collapsed menu after template serialization',()=>{
|
||||
localStorage.setItem('fuc_themeLight','cyan');localStorage.setItem('fuc_themeMod','dark');localStorage.setItem('fuc_menuToggle','close');
|
||||
try{const view=new DOMParser().parseFromString(native.nativeHeader({},'QA','plans'),'text/html');
|
||||
assert.equal(view.querySelector('#themeLight').value,'cyan');assert.deepEqual([...view.querySelector('#themeLight').options].map(o=>[o.value,o.textContent.trim()]),[['cyan','绿色'],['purple','紫色']]);assert.equal(view.querySelector('#themeDark').value,'purple');assert.equal(view.querySelector('.season-palette-options'),null);assert.equal(view.querySelector('#themeMod').value,'dark');assert.equal(view.querySelector('#menuToggle').value,'close');
|
||||
assert.ok(view.querySelector('.dropdown-user .dropdown-menu [data-target="#panel-option-modal"]'),'mobile users can open panel settings from their account menu');
|
||||
}finally{localStorage.clear();}
|
||||
});
|
||||
test('native header restores the original light/dark menu scheme without conflicting classes',()=>{
|
||||
try{for(const mode of ['light','dark']){
|
||||
document.documentElement.dataset.color=mode;const view=new DOMParser().parseFromString(native.nativeHeader({},'QA','plans'),'text/html'),menu=view.querySelector('.main-menu');
|
||||
assert.equal(menu.classList.contains('menu-light'),mode==='light');assert.equal(menu.classList.contains('menu-dark'),mode==='dark');
|
||||
}}finally{delete document.documentElement.dataset.color;}
|
||||
});
|
||||
test('auth removes unsupported 2FA and optional verification without weakening required fields',()=>{
|
||||
const login=new DOMParser().parseFromString(native.nativeAuth('login','QA',{}),'text/html');
|
||||
assert.equal(login.querySelector('[id="2fa-form"]'),null);assert.equal(login.querySelector('[name=password]').required,true);
|
||||
for(const required of [0,1]){const view=new DOMParser().parseFromString(native.nativeAuth('register','QA',{is_email_verify:required}),'text/html');assert.equal(!!view.querySelector('[name=email_code]'),!!required);}
|
||||
});
|
||||
test('dashboard retains source empty-subscription state and profile does not invent FUC user level',()=>{
|
||||
const view=new DOMParser().parseFromString(native.nativeDashboard({},{},[],'QA',richText,[]),'text/html');
|
||||
assert.equal(view.querySelector('#donut-chart').hidden,true);assert.match(view.body.textContent,/无可用流量/);
|
||||
assert.ok(view.querySelector('[data-action=subscription-unavailable]'));
|
||||
const checkin=view.querySelector('button[title="本站未开放签到"]');assert.equal(checkin.disabled,true);assert.doesNotMatch(checkin.textContent,/已签到/);
|
||||
const profile=new DOMParser().parseFromString(native.nativeSecondary('profile',{sub:{plan:{name:'Long plan is not an account level'}},richText}),'text/html');
|
||||
assert.equal(profile.querySelector('.card-profile-stats .heading').textContent,'—');
|
||||
});
|
||||
test('the dashboard enables each Nyanpasu download against the configured Resource origin',()=>{
|
||||
const render=origin=>new DOMParser().parseFromString(native.nativeDashboard({},{},[],'QA',richText,null,origin),'text/html');
|
||||
const links=view=>[...view.querySelectorAll('[data-nyanpasu-package]')];
|
||||
assert.ok(links(render('')).every(link=>link.href.startsWith('https://github.com/libnyanpasu/clash-nyanpasu/releases/download/')));
|
||||
const connected=links(render('http://resource.loc:8612'));
|
||||
assert.deepEqual(connected.map(link=>link.getAttribute('href')),[
|
||||
'http://resource.loc:8612/downloads/software/clash-nyanpasu/clash-nyanpasu-windows-x64.exe',
|
||||
'http://resource.loc:8612/downloads/software/clash-nyanpasu/clash-nyanpasu-macos-arm64.dmg',
|
||||
'http://resource.loc:8612/downloads/software/clash-nyanpasu/clash-nyanpasu-macos-x64.dmg',
|
||||
]);
|
||||
assert.ok(connected.every(link=>!link.hasAttribute('data-action')));
|
||||
});
|
||||
test('shop mirrors source plan-group tabs with period cards and original purchase modals',()=>{
|
||||
const plans=[{id:1,name:'轻量套餐',month_price:1200,year_price:12000,reset_price:500,transfer_enable:100},{id:2,name:'标准套餐',month_price:0,transfer_enable:10}];
|
||||
const html=native.nativeSecondary('plans',{user:{plan_id:2},sub:{},data:plans,period:'plan-1',richText,config:{}});
|
||||
const view=new DOMParser().parseFromString(html,'text/html');
|
||||
assert.deepEqual([...view.querySelectorAll('.shop_tab span')].map(n=>n.textContent),['轻量套餐','标准套餐']);
|
||||
const group=view.getElementById('top-home-plan-1');assert.equal(group.classList.contains('show'),true);
|
||||
assert.deepEqual([...group.querySelectorAll('[data-action=buy]')].map(n=>[n.dataset.id,n.dataset.period]),[['1','month_price'],['1','year_price']]);
|
||||
assert.equal(view.querySelector('#coupon_modal [name=coupon_code]').required,false);
|
||||
assert.equal(view.querySelector('#order_modal form').dataset.form,'purchase');
|
||||
assert.equal(view.querySelector('#pay-confirm').closest('[data-action]'),null,'submit must not inherit an unrelated banner action');
|
||||
native.fillPurchaseModal(view,plans[0],'year_price','QA');
|
||||
assert.match(view.querySelector('[data-confirm-plan-specs]').textContent,/套餐流量:100 GB/);
|
||||
assert.match(view.querySelector('[data-confirm-plan-specs]').textContent,/优惠码:QA/);
|
||||
assert.equal(view.querySelector('#order_modal [name=coupon_code]').value,'QA');
|
||||
assert.match(view.querySelector('#shop_time').textContent,/12 个月/);
|
||||
assert.equal(view.querySelector('#order_modal #autorenew'),null);
|
||||
assert.doesNotMatch(view.querySelector('#order_modal').textContent,/自动续订|从本地钱包扣费/);
|
||||
assert.doesNotMatch(view.querySelector('.selling-slide').textContent,/—GB|满—元/);
|
||||
assert.match(group.querySelector('.pricing-content').textContent,/跟随系统设置/);
|
||||
});
|
||||
test('captcha contracts cover Turnstile, v2, v3, expiration and disposal with SDK doubles',async()=>{
|
||||
const {createCaptcha}=await import('../../theme/Fuc/assets/captcha.mjs');
|
||||
const original=document.head.append.bind(document.head);document.head.append=node=>{original(node);queueMicrotask(()=>node.onload?.());};
|
||||
try{
|
||||
for(const [type,key,field] of [['turnstile','turnstile_site_key','turnstile_token'],['recaptcha','recaptcha_site_key','recaptcha_data'],['recaptcha-v3','recaptcha_v3_site_key','recaptcha_v3_token']]){
|
||||
let callbacks;const sdk={ready:fn=>fn(),render:(el,options)=>{callbacks=options;return 0;},execute:async()=> 'synthetic-token',reset:()=>{},remove:()=>{}};
|
||||
window.turnstile=sdk;window.grecaptcha=sdk;
|
||||
const container=document.createElement('div');document.body.append(container);
|
||||
const captcha=createCaptcha({is_captcha:1,captcha_type:type,[key]:'test-key'},container);
|
||||
if(type!=='recaptcha-v3'){await assert.rejects(captcha.payload(),/请先完成/);callbacks.callback('synthetic-token');}
|
||||
assert.deepEqual(await captcha.payload(),{[field]:'synthetic-token'});
|
||||
if(callbacks){callbacks['expired-callback']();await assert.rejects(captcha.payload(),/请先完成/);}
|
||||
captcha.dispose();await assert.rejects(captcha.payload(),/页面已切换/);container.remove();
|
||||
}
|
||||
}finally{document.head.append=original;}
|
||||
});
|
||||
test('Stripe hosted card tokenization passes only SDK token and destroys card',async()=>{
|
||||
const {mountCard}=await import('../../theme/Fuc/assets/payments.mjs');let destroyed=false;
|
||||
const original=document.head.append.bind(document.head);document.head.append=node=>{original(node);queueMicrotask(()=>node.onload?.());};
|
||||
window.Stripe=()=>({elements:()=>({create:()=>({mount:()=>{},destroy:()=>destroyed=true})}),createToken:async()=>({token:{id:'tok_test_only'}})});
|
||||
const container=document.createElement('div');document.body.append(container);
|
||||
try{const card=await mountCard(async()=> 'pk_test_fixture',1,container);assert.equal(await card.token(),'tok_test_only');card.dispose();assert.equal(destroyed,true);}finally{document.head.append=original;container.remove();}
|
||||
});
|
||||
@@ -18,6 +18,8 @@ function source($path) {
|
||||
$text=preg_replace('/<!--.*?-->/s','',$text);
|
||||
$text=preg_replace('/<script\b[^>]*>.*?<\/script>/is','',$text);
|
||||
$text=str_replace("{include file='brand/head.tpl'}",file_get_contents('/Users/hellcat/Documents/GemCodes/fuc-new.loc/resources/views/tabler/brand/head.tpl'),$text);
|
||||
// XB has no automatic-renewal quote. Keep this optional source include inert.
|
||||
$text=preg_replace("/^[\\t ]*\\{include file='user\\/plan\\/renewal_quote\\.tpl'\\}[\\t ]*$/m",'',$text);
|
||||
$text=preg_replace('/\{include[^}]*\}/','',$text);
|
||||
// Keep the data output branch, without comparing placeholder strings.
|
||||
$text=preg_replace('/\{if \$user->LastusedTrafficPercent\(\) < \'1\'\}.*?\{else\}(.*?)\{\/if\}/s','$1',$text);
|
||||
@@ -96,6 +98,7 @@ foreach($pages as $name=>$file){
|
||||
// CSS uses braces; Smarty auto-literal handles them unchanged.
|
||||
$html=$smarty->fetch('string:'.$text);
|
||||
recordOriginal($name??$file,$html);
|
||||
if(in_array($name,['plans','purchase'],true))$html=str_replace(['__P_PERIOD__天','__P_PERIOD__ 天'],'__P_PERIOD__',$html);
|
||||
if(str_contains($html,'Warning:'))throw new Exception("template warning: $name");
|
||||
file_put_contents("$out/$name.html",$html);echo "$name extracted\n";
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ DOMAIN='xb.loc'
|
||||
HOSTS=Path('/etc/hosts')
|
||||
CONF=Path('/usr/local/etc/nginx/servers/xb.loc.conf')
|
||||
NGINX='/usr/local/bin/nginx'
|
||||
CONTENT='''# Isolated XB Fuc theme preview. Synthetic data only.
|
||||
CONTENT='''# Isolated XB Fuc theme preview. Dedicated Fuc acceptance instance; no DPL/HN data.
|
||||
server {
|
||||
listen 127.0.0.1:80;
|
||||
listen [::1]:80;
|
||||
@@ -45,6 +45,6 @@ def main():
|
||||
if had_conf:shutil.copy2(backup/'xb.loc.conf',CONF)
|
||||
else:CONF.unlink()
|
||||
raise
|
||||
print('Configured http://xb.loc -> local synthetic preview on 8594; verify HTTP separately.')
|
||||
print('Configured http://xb.loc -> isolated local XB acceptance instance on 8594; verify HTTP separately.')
|
||||
print('Recovery files:',backup)
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
// Isolated acceptance environment. Uses the real XB kernel, routes and services.
|
||||
// Never loads DPL/HN environment or sends external mail, payments or notifications.
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$root=dirname(__DIR__,2);
|
||||
$dir=$root.'/instances/fuc-acceptance';
|
||||
if (!is_file($dir.'/.fuc-acceptance')) throw new RuntimeException('Run integration-setup.php first');
|
||||
$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-acceptance';putenv('XB_INSTANCE=fuc-acceptance');
|
||||
$app=require $root.'/bootstrap/app.php';
|
||||
$app->beforeBootstrapping(Illuminate\Foundation\Bootstrap\RegisterProviders::class,function($app)use($dir){
|
||||
$app['config']->set([
|
||||
'app.env'=>'testing','app.debug'=>false,'app.url'=>'http://xb.loc',
|
||||
'database.default'=>'sqlite','database.connections.sqlite.database'=>$dir.'/database/acceptance.sqlite',
|
||||
'cache.default'=>'file','cache.stores.redis'=>['driver'=>'file','path'=>$dir.'/storage/framework/cache/redis'],
|
||||
'session.driver'=>'file','queue.default'=>'sync','mail.default'=>'array',
|
||||
'site.theme'=>'Fuc','site.name'=>'Fuc 验收站','site.admin_only_plan_ids'=>[],
|
||||
]);
|
||||
});
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
Illuminate\Support\Facades\Http::preventStrayRequests();
|
||||
Illuminate\Support\Facades\Queue::fake()->except([App\Jobs\OrderHandleJob::class]);
|
||||
Illuminate\Support\Facades\Mail::fake();
|
||||
return $app;
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
$app=require __DIR__.'/integration-bootstrap.php';
|
||||
$email=$argv[1]??'';
|
||||
if(!preg_match('/^qa-[0-9]+@example\.test$/D',$email))throw new RuntimeException('Only generated local acceptance accounts allowed');
|
||||
App\Models\User::byEmail($email)->update(['commission_balance'=>2000]);
|
||||
$suffix=explode('@',$email)[0];
|
||||
App\Models\Coupon::firstOrCreate(['code'=>$suffix],['name'=>'Local QA coupon','type'=>1,'value'=>100,'show'=>true,'started_at'=>time()-60,'ended_at'=>time()+86400,'limit_plan_ids'=>[1]]);
|
||||
$template=App\Models\GiftCardTemplate::firstOrCreate(['name'=>'Local QA balance'],['type'=>1,'status'=>true,'rewards'=>['balance'=>500],'admin_id'=>0]);
|
||||
App\Models\GiftCardCode::firstOrCreate(['code'=>$suffix],['template_id'=>$template->id,'status'=>0,'max_usage'=>1]);
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
// Read only a code generated by this isolated test, never a real mailbox.
|
||||
$app=require __DIR__.'/integration-bootstrap.php';
|
||||
$email=$argv[1]??'';
|
||||
if(!preg_match('/^qa-[0-9]+@example\.test$/D',$email))throw new RuntimeException('Only generated local acceptance accounts allowed');
|
||||
echo Illuminate\Support\Facades\Cache::get(App\Utils\CacheKey::get('EMAIL_VERIFY_CODE',$email));
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
// Loopback only, disposable acceptance instance, not a production entry point.
|
||||
$path=parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH);
|
||||
if(str_starts_with($path,'/theme/Fuc/assets/')){
|
||||
$base=realpath(__DIR__.'/../../theme/Fuc/assets');$file=realpath($base.'/'.substr(rawurldecode($path),strlen('/theme/Fuc/assets/')));
|
||||
if(!$file||!str_starts_with($file,$base.'/')||!is_file($file)){http_response_code(404);exit;}
|
||||
$types=['mjs'=>'text/javascript','js'=>'text/javascript','css'=>'text/css','html'=>'text/html','json'=>'application/json','svg'=>'image/svg+xml','png'=>'image/png','jpg'=>'image/jpeg','woff2'=>'font/woff2','woff'=>'font/woff'];
|
||||
header('Content-Type: '.($types[pathinfo($file,PATHINFO_EXTENSION)]??'application/octet-stream'));header('Cache-Control: no-store');readfile($file);exit;
|
||||
}
|
||||
if($path!=='/'&&!str_starts_with($path,'/api/v1/')&&!str_starts_with($path,'/api/v2/')&&$path!=='/fuc-qa-admin'&&$path!=='/fuc-qa-admin/customer-service'&&!str_starts_with($path,'/customer-service/')&&!str_starts_with($path,'/admin-custom/')&&!str_starts_with($path,'/assets/admin/')&&!preg_match('#^/s/[a-f0-9]+$#D',$path)){http_response_code(404);exit;}
|
||||
if (($path !== '/customer-service/status' && str_starts_with($path, '/customer-service/')) || str_starts_with($path, '/admin-custom/') || str_starts_with($path, '/assets/admin/')) {
|
||||
$base=realpath(__DIR__.'/../../public'); $file=realpath($base.$path);
|
||||
if(!$file || !str_starts_with($file,$base.'/') || !is_file($file)){http_response_code(404);exit;}
|
||||
$types=['mjs'=>'text/javascript','js'=>'text/javascript','css'=>'text/css','json'=>'application/json','svg'=>'image/svg+xml','woff2'=>'font/woff2'];
|
||||
header('Content-Type: '.($types[pathinfo($file,PATHINFO_EXTENSION)]??'application/octet-stream'));readfile($file);exit;
|
||||
}
|
||||
$app=require __DIR__.'/integration-bootstrap.php';
|
||||
$kernel=$app->make(Illuminate\Contracts\Http\Kernel::class);
|
||||
$request=Illuminate\Http\Request::capture();$response=$kernel->handle($request);$response->send();$kernel->terminate($request,$response);
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
$app=require __DIR__.'/integration-bootstrap.php';
|
||||
use App\Models\{User,Plan,Notice,Knowledge};
|
||||
use Illuminate\Support\Facades\DB;
|
||||
if(User::count())throw new RuntimeException('Instance is already seeded');
|
||||
admin_setting(['app_name'=>'Fuc 验收站','app_url'=>'http://xb.loc','frontend_theme'=>'Fuc','secure_path'=>'fuc-qa-admin','captcha_enable'=>0,'email_verify'=>0,'telegram_bot_enable'=>0,'commission_withdraw_method'=>['支付宝','USDT'],'commission_withdraw_limit'=>1,'mail_flow'=>['enabled'=>false],'safe_mode_enable'=>0]);
|
||||
$group=DB::table('v2_server_group')->insertGetId(['name'=>'验收组','created_at'=>time(),'updated_at'=>time()]);
|
||||
$plan=Plan::create(['name'=>'本地验收月付','group_id'=>$group,'prices'=>['monthly'=>12,'yearly'=>120,'reset_traffic'=>5],'transfer_enable'=>100,'capacity_limit'=>null,'show'=>true,'sell'=>true,'renew'=>true,'content'=>'<p>真实 XB 接口验收套餐</p>']);
|
||||
$free=Plan::create(['name'=>'本地零元开通验收','group_id'=>$group,'prices'=>['monthly'=>0],'transfer_enable'=>10,'capacity_limit'=>null,'show'=>true,'sell'=>true,'renew'=>true]);
|
||||
$user=User::create(['email'=>'[email protected]','password'=>password_hash('Fuc-QA-Only-2026!',PASSWORD_DEFAULT),'uuid'=>(string)Illuminate\Support\Str::uuid(),'token'=>bin2hex(random_bytes(16)),'balance'=>0,'commission_balance'=>2000]);
|
||||
Notice::create(['title'=>'Fuc 真实接口验收','content'=>'<p>本页面读取独立 SQLite 中的 XB 数据。</p>','show'=>1]);
|
||||
Knowledge::create(['title'=>'配置指南','category'=>'使用说明','language'=>'zh-CN','body'=>"## 订阅导入\n\n使用个人订阅链接:{{subscribeUrl}}\n\n| 客户端 | 状态 |\n| --- | --- |\n| Clash | 支持 |",'show'=>1]);
|
||||
echo "Seeded isolated account, two plans, notice and knowledge; no live data copied.\n";
|
||||
@@ -0,0 +1,15 @@
|
||||
// Node absorbs speculative idle browser connections; one PHP kernel remains isolated.
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
const root=fileURLToPath(new URL('../../',import.meta.url));
|
||||
for(const port of [8594,8595])await new Promise((resolve,reject)=>{const probe=net.createServer();probe.once('error',reject);probe.listen(port,'127.0.0.1',()=>probe.close(resolve));});
|
||||
const php=spawn('/usr/local/bin/php',['-S','127.0.0.1:8595',root+'scripts/theme-fuc/integration-router.php'],{cwd:root,stdio:['ignore','ignore','ignore']});
|
||||
const server=http.createServer((req,res)=>{
|
||||
const upstream=http.request({hostname:'127.0.0.1',port:8595,path:req.url,method:req.method,headers:{...req.headers,connection:'close'},agent:false},response=>{res.writeHead(response.statusCode,response.headers);response.pipe(res);});
|
||||
upstream.setTimeout(30000,()=>upstream.destroy());upstream.on('error',()=>{if(!res.headersSent)res.writeHead(502);res.end('Acceptance backend unavailable');});req.on('aborted',()=>upstream.destroy());req.pipe(upstream);
|
||||
});
|
||||
let stopping=false;function stop(){if(stopping)return;stopping=true;server.close();server.closeAllConnections();php.kill();}
|
||||
process.on('SIGINT',stop);process.on('SIGTERM',stop);php.on('exit',stop);php.on('error',stop);server.on('error',stop);
|
||||
server.listen(8594,'127.0.0.1',()=>console.log('Fuc isolated XB acceptance: loopback 8594; no live data.'));
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user