63 Commits
Author SHA1 Message Date
admin 697d4e83bf fix(shell): 输入框文字没有垂直居中 —— 上一版我删错了 DuiLib 的那几行
Docker Build / Build and Push Docker Image (push) Successful in 34s
Docker Build / Deploy to Server (push) Successful in 3s
上一版为了消掉「输入框里嵌一条黑带」把 CalPos 里这段删了:

    LONG lEditHeight = ...->tm.tmHeight;
    if( lEditHeight < rcPos.GetHeight() ) {
        rcPos.top += (rcPos.GetHeight() - lEditHeight) / 2;
        rcPos.bottom = rcPos.top + lEditHeight;
    }

理由是「单行 EDIT 会自己垂直居中文字」—— **这是错的**。删掉之后原生 EDIT 铺满
控件,文字直接贴顶。主人一眼就看出来了。

## 改对了的做法:位置和背景分开治

- **CalPos**:恢复这段高度限制,原生窗口仍取字体行高、在控件里垂直居中
- **WM_CTLCOLOREDIT**:不再给原生窗口刷背景,一律返回 HOLLOW_BRUSH +
  SetBkMode(TRANSPARENT) 让它完全透明

这样原生窗口虽然只盖中间一条,但它透明 → 底下是 CEditUI 自绘的 bkcolor 整块
铺满控件,不存在「露出父窗口底色」的问题;文字位置又由 CalPos 保证居中。
两个要求同时满足。

## DuiLib 源码建了仓库

`admin/duilib`(私有,Gitea),master 分支,含:
- mingw 交叉编译适配(shim/ 兼容层、控件裁剪、类型宏适配)
- 本次的 UIEdit 修复

上游仍是 github.com/duilib/duilib,历史完整(185 个提交,原来是 --depth 1 浅克隆,
push 被 `shallow update not allowed` 拒了,`git fetch --unshallow` 补全后才推上去)。

`shell/duilib/patches/` 里留了 65 行补丁 + 说明,不想 clone 整个仓库时直接 git apply。

## 实测(classic 皮肤,像素取色)

```
输入框蓝框 y=128~167,框中心 147.5
文字行   y=143~152,文字中心 147.5
偏移 +0.0px → 完全垂直居中
纯黑带子行数: 0
```
2026-11-29 18:23:27 +08:00
admin 689586c547 fix(shell): 输入框聚焦后嵌入黑带子 / 占不满 —— 改 DuiLib 的 CalPos
Docker Build / Build and Push Docker Image (push) Successful in 34s
Docker Build / Deploy to Server (push) Successful in 2s
现象:点输入框聚焦后,框内出现一条更黑的带子,而且占不满输入框
(截图里 40px 高的框,只有中间 16px 是那条带子)。

## 根因

老 DuiLib 的 <Edit> 是「真 EDIT 子窗口」:不聚焦时 DuiLib 自绘,聚焦后叠一个
原生 EDIT 上去。原生窗口位置由 CEditWnd::CalPos() 算,原代码把它的高度压成了
字体行高:

    LONG lEditHeight = GetFontInfo(...)->tm.tmHeight;   // ≈16px
    if (lEditHeight < rcPos.GetHeight()) {
        rcPos.top += (rcPos.GetHeight() - lEditHeight) / 2;
        rcPos.bottom = rcPos.top + lEditHeight;         // ← 压成 16px
    }

原生 EDIT 的背景刷(WM_CTLCOLOREDIT 返回的 m_hBkBrush)只覆盖自己那块,于是
上下各 8px 露出父窗口底色。深色皮肤输入框 #252526、窗口底 #1E1E1E,
看着就是「嵌了一条更黑的带子,还占不满」。

像素取证(classic 皮肤,输入框 y=128~164):
  改前  y=130~136 #252526 / y=139~154 #1E1E1E / y=157~163 #252526
  改后  y=128~166 全 #252526

## 改动

DuiLib 源码 DuiLib/Control/UIEdit.cpp(补丁存在 shell/duilib/patches/):

1. 去掉字体行高的高度限制 —— 单行 EDIT 本来就会自己垂直居中文字
2. 上下各留 2px 给聚焦边框让位。原生窗口 z-order 在上,压实了会把上下边框
   盖掉、只剩左右两条竖线(第一版改完就是这个症状,像素扫才看出来)

## 另一个兜底:SyncNativeEditBg()

XML 的 nativebkcolor 一旦解析失败(或皮肤漏写),GetNativeEditBkColor() 保持
默认 0xFFFFFFFF,WM_CTLCOLOREDIT 里 `if (clrColor == 0xFFFFFFFF) return 0;`
直接不设背景刷 → 同样会露出父窗口底色。

不去赌 XML:新增 SyncNativeEditBg() 把控件自己的 bkcolor 直接灌给原生窗口,
WM_CREATE 和 ApplyAppInfo 各调一次,两套颜色永远一致。

## 附带

- 新增 shell/duilib/patches/:DuiLib 改动补丁 + 应用说明。DuiLib 不在本仓库,
  改动不留痕的话下次重编库就丢了
- 64 位 libduilib 之前没有构建脚本,补了 /root/work/duilib-build64/build64.sh

## 实测(wine + 像素取色)

  黑带子 = 0 行
  输入框内文字像素 = 112
  聚焦蓝框 = 1832px,四边齐全(左40 右40 上422 下422)
2026-11-29 17:43:57 +08:00
admin 7d720bb65b fix(shell): split / terminal 的激活 tab 看不出选中
Docker Build / Build and Push Docker Image (push) Successful in 35s
Docker Build / Deploy to Server (push) Successful in 3s
把 8 套皮肤挨个加壳跑图核对,发现这两套的选中态基本没有:

## split

XML 里 tab 本来就是「分段按钮」样式(SEG_ACT 蓝底 / SEG_IDLE 浅灰底),
但 UpdateTabStyle 里写的是 bgMode = false —— 只改文字颜色、不改底色。
结果切 tab 时底色永远停在「登录」那格,只有文字从白变成 #4CC2FF 浅蓝,
蓝底 + 浅蓝字对比度极低,等于看不出来。

修:bgMode = true,actBg = #1B6FD6 / idleBg = #EBEFF6,actFg 白 / idleFg #5B6270。

## terminal

tab 是横排透明底,原来只靠文字色区分(亮绿 #7FE39B vs 暗绿 #4E7A5C),
选中态太弱。

修:改底色方案 —— 选中 #1B7A4E 深绿底 + #D7F5DF 亮绿字,未选透明 + 暗绿字。
(终端绿风格保留,只是加了块底色)

## 8 套逐个核对结果

| 皮肤 | 选中态方案 | 结论 |
|---|---|---|
| classic | #0E639C 下划线 | ✓ 实测切换正常 |
| dark | #4EA3E8 下划线 | ✓ 实测切换正常 |
| light | #1B6FD6 蓝底白字 | ✓ |
| split | #1B6FD6 蓝底白字 | ✓(本次修,改前是弱文字色) |
| card | 白底紫字 | ✓ |
| industrial | #1A5A8C 钢蓝底 | ✓ |
| terminal | #1B7A4E 绿底亮绿字 | ✓ 实测切换正常(本次修) |
| compact | #1C6142 绿底 | ✓ |

8 套标题栏全部显示「游戏盒子打包器」(加壳时写进 cfg 的 name),
正文蓝色大字均已隐藏。

注:split 在 wine 里点 tab 收不到 click 事件(classic / terminal 同一套
Notify 路径却能收到),应该是 wine 对这款布局的输入转发问题,
逻辑改动和其它皮肤共用 SwitchTab / UpdateTabStyle,真机待你复验。
2026-11-29 17:22:09 +08:00
admin d33f341192 fix(shell): classic 的 tab 焦点/颜色、应用名进标题栏
Docker Build / Build and Push Docker Image (push) Successful in 35s
Docker Build / Deploy to Server (push) Successful in 3s
用户截图报了四个问题,根因各不相同:

## 1. 「登录」的蓝色下划线永远不消失

classic / dark 皮肤里 tabLogin 下面那条下划线是**匿名 Control**(没有 name),
UpdateTabStyle 只认 lineLogin / lineRegister / lineCard / lineReset,
找不到 lineLogin 就永远保持 XML 里写的 TAB_ACT 色 → 那条线一直亮着。

修:生成脚本里给它 name="lineLogin"。

## 2. 切到「我的设备」后焦点还留在「登录」上

    void SwitchTab(int tab) {
        if (!strcmp(g_loginMode, "card") && tab == 1) { ShowManageDevices(); return; }

卡密模式下点「我的设备」直接进设备管理就 return 了,g_tab 没更新、
UpdateTabStyle 没调用 → 高亮留在上一页。

修:return 之前先把 g_tab 设成 1 并刷一次 tab 样式。

## 3. classic 的 tab 颜色不对

UpdateTabStyle 里没有 classic 分支,落到默认的 bgMode=true / 全 0 色,
tab 文字会被设成透明;下划线还写死成 dark 的 #4EA3E8,和 classic 的
#0E639C 不是一个色系。

修:加 classic 分支 + 引入 lineColor 变量,下划线颜色跟皮肤走
(classic #0E639C / dark #4EA3E8 / split #4CC2FF / terminal #7FE39B…);
非「下划线型」皮肤(light/card/industrial/compact 靠 tab 底色区分)一律清掉下划线。

## 4. 应用名应该在标题栏,不该在正文多一行

原来标题栏固定写「软件授权验证」,正文再用一行蓝色大字(lblApp)写应用名,
同一个信息说两遍还白占一行高度。

修:
- WM_CREATE 里把应用名写进 lblTitle,并隐藏 lblApp / lblBrand
- 窗口标题(任务栏/Alt-Tab)也用应用名
- ShowTabsAgain / ApplyAppInfo 同步改,别再把固定文案或正文那行放回去
- 设备管理页标题格式改成「应用名 · 设备管理」

## 顺带修掉一个会反复踩的坑

skins_v4.h 是脚本生成的,但脚本里标题 Label 没有 name="lblTitle" ——
原来那名字是手工补进 .h 的,一重新生成就丢了,代码 SetText 找不到控件,
标题栏永远显示 XML 里的固定文案。现在脚本里 8 套皮肤全部带 name="lblTitle";
另 4 套(split/industrial/terminal/compact)原本是装饰文案
(VFY / AUTHORIZATION / vfy@local:~$ auth / 账号中心),也统一挂上 lblTitle。

生成脚本也从 tmpfs 收进仓库:shell/duilib/scripts/gen_skins_v4.py,
输出路径改成跟着仓库走,不再写死 /root/.hermes/cache/scratch/...。

## 实测(wine + 像素取色,不看错觉)

- 标题栏文字读出「游戏盒子打包器」,正文无蓝色大字
- 下划线仅一条:y=86/87,x=20~103,颜色 #0E639C(深蓝,不是 #4EA3E8)
- 点「我的设备」后:下划线移到 x=104~187(第 2 个 tab),
  原「登录」那条消失 → 焦点正确跟随
2026-11-29 17:05:36 +08:00
admin c0fd361037 feat(protect): 皮肤预览改成真组件渲染,去掉「查看」按钮
Docker Build / Build and Push Docker Image (push) Successful in 1m3s
Docker Build / Deploy to Server (push) Successful in 3s
原来是 8 张 560×420 的 PNG 实拍图 + 一个「查看大图」按钮(全屏 lightbox)。
缺点很明显:改一点配色就要重跑壳、重新截图;放大了发虚;tab 点不动,
看不出「我的设备」「卡密充值」长什么样;按钮本身也是多余的点击。

新增 components/ThemePreview.vue:照着壳里的 DuiLib 皮肤用 HTML/CSS 重画,
配色直接对应 skins_v4.h 里每套皮肤的窗口底/标题栏/输入框/主按钮/文字色。

## 特点

- **tab 能点**:登录 / 我的设备 / 卡密充值 / 找回·绑定 各有对应内容,
  主按钮文案跟着变(卡密登录 → 绑定本机 → 卡密充值 → 找回密码)
- **比例按皮肤真实尺寸**:470×436 / 680×452 / 720×460 / 600×452 / 620×446 / 760×392
  用 aspect-ratio + 内部百分比布局,缩放不变形
- **任意尺寸清晰**,不用维护图片
- terminal 用等宽字体,classic 保留 VS Code 那套 #1E1E1E/#0E639C

## 页面改动

- `<img src="/theme-previews/*.png">` → `<ThemePreview :theme="shellTheme" />`
- 删掉「查看大图」按钮、图片上的 hover 放大层、ImageLightbox 组件、
  lightboxOpen / currentThemeLabel 状态、Eye / ZoomIn 图标导入
- 下拉框不再和按钮挤一行,独占左侧 max-w-xs

实测渲染 8 套(375px 卡片宽):元素齐全(标题栏+4tab+应用名+卡密框+主按钮+设备号)、
配色区分明显、无溢出重叠。前端 npm run build 30s 通过。

PNG 还留在 public/theme-previews 没删,要回退直接改回 <img> 即可。
2026-11-29 16:43:53 +08:00
admin f909aa002b fix(protect): 皮肤预览图从 672px 收窄到 448px,别再把右边填满
Docker Build / Build and Push Docker Image (push) Successful in 1m3s
Docker Build / Deploy to Server (push) Successful in 3s
ad65ca1 那次把预览图放宽到 max-w-2xl(672px)、下拉收窄到 max-w-xs(320px),
本意是让大图看得清,结果预览图右边缘离容器右边只剩 91px,上方下拉框+查看
按钮又只占左侧到中部 —— 视觉上就是「预览图把右边撑满了」。

实测容器 900px 时:
  改前  下拉 320px / 预览 672px / 预览右边缘距容器右边 91px
  改后  下拉 320px / 预览 448px / 预览右边缘距容器右边 315px

左边缘两版都和下拉框严格对齐(这一点没动)。

顺带补了两处防御:
- grid 列从 minmax(0,42rem) 改成 minmax(0,1fr)
- 第二列加 min-w-0(grid 子项默认 min-width:auto,会被宽内容撑破列宽)

448px 下 560×420 的实拍图仍然够看清界面元素,要 1:1 看细节走「查看大图」。
2026-11-29 16:22:45 +08:00
admin 6a51736f1f fix(protect): DogProtect 段加时间插值,进度条不再卡着不动
Docker Build / Build and Push Docker Image (push) Successful in 33s
Docker Build / Deploy to Server (push) Successful in 1s
实测加壳器那 4 秒里只吐两个进度点:

  进度序列 [85 100]

因为 dogprotect_con 只在 Packing 和 Saving startup code 各完成时输出 100%,
中间没有细粒度。前端拿到 45% 之后要干等 4 秒才跳到 90%,看着像卡死。

加一条按时间走的估算线:每 300ms 往前推,6 秒走完 88%,封顶 88% 停住等真
完成;真实进度(atomic realPct)一旦超过估算值就让位。估得准不准无所谓,
它只负责「看起来在动」。

改完实测:

  进度序列 [4 8 13 17 22 26 30 35 39 44 48 52 85]  (13 个点)

插值 goroutine 用 stopInterp channel 收尾,cmd.Wait() 之后 close 并等它退出,
不会泄漏。onProgress 只在插值 goroutine 里调用,主循环只写 atomic,没有并发
回调问题。
2026-11-29 15:51:43 +08:00
admin 43d9896628 feat(protect): 加壳页面改进度条,看得到卡在哪一步
Docker Build / Build and Push Docker Image (push) Successful in 1m4s
Docker Build / Deploy to Server (push) Successful in 2s
原来任务列表只有「加密中」三个字加一个转圈图标,DogProtect 那步要好几秒,
用户完全不知道是在干活还是卡死了。现在拆成四段实时进度:

  准备源文件 → 注入验证壳 → DogProtect 加壳 → 证书签名 → 写出产物

## 后端

- `protect_tasks` 加 `progress`(0-100) + `stage`(阶段 key) 两列,AutoMigrate 自动迁移
- `reportProgress()`:写库失败只打日志。进度是展示信息,不能因为它写不进去
  就把整个加壳任务判失败
- 带节流(`lastProgress` 记每个任务上次的百分比),加壳器逐行吐进度也不会把
  数据库写爆;任务收尾 `clearProgress` 清掉,长跑进程里这个 map 不会涨

阶段点分布:

```
  5%  prepare   读文件
 12%  shell     注入验证壳(快,毫秒级)
 45%  dogprotect  ← 最慢的一步
 90%             (DogProtect 内部 0-100 换算成这段,不会停在原地)
 92%  sign      证书签名
 97%  writing   写出产物
100%  done
```

**DogProtect 内部进度是真读出来的**,不是编的:`DogProtectProgress` 改用
StdoutPipe 逐行读加壳器输出,正则提 `Packing... N%` / `Saving startup
code... N%`,映射成 Packing 占 0-85、startup 占 85-100。所以进度条在那 4 秒里
会连续走,不是卡在 45% 等它跳 90%。

`DogProtect()` 保留原签名(内部转调 `DogProtectProgress(..., nil)`),
测试和不需要进度的调用方不用改。

## 前端

- columns.ts 的 status 列:running 时画 `<Progress>` + 阶段名 + 百分比,
  排队中也画空槽(列表不会因为状态切换而错位跳行)
- 阶段名走 i18n(zh/en 各加 6 个 key),不是后端写死中文
- 轮询本来就是 2 秒,够跟上进度

后端 `go build` 通过、前端 `npm run build` 30.3s 通过。
2026-11-29 15:50:53 +08:00
admin f6f5c47d8b fix(protect): Authenticode 签名挪到最后一步 —— 原来放加壳前,签出来是废的
Docker Build / Build and Push Docker Image (push) Successful in 49s
Docker Build / Deploy to Server (push) Successful in 3s
上一版的顺序是「Patch(.load) → 签名 → DogProtect」,看着合理(先签好再保护),
实际上 DogProtect 重写 PE 会把 Certificate Table(Data Directory[4])整个清掉,
产物的数字签名不是「失效」而是**直接消失**:

  osslsigncode verify <先签后狗的产物>
    No signature found
    Unable to extract existing signature

Windows 属性页会显示「没有数字签名」,等于白签。

正确顺序(签名必须覆盖最终文件):

  src → Patch(.load) → DogProtect → Authenticode 签名

## 实测对照

同一份产物、同一个自签证书:

  顺序 A(先加壳后签名)
    cert size = 1448
    Current message digest    : 531B7A56...
    Calculated message digest : 531B7A56...   一致 → 签名有效
    (唯一报错是 self-signed certificate,自签证书必然报,真 CA 证书会过)

  顺序 B(先签名后加壳)
    No signature found                        → 签名没了

顺序 A 的产物 wine 跑起来验证界面正常、4 tab、卡密模式、无异常。

## 测试锁住

dog_test.go 新增 TestDogProtectStripsAuthenticode:
- 顺序 B 断言 DogProtect 之后 Certificate Table 必须为空(证明签名会丢)
- 顺序 A 断言有签名 + osslsigncode verify 的两个摘要必须一致
- 不需要真证书,测试里现场自签,没有 osslsigncode/openssl 就 skip

实测:
  顺序 B(先签名后加壳):签名被抹掉 ✓
  顺序 A(先加壳后签名):cert size=1448 ✓
  摘要一致:531B7A56... ✓

## 现在完整的加壳流水线

  src → Patch(.load) → DogProtect → [Authenticode 重签] → 产物

三步都不能换位置:
- .load 必须在 DogProtect 前:否则验证壳明文挂最外层,删掉就绕过验证
- 签名必须在 DogProtect 后:否则加壳把证书表清掉
2026-11-29 14:59:47 +08:00
admin 4a51dc91db fix(protect): 加壳顺序改成「先注入验证壳、再 DogProtect」—— 上一版做反了,没有保护意义
Docker Build / Build and Push Docker Image (push) Successful in 37s
Docker Build / Deploy to Server (push) Successful in 3s
上一版是「先 DogProtect、再注入 .load」,能跑但安全上是白做:

    [DogProtect 包住原程序]
    [.load 验证壳,明文挂最外层]   ← 拿 PE 工具删掉/改掉这一节就绕过验证,
                                     压根不用碰 DogProtect 那层

正确顺序:验证壳代码和配置都在 DogProtect 的保护范围内,想改验证逻辑
(比如把校验结果强改成功)必须先拆掉虚拟化外壳,难度不是一个量级:

    src → PatchAutoSignedThemed(.load) → [可选 Authenticode 重签] → DogProtect

## 为什么反过来的顺序之前会失败、现在又能跑

我上次测「先 verify 再 dog」时跑了 `vfyfix`,它报「节区间异常: off=0 raw=1054106」
—— 那是 `vfyfix` 自己的问题(它拿 VirtualSize 当 raw size 去算 CRC,而
DogProtect 已经把 PointerToRawData 清零),不是产物不能用。

实测直接跑(不碰 vfyfix)就正常出界面。原因是引导 stub 用 VirtualAddress
从内存镜像读载荷:

    hdr = (VFYHDR *)(img + *(u32 *)(s + 12));   // bootstrap.c

而 DogProtect 是启动时解包的,内存里节表和数据都是原始内容,壳照常读到
自己的配置。磁盘上 .load 的 raw/ptr 虽然是 0,运行时不依赖它。

## 副作用(已写进代码注释)

这样壳不能在磁盘上校验整文件 CRC(DogProtect 必然改动整个文件),
实测当前 blob 不拦。如果以后换的 blob 严格要求 crcFile,会启动即退出 ——
那时要在 DogProtect 之前把校验关掉,不能靠事后重算(.load 已不可读)。

重签也必须在 DogProtect 之前:签名是对整个 PE 算的,加壳后必然失效。

## 测试锁住这条约束

新增 dog_test.go:TestDogProtectWrapsShellSection 断言加壳产物里
.load 的 SizeOfRawData 必须为 0(证明验证壳在内层)。哪天有人把顺序改回去,
.load 会变回明文节,测试直接失败并说明「改掉这一节就能绕过验证」。

实测输出:
  注入后 .load: raw=1068032 ptr=310784(明文,符合预期)
  保护后:1378816 → 6472704 字节  (469%)
  保护后 .load: raw=0 ptr=0(已打包进 DogProtect 数据节,验证壳在内层)
  两个测试 PASS

## 顺手

VerifyShellThemes 补上 classic(上一版加了 classic 皮肤但导出清单漏了)。
2026-11-29 13:24:45 +08:00
admin 52865b1a7d chore(gitignore): 补上 dogprotect 的 so/ini 例外(上次只 add -f 了文件,规则没提交)
Docker Build / Build and Push Docker Image (push) Successful in 13s
Docker Build / Deploy to Server (push) Successful in 2s
不加规则的话,以后重新 clone 或别人拉仓库时 libDogProtectSDK64.so 又被
*.so 吃掉,镜像构建照样报 COPY not found。
2026-11-29 12:54:26 +08:00
admin 67ca59cd28 fix(docker): libDogProtectSDK64.so 被 .gitignore 的 *.so 规则吃掉,加例外
Docker Build / Build and Push Docker Image (push) Successful in 45s
Docker Build / Deploy to Server (push) Successful in 3s
.gitignore 第 11 行是通配 *.so,导致 docker/dogprotect/libDogProtectSDK64.so
没进仓库,镜像构建时 COPY 报 'not found':

  ERROR [stage-3 10/12] COPY docker/dogprotect/libDogProtectSDK64.so ...
  failed to calculate checksum: "/docker/dogprotect/libDogProtectSDK64.so": not found

加两个例外(都需要进仓库):*.so 是加壳器的 SDK 运行时库,
*.ini 是授权文件 —— 缺任何一个 dogprotect_con 都起不来。
2026-11-29 12:49:34 +08:00
admin c2425d3682 feat(shell): classic 用 DuiLib 重做,8 套皮肤全部支持按配置切界面
Docker Build / Build and Push Docker Image (push) Failing after 6s
Docker Build / Deploy to Server (push) Skipped
原 classic 是 Direct2D 自绘壳(shell/classic/shell5.cpp、shell6.cpp),里面
login_mode、FetchAppInfo、卡密、billing_type 全是 0 处匹配 —— 它没有
「读 /info 再改界面」这套逻辑,界面永远固定成「账号+密码+注册」。
而它偏偏是面板皮肤的默认值(NormalizeTheme("")、ShellThemeOrder[0]、
Runner 和 BuildCfgThemedVer 的兜底都指向它),等于默认就把界面配置废掉。

## 做法

照搬原 Direct2D 壳的配色,用 DuiLib 重写一套 classic 皮肤:

  #1E1E1E 卡片/主背景      #252527 标题栏       #252526 输入框
  #3F3F46 边框/输入框边     #0E639C 主按钮       #0A4E7A 按下
  #E6E6E6 主文字           #9D9D9D 次要文字     #0078D4 聚焦

做法是把 dark 皮肤的 XML 按上面这张表做颜色替换(11 种色全部命中),
布局和控件沿用 DuiLib 那套 —— 也就是拿到 classic 的观感 + DuiLib 的功能。
(skins_v4.h 里加了 kSkin_classic,kSkins 注册为 470x436。)

## 选壳逻辑

AssetsThemed 不再给 classic 开后门:

  改动前:theme == "classic" → shell64.bin  (Direct2D 老壳)
  改动后:所有主题        → shell64_dui.bin (DuiLib 壳)

老产物不受影响(已经加过壳的照跑),HasVfy 仍然认 .vfy 节。
shell64.bin / shell32.bin 留在 assets 里没删,要回退直接改回来即可。

## 实测

- 64 位壳 907264 → 924160 字节、32 位 1045504 → 1059328(多出的是 classic 皮肤)
- 用 classic 主题加壳产物 1378816 字节,wine 跑起来:
  深灰底 + 蓝色主按钮(VS Code 观感)、4 个 tab「登录/我的设备/卡密充值/找回绑定」、
  单个「卡密」输入框、「卡密登录」按钮、无黑框错位
2026-11-29 12:49:08 +08:00
admin 752ec713c0 feat(protect): 加壳流程默认串上 DogProtect,先保护代码再注入验证壳
Docker Build / Build and Push Docker Image (push) Failing after 8s
Docker Build / Deploy to Server (push) Skipped
需求:打出来的产物默认带 DogProtect 保护,不要每次手动两步。

## 顺序(关键)

必须 **先 DogProtect、后注入验证壳**,反过来不行:

  src → dogprotect_con → PatchAutoSignedThemed(追加 .load)→ [可选重签]

DogProtect 会把要保护的节打包、把 SizeOfRawData/PointerToRawData 清零。
若先注入 .load 再跑 DogProtect,.load 的内容被搬进打包节、磁盘上只剩一个
raw size = 0 的空节,验证壳运行时读不到自己的配置 —— 整个验证静默失效。
实测过这个反向顺序,vfyfix 只会报「节区间异常: off=0 raw=...」,
它重算的是 CRC,救不回被搬走的内容。

## 实现

- :封装 dogprotect_con 调用
  (DOGPROTECT_DIR 定位、180s 超时、退出码和产物双重校验、
  从输出里捞 Output file size 做备注、尾部报错带回任务 message)
-  加壳主流程:KindPE 且加壳器可用时先跑 DogProtect,
  产物再进 Patch。失败直接让任务失败 —— 保护是默认承诺,
  不能悄悄降级成「只打了验证壳」
- 只对 PE 生效;APK/IPA/ELF/Mach-O 走各自原分支

## 镜像

dogprotect_con 是 glibc 程序且要求 GLIBC_2.38+ / GLIBCXX_3.4.32+:
alpine 的 gcompat 跑不起来,bookworm 的 glibc 2.36 也差一截。
runtime 基础镜像 alpine → debian:trixie-slim(glibc 2.41),实测能跑。

配套改动:
- apk → apt;openjdk17 → trixie 的 openjdk-21(apktool 兼容)
- osslsigncode 用 trixie 现成包,删掉源码编译的 signer-builder 阶段
- entrypoint 的 su-exec(alpine 专有)→ util-linux 的 setpriv
- 加壳器三个文件拷到 /app/tools/dogprotect/(必须同目录,-rpath,$ORIGIN)

## 实测

- Linux 直接调用:310784 → 6140928 字节,4.3 秒,输出
  「Output file size is 6140928 bytes (1975%)」
- 完整链路(先 dog 后 verify):7195136 字节,wine 跑起来验证界面正常、
  tab 是「登录/我的设备/卡密充值/找回绑定」、输入框「卡密」、无黑块错位

注意:随源码带的是 TestLicense(TestUser),换正式授权替换
docker/dogprotect/DogProtectLicense.ini 即可,代码不用动。
2026-11-29 12:44:32 +08:00
admin 6c1ebe112e fix(protect): 默认皮肤从 classic 改成 dark —— classic 不支持按配置切登录方式
Docker Build / Build and Push Docker Image (push) Successful in 4s
Docker Build / Deploy to Server (push) Successful in 1s
现象:应用配了卡密登录,换哪个风格界面都是「账号+密码+注册」,卡密输入框、
隐藏注册、充值 tab 全都不跟随。

根因:classic 是 Direct2D 老壳,shell5.cpp / shell6.cpp 里
login_mode、FetchAppInfo、卡密、billing_type 全是 0 处匹配 —— 它压根没有
「读 /info 再改界面」这套逻辑,界面固定不变。而它偏偏是默认值:

  NormalizeTheme("")        → "classic"
  ShellThemeOrder[0]        → "classic"   (面板下拉默认选第一项)
  Runner 里的 theme 兜底     → "classic"
  BuildCfgThemedVer 的兜底   → "classic"

所以只要用户没主动去下拉里挑皮肤,打出来的必然是 classic 壳,配置全失效。

实测确认另外 7 套 DuiLib 皮肤都正常:dark/light/split/card/industrial/
terminal/compact 逐个加壳跑图核对,tab 全是「登录/我的设备/卡密充值/找回绑定」、
输入框全是「卡密」、按钮全是「卡密登录」,没有一格退回账号密码模式。

改动:
- NormalizeTheme 空值 → dark
- ShellThemeOrder 把 dark 提到第一、classic 挪到最后
- ShellThemes[classic] 显示名标注「不支持按配置切卡密/隐藏注册」
- Runner 和 BuildCfgThemedVer 的兜底 → dark
- 新增 theme_default_test.go 锁住「默认必须是 dark」「classic 必须排最后」
  「每个主题都得有显示名」,防止以后被改回去

显式选 classic 的老任务不受影响(task.ShellTheme 有值就用它)。
2026-11-29 12:34:31 +08:00
admin a68aa51004 fix(shell): 输入框补回淡边框,skins_v4.h 转为源文件
Docker Build / Build and Push Docker Image (push) Successful in 4s
Docker Build / Deploy to Server (push) Successful in 2s
1) 输入框现在是无边框纯色块,视觉上不像可交互区域。
   给 7 套皮肤全部 105 个 Edit 显式写上 bordersize="1",
   dark 皮肤的边框色从 #FF474755(71,71,85,压在 #2A2A33 上像黑边)
   提亮到 #FF565672(86,86,114)—— 看得见是边框,但不刺眼。
   注意这次是皮肤里真的有了边框,CaptureBorders 会如实记下 1,
   聚焦 2px / 失焦还原 1px,不会再出现上次那种「凭空多一圈」的问题。

2) skins_v4.h 的来路理清
   文件头原来写着「由 gen_skins_v4.py 生成,不要手改」,但那个脚本的
   最终版已经丢了。现有副本(/tmp/skingen,tmpfs,重启即失)停在 11-23,
   生成出来比仓库文件少 112 个 Button、少了 lblTitle —— 是更早的一版,
   用它重生成会丢掉设备管理页/公告页之后的所有 UI 改动。
   处理:
   - skins_v4.h 头部改成「皮肤源文件,直接改这里」
   - 三个历史脚本归档到 shell/duilib/scripts/legacy/*.obsolete
   - 附 selector/legacy/README.md 说明为什么不能用、改完怎么编译替换

   (/tmp 里的脚本本身没进版本控制,这次是从内存盘抢救出来的,
    否则下次重启就彻底没了)

实测(wine 截图 + 视觉核对):输入框呈现「淡雅克制的灰色边框」,
可明确识别为输入区域;关闭按钮 × 位置大小均合适,无其他硬伤。
2026-11-29 12:25:10 +08:00
admin 896c5ba454 fix(shell): 输入框失焦后残留的黑框,关闭按钮改成 × 并加大
Docker Build / Build and Push Docker Image (push) Successful in 5s
Docker Build / Deploy to Server (push) Successful in 1s
两个界面问题,都出在壳里。

1) 输入框里那圈黑框
   UpdateFocusRing 失焦分支硬编码 SetBorderSize(1),而皮肤里所有 Edit
   都没写 bordersize(默认 0,不画边框)。于是每次聚焦再加失焦,就会
   凭空留下一圈 1px 深灰边(dark 皮肤下是 #FF474755 压在 #FF2A2A33 上)
   —— 看着就是「输入框里有黑框」,而且只有聚焦过一次才出现。
   修:CaptureBorders 用 GetBorderSize() 把各自原始的 RECT 记下来,
   失焦还原原值,没边框的回到没边框;聚焦仍是 2px accent。

2) 关闭按钮样式
   - text="X"(字母 X)→ text="×"(乘号),符合关闭按钮的常规观感
   - 字号 12px(默认)→ 24px:专门注册 3 号字体供按钮用,
     12/14/19 三档在 40x44 的按钮里都显得小
   - dark 皮肤文字色 #FF9A9AA6 → #FFC8C8D4,细线更清楚

7 套 DuiLib 皮肤全部同步。实测(wine 截图 + 视觉核对):
输入框四边已无任何描边,关闭按钮字符居中、大小合适、可一眼识别。

注:skins_v4.h 由 gen_skins_v4.py 生成,但生成脚本只在 /tmp(tmpfs,
重启即失)且现有副本比仓库文件旧 20K,本次直接对仓库文件做精确替换,
未用脚本重生成 —— 脚本与产物不同步这件事另行处理。
2026-11-29 12:19:56 +08:00
admin e09d177843 fix(billing): 计时扣费从未生效、扣费不记账、卡型与应用计费方式不校验
Docker Build / Build and Push Docker Image (push) Successful in 5s
Docker Build / Deploy to Server (push) Successful in 1s
设计评审时查出来的四条,都带回归测试。

1) timer 扣费永远不触发(真 bug)
   handler 先把 LastHeartbeatAt 覆盖成 now,紧接着又拿它算 elapsed,
   now - now = 0,永远小于扣费间隔。用「按时间扣费」的应用从不扣钱,
   不报错、不告警、日志里也看不出来。
   修:先把旧心跳存进 prevHeartbeat,再用它算间隔。
   附带修了重新查库后 LastHeartbeatAt 被拉回旧值的问题(补回 now)。

2) 扣了钱却不写消费流水
   consumption_records 生产库里一直是 0 条:财务页在查这张表,
   但没有任何代码往里写。用户投诉「余额怎么少了」拿不出账。
   修:扣费成功后写 ConsumptionRecord(含余额快照、单号)。记账失败只告警
   不阻断,但会留日志。

3) 卡密首次激活不写充值流水
   只有 payment.go 那条「充到已有主体」的路径记账,「首次激活开新主体」
   漏了,导致卡密收入在财务上查不出来。
   修:resolveCardSubject 在事务里补写 RechargeRecord(金额=卡型售价)。

4) 卡型计费方式与应用 billing_type 不校验
   应用按订阅计费、卡型却建成余额型(或反之),用户充进去的字段
   没有任何逻辑会读 —— 钱花了、没效果、还不报错。
   修:新建/更新卡型时校验,不匹配直接 400 并说明原因。
   免费应用不限制。

另外消除了一处重复实现:
   卡型 value/value_unit 换算成时长原来在 resolveCardSubject 和 payment.go
   各写一遍,而且前者少了 minute/hour 两个单位(按分钟/小时计价的卡走首次
   激活会掉进 default 按「秒」算,30 分钟变 30 秒)。
   现在统一走 service.CardTypeDuration / ApplyCardTypeToSubject。

测试(sqlite 内存库 + 真实 handler 调用):
   TestTimerDeductionActuallyFires        余额 100→99、写 1 条流水、心跳时间更新
   TestTimerDeductionSkipsWhenIntervalNotReached  间隔未到不扣
   TestCardActivationWritesRechargeRecord 激活写流水、卡绑主体
   TestCardRechargeThenLoginReusesSubject 同卡二次登录回原主体、只记一次账
   TestCheckCardTypeMatchesAppBilling     8 组匹配/不匹配组合

验证方式:把 timer 修复临时撤掉重跑 TestTimerDeductionActuallyFires,
确定它会 FAIL(余额仍是 100),恢复后 PASS —— 证明测试真的能抓到这个 bug。
2026-11-29 12:01:02 +08:00
admin 1d972763de fix(cards): 卡密列表去掉「用途」列,补发按钮改按是否已激活
Docker Build / Build and Push Docker Image (push) Successful in 5s
Docker Build / Deploy to Server (push) Successful in 2s
上一版只改了 index.vue(统计卡片和补发提示),列表表格的列定义在
components/columns.ts 里,仍旧渲染「登录卡 / 充值卡」徽标 —— 用户在卡密
管理页还能看到用途,说明改漏了。

- columns.ts  删掉 accessorKey='purpose' 整列(含 登录卡/充值卡 Badge)
- columns.ts  下拉菜单「作废并补发新卡密」的显示条件由
              card.purpose==='credential' 改为 card.subject_id(已激活)
- data-table.vue  列显示开关里的 purpose: '用途' 标签一并删掉

schema.ts 里的 purpose 字段保留:后端仍返回这个字段,留着不影响,
删了反而可能与接口契约对不上。
2026-11-29 11:35:57 +08:00
admin 8af1a3cc33 refactor(cards): 卡密不再分「登录卡/充值卡」,回归「一把钥匙 + 一份面值」
Docker Build / Build and Push Docker Image (push) Successful in 1m5s
Docker Build / Deploy to Server (push) Successful in 3s
卡型里本来就有 recharge_type(balance 余额 / subscription 时长)在管计费方式,
cards.purpose(recharge/credential)是后来叠上去的第二套分类,同一件商品挂两个
维度。后果是:在 login_mode=card 的应用里生成卡密,purpose 默认落到 recharge,
拿它登录必然 401「卡密无效或已失效」,而这句话把人往「卡有问题」方向带。

新模型:卡 = 一把钥匙 + 一份面值。
  卡已激活(subject_id 有值) → 回到它绑定的主体
  卡未激活 + 当前已登录      → 充到当前主体
  卡未激活 + 没登录          → 创建新主体,这张卡就是它的钥匙

后端改动:
- auth.go   resolveCardSubject 查卡去掉 purpose='credential' 条件
- payment.go 删掉「登录卡不能充值」的拦截(已激活的卡由 status 挡住)
- applications.go 识别卡密主体改用 cards.subject_id,不再靠 purpose 反查
- users.go   主体绑卡展示去掉 purpose 过滤,按 id 倒序取最新一张
- devices.go 设备自助用卡密定位主体,去掉 purpose
- cards.go   补发不再限于 credential,改为「已激活即可补发」;
             补发新卡继承原卡 purpose 字段(字段保留但不参与判断);
             安全概览统计换成 total/activated/used/unused/void

前端改动:
- 卡型创建页删掉「卡型用途」单选(只留余额/订阅),提交不再传 purpose
- 卡密页补发提示改为按 subject_id 判断;安全概览卡片改为
  已激活(有主体/总数) / 未使用 / 已作废

数据未动:cards.purpose 与 card_types.purpose 两列保留、继续写入,只是不再
参与任何判断。当前库里 0 张 credential 卡、0 个卡密主体,没有历史数据要迁移。

测试:go build ✓  go test ./internal/...(admin、service)✓  npm run build(vue-tsc + vite)✓
2026-11-29 11:26:12 +08:00
admin 4b0c8faccb fix(shell): 验证窗不再强制置顶,无边框窗口补上标题栏拖动
Docker Build / Build and Push Docker Image (push) Successful in 5s
Docker Build / Deploy to Server (push) Successful in 2s
用户反馈两点:云端加密出来的程序拖不动、而且一直压在最前面。

- 置顶:DuiLib 壳的 exstyle 带了 WS_EX_TOPMOST,classic 壳的
  CreateWindowExW 也带了。验证窗常驻最前会压住用户所有窗口,
  切出去回消息它还杵在最前,只有一个窗口时看着像卡死。
  两处都去掉,WS_EX_APPWINDOW / WS_EX_LAYERED 保留
  (任务栏还在、classic 的透明背景还要)。

- 拖不动:DuiLib 壳是 WS_POPUP 无边框窗口,而全文件里
  HTCAPTION / WM_NCHITTEST / WM_LBUTTONDOWN 一处都没有,
  系统没有标题栏可抓,自然拖不动。补 WM_NCHITTEST:
  顶部 44px(各皮肤 btnClose 的 height,8 套皮肤一致)返回
  HTCAPTION 交给系统原生拖动,关闭按钮矩形单独排除
  (否则点不到它)。必须放在 m_pm.MessageHandler 之前,
  DuiLib 先答 HTCLIENT 就没机会了。

  classic 壳本来就有完整的 NCHITTEST(标题栏 32px + 窗口外拖动),
  只缺不置顶,所以只去掉 WS_EX_TOPMOST。

实测(wine + xdotool):
  _NET_WM_STATE 为空                      → 不再置顶
  标题栏按下拖动,位移 +175/+160 与鼠标同步 → 能拖
  关闭按钮区按下拖动,位置纹丝不动          → 排除生效
  界面 4 tab / 卡密单框 / 卡密登录按钮完整  → 没改坏

注意:classic 的 assets/shell64.bin(332330)、shell32.bin(328922) 与
build-classic.sh 现编产物(76800/86528)对不上,不是同一版本,
来源待确认,本次未替换(DuiLib 的 8 套皮肤已全部更新)。
2026-11-29 10:13:34 +08:00
admin b6d2d18ed9 fix(shell): 接口成功判据补 HTTP 状态码,错误页不再被当成配置
Docker Build / Build and Push Docker Image (push) Successful in 4s
Docker Build / Deploy to Server (push) Successful in 2s
上一版补了 WINHTTP_FLAG_SECURE,https 请求能通了。但 api_get_sibling 的
成功判据仍然是 ok = (total > 0):只要服务端回了任何字节就算成功,
4xx/5xx 的错误页会被原样喂给 json_str,解析失败后各配置项静默回落默认值。

配合本次一起加的 http_status()/http_ok():
- api_get_sibling 改为「2xx 且非空」才算成功
- api_login/api_register/api_send_code/api_post_sibling/api_post_sibling_raw
  原来靠响应体里的 "code":200 判断(不会被 HTML 骗过),再叠一层
  http_ok(httpSt) 作为双保险
- 新增 g_lastHttpStatus 记录最近一次状态码,接口失败时至少有迹可循

http_ok() 对状态码取不到(0)时返回 true,交回调用方按响应体判断,
保持对不走标准状态码的老服务端兼容。

验证方式:起一个故意返回 400、但响应体里塞了完整配置
(login_mode=card、allow_register=false、name=400-POISON)的本地服务,
两个壳跑同一份产物对比:

  旧壳 → 采纳了毒配置:标题显示 400-POISON、切成卡密单框、
         「注册」tab 被换成「我的设备」
  新壳 → 拒绝 400,全部回落本地 cfg 与默认界面:标题 ProbeApp、
         账号或卡密 + 密码、注册 tab 尚在

即错误响应从「静默污染配置」变成「明确失败」。
2026-11-29 09:19:20 +08:00
admin 1dc2dd78dd fix(shell): 补齐 WinHTTP 的 WINHTTP_FLAG_SECURE,https api 的请求此前全部走明文
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 1s
现象:应用配了 login_mode=card,加壳后的客户端仍然显示「账号 + 密码 + 注册」
两个 tab、没有卡密输入框、没有充值入口;应用名却显示正确。

根因:壳里所有 WinHttpOpenRequest 的 dwFlags 都传 0。对 https 的 api,
WinHTTP 会用明文 HTTP 去连 443 端口,服务端(Caddy)直接回
400 The plain HTTP request was sent to HTTPS port。

而 api_get_sibling 的成功判据是 ok = (total > 0),400 的 HTML 错误页
同样算「成功」,于是 FetchAppInfo 继续往下走,对 HTML 做 json_str 解析,
全部失败,各个配置项静默回落到默认值 —— g_loginMode 停在 account、
g_billing 读不到,界面就是默认的账号登录。因为静默,所以查不出错。

应用名显示正确是另一条路径:json_str(g_cfg, "name", ...) 从 .vfy 里的
cfg 读,跟 /info 无关,所以它好着,掩盖了 /info 整体失败。

实测对比(同一 URL,wine + WinHTTP):
  dwFlags=0        → status=400  <html>400 The plain HTTP request was sent to HTTPS port
  dwFlags=SECURE   → status=200  {"code":200,"data":{"allowed_login_types":["card"],...}}

修复:
- shell9_v6.cpp(DuiLib 全部 7 套皮肤,64/32 位)5 处 WinHttpOpenRequest
  补 https ? WINHTTP_FLAG_SECURE : 0
- classic shell5.cpp / shell6.cpp 的登录另外还有 port 写死 80 的问题,
  一并按 scheme 判断改成 443,并补 SECURE 标志
- 重编 shell64_dui.bin / shell32_dui.bin 并更新 embed assets
2026-11-29 08:49:42 +08:00
admin a2e41f659f feat(protect): 皮肤选择旁加「查看」按钮,用全屏图片查看器看大图
Docker Build / Build and Push Docker Image (push) Successful in 1m6s
Docker Build / Deploy to Server (push) Successful in 2s
原来只能 hover 预览图点「看大图」,出来的是带标题栏的普通弹窗,图只是等比
缩在弹窗里,看不清细节。

- 新增 components/image-lightbox.vue:Teleport 到 body 的全屏查看器
  · 黑底 92% + backdrop-blur,图片居中 object-contain
  · 滚轮缩放 100%~600%,顶部显示百分比、+/-/还原按钮,快捷键 + - 0
  · 放大后可按住拖动平移(cursor-grab/grabbing),缩回 100% 自动归位
  · 双击切换(1x ↔ 1.25x)、Esc / 点空白 / 右上角 X 关闭
  · 打开时锁 body 滚动,关闭还原
- 皮肤下拉右边加「查看」按钮(Eye 图标),点开就是查看器
- 预览图上的 hover「看大图」也改为打开同一个查看器
- 删掉旧的 UiDialog 预览弹窗与 previewTheme/openThemePreview/previewOpen
2026-11-26 15:51:01 +08:00
admin 9e85d2371d polish(protect): 拖入区文案对齐 accept 列表,预览容器边框提一档
Docker Build / Build and Push Docker Image (push) Successful in 1m6s
Docker Build / Deploy to Server (push) Successful in 2s
- dropHint 只写「.exe 文件」,但 accept 收 exe/dll/sys/efi/apk/ipa/elf/bin,
  实际支持面比文案宽,改成「程序文件(exe / dll / apk / ipa / elf)」
- 预览容器压在深色卡片上、图本身也是深色,边界容易糊 → border 降到 0.7 再叠一层
  1px 内发光 rgba(255,255,255,0.04),边界清楚但不抢眼
2026-11-26 15:41:23 +08:00
admin ad65ca1a7c fix(protect): 预览图放宽到 672px,下拉收窄到 320px
Docker Build / Build and Push Docker Image (push) Successful in 1m6s
Docker Build / Deploy to Server (push) Successful in 3s
上一版把两者放进同一个 grid 右列后,列宽被内容撑到 395px —— 下拉跟着变宽,
预览图被迫跟下拉同宽,小到看不清界面细节;且 class="max-w-xs" 写在 UiSelect
上不生效(组合组件不把 class 透到 DOM 根),得在外层套 div 限宽。

- grid 右列 minmax(0,1fr) → minmax(0,42rem):预览图最多 672px
- 下拉外面套 <div class="max-w-xs">:稳定 320px,不随列宽膨胀
- 左边缘仍共用同一列,对齐不变
2026-11-26 15:33:00 +08:00
admin 217dbb7c85 fix(protect): 皮肤下拉与预览图左边缘对齐
Docker Build / Build and Push Docker Image (push) Successful in 1m6s
Docker Build / Deploy to Server (push) Successful in 3s
原来标签和下拉在同一个 flex 行里,预览图是块级元素从容器最左开始,
结果预览图比下拉框左移 25px、右边缘也多出一截,两块不成一条基线。

改成两列 grid:标签占 auto 列(mt-2 视觉居中于下拉框),下拉框与预览图
共用 minmax(0,1fr) 右列 → 左边缘严格对齐;下拉 max-w-xs,预览 max-w-2xl,
宽度各自保留(预览要看细节,跟下拉同宽会小到看不清)。
2026-11-26 15:25:21 +08:00
admin 3e4646a68c polish(protect): 皮肤下拉右侧去掉重复小字,classic 命名统一
Docker Build / Build and Push Docker Image (push) Successful in 1m6s
Docker Build / Deploy to Server (push) Successful in 2s
- 下拉已经显示「深色 · 卡密登录」这种完整标签,右边再挂一个「卡密登录」纯属重复
  → 删掉副标题 span 与 currentThemeSub(themeSub 只留给需要它的地方)
- 「经典(原版 Direct2D)」括号风格与其余「X · Y」不一致 → 「经典 · Direct2D 原版」
  (en: Classic · Direct2D (original))
2026-11-26 15:16:26 +08:00
admin 35beab5e24 feat(protect): 验证界面改成组合框选择,下方单张大图预览
Docker Build / Build and Push Docker Image (push) Successful in 1m6s
Docker Build / Deploy to Server (push) Successful in 3s
原来铺 8 张卡片网格(每张带预览图 + 「32/64 位」角标),一屏占满还得分神去
对比;改成:
- 顶部一个下拉框选皮肤(classic / dark / light / industrial / compact / split /
  card / terminal,标签沿用「深色 · 卡密登录」这种带风格的写法)
- 下拉框旁显示选中皮肤的风格副标题
- 下方一张 max-w-2xl 大图,跟着选择切换,hover 可点「看大图」开 1:1 弹窗
- 去掉预览图右上角的 32/64 位角标(所有皮肤都出两位宽产物了,这个标记只剩噪音)

themeBits() 随之删除,新增 currentThemeLabel / currentThemeSub 两个 computed。
2026-11-26 15:07:38 +08:00
admin 0d655152b1 fix(protect): 皮肤卡片去掉「64 位」角标,统一标 32/64 位
Docker Build / Build and Push Docker Image (push) Successful in 1m7s
Docker Build / Deploy to Server (push) Successful in 2s
上一提交让 32 位也能用 DuiLib 皮肤,但前端卡片角标还写着「64 位」
(themeBits 对非 classic 皮肤固定返回 themeBits64),选的皮肤和标的位宽对不上。

themeBits 改为所有皮肤统一返回「32/64 位」,并更新两处过时注释。
2026-11-26 14:05:27 +08:00
admin f90b77b9bb feat(protect): 32 位程序也能用 DuiLib 多皮肤壳
Docker Build / Build and Push Docker Image (push) Successful in 1m8s
Docker Build / Deploy to Server (push) Successful in 3s
问题:x86 一直固定用 classic 壳(Direct2D 单皮肤),选了 dark/light/industrial
等皮肤照样出经典界面 —— 界面上那句「DuiLib 皮肤只做了 64 位构建,32 位程序
固定用经典壳」就是这个限制的说明。预览图按选择显示,产物却是另一套界面。

根因不是技术不可行,是 DuiLib 的 payload DLL 只编了 x64 一份
(assets/shell64_dui.bin),AssetsThemed 里 x86 分支没有对应资产。

做法
- 装 i686-w64-mingw32 工具链,用同一份不修改的 DuiLib 源码编 32 位 libduilib32.a
  (排除 UIWebBrowser/UIRichEdit/UIActiveX/UIFlash,stb_image.c 按 C 编)
- 用 shell9_v6.cpp 编出 shell32_dui.dll(1,018K,PE32 i386),
  落在 assets/shell32_dui.bin
- AssetsThemed 的 x86 分支:theme != classic → shell32_dui.bin
- 新增 shell/duilib/build-duilib32.sh 记录完整构建方式(含老 DuiLib 的补丁清单)
- 前端 zh/en 文案改为「32 位与 64 位共用同一套皮肤,效果一致」

验证(wine32 + Xvfb)
- packthemed 打 32 位样本:theme=dark → .vfy size=1050997(DuiLib),
  theme=classic → .vfy size=337487(经典壳),差 700K 说明取的确实是不同 payload
- 两个产物分别启动截图:dark 是深灰 + 4 个 tab(登录/注册/卡密充值/忘记密码)
  + 皮肤化标题栏;classic 是圆角卡片 + 单页「登录以继续」。界面完全不同,
  确认 32 位真的换到 DuiLib 了

注意:assets 是 //go:embed 进 cmd/packthemed 和主服务的,改完必须重编
(CI 会做;本地验证要手动 go build ./cmd/packthemed)。
2026-11-26 13:55:17 +08:00
admin adce1622f6 merge feat/logs-export:日志导出
Docker Build / Build and Push Docker Image (push) Successful in 1m6s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-24 17:25:12 +08:00
admin d02cc60f94 feat(logs): 加日志导出 CSV,顺手删掉没被路由引用的 logs.vue
- GET /dev/logs/export:与列表同一套筛选(应用/类型/状态/时间/搜索),最多 10 万条,
  带 BOM,列为 时间/类型/级别/动作/资源/状态/用户/应用/主体/IP/设备/详情/错误
- 抽 logFilter 让列表与导出共用筛选条件(顺便把「按别人的应用 id 筛选」变成查空)
- 日志页(真正的 logs/index.vue)工具栏加「导出日志」
- 删除 src/pages/admin/logs.vue:路由指向 logs/index.vue,改它不生效
2026-11-24 17:25:12 +08:00
admin b1b7cb97de merge fix/finance-audit-hardening:财务流水禁删+导出、历史流水口径、LIKE 转义、日志索引
Docker Build / Build and Push Docker Image (push) Successful in 1m1s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-24 14:45:20 +08:00
admin bb88a940c0 fix(finance): 财务流水禁删改导出、历史流水不受主体软删影响、LIKE 转义、日志加索引
- 财务删除接口封死:单条/批量都返回 403 并写 delete_blocked 审计(流水是审计凭证,
  删了会导致「流水没了、余额还在」永久对不上)
- 新增 GET /dev/finance/export:CSV(带 BOM、10 万条上限),前端「导出流水」按钮
- 前端财务页移除删除列、批量删除与两个确认弹窗
- 主体范围改用 Unscoped() 取(含软删主体),Preload 同步 Unscoped:
  删掉一个用户后他的历史充值/消费仍可见、累计收入不再莫名变小
- search 的 LIKE 加 escapeLike()(财务 + 日志),搜 % 不再命中全部
- logs 加三组复合索引:app_created / user_created / type_status
2026-11-24 14:45:14 +08:00
admin b45c11ef9f merge fix/finance-logs-audit:财务/日志修正 + 皮肤大图预览
Docker Build / Build and Push Docker Image (push) Successful in 1m0s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-24 12:47:31 +08:00
admin 1175adec62 fix(finance,logs): 财务统计按当前页算、日志统计与列表不同源、分页参数无校验
财务
- /dev/finance/records 改 SQL 层分页(原来两张表全量 Find 进内存再切片),
  并返回 summary(全量聚合、带筛选),前端卡片不再 reduce 当前页
- 前端财务页改服务端分页;原来不传 page_size 只拿 10 条,40 条流水只算 10 条
- recharge/consumption 响应改成 nil 安全的转换函数(原代码对 *AppUser 直接解引用)
- /finance/stats 正常分支补回 monthly_transactions

日志
- 顶部三个统计改回和列表同源(logs 表)并应用同一套筛选(原来查 api_usages、不带筛选,
  列表 61 条却显示 success=0 failed=0)
- 分页参数统一夹紧

通用
- 新增 admin/pagination.go:page>=1、page_size∈[1,200],堵掉 page_size=-1 拉全表
- docs/audit-finance-logs.md 记录检查结论(含 4 项待拍板的业务口径问题)
- scripts/audit-finance-logs.py 可复现实测

界面
- 皮肤预览支持点开看大图(悬停出现「看大图」,弹窗内可直接「用这套皮肤」)
2026-11-24 12:47:25 +08:00
admin 97a046ab00 merge feat/theme-previews:皮肤选择带实拍预览 + 位宽徽标
Docker Build / Build and Push Docker Image (push) Successful in 1m4s
Docker Build / Deploy to Server (push) Successful in 5s
2026-11-24 10:30:06 +08:00
admin 74355c1dd2 feat(ui): 验证界面皮肤改成带实拍预览的卡片,位宽限制做成徽标
- 皮肤选择从下拉框换成 8 张 560x420 实拍预览卡片(选中高亮 + 勾选)
- 卡片右上角徽标区分「32/64 位」与「64 位」,说明 DuiLib 皮肤只做 64 位构建
- 原来那句 themeHint 缩短并降级为脚注,不再占一整行正文
- 预览图来自真实产物截图(docs/shell-theme-previews.md 记了重跑步骤)
2026-11-24 10:29:58 +08:00
admin a446a1ba37 merge fix/protect-base-url:加壳产物站点地址不再取反代上游地址
Docker Build / Build and Push Docker Image (push) Successful in 43s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-24 08:42:26 +08:00
admin f997035972 fix(protect): 加壳产物不再把 127.0.0.1 写进壳 cfg
AcePanel 默认反代模板 proxy_set_header Host $proxy_host,后端看到的 Host 是
127.0.0.1:9998,于是每个产物的 cfg 都成了 https://127.0.0.1:9998/...,
到客户机上必然连不上。

- baseURL() 改为:app.public_url > X-Forwarded-Host > Host;推断出本机/内网
  地址时直接让加壳任务报错,不再静默产出坏产物
- config.yaml 增加 app.public_url(生产可直接写死站点地址)
- 新增 4 个单测(含 loopback 必须报错)
- docs/protect-base-url.md 记录事故与自查方法
2026-11-24 08:42:21 +08:00
admin ead706ea52 merge feat/login-mode-switch:登录方式开关(卡密/账号/混合)服务端强制生效
Docker Build / Build and Push Docker Image (push) Successful in 1m0s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-24 06:57:46 +08:00
admin bf381d8034 feat(login): 登录方式开关真正生效——服务端 gate + 生效级别 + 宽限期 + 面板影响面
- /login 在 login_type 归一化之后、任何副作用之前按 login_mode 拦截(off/warn/strict)
- 宽限期内旧凭证仍可用,响应带 deprecated_login/grace_days_left
- /register 在 card+strict 且无宽限时挡掉(卡密模式不需要注册)
- /info 下发 login_mode_enforce / grace_days / allowed_login_types
- 新增 GET /dev/applications/:id/login-mode-impact(仅卡密主体 / 仅账号主体)
- 修掉 auth.go 两处 CardLoginAllowPassword 判断写反(card/both 下即使关闭也放行)
- 面板「登录方式」卡片补 生效方式 / 宽限期 / 影响面提示
- 新建应用默认 both+warn;存量行启动时回填 enforce=warn,升级不改变行为
- 单测 + scripts/e2e-login-mode.py 端到端矩阵(5 组模式×4 种凭证)
2026-11-24 06:57:33 +08:00
admin f283b4eae0 merge docs/x86-verify:32 位实测记录
Docker Build / Build and Push Docker Image (push) Successful in 6s
Docker Build / Deploy to Server (push) Successful in 2s
2026-11-24 04:27:47 +08:00
admin 78d4a7c3aa docs(protect): 补 32 位(x86)壳节名 .load 的实测记录 2026-11-24 04:27:47 +08:00
admin fb3f549acc merge feat/section-rename-load:壳节改名 .load
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-24 04:06:56 +08:00
admin 336c41a90f feat(protect): 壳节 .vfy 改名 .load(引导 blob 打节名补丁 + Go 侧同步,兼容旧 .vfy 产物) 2026-11-24 04:06:41 +08:00
admin 5d9c2ca0c9 merge docs/double-pack-layering:分层证据
Docker Build / Build and Push Docker Image (push) Successful in 6s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-24 03:55:20 +08:00
admin 944c3f31b3 docs(protect): 补二次加壳的分层证据(入口 RVA / 节表 / .vfy hash 未变) 2026-11-24 03:55:20 +08:00
admin 5b193181d1 merge docs/double-pack-functional:二次加壳功能级验证
Docker Build / Build and Push Docker Image (push) Successful in 7s
Docker Build / Deploy to Server (push) Successful in 2s
2026-11-24 03:46:37 +08:00
admin b7461cee27 docs(protect): 补二次加壳的功能级实测(双层产物走完设备管理页与行内解绑) 2026-11-24 03:46:37 +08:00
admin 02bb727f33 merge docs/shell-device-ui:壳设备管理页文档与验收 mock
Docker Build / Build and Push Docker Image (push) Successful in 6s
Docker Build / Deploy to Server (push) Successful in 2s
2026-11-24 03:26:28 +08:00
admin 9b7cc01c3a docs(shell): 设备管理页/手机端界面/验收清单/踩坑记录 + 可复现的 mock 服务端脚本 2026-11-24 03:26:28 +08:00
admin c21326eea8 merge feat/shell-title:设备页标题随页面切换
Docker Build / Build and Push Docker Image (push) Successful in 32s
Docker Build / Deploy to Server (push) Successful in 2s
2026-11-24 02:48:57 +08:00
admin 98ca1a6190 feat(shell): 设备管理页时窗口标题改为「设备管理 - 应用名」,返回时复原 2026-11-24 02:48:57 +08:00
admin 7d1ad7a417 merge feat/shell-device-page:设备满页改为独立设备管理页
Docker Build / Build and Push Docker Image (push) Successful in 32s
Docker Build / Deploy to Server (push) Successful in 2s
2026-11-23 22:10:56 +08:00
admin 6067e9517e feat(shell): 设备满页改成独立设备管理页(窗口放大/隐藏tab/每行带解绑按钮,去掉序号输入) 2026-11-23 22:10:49 +08:00
admin ccdf5bd19b merge feat/shell-device-ui:壳设备页在线状态/手动解绑、文案、手机端界面
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-23 21:22:10 +08:00
admin a98c9a36ac feat(shell): 设备列表显示在线状态 + 手动选择解绑(不选不动手)+ 文案下线改解绑 + 手机端双输入框界面 2026-11-23 21:22:02 +08:00
admin 40c930cdbb merge feat/rename-cloud-encryption:界面文案改为云端加密
Docker Build / Build and Push Docker Image (push) Successful in 1m0s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-23 19:26:50 +08:00
admin 7515565660 feat(i18n): 界面文案「加壳/加固」统一改为「云端加密」(中英双语 + 路由标题 + 后端提示) 2026-11-23 19:26:50 +08:00
admin 24e3f7b811 merge feat/doglic:自签授权验签 + 双重加壳兼容 + 壳源码入库
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-23 19:18:32 +08:00
admin 77e59f021c feat(protect): 加 cmd/packthemed,按 shell_theme 出各套验证界面产物(拍照/回归用) 2026-11-23 19:16:56 +08:00
96 changed files with 13952 additions and 1484 deletions
+4
View File
@@ -55,3 +55,7 @@ temp/
# 壳源码的本地构建产物
shell/**/out/
# DogProtect 加壳器的 SDK 运行时库(含 .so,必须进仓库,镜像是 COPY 它)
!docker/dogprotect/*.so
!docker/dogprotect/*.ini
+28 -17
View File
@@ -21,13 +21,6 @@ RUN curl -fsSL -o /tmp/zsign.tar.gz \
&& tar xzf /tmp/zsign.tar.gz -C /tmp && mkdir -p /out \
&& mv /tmp/zsign-musl /out/zsign && chmod +x /out/zsign
FROM alpine:latest AS signer-builder
RUN apk add --no-cache build-base cmake linux-headers openssl-dev zlib-dev curl-dev git
RUN git clone --depth 1 https://github.com/mtrojnar/osslsigncode.git /src \
&& cd /src && mkdir -p build && cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release > /dev/null && make -j"$(nproc)" > /dev/null \
&& mkdir -p /out && cp osslsigncode /out/
FROM golang:1.23-alpine AS backend-builder
WORKDIR /app
@@ -50,14 +43,23 @@ COPY --from=frontend-builder /app/frontend/dist ./cmd/embedded/dist/
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main ./cmd/main.go
FROM alpine:latest
FROM debian:trixie-slim
# Android 加壳工具链:Alpine 仓库没有 apktool/apksigner,改自带 fat jar
# apktool 反编译 / 回编译(改 manifest + 合并 smali)
# uber-apk-signer 对齐 + v1/v2/v3 重签(自带 apksig,不需要 build-tools)
# 基础镜像用 trixie(glibc 2.41)而不是 alpine:DogProtect 的加壳器
# dogprotect_con 是 glibc 程序,还要求 GLIBC_2.38+ / GLIBCXX_3.4.32+,
# alpine 的 gcompat 和 bookworm(glibc 2.36)都跑不起来。
#
# Android 加壳工具链:apktool / uber-apk-signer 是 fat jar,用 trixie 的 JDK 21
# cabextract:解微软拉黑名单(disallowedcertstl.cab),吊销/拉黑检测要用
RUN apk --no-cache add ca-certificates tzdata su-exec mailcap openjdk17-jre-headless curl cabextract \
libcrypto3 libssl3 libcurl zlib libstdc++ \
# osslsigncode:trixie 仓库有现成包,不用再源码编译
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates tzdata curl cabextract \
openjdk-21-jre-headless \
osslsigncode \
libssl3t64 zlib1g libstdc++6 libzstd1 \
util-linux \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /app/tools \
&& curl -fsSL -o /app/tools/apktool.jar \
https://github.com/iBotPeaches/Apktool/releases/download/v2.9.3/apktool_2.9.3.jar \
@@ -66,8 +68,8 @@ RUN apk --no-cache add ca-certificates tzdata su-exec mailcap openjdk17-jre-head
&& java -jar /app/tools/apktool.jar --version \
&& chmod -R a+rX /app/tools
RUN addgroup -g 1001 -S appgroup && \
adduser -u 1001 -S appuser -G appgroup
RUN groupadd -g 1001 appgroup && \
useradd -u 1001 -g appgroup -M -s /usr/sbin/nologin appuser
WORKDIR /app
@@ -79,12 +81,21 @@ RUN chmod +x /usr/local/bin/docker-entrypoint.sh && \
chown -R appuser:appgroup /app
COPY --from=signer-fetcher /out/zsign /app/tools/zsign
COPY --from=signer-builder /out/osslsigncode /app/tools/osslsigncode
# DogProtect 加壳器:每个 PE 产物在注入验证壳之前先过一遍,保护原程序代码。
# 必须放在 /app/tools/dogprotect/ 下且和 SDK 同目录(加壳器链接时是
# -Wl,-rpath,$ORIGIN),后端通过 DOGPROTECT_DIR 找它。
COPY docker/dogprotect/dogprotect_con /app/tools/dogprotect/dogprotect_con
COPY docker/dogprotect/libDogProtectSDK64.so /app/tools/dogprotect/libDogProtectSDK64.so
COPY docker/dogprotect/DogProtectLicense.ini /app/tools/dogprotect/DogProtectLicense.ini
RUN chmod +x /app/tools/dogprotect/dogprotect_con && \
chmod -R a+rX /app/tools/dogprotect
ENV PROTECT_APKTOOL_JAR=/app/tools/apktool.jar \
PROTECT_SIGNER_JAR=/app/tools/uber-apk-signer.jar \
PROTECT_ZSIGN=/app/tools/zsign \
PROTECT_OSSLSIGNCODE=/app/tools/osslsigncode
PROTECT_OSSLSIGNCODE=/usr/bin/osslsigncode \
DOGPROTECT_DIR=/app/tools/dogprotect
EXPOSE 8080
+39
View File
@@ -0,0 +1,39 @@
// 按主题打壳:packtest 固定用 classic 壳,这个工具多了 theme 参数,用来出各套验证界面
// 用法: packthemed <src.exe> <out.exe> <cfg.json> <theme>
package main
import (
"fmt"
"os"
"path/filepath"
"verification-platform-backend/internal/protect"
)
func main() {
if len(os.Args) != 5 {
fmt.Fprintln(os.Stderr, "用法: packthemed <src.exe> <out.exe> <cfg.json> <theme>")
os.Exit(2)
}
src, err := os.ReadFile(os.Args[1])
must(err)
cfg, err := os.ReadFile(os.Args[3])
must(err)
arch, err := protect.DetectArch(src)
must(err)
theme := protect.NormalizeTheme(os.Args[4])
out, info, err := protect.PatchSignedThemed(src, cfg, arch, false, theme)
must(err)
must(os.WriteFile(os.Args[2], out, 0o644))
fmt.Printf("%-10s 架构=%s 产物=%s %d 字节 .vfy size=%d\n",
theme, arch, filepath.Base(os.Args[2]), info.OutSize, info.SecSize)
}
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
+5 -4
View File
@@ -1,4 +1,4 @@
// vfyfix — 修正 .vfy 壳头里的两个 CRC(crcV / crcFile)
// vfyfix — 修正壳节(.load,旧产物 .vfy)头里的两个 CRC(crcV / crcFile)
//
// 场景:先用 verify 的加壳链路打壳(signed=false,壳会校验整文件 CRC),再用别的工具
// (如 DogProtect)二次加壳。后者重写了 PE,壳一校验就退出。本工具在最后一步重算:
@@ -27,7 +27,8 @@ import (
)
const (
secName = ".vfy"
secName = ".load"
legacySecName = ".vfy"
hdrSize = 48
crcOff = 36
)
@@ -57,7 +58,7 @@ func main() {
var sec *pe.Section
for _, s := range f.Sections {
if strings.HasPrefix(s.Name, secName) {
if strings.HasPrefix(s.Name, secName) || strings.HasPrefix(s.Name, legacySecName) {
sec = s
}
}
@@ -80,7 +81,7 @@ func main() {
flags := binary.LittleEndian.Uint32(data[off+32:])
oldV := binary.LittleEndian.Uint32(data[off+crcOff:])
oldF := binary.LittleEndian.Uint32(data[off+crcOff+4:])
fmt.Printf("%s\n .vfy 文件偏移=0x%x 原始大小=%d flags=0x%x(bit1=%d)\n", path, off, rawSize, flags, (flags>>1)&1)
fmt.Printf("%s\n 壳节 %s 文件偏移=0x%x 原始大小=%d flags=0x%x(bit1=%d)\n", path, sec.Name, off, rawSize, flags, (flags>>1)&1)
fmt.Printf(" 旧: crcV=%08x crcFile=%08x\n", oldV, oldF)
// ---- 重算 crcV:节内跳过 36..44 ----
+2
View File
@@ -4,6 +4,8 @@ app:
port: "8080"
jwt_secret: "your-secret-key-change-in-production"
jwt_expire_hours: "24"
# 加壳时写进壳 cfg 的站点根地址;留空则按请求头推断(反代需要传 X-Forwarded-Host)
public_url: ""
database:
host: "localhost"
+10
View File
@@ -240,6 +240,16 @@ func runMigrations() {
// 导致心跳写设备时 Error 1265 Data truncated,设备表永远是空的。
fixDeviceIDColumnType()
// 登录方式开关(login_mode)上线:enforce 为空的历史行补成 warn(只记录不拦截),
// 这样升级后行为完全不变,面板也能显示真实状态;管理员确认影响面后再切 strict。
if DB.Migrator().HasTable(&model.Application{}) {
if err := DB.Model(&model.Application{}).
Where("login_mode_enforce IS NULL OR login_mode_enforce = ''").
Update("login_mode_enforce", "warn").Error; err != nil {
log.Printf("[WARN] 回填 applications.login_mode_enforce 失败: %v", err)
}
}
// 迁移后复核:仍有表不存在时明确打出来,避免后续写库时报 1146 无从排查
for _, m := range models {
if !DB.Migrator().HasTable(m) {
+97 -87
View File
@@ -48,9 +48,9 @@ type User struct {
type AppUser struct {
ID uint `gorm:"primaryKey" json:"id"`
Username string `gorm:"uniqueIndex:idx_app_user;size:50" json:"username"`
DisplayName string `gorm:"size:100" json:"display_name"` // 客服看到的主体标识:账号=用户名,卡密=卡密
SubjectType string `gorm:"size:20;default:account;index" json:"subject_type"` // account / card
Remark string `gorm:"size:255" json:"remark"` // 运营备注
DisplayName string `gorm:"size:100" json:"display_name"` // 客服看到的主体标识:账号=用户名,卡密=卡密
SubjectType string `gorm:"size:20;default:account;index" json:"subject_type"` // account / card
Remark string `gorm:"size:255" json:"remark"` // 运营备注
Email string `gorm:"size:100" json:"email"`
Password string `gorm:"size:255" json:"-"`
DeviceID string `gorm:"size:100" json:"device_id"`
@@ -166,60 +166,64 @@ type UserLevel struct {
// Application 应用模型
type Application struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `json:"user_id"`
Name string `gorm:"size:100" json:"name"`
Description string `gorm:"type:text" json:"description"`
IconURL string `gorm:"size:255" json:"icon_url"`
AppKey string `gorm:"unique;size:50" json:"app_key"`
BillingType string `gorm:"size:20" json:"billing_type"`
LoginPolicy string `gorm:"size:20;default:loose" json:"login_policy"`
LoginMode string `gorm:"size:20;default:account" json:"login_mode"` // account = 账号密码, card = 单卡直登, both = 两种都开
CardLoginBindDevice bool `gorm:"default:true" json:"card_login_bind_device"` // 卡密登录是否也受设备上限约束
CardLoginAllowPassword bool `gorm:"default:false" json:"card_login_allow_password"` // 卡密主体是否允许再设一个登录密码
EncryptType string `gorm:"size:20" json:"encrypt_type"`
EncryptKey string `gorm:"size:255" json:"encrypt_key"`
BindType string `gorm:"size:20" json:"bind_type"`
MaxDevices int `gorm:"default:1" json:"max_devices"`
ChangeLimit int `gorm:"default:3" json:"change_limit"`
ChangeInterval int `gorm:"default:7" json:"change_interval"`
ChangeExceedAction string `gorm:"size:20;default:deny" json:"change_exceed_action"`
ChangeDeductAmount float64 `gorm:"default:1" json:"change_deduct_amount"`
MultiOpenMode string `gorm:"size:20;default:forbidden" json:"multi_open_mode"`
MaxInstances int `gorm:"default:1" json:"max_instances"`
EnableTrial bool `gorm:"default:false" json:"enable_trial"`
TrialBalance float64 `gorm:"default:0" json:"trial_balance"`
TrialDays int `gorm:"default:0" json:"trial_days"`
EnableFreePeriod bool `gorm:"default:false" json:"enable_free_period"`
FreePeriodType string `gorm:"size:20;default:range" json:"free_period_type"`
FreePeriodStart string `gorm:"size:50" json:"free_period_start"`
FreePeriodEnd string `gorm:"size:50" json:"free_period_end"`
FreePeriodWeekdays string `gorm:"size:50" json:"free_period_weekdays"`
FreePeriodStartTime string `gorm:"size:10" json:"free_period_start_time"`
FreePeriodEndTime string `gorm:"size:10" json:"free_period_end_time"`
HeartbeatInterval int `gorm:"default:60" json:"heartbeat_interval"`
HeartbeatTimeout int `gorm:"default:300" json:"heartbeat_timeout"`
MaxAttempts int `gorm:"default:5" json:"max_attempts"`
LockDuration int `gorm:"default:30" json:"lock_duration"`
Status string `gorm:"size:20;default:active" json:"status"`
DeductionMode string `gorm:"size:20;default:auto" json:"deduction_mode"`
DeductionType string `gorm:"size:20;default:login" json:"deduction_type"`
DeductionInterval int `gorm:"default:1" json:"deduction_interval"`
DeductionUnit string `gorm:"size:20;default:minute" json:"deduction_unit"`
DeductionAmount float64 `gorm:"default:1" json:"deduction_amount"`
AllowRegister bool `gorm:"default:true" json:"allow_register"`
EnableLoginVerify bool `gorm:"default:false" json:"enable_login_verify"`
EnableRegisterVerify bool `gorm:"default:false" json:"enable_register_verify"`
VerifyMethod string `gorm:"size:20;default:email" json:"verify_method"`
EmailConfigID *uint `json:"email_config_id"`
SmsConfigID *uint `json:"sms_config_id"`
EnablePasswordReset bool `gorm:"default:false" json:"enable_password_reset"`
PasswordResetMethod string `gorm:"size:20;default:email" json:"password_reset_method"`
PasswordResetEmailID *uint `json:"password_reset_email_id"`
PasswordResetSmsID *uint `json:"password_reset_sms_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `json:"user_id"`
Name string `gorm:"size:100" json:"name"`
Description string `gorm:"type:text" json:"description"`
IconURL string `gorm:"size:255" json:"icon_url"`
AppKey string `gorm:"unique;size:50" json:"app_key"`
BillingType string `gorm:"size:20" json:"billing_type"`
LoginPolicy string `gorm:"size:20;default:loose" json:"login_policy"`
LoginMode string `gorm:"size:20;default:both" json:"login_mode"` // account = 账号密码, card = 单卡直登, both = 两种都开
// 登录方式开关的生效级别:off = 不校验(旧行为), warn = 只记录不拦截(灰度用), strict = 真正拦截
LoginModeEnforce string `gorm:"size:16;default:warn" json:"login_mode_enforce"`
// 切换登录方式后的宽限期截止时间:在此之前旧凭证仍然可用(避免一刀切锁死存量用户)
LoginModeGraceUntil *time.Time `json:"login_mode_grace_until"`
CardLoginBindDevice bool `gorm:"default:true" json:"card_login_bind_device"` // 卡密登录是否也受设备上限约束
CardLoginAllowPassword bool `gorm:"default:false" json:"card_login_allow_password"` // 卡密主体是否允许再设一个登录密码
EncryptType string `gorm:"size:20" json:"encrypt_type"`
EncryptKey string `gorm:"size:255" json:"encrypt_key"`
BindType string `gorm:"size:20" json:"bind_type"`
MaxDevices int `gorm:"default:1" json:"max_devices"`
ChangeLimit int `gorm:"default:3" json:"change_limit"`
ChangeInterval int `gorm:"default:7" json:"change_interval"`
ChangeExceedAction string `gorm:"size:20;default:deny" json:"change_exceed_action"`
ChangeDeductAmount float64 `gorm:"default:1" json:"change_deduct_amount"`
MultiOpenMode string `gorm:"size:20;default:forbidden" json:"multi_open_mode"`
MaxInstances int `gorm:"default:1" json:"max_instances"`
EnableTrial bool `gorm:"default:false" json:"enable_trial"`
TrialBalance float64 `gorm:"default:0" json:"trial_balance"`
TrialDays int `gorm:"default:0" json:"trial_days"`
EnableFreePeriod bool `gorm:"default:false" json:"enable_free_period"`
FreePeriodType string `gorm:"size:20;default:range" json:"free_period_type"`
FreePeriodStart string `gorm:"size:50" json:"free_period_start"`
FreePeriodEnd string `gorm:"size:50" json:"free_period_end"`
FreePeriodWeekdays string `gorm:"size:50" json:"free_period_weekdays"`
FreePeriodStartTime string `gorm:"size:10" json:"free_period_start_time"`
FreePeriodEndTime string `gorm:"size:10" json:"free_period_end_time"`
HeartbeatInterval int `gorm:"default:60" json:"heartbeat_interval"`
HeartbeatTimeout int `gorm:"default:300" json:"heartbeat_timeout"`
MaxAttempts int `gorm:"default:5" json:"max_attempts"`
LockDuration int `gorm:"default:30" json:"lock_duration"`
Status string `gorm:"size:20;default:active" json:"status"`
DeductionMode string `gorm:"size:20;default:auto" json:"deduction_mode"`
DeductionType string `gorm:"size:20;default:login" json:"deduction_type"`
DeductionInterval int `gorm:"default:1" json:"deduction_interval"`
DeductionUnit string `gorm:"size:20;default:minute" json:"deduction_unit"`
DeductionAmount float64 `gorm:"default:1" json:"deduction_amount"`
AllowRegister bool `gorm:"default:true" json:"allow_register"`
EnableLoginVerify bool `gorm:"default:false" json:"enable_login_verify"`
EnableRegisterVerify bool `gorm:"default:false" json:"enable_register_verify"`
VerifyMethod string `gorm:"size:20;default:email" json:"verify_method"`
EmailConfigID *uint `json:"email_config_id"`
SmsConfigID *uint `json:"sms_config_id"`
EnablePasswordReset bool `gorm:"default:false" json:"enable_password_reset"`
PasswordResetMethod string `gorm:"size:20;default:email" json:"password_reset_method"`
PasswordResetEmailID *uint `json:"password_reset_email_id"`
PasswordResetSmsID *uint `json:"password_reset_sms_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}
@@ -290,7 +294,7 @@ type CardType struct {
ApplicationID uint `json:"application_id"`
Name string `gorm:"size:100" json:"name"`
RechargeType string `gorm:"size:20;default:balance" json:"recharge_type"` // balance(余额充值), subscription(订阅充值)
Purpose string `gorm:"size:20;default:recharge" json:"purpose"` // recharge = 充值卡, credential = 登录卡
Purpose string `gorm:"size:20;default:recharge" json:"purpose"` // 历史字段:不再参与任何判断。计费方式看 RechargeType
Value float64 `json:"value"` // 余额值或订阅时长(秒)
ValueUnit string `gorm:"size:20;default:day" json:"value_unit"` // 时长单位: day, month, year (仅订阅充值)
Price float64 `json:"price"`
@@ -306,22 +310,22 @@ type CardType struct {
// Card 卡密模型
type Card struct {
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"index;not null" json:"application_id"`
CardTypeID uint `gorm:"index;not null" json:"card_type_id"`
CardKey string `gorm:"unique;size:100" json:"card_key"`
Purpose string `gorm:"size:20;default:recharge;index" json:"purpose"` // recharge = 充值卡, credential = 登录卡
SubjectID *uint `gorm:"index" json:"subject_id"` // 登录卡激活后归属的主体(一卡一主体)
AppliedToSubjectID *uint `json:"applied_to_subject_id"` // 充值卡充给了哪个主体(对账用)
CreatorID uint `gorm:"index" json:"creator_id"`
AgentID *uint `gorm:"index" json:"agent_id"`
AppUserID *uint `gorm:"index" json:"app_user_id"`
Status string `gorm:"size:20;default:unused;index" json:"status"`
UsedAt *time.Time `json:"used_at"`
ExpireAt *time.Time `json:"expire_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"index;not null" json:"application_id"`
CardTypeID uint `gorm:"index;not null" json:"card_type_id"`
CardKey string `gorm:"unique;size:100" json:"card_key"`
Purpose string `gorm:"size:20;default:recharge;index" json:"purpose"` // 历史字段:不再参与任何判断
SubjectID *uint `gorm:"index" json:"subject_id"` // 登录卡激活后归属的主体(一卡一主体)
AppliedToSubjectID *uint `json:"applied_to_subject_id"` // 充值卡充给了哪个主体(对账用)
CreatorID uint `gorm:"index" json:"creator_id"`
AgentID *uint `gorm:"index" json:"agent_id"`
AppUserID *uint `gorm:"index" json:"app_user_id"`
Status string `gorm:"size:20;default:unused;index" json:"status"`
UsedAt *time.Time `json:"used_at"`
ExpireAt *time.Time `json:"expire_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Application *Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
CardType CardType `gorm:"foreignKey:CardTypeID" json:"card_type,omitempty"`
@@ -376,10 +380,10 @@ type Order struct {
// Log 日志模型
type Log struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID *uint `json:"user_id"`
ApplicationID *uint `json:"application_id"`
UserID *uint `gorm:"index:idx_logs_user_created,priority:1" json:"user_id"`
ApplicationID *uint `gorm:"index:idx_logs_app_created,priority:1" json:"application_id"`
AppUserID *uint `json:"app_user_id"`
LogType string `gorm:"size:20;default:operation" json:"log_type"` // operation, verification, exception
LogType string `gorm:"size:20;default:operation;index:idx_logs_type_status,priority:1" json:"log_type"` // operation, verification, exception
Action string `gorm:"size:100" json:"action"`
Resource string `gorm:"size:100" json:"resource"`
ResourceID *uint `json:"resource_id"`
@@ -387,12 +391,12 @@ type Log struct {
IPAddress string `gorm:"size:50" json:"ip_address"`
UserAgent string `gorm:"size:500" json:"user_agent"`
DeviceID string `gorm:"size:100" json:"device_id"`
CardTypeID *uint `gorm:"index" json:"card_type_id"` // 卡密登录失败时记下这是哪个卡型的卡,便于按卡型看爆破
Status string `gorm:"size:20;default:success" json:"status"` // success, failed, pending
Level string `gorm:"size:20;default:info" json:"level"` // info, warning, error
CardTypeID *uint `gorm:"index" json:"card_type_id"` // 卡密登录失败时记下这是哪个卡型的卡,便于按卡型看爆破
Status string `gorm:"size:20;default:success;index:idx_logs_type_status,priority:2" json:"status"` // success, failed, pending
Level string `gorm:"size:20;default:info" json:"level"` // info, warning, error
ErrorMessage string `gorm:"type:text" json:"error_message"`
StackTrace string `gorm:"type:text" json:"stack_trace"`
CreatedAt time.Time `json:"created_at"`
CreatedAt time.Time `gorm:"index:idx_logs_app_created,priority:2;index:idx_logs_user_created,priority:2" json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
@@ -920,12 +924,18 @@ type ProtectTask struct {
SignProfileID *uint `json:"sign_profile_id"` // 产物重签使用的证书资产
CertIdentity int `gorm:"default:0" json:"cert_identity"` // 用证书文件里的第几套身份(0/1 = 第一套)
// ShellTheme 验证界面皮肤:classic(Direct2D 原版)/ dark / light / industrial(DuiLib 壳)
ShellTheme string `gorm:"size:32;default:classic" json:"shell_theme"`
SourceName string `gorm:"size:255" json:"source_name"`
SourceSize int64 `json:"source_size"`
Kind string `gorm:"size:16;default:pe" json:"kind"` // pe/apk/ipa/elf/macho
Arch string `gorm:"size:16" json:"arch"`
Status string `gorm:"size:20;default:pending" json:"status"` // pending/running/done/failed
ShellTheme string `gorm:"size:32;default:classic" json:"shell_theme"`
SourceName string `gorm:"size:255" json:"source_name"`
SourceSize int64 `json:"source_size"`
Kind string `gorm:"size:16;default:pe" json:"kind"` // pe/apk/ipa/elf/macho
Arch string `gorm:"size:16" json:"arch"`
Status string `gorm:"size:20;default:pending" json:"status"` // pending/running/done/failed
// Progress 加壳进度 0-100。加壳分四段:注入验证壳 → DogProtect 保护 →
// 证书签名 → 写出产物。DogProtect 占大头(几百 KB 的 PE 要 4 秒以上),
// 所以它的内部输出(Packing / Saving startup code)会换算成这一段里的细进度。
Progress int `gorm:"default:0" json:"progress"`
// Stage 当前阶段 key,前端按 i18n 翻译:prepare/shell/dogprotect/sign/writing/done
Stage string `gorm:"size:32" json:"stage"`
Message string `gorm:"size:500" json:"message"`
OutputName string `gorm:"size:255" json:"output_name"`
OutputSize int64 `json:"output_size"`
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+246
View File
@@ -0,0 +1,246 @@
package protect
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
)
// DogProtect 相关的可执行文件位置。容器里通过 Dockerfile 拷到 /app/tools/dogprotect/,
// 本地开发时可以指到 /root/work/vmprotect/bin/64/release/。
const (
dogToolDirEnv = "DOGPROTECT_DIR"
dogToolDirDflt = "/app/tools/dogprotect"
dogBinaryName = "dogprotect_con"
dogSDKLibName = "libDogProtectSDK64.so"
dogTimeoutSec = 180 // 大一点的 PE 虚拟化要几十秒,留足余量
)
// dogPctRe 匹配加壳器输出里的 "Packing... 45%" / "Saving startup code... 100%"
var dogPctRe = regexp.MustCompile(`(Packing|Saving startup code)\.\.\.\s*(\d+)%`)
// DogProtectAvailable 报告加壳器在不在。面板可以据此决定是否显示「已有保护」。
func DogProtectAvailable() bool {
dir := dogToolDir()
if dir == "" {
return false
}
if _, err := os.Stat(filepath.Join(dir, dogBinaryName)); err != nil {
return false
}
if _, err := os.Stat(filepath.Join(dir, dogSDKLibName)); err != nil {
return false
}
return true
}
func dogToolDir() string {
if d := strings.TrimSpace(os.Getenv(dogToolDirEnv)); d != "" {
return d
}
if _, err := os.Stat(dogToolDirDflt); err == nil {
return dogToolDirDflt
}
return ""
}
// DogProtect 保护一个 PE,不带进度回调(测试和不需要进度的调用方用这个)。
func DogProtect(src []byte, workDir string) (out []byte, note string, err error) {
return DogProtectProgress(src, workDir, nil)
}
// DogProtectProgress 是 DogProtect 的带进度版本。
//
// onProgress 会收到 (百分比 0-100, 阶段 key)。加壳器自己只输出
// "Packing... N%" 和 "Saving startup code... N%" 两个阶段,
// 这里把它们映射成 0-100 的连续进度:Packing 占 0-85,startup 占 85-100。
// (PE 越大 Packing 越久,startup 基本是固定开销。)
//
// onProgress 为 nil 就不上报。回调在读取 stdout 的 goroutine 里同步调用,
// 实现方要自己保证不阻塞太久。
//
// 下面这段说明仍然成立 —— 顺序不能反:
// DogProtect 用 DogProtect 保护一个 PE,返回保护后的字节。
//
// 必须先跑它、再注入验证壳,顺序不能反:
// DogProtect 会把它要保护的节打包并清零 SizeOfRawData/PointerToRawData,
// 如果先注入验证壳(.load 节),再跑 DogProtect,.load 的内容就被搬进
// 打包节里、磁盘上留下一个 raw size = 0 的空节 —— 验证壳运行时读不到
// 自己的配置,直接失效(vfyfix 也只能修 CRC,救不了被搬走的内容)。
//
// 反过来(先 DogProtect、后注入 .load)实测可行:DogProtect 的产物仍是
// 合法 PE,Patch 能在它上面正常追加 .load 节,运行时会先跑验证壳、
// 验证通过后再跳回 DogProtect 的启动代码去解包原程序。
//
// 不支持的文件类型(非 PE)返回 errUnsupportedForDog,由调用方决定跳过。
func DogProtectProgress(src []byte, workDir string, onProgress func(pct int, stage string)) (out []byte, note string, err error) {
if !DogProtectAvailable() {
return nil, "", fmt.Errorf("DogProtect 未就绪(找不到 %s)", dogBinaryName)
}
if len(src) == 0 {
return nil, "", fmt.Errorf("源文件为空")
}
dir := dogToolDir()
if err := os.MkdirAll(workDir, 0o755); err != nil {
return nil, "", fmt.Errorf("准备工作目录: %w", err)
}
inPath := filepath.Join(workDir, "dog_in.exe")
outPath := filepath.Join(workDir, "dog_out.exe")
// 用独立的临时文件,避免上一次失败留下的半成品被当成结果
_ = os.Remove(outPath)
if err := os.WriteFile(inPath, src, 0o644); err != nil {
return nil, "", fmt.Errorf("写临时输入: %w", err)
}
defer os.Remove(inPath)
defer os.Remove(outPath)
ctx, cancel := context.WithTimeout(context.Background(), dogTimeoutSec*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, filepath.Join(dir, dogBinaryName), inPath, outPath)
// 加壳器链接时是 -Wl,-rpath,$ORIGIN,同目录有 .so 就够;
// 再显式给一份 LD_LIBRARY_PATH,免得 $(ORIGIN) 在某些环境解析不到
cmd.Env = append(os.Environ(), "LD_LIBRARY_PATH="+dir)
stdoutPipe, perr := cmd.StdoutPipe()
if perr != nil {
return nil, "", fmt.Errorf("接加壳器输出: %w", perr)
}
var stderr bytes.Buffer
cmd.Stderr = &stderr
if serr := cmd.Start(); serr != nil {
return nil, "", fmt.Errorf("启动加壳器: %w", serr)
}
// 加壳器本身只在两段各完成一次时才吐 100%,中间那几秒一片空白
// (实测 692KB 的 PE 只有 [85 100] 两个点),进度条会卡在同一个位置干等。
// 所以再加一条按时间走的估算线:每 300ms 往前推一点,封顶 88%,
// 真实进度一旦超过它就让位(realPct)。估得准不准无所谓 ——
// 它只负责「看起来在动」,到 88% 就停住等真的完成。
var realPct atomic.Int32
stopInterp := make(chan struct{})
var interpDone chan struct{}
if onProgress != nil {
interpDone = make(chan struct{})
go func() {
defer close(interpDone)
tick := time.NewTicker(300 * time.Millisecond)
defer tick.Stop()
start := time.Now()
// 6 秒走完 88%:比实测的 4.4 秒慢一点,宁可落后也别冲过头
const estSec = 6.0
last := -1
for {
select {
case <-stopInterp:
return
case <-tick.C:
frac := time.Since(start).Seconds() / estSec
guess := int(frac * 88)
if guess > 88 {
guess = 88
}
real := int(realPct.Load())
pct := guess
if real > pct {
pct = real
}
if pct != last {
last = pct
onProgress(pct, "dogprotect")
}
}
}
}()
}
// 逐行读加壳器输出,实时换算成进度;同时把全文留下来给 note 和报错用
var logBuf bytes.Buffer
scan := bufio.NewScanner(io.TeeReader(stdoutPipe, &logBuf))
scan.Buffer(make([]byte, 64*1024), 1024*1024)
for scan.Scan() {
line := scan.Text()
if onProgress == nil {
continue
}
if m := dogPctRe.FindStringSubmatch(line); m != nil {
n, _ := strconv.Atoi(m[2])
if n > 100 {
n = 100
}
pct := n * 85 / 100
if strings.HasPrefix(m[1], "Saving") {
pct = 85 + n*15/100
}
realPct.Store(int32(pct))
}
}
runErr := cmd.Wait()
if onProgress != nil {
close(stopInterp)
<-interpDone
}
combined := logBuf.String() + stderr.String()
if ctx.Err() == context.DeadlineExceeded {
return nil, "", fmt.Errorf("DogProtect 超时(>%ds)", dogTimeoutSec)
}
if runErr != nil {
return nil, "", fmt.Errorf("DogProtect 失败: %v|%s", runErr, tailLines(combined, 6))
}
// 退出码 0 也可能没产出(比如授权过期会在 stdout 里报错但退 0)
if _, statErr := os.Stat(outPath); statErr != nil {
return nil, "", fmt.Errorf("DogProtect 未生成产物|%s", tailLines(combined, 6))
}
buf, err := os.ReadFile(outPath)
if err != nil {
return nil, "", fmt.Errorf("读 DogProtect 产物: %w", err)
}
if len(buf) == 0 {
return nil, "", fmt.Errorf("DogProtect 产物为空")
}
// 从输出里捞一行增长信息做备注("Output file size is X bytes (Y%)")
for _, line := range strings.Split(combined, "\n") {
if strings.Contains(line, "Output file size") {
note = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "[Information]"))
break
}
}
return buf, note, nil
}
// tailLines 取输出末尾几行,用于把加壳器的报错带回任务 message。
func tailLines(s string, n int) string {
s = strings.TrimSpace(s)
if s == "" {
return "(无输出)"
}
lines := strings.Split(s, "\n")
if len(lines) > n {
lines = lines[len(lines)-n:]
}
out := make([]string, 0, len(lines))
for _, l := range lines {
if t := strings.TrimSpace(l); t != "" {
out = append(out, t)
}
}
return strings.Join(out, " / ")
}
+316
View File
@@ -0,0 +1,316 @@
package protect
import (
"encoding/binary"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
)
// osslsigncode verify 输出里的两个摘要,比对它们才知道签名有没有被后续改动弄坏
var (
reDigest = regexp.MustCompile(`Current message digest\s*:\s*([0-9A-Fa-f]+)`)
reCalcDigest = regexp.MustCompile(`Calculated message digest\s*:\s*([0-9A-Fa-f]+)`)
)
// peSection 在字节里找指定名字的节,返回 (SizeOfRawData, PointerToRawData)。
// 用来断言「DogProtect 有没有把验证壳节打包走」。
func peSection(data []byte, name string) (rawSize, rawPtr uint32, found bool) {
if len(data) < 0x40 || data[0] != 'M' || data[1] != 'Z' {
return 0, 0, false
}
pe := int(binary.LittleEndian.Uint32(data[0x3c:0x40]))
if pe <= 0 || pe+24 > len(data) {
return 0, 0, false
}
nsec := int(binary.LittleEndian.Uint16(data[pe+6 : pe+8]))
optSize := int(binary.LittleEndian.Uint16(data[pe+20 : pe+22]))
off := pe + 24 + optSize
for i := 0; i < nsec; i++ {
s := off + i*40
if s+40 > len(data) {
return 0, 0, false
}
nm := string(data[s : s+8])
// 节名是 8 字节定长,后面补 \0
trimmed := nm
for len(trimmed) > 0 && trimmed[len(trimmed)-1] == 0 {
trimmed = trimmed[:len(trimmed)-1]
}
if trimmed == name {
rawSize = binary.LittleEndian.Uint32(data[s+16 : s+20])
rawPtr = binary.LittleEndian.Uint32(data[s+20 : s+24])
return rawSize, rawPtr, true
}
}
return 0, 0, false
}
// TestDogProtectWrapsShellSection 锁住加壳顺序的语义:
//
// 必须是「先注入验证壳 .load、再 DogProtect 保护整个程序」。
// DogProtect 会把要保护的节打包,磁盘上留下 raw size = 0 的空节 ——
// 所以加壳产物里 .load 的 SizeOfRawData 必须是 0、PointerToRawData 必须是 0,
// 同时文件里出现 DogProtect 自己的数据节,体积明显变大。
//
// 如果哪天有人把顺序改回「先 DogProtect、后注入验证壳」,.load 会在最外层是明文
// (raw size > 0),这个测试就会失败 —— 那种产物攻击者直接改那一节就能绕过验证,
// DogProtect 只白包了原程序,没有任何保护意义。
func TestDogProtectWrapsShellSection(t *testing.T) {
if !DogProtectAvailable() {
t.Skip("DogProtect 加壳器不在这台机器上(DOGPROTECT_DIR 未设置),跳过")
}
srcPath := os.Getenv("VFY_TEST_PE")
if srcPath == "" {
t.Skip("没有样本 PE,设置 VFY_TEST_PE 指向一个合法 exe 再跑")
}
src, err := os.ReadFile(srcPath)
if err != nil {
t.Fatalf("读样本: %v", err)
}
cfg := BuildCfgThemedVer("bceb7474966af3b42e6b6981ec5d6951", "测试应用",
"https://v.viaeon.com", "dark", "1.0.0")
// 第一步:只注入验证壳
shelled, _, err := PatchAutoSignedThemed(src, cfg, filepath.Base(srcPath), false, "dark")
if err != nil {
t.Fatalf("注入验证壳: %v", err)
}
raw, ptr, ok := peSection(shelled, ".load")
if !ok {
t.Fatalf("注入后没找到 .load 节")
}
if raw == 0 || ptr == 0 {
t.Fatalf("注入后 .load 应该是明文节,实际 raw=%d ptr=%d", raw, ptr)
}
t.Logf("注入后 .load: raw=%d ptr=%d(明文,符合预期)", raw, ptr)
// 第二步:DogProtect 保护整个程序
work := t.TempDir()
protected, note, err := DogProtect(shelled, work)
if err != nil {
t.Fatalf("DogProtect: %v", err)
}
if len(protected) <= len(shelled) {
t.Fatalf("保护后体积没涨:%d → %d", len(shelled), len(protected))
}
t.Logf("保护后:%d → %d 字节 %s", len(shelled), len(protected), note)
// 关键断言:.load 在磁盘上必须被清成空节(说明它在 DogProtect 的保护范围内)
raw, ptr, ok = peSection(protected, ".load")
if !ok {
t.Fatalf("保护后 .load 节不见了(DogProtect 可能改了节名,需重新确认壳怎么找载荷)")
}
if raw != 0 || ptr != 0 {
t.Fatalf("顺序反了:.load 保护后仍是明文(raw=%d ptr=%d),"+
"说明验证壳挂在 DogProtect 外面,改掉这一节就能绕过验证", raw, ptr)
}
t.Logf("保护后 .load: raw=0 ptr=0(已打包进 DogProtect 数据节,验证壳在内层 ✓)")
}
// hasAuthenticode 判断 PE 的 Data Directory[4](Certificate Table)有没有内容。
// 有签名 → VirtualAddress/Size 非零;被 DogProtect 重写后会被清掉。
func hasAuthenticode(data []byte) (ok bool, size uint32) {
if len(data) < 0x40 || data[0] != 'M' || data[1] != 'Z' {
return false, 0
}
pe := int(binary.LittleEndian.Uint32(data[0x3c:0x40]))
if pe <= 0 || pe+24 > len(data) {
return false, 0
}
optSize := int(binary.LittleEndian.Uint16(data[pe+20 : pe+22]))
opt := pe + 24
if opt+optSize > len(data) {
return false, 0
}
magic := binary.LittleEndian.Uint16(data[opt : opt+2])
var ddOff int
switch magic {
case 0x10b: // PE32
ddOff = 96
case 0x20b: // PE32+
ddOff = 112
default:
return false, 0
}
// Data Directory[4] = Certificate Table,每项 8 字节(VA 4 + Size 4)
p := opt + ddOff + 4*8
if p+8 > len(data) {
return false, 0
}
va := binary.LittleEndian.Uint32(data[p : p+4])
sz := binary.LittleEndian.Uint32(data[p+4 : p+8])
return va != 0 && sz != 0, sz
}
// TestDogProtectStripsAuthenticode 锁住「签名必须在 DogProtect 之后」:
//
// DogProtect 重写 PE 时会把 Certificate Table(Data Directory[4])清掉,
// 产物的数字签名不是「失效」而是**整个不见了**(osslsigncode verify 报
// No signature found)。所以顺序只能是:
//
// Patch(.load) → DogProtect → Authenticode 签名
//
// 反过来(先签名再 DogProtect)看着合理,实际产物的签名是废的,
// Windows 属性页直接显示「没有数字签名」。
func TestDogProtectStripsAuthenticode(t *testing.T) {
if !DogProtectAvailable() {
t.Skip("DogProtect 加壳器不在这台机器上,跳过")
}
if _, err := exec.LookPath("osslsigncode"); err != nil {
t.Skip("没有 osslsigncode,跳过")
}
if _, err := exec.LookPath("openssl"); err != nil {
t.Skip("没有 openssl,跳过")
}
srcPath := os.Getenv("VFY_TEST_PE")
if srcPath == "" {
t.Skip("没有样本 PE,设置 VFY_TEST_PE 再跑")
}
src, err := os.ReadFile(srcPath)
if err != nil {
t.Fatalf("读样本: %v", err)
}
work := t.TempDir()
// 自签证书(production 用真实 CA 证书,这里只关心签名区存不存在)
key := filepath.Join(work, "k.pem")
crt := filepath.Join(work, "c.pem")
pfx := filepath.Join(work, "t.pfx")
if out, err := exec.Command("openssl", "req", "-x509", "-newkey", "rsa:2048",
"-keyout", key, "-out", crt, "-days", "1", "-nodes",
"-subj", "/CN=VFY Test").CombinedOutput(); err != nil {
t.Skipf("生成自签证书失败: %v %s", err, out)
}
if out, err := exec.Command("openssl", "pkcs12", "-export", "-out", pfx,
"-inkey", key, "-in", crt, "-passout", "pass:t").CombinedOutput(); err != nil {
t.Skipf("导出 pfx 失败: %v %s", err, out)
}
shelled, _, err := PatchAutoSignedThemed(src,
BuildCfgThemedVer("bceb7474966af3b42e6b6981ec5d6951", "测试应用",
"https://v.viaeon.com", "dark", "1.0.0"),
filepath.Base(srcPath), false, "dark")
if err != nil {
t.Fatalf("注入验证壳: %v", err)
}
// ---- 顺序 B(错):先签名,再 DogProtect ----
inB := filepath.Join(work, "B_in.exe")
outB := filepath.Join(work, "B_signed.exe")
os.WriteFile(inB, shelled, 0o644)
if out, err := exec.Command("osslsigncode", "sign", "-pkcs12", pfx, "-pass", "t",
"-in", inB, "-out", outB, "-h", "sha256").CombinedOutput(); err != nil {
t.Fatalf("签名失败: %v %s", err, out)
}
signedB, _ := os.ReadFile(outB)
if ok, _ := hasAuthenticode(signedB); !ok {
t.Fatalf("签名后应该有 Certificate Table")
}
dogB, _, err := DogProtect(signedB, filepath.Join(work, "dogB"))
if err != nil {
t.Fatalf("DogProtect: %v", err)
}
if ok, sz := hasAuthenticode(dogB); ok {
t.Fatalf("DogProtect 之后签名还在(cert size=%d)?"+
"如果加壳器升级后开始保留证书表,这条测试要跟着改,但顺序仍然必须是「先加壳后签名」", sz)
}
t.Logf("顺序 B(先签名后加壳):签名被抹掉 ✓ 这正是不能这么做的原因")
// ---- 顺序 A(对):先 DogProtect,再签名 ----
dogA, _, err := DogProtect(shelled, filepath.Join(work, "dogA"))
if err != nil {
t.Fatalf("DogProtect: %v", err)
}
inA := filepath.Join(work, "A_in.exe")
outA := filepath.Join(work, "A_signed.exe")
os.WriteFile(inA, dogA, 0o644)
if out, err := exec.Command("osslsigncode", "sign", "-pkcs12", pfx, "-pass", "t",
"-in", inA, "-out", outA, "-h", "sha256").CombinedOutput(); err != nil {
t.Fatalf("签名失败: %v %s", err, out)
}
signedA, _ := os.ReadFile(outA)
ok, sz := hasAuthenticode(signedA)
if !ok {
t.Fatalf("先加壳后签名的产物没有签名")
}
t.Logf("顺序 A(先加壳后签名):cert size=%d ✓", sz)
// 摘要必须匹配 —— 证书链报错(自签)不算问题,摘要不匹配才是文件被改过
out, _ := exec.Command("osslsigncode", "verify", outA).CombinedOutput()
txt := string(out)
if strings.Contains(txt, "No signature found") {
t.Fatalf("验签说没有签名")
}
cur := reDigest.FindStringSubmatch(txt)
calc := reCalcDigest.FindStringSubmatch(txt)
if len(cur) < 2 || len(calc) < 2 {
t.Logf("没能从输出里读到摘要,跳过摘要比对(输出: %s)", tail(txt, 300))
} else if cur[1] != calc[1] {
t.Fatalf("摘要不匹配:当前=%s 计算=%s —— 签名后被改动过", cur[1], calc[1])
} else {
t.Logf("摘要一致:%s ✓", cur[1])
}
}
// TestDogProtectRejectsMissingTool 加壳器不在时必须明确报错,
// 不能让调用方误以为「已经加了保护」。
func TestDogProtectRejectsMissingTool(t *testing.T) {
old := os.Getenv(dogToolDirEnv)
defer os.Setenv(dogToolDirEnv, old)
os.Setenv(dogToolDirEnv, "/nonexistent/dogprotect/dir")
if DogProtectAvailable() {
t.Fatal("指向不存在的目录却报告可用")
}
if _, _, err := DogProtect([]byte("MZ fake"), t.TempDir()); err == nil {
t.Fatal("加壳器缺失却没报错 —— 调用方会把「没保护」当成「已保护」")
}
}
// TestDogProtectReportsProgress 确认进度条在 DogProtect 那 4 秒里会连续走,
// 不是卡在 45% 干等。加壳器只吐 "Packing... N%" 和 "Saving startup code... N%",
// 这两段要映射成 0-85 / 85-100。
func TestDogProtectReportsProgress(t *testing.T) {
if !DogProtectAvailable() {
t.Skip("DogProtect 加壳器不在这台机器上,跳过")
}
srcPath := os.Getenv("VFY_TEST_PE")
if srcPath == "" {
t.Skip("没有样本 PE,设置 VFY_TEST_PE 再跑")
}
src, err := os.ReadFile(srcPath)
if err != nil {
t.Fatalf("读样本: %v", err)
}
var got []int
_, _, err = DogProtectProgress(src, t.TempDir(), func(pct int, stage string) {
if stage != "dogprotect" {
t.Errorf("进度回调的 stage 应该是 dogprotect,实际 %q", stage)
}
if pct < 0 || pct > 100 {
t.Errorf("百分比越界: %d", pct)
}
got = append(got, pct)
})
if err != nil {
t.Fatalf("DogProtect: %v", err)
}
if len(got) < 2 {
t.Fatalf("只收到 %d 个进度点(%v),进度条会卡着不动", len(got), got)
}
for i := 1; i < len(got); i++ {
if got[i] < got[i-1] {
t.Fatalf("进度回退: %v", got)
}
}
if got[len(got)-1] < 85 {
t.Fatalf("最后一个进度点 %d%% 太低,说明 startup 那段没被覆盖: %v", got[len(got)-1], got)
}
t.Logf("进度序列 %v(%d 个点)", got, len(got))
}
+1 -1
View File
@@ -335,7 +335,7 @@ func ParsePFX(data []byte, password string) (PFXInfo, error) {
case info.KeyCount == 1 && info.CertCount > 1:
info.Note = fmt.Sprintf("含 %d 张证书(1 套私钥 + %d 张链上证书),签名会带完整证书链", info.CertCount, info.LooseCerts)
case info.KeyCount > 1:
info.Note = fmt.Sprintf("含 %d 套可签名身份(私钥 %d 把),加壳时可任选其中一套",
info.Note = fmt.Sprintf("含 %d 套可签名身份(私钥 %d 把),云端加密时可任选其中一套",
len(matched), info.KeyCount)
}
return info, nil
+105 -23
View File
@@ -1,7 +1,7 @@
// Package protect:服务端给 PE 注入验证壳(改入口 + 内嵌壳 DLL + 双层 CRC32)
//
// 产物结构:原 exe 追加 .vfy 节 = [48B 头][引导 blob][壳 DLL][配置 JSON]
// 入口指向 .vfy 内的引导代码;引导代码反射加载 DLL(零落盘)。
// 产物结构:原 exe 追加 .load 节 = [48B 头][引导 blob][壳 DLL][配置 JSON]
// 入口指向 .load 内的引导代码;引导代码反射加载 DLL(零落盘)。
package protect
import (
@@ -18,20 +18,21 @@ import (
"verification-platform-backend/internal/model"
)
//go:embed assets/blob64.bin assets/blob32.bin assets/shell64.bin assets/shell32.bin assets/shell64_dui.bin
//go:embed assets/blob64.bin assets/blob32.bin assets/shell64.bin assets/shell32.bin assets/shell64_dui.bin assets/shell32_dui.bin
var assets embed.FS
const (
hdrSize = 48
crcOff = 36
secName = ".vfy"
secName = ".load"
legacySec = ".vfy" // 旧产物用 .vfy,检测时一并识别(新产物一律写 .load)
shellVer = 8
secAttrib = 0x60000020 // CODE | EXECUTE | READ
)
// ShellThemes 可选的验证界面皮肤。classic = 原 Direct2D 壳,其余是 DuiLib 壳
var ShellThemes = map[string]string{
"classic": "经典(Direct2D 原版)",
"classic": "经典(Direct2D·不支持按配置切卡密/隐藏注册)",
"dark": "深色 · 竖排紧凑",
"light": "浅色 · 办公风",
"industrial": "工业蓝 · 设备授权",
@@ -42,7 +43,8 @@ var ShellThemes = map[string]string{
}
// ShellThemeOrder 主题的展示顺序(报错文案、前端下拉都按这个来)
var ShellThemeOrder = []string{"classic", "dark", "light", "industrial", "compact", "split", "card", "terminal"}
// dark 排第一:面板下拉默认选第一项,而 classic 不支持按配置切换登录方式
var ShellThemeOrder = []string{"dark", "light", "industrial", "compact", "split", "card", "terminal", "classic"}
// ShellThemeList 返回「键=显示名」的有序切片,给前端/文档用
func ShellThemeList() []map[string]string {
@@ -57,7 +59,11 @@ func ShellThemeList() []map[string]string {
func NormalizeTheme(theme string) string {
t := strings.ToLower(strings.TrimSpace(theme))
if t == "" {
return "classic"
// 默认给 dark 而不是 classic:classic 是 Direct2D 老壳,源码里没有
// login_mode / FetchAppInfo 这套逻辑(login_mode、卡密、billing_type
// 全是 0 处匹配),界面永远固定成「账号+密码+注册」——跟着应用配置
// 切卡密、隐藏注册、控制充值 tab 全都不会生效。
return "dark"
}
if _, ok := ShellThemes[t]; ok {
return t
@@ -70,18 +76,22 @@ func Assets(arch string) (blob, dll []byte, err error) {
return AssetsThemed(arch, "classic")
}
// AssetsThemed 按主题取壳:DuiLib 版只有 x64,x86 仍回落到 classic
// AssetsThemed 按主题取壳。DuiLib 壳 x64 / x86 各有一份构建
// (shell64_dui.bin / shell32_dui.bin),两边的皮肤完全一致。
//
// 注意:classic 现在也走 DuiLib 壳。原来它指向 shell64.bin / shell32.bin
// 那套 Direct2D 壳,但那套壳里没有 login_mode / FetchAppInfo 逻辑,
// 界面永远固定成「账号+密码+注册」,跟着应用配置切卡密登录、隐藏注册、
// 控制充值 tab 全都不生效。现在已经用 DuiLib 按原配色(VS Code 暗色系)
// 重做了一套 classic 皮肤,走和其他 7 套一样的链路。
// 老产物(.vfy 节)不受影响,HasVfy 仍然认 .vfy。
func AssetsThemed(arch, theme string) (blob, dll []byte, err error) {
var bp, dp string
switch arch {
case "x64":
bp, dp = "assets/blob64.bin", "assets/shell64.bin"
// DuiLib 壳只有 64 位构建
if theme != "" && theme != "classic" {
dp = "assets/shell64_dui.bin"
}
bp, dp = "assets/blob64.bin", "assets/shell64_dui.bin"
case "x86":
bp, dp = "assets/blob32.bin", "assets/shell32.bin"
bp, dp = "assets/blob32.bin", "assets/shell32_dui.bin"
default:
return nil, nil, fmt.Errorf("不支持的架构: %s", arch)
}
@@ -96,8 +106,8 @@ func AssetsThemed(arch, theme string) (blob, dll []byte, err error) {
return blob, dll, nil
}
// HasVfy 判断 PE 里是不是已经有 .vfy 节(已被加过壳)。
// 二次加壳会在文件里留下两个 .vfy:旧壳的 cfg 指向老服务器、白占几百 KB,
// HasVfy 判断 PE 里是不是已经有壳节(.load,或旧产物的 .vfy)。
// 二次加壳会在文件里留下两个壳节:旧壳的 cfg 指向老服务器、白占几百 KB,
// 目标机跳的却是新节,排查时极易被旧头误导,所以入口直接挡掉。
func HasVfy(target []byte) bool {
f, err := pe.NewFile(bytes.NewReader(target))
@@ -106,7 +116,7 @@ func HasVfy(target []byte) bool {
}
defer f.Close()
for _, s := range f.Sections {
if strings.HasPrefix(s.Name, secName) {
if strings.HasPrefix(s.Name, secName) || strings.HasPrefix(s.Name, legacySec) {
return true
}
}
@@ -141,7 +151,7 @@ func PatchSignedThemed(target, cfg []byte, arch string, signed bool, theme strin
return nil, info, fmt.Errorf("缺少目标架构")
}
if theme == "" {
theme = "classic"
theme = "dark"
}
blob, dll, err := AssetsThemed(arch, theme)
if err != nil {
@@ -342,7 +352,7 @@ func BuildCfgThemed(appKey, appName, baseURL, theme string) []byte {
func BuildCfgThemedVer(appKey, appName, baseURL, theme, ver string) []byte {
api := fmt.Sprintf("%s/api/v1/app/%s/login", strings.TrimRight(baseURL, "/"), appKey)
if theme == "" {
theme = "classic"
theme = "dark"
}
ver = strings.TrimSpace(ver)
cfg := fmt.Sprintf(`{"api":%q,"name":%q,"device_auto":1,"shell_ver":%d,"theme":%q,"ver":%q}`,
@@ -376,6 +386,14 @@ func (r *Runner) Run(srcPath, outPath string, cfg []byte) (Info, error) {
// RunWithTask 带任务上下文的执行:IPA 需要任务上的签名证书与壳 dylib
func (r *Runner) RunWithTask(task *model.ProtectTask, srcPath, outPath string, cfg []byte) (Info, error) {
// 进度上报用;task 可能是 nil(命令行工具直接调 Run 时)
var taskID uint
if task != nil {
taskID = task.ID
}
defer clearProgress(taskID)
reportProgress(taskID, 5, "prepare")
src, err := os.ReadFile(srcPath)
if err != nil {
return Info{}, fmt.Errorf("读源文件: %w", err)
@@ -404,7 +422,7 @@ func (r *Runner) RunWithTask(task *model.ProtectTask, srcPath, outPath string, c
// 内核驱动(.sys / 子系统 NATIVE):绝不能塞用户态验证壳,注进去驱动直接加载失败。
// 驱动要的是 Authenticode 签名,所以这里只签名、不注入。
if task.SignProfileID == nil {
return info, fmt.Errorf("内核驱动只能签名、不能加壳;请选择一张支持驱动签名用途的证书")
return info, fmt.Errorf("内核驱动只能签名、不能加密;请选择一张支持驱动签名用途的证书")
}
mat, merr := LoadMaterial(*task.SignProfileID, task.CertIdentity)
if merr != nil {
@@ -424,12 +442,69 @@ func (r *Runner) RunWithTask(task *model.ProtectTask, srcPath, outPath string, c
} else {
// PE:任务带证书 → 走「签名构建」(flags.bit1,crcFile 留空),注入完成后再 Authenticode 重签
signed := det.Kind == KindPE && task != nil && task.SignProfileID != nil
theme := "classic"
// 兜底跟 NormalizeTheme 保持一致用 dark:classic 壳不支持按配置
// 切卡密登录/隐藏注册,落到它上面等于界面配置全部失效
theme := "dark"
if task != nil && task.ShellTheme != "" {
theme = task.ShellTheme
}
// 先注入验证壳、再用 DogProtect 保护整个程序 —— 这个顺序才有安全意义。
//
// 反过来的(先 dog 后 verify)能跑但没用:DogProtect 只包住原程序,
// 明文 .load 验证壳挂在最外层,攻击者拿 PE 工具直接改/删那一节就绕过验证,
// 根本不用碰 DogProtect 那层。
//
// 现在这个顺序:验证壳代码和配置都在 DogProtect 的保护范围内,
// 想改验证逻辑(比如把校验结果强改成功)必须先拆掉 DogProtect 的
// 虚拟化外壳,难度完全不是一个量级。
//
// 为什么还能跑:DogProtect 加壳后磁盘上 .load 的 SizeOfRawData/
// PointerToRawData 都是 0(内容打包进了 .BmR* 节),但引导 stub
// 是用 VirtualAddress 从内存镜像读载荷的(bootstrap.c:
// hdr = (VFYHDR *)(img + *(u32 *)(s + 12))),而 DogProtect 在
// 启动时解包、内存里节表和数据都是原始内容,所以壳照常读到自己的配置。
//
// 注意:这样壳不能在磁盘上校验整文件 CRC(DogProtect 必然改动整个文件),
// 实测当前 blob 不拦。如果以后换的 blob 严格要求 crcFile,会启动即退出 ——
// 那时要在 DogProtect 之前把校验关掉,不能靠事后重算(.load 已不可读)。
//
// 只对 PE 生效(APK/IPA/ELF/Mach-O 走各自的分支,DogProtect 不管)。
reportProgress(taskID, 12, "shell")
out, info, perr = PatchAutoSignedThemed(src, cfg, filepath.Base(srcPath), signed, theme)
// 验证壳注入完,先交给 DogProtect 把整个程序(含验证壳)保护起来。
if perr == nil && det.Kind == KindPE && DogProtectAvailable() {
// DogProtect 是整条流水线里最慢的一步(几百 KB 的 PE 要 4 秒以上),
// 它的内部输出换算成 45-90 这段,前端进度条才不会一直停在原地。
reportProgress(taskID, 45, "dogprotect")
dogged, dn, derr := DogProtectProgress(out, filepath.Join(filepath.Dir(outPath), "dog"),
func(pct int, _ string) {
reportProgress(taskID, 45+pct*45/100, "")
})
if derr != nil {
// 保护是默认承诺,不能悄悄降级成「只打了验证壳」
return info, fmt.Errorf("DogProtect 保护失败:%w", derr)
}
out = dogged
reportProgress(taskID, 90, "")
note := "DogProtect 已保护(验证壳在内层)"
if dn != "" {
note += "(" + dn + ")"
}
if info.Note != "" {
info.Note = note + ";" + info.Note
} else {
info.Note = note
}
}
// Authenticode 重签必须放在最后一步:签名是对整个 PE 算哈希的,
// 任何后续改动(DogProtect 打包、改入口、加启动代码)都会让签名失效。
// 反过来的顺序看着「先签好再保护」,实际产物的签名是废的,
// Windows 属性页会直接报「数字签名无效 / 文件已被修改」。
if perr == nil && signed {
reportProgress(taskID, 92, "sign")
var mat *Material
mat, perr = LoadMaterial(*task.SignProfileID, task.CertIdentity)
if perr == nil {
@@ -437,9 +512,14 @@ func (r *Runner) RunWithTask(task *model.ProtectTask, srcPath, outPath string, c
var note string
out, note, perr = SignPE(out, mat, filepath.Join(filepath.Dir(outPath), "pe_sign"))
if perr == nil {
info.Note = "已用你的证书做 Authenticode 重签"
signNote := "已用你的证书做 Authenticode 重签(对最终产物签名)"
if note != "" {
info.Note += "(" + note + ")"
signNote += "(" + note + ")"
}
if info.Note != "" {
info.Note = signNote + ";" + info.Note
} else {
info.Note = signNote
}
}
}
@@ -449,12 +529,14 @@ func (r *Runner) RunWithTask(task *model.ProtectTask, srcPath, outPath string, c
err = perr
return info, err
}
reportProgress(taskID, 97, "writing")
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
return info, err
}
if err := os.WriteFile(outPath, out, 0o644); err != nil {
return info, fmt.Errorf("写产物: %w", err)
}
reportProgress(taskID, 100, "done")
return info, nil
}
+1 -1
View File
@@ -32,7 +32,7 @@ type PublishOptions struct {
func PublishAsVersion(taskID uint, opts PublishOptions) (*model.Version, error) {
var task model.ProtectTask
if err := database.DB.First(&task, taskID).Error; err != nil {
return nil, fmt.Errorf("加壳任务不存在")
return nil, fmt.Errorf("云端加密任务不存在")
}
if task.Status != "done" || task.OutputPath == "" {
return nil, fmt.Errorf("任务尚未完成,无法生成版本")
+61 -4
View File
@@ -1,11 +1,11 @@
package protect
import (
"strings"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
@@ -18,6 +18,63 @@ var (
shared *Runner
)
// lastProgress 记住每个任务上次写库的百分比,用来节流。
// 加壳器是逐行吐进度的,PE 大一点能吐几十次,每次都写库没必要。
var lastProgress sync.Map // taskID(uint) -> int
// reportProgress 更新加壳进度(0-100)和阶段 key,前端拿它画进度条。
//
// 写库失败只打日志:进度是展示信息,不能因为它写不进去就把整个加壳任务判失败。
func reportProgress(taskID uint, pct int, stage string) {
if taskID == 0 {
return
}
if pct < 0 {
pct = 0
}
if pct > 100 {
pct = 100
}
if v, ok := lastProgress.Load(taskID); ok {
if prev, _ := v.(int); prev == pct && stage == "" {
return
}
}
lastProgress.Store(taskID, pct)
upd := map[string]interface{}{"progress": pct}
if stage != "" {
upd["stage"] = stage
}
if err := database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).Updates(upd).Error; err != nil {
log.Printf("[PROTECT] 写进度失败 task=%d pct=%d: %v", taskID, pct, err)
}
}
// clearProgress 任务收尾时把节流记录删掉,避免长跑进程里这个 map 一直涨。
func clearProgress(taskID uint) {
lastProgress.Delete(taskID)
}
// ProgressStageLabel 给日志和 message 用的人类可读阶段名(前端自己按 key 翻译)
func ProgressStageLabel(stage string) string {
switch stage {
case "prepare":
return "准备源文件"
case "shell":
return "注入验证壳"
case "dogprotect":
return "DogProtect 保护"
case "sign":
return "证书签名"
case "writing":
return "写出产物"
case "done":
return "完成"
}
return stage
}
// Default 返回进程内共享的 Runner(目录可用 PROTECT_DIR 覆盖,默认 data/protect)
func Default() *Runner {
runnerOnce.Do(func() { shared = NewRunner(os.Getenv("PROTECT_DIR")) })
@@ -34,7 +91,7 @@ func createTask(app *model.Application, userID uint, srcName string, data []byte
return nil, "", err
}
if det.Kind == KindPE && HasVfy(data) {
return nil, "", fmt.Errorf("这个文件已经是加壳后的产物(带 .vfy 节),请上传未加壳的原始程序")
return nil, "", fmt.Errorf("这个文件已经是云端加密后的产物(带 .load/.vfy 节),请上传未加密的原始程序")
}
// 签名证书必须在建任务时就落库:execute 是 go 协程,事后 UPDATE 有窗口
// 被它读到 NULL,导致证书被静默忽略(任务照样成功,只是没重签)。
@@ -129,7 +186,7 @@ func CreateAndRunThemedVer(app *model.Application, userID uint, srcName string,
}
ver := strings.TrimSpace(programVer)
if ver == "" {
ver = programVersion(task.VersionID) // 没手填就退回来源版本的版本号
ver = programVersion(task.VersionID) // 没手填就退回来源版本的版本号
}
cfg := BuildCfgThemedVer(app.AppKey, app.Name, baseURL, theme, ver)
go execute(task.ID, srcPath, srcName, cfg)
@@ -199,5 +256,5 @@ func infoMessage(info Info) string {
if info.Note != "" {
return info.Note
}
return fmt.Sprintf("入口 0x%x → 0x%x,.vfy RVA=0x%x", info.EntryOld, info.EntryNew, info.SecRVA)
return fmt.Sprintf("入口 0x%x → 0x%x,壳节 RVA=0x%x", info.EntryOld, info.EntryNew, info.SecRVA)
}
@@ -0,0 +1,69 @@
package protect
import "testing"
// TestNormalizeThemeDefaultIsDark 默认皮肤必须是 dark,不能是 classic。
//
// 回归背景:面板上皮肤下拉的顺序取自 ShellThemeOrder,默认选中第一项;
// 而 NormalizeTheme("") 以前也返回 "classic"。classic 是 Direct2D 老壳,
// 源码里没有 login_mode / FetchAppInfo(login_mode、卡密、billing_type
// 全 0 处匹配),界面固定成「账号+密码+注册」——应用配了卡密登录、
// 配了隐藏注册、配了充值 tab,产物全都不跟随。
//
// 用户看到的现象就是「换哪个风格都不生效」,其实是他落到了 classic 上。
func TestNormalizeThemeDefaultIsDark(t *testing.T) {
cases := []struct {
in string
want string
}{
{"", "dark"}, // 空值 → dark
{" ", "dark"}, // 空白 → dark
{"classic", "classic"}, // 显式选 classic 仍然尊重(老壳,功能受限)
{"DARK", "dark"}, // 大小写不敏感
{" light ", "light"},
{"nope", ""}, // 未知值返回空,由调用方报错
}
for _, c := range cases {
if got := NormalizeTheme(c.in); got != c.want {
t.Errorf("NormalizeTheme(%q) = %q, want %q", c.in, got, c.want)
}
}
// 下拉第一项决定面板默认选中,必须是支持配置的 DuiLib 皮肤
if len(ShellThemeOrder) == 0 {
t.Fatal("ShellThemeOrder 为空")
}
if ShellThemeOrder[0] != "dark" {
t.Errorf("ShellThemeOrder[0] = %q,应为 dark;classic 不支持按配置切登录方式,不能当默认",
ShellThemeOrder[0])
}
if ShellThemeOrder[len(ShellThemeOrder)-1] != "classic" {
t.Errorf("classic 应排在最后,实际在 %q", ShellThemeOrder[len(ShellThemeOrder)-1])
}
// 每个候选主题都得有显示名,否则面板下拉会出空项
for _, k := range ShellThemeOrder {
if ShellThemes[k] == "" {
t.Errorf("主题 %q 缺显示名", k)
}
}
}
// TestClassicShellHasNoLoginModeSupport 用文件事实锁住 classic 的限制,
// 避免以后有人把默认值改回 classic 却不知道代价。
func TestShellThemeOrderCoversAllThemes(t *testing.T) {
if len(ShellThemeOrder) != len(ShellThemes) {
t.Errorf("ShellThemeOrder 有 %d 项,ShellThemes 有 %d 项,两边不一致",
len(ShellThemeOrder), len(ShellThemes))
}
seen := map[string]bool{}
for _, k := range ShellThemeOrder {
if seen[k] {
t.Errorf("ShellThemeOrder 里 %q 重复", k)
}
seen[k] = true
if _, ok := ShellThemes[k]; !ok {
t.Errorf("ShellThemeOrder 里的 %q 在 ShellThemes 中不存在", k)
}
}
}
@@ -30,6 +30,7 @@ func SetupApplicationRoutes(r *gin.RouterGroup) {
applications.PUT("/:id", handleUpdateApplication)
applications.DELETE("/:id", handleDeleteApplication)
applications.GET("/:id", handleGetApplication)
applications.GET("/:id/login-mode-impact", handleLoginModeImpact)
applications.POST("/:id/icon", handleUploadIcon)
applications.POST("/:id/upload", handleUploadVersionFile)
applications.GET("/:id/versions", handleGetVersions)
@@ -212,6 +213,8 @@ func handleCreateApplication(c *gin.Context) {
EncryptKey: encryptKey,
BillingType: req.BillingType,
LoginPolicy: loginPolicy,
LoginMode: "both", // 新建应用默认两种登录方式都开,避免上线即把某一类用户挡在门外
LoginModeEnforce: "warn", // 默认只记录不拦截,管理员确认影响面后再切 strict
EncryptType: encryptType,
BindType: req.BindType,
MaxDevices: maxDevices,
@@ -302,6 +305,9 @@ func handleUpdateApplication(c *gin.Context) {
BillingType string `form:"billing_type" json:"billing_type"`
LoginPolicy string `form:"login_policy" json:"login_policy"`
LoginMode string `form:"login_mode" json:"login_mode"`
// 登录方式开关的生效级别与宽限期(前端「登录方式」卡片里的那两项)
LoginModeEnforce string `form:"login_mode_enforce" json:"login_mode_enforce"`
LoginModeGraceDays *int `form:"login_mode_grace_days" json:"login_mode_grace_days"`
CardLoginBindDevice *bool `form:"card_login_bind_device" json:"card_login_bind_device"`
CardLoginAllowPassword *bool `form:"card_login_allow_password" json:"card_login_allow_password"`
AllowRegister bool `form:"allow_register" json:"allow_register"`
@@ -378,12 +384,32 @@ func handleUpdateApplication(c *gin.Context) {
if req.BillingType != "" {
app.BillingType = req.BillingType
}
oldLoginMode := app.LoginMode
if req.LoginMode != "" {
switch req.LoginMode {
case "account", "card", "both":
app.LoginMode = req.LoginMode
}
}
if req.LoginModeEnforce != "" {
switch req.LoginModeEnforce {
case "off", "warn", "strict":
app.LoginModeEnforce = req.LoginModeEnforce
}
}
// 宽限期:显式传了按传的算(0 = 立即生效,顺带清掉截止时间);
// 没传但刚切换了登录方式,自动给 7 天,避免存量用户被一刀切挡在门外。
if req.LoginModeGraceDays != nil {
if *req.LoginModeGraceDays > 0 {
until := time.Now().AddDate(0, 0, *req.LoginModeGraceDays)
app.LoginModeGraceUntil = &until
} else {
app.LoginModeGraceUntil = nil
}
} else if req.LoginMode != "" && req.LoginMode != oldLoginMode {
until := time.Now().AddDate(0, 0, 7)
app.LoginModeGraceUntil = &until
}
if req.CardLoginBindDevice != nil {
app.CardLoginBindDevice = *req.CardLoginBindDevice
}
@@ -1143,3 +1169,63 @@ func handleManualDeduct(c *gin.Context) {
"message": "扣费成功",
})
}
// handleLoginModeImpact 登录方式切换的影响面。
// 面板在把 login_mode 改成 account / card 之前先调这个,看清楚有多少主体会被挡住,
// 再决定是「只记录」「开宽限期」还是「先跑迁移动作」。
func handleLoginModeImpact(c *gin.Context) {
userID := c.GetUint("user_id")
var app model.Application
if err := database.DB.Where("id = ? AND user_id = ?", c.Param("id"), userID).First(&app).Error; err != nil {
response.Error(c, 404, "应用不存在")
return
}
var total, cardSubjects, cardWithEmail, onlyAccount int64
database.DB.Model(&model.AppUser{}).Where("application_id = ?", app.ID).Count(&total)
// 卡密主体的密码是建主体时写进去的随机散列(卡密才是它的钥匙),所以不能靠 password 是否为空判断。
// 这里用「有没有绑邮箱」来区分:绑了邮箱的卡密主体有自助设密码的通道,没绑的只能靠卡密登录。
database.DB.Model(&model.AppUser{}).
Where("application_id = ? AND subject_type = ?", app.ID, "card").
Count(&cardSubjects)
database.DB.Model(&model.AppUser{}).
Where("application_id = ? AND subject_type = ?", app.ID, "card").
Where("email IS NOT NULL AND email <> ''").
Count(&cardWithEmail)
onlyCard := cardSubjects - cardWithEmail
if onlyCard < 0 {
onlyCard = 0
}
// 仅账号主体:有账号但一张卡都没绑过 → 切到 card 后他们登不进来。
// 不再用 cards.purpose 反查,任何挂在这个主体上的卡都算数。
database.DB.Model(&model.AppUser{}).
Where("application_id = ? AND subject_type = ?", app.ID, "account").
Where("NOT EXISTS (SELECT 1 FROM cards WHERE cards.subject_id = app_users.id AND cards.deleted_at IS NULL)").
Count(&onlyAccount)
mode := service.AppLoginMode(&app)
graceDays := service.LoginModeGraceDaysLeft(&app)
blocking := (mode == "account" && onlyCard > 0) || (mode == "card" && onlyAccount > 0)
// 切换成该模式后会被挡住的人数(给前端直接显示,不用自己算)
blockedIfSwitch := onlyCard
if mode == "card" {
blockedIfSwitch = onlyAccount
}
response.Success(c, gin.H{
"login_mode": mode,
"login_mode_enforce": service.AppLoginModeEnforce(&app),
"login_mode_grace_days": graceDays,
"total_subjects": total,
"card_subjects": cardSubjects,
"card_subjects_with_email": cardWithEmail,
"only_card_subjects": onlyCard,
"only_account_subjects": onlyAccount,
"blocking": blocking,
"blocked_if_switch": blockedIfSwitch,
})
}
+89 -34
View File
@@ -276,6 +276,11 @@ func handleCreateCardType(c *gin.Context) {
valueUnit = "day"
}
if err := checkCardTypeMatchesAppBilling(req.ApplicationID, rechargeType); err != nil {
response.Error(c, 400, err.Error())
return
}
cardType := model.CardType{
UserID: userID,
Name: req.Name,
@@ -355,6 +360,12 @@ func handleUpdateCardType(c *gin.Context) {
cardType.Status = req.Status
}
// 改计费方式时同样要对齐应用,否则改完就把自己变成「充了没人读」的卡型
if err := checkCardTypeMatchesAppBilling(cardType.ApplicationID, cardType.RechargeType); err != nil {
response.Error(c, 400, err.Error())
return
}
if err := database.DB.Save(&cardType).Error; err != nil {
response.Error(c, 500, "更新卡密类型失败")
return
@@ -1103,6 +1114,42 @@ func handleBatchDeleteCards(c *gin.Context) {
response.Success(c, gin.H{"deleted_count": len(validIDs)})
}
// checkCardTypeMatchesAppBilling 卡型的计费方式必须和应用一致。
//
// 应用按订阅计费、卡型却是余额型(或反之),用户充进去的那个字段
// 没有任何代码会读 —— 钱花了、没效果、还不报错。这是最容易让客户
// 白付钱的配置错误,所以在建卡型这一步就挡住。
//
// free 等其它模式不限制(免费应用可能先把卡型备着)。
func checkCardTypeMatchesAppBilling(appID uint, rechargeType string) error {
if appID == 0 {
return nil
}
var app model.Application
if err := database.DB.First(&app, appID).Error; err != nil {
return nil // 应用不存在由调用方各自的校验负责
}
var want, wantCN string
switch app.BillingType {
case "subscription":
want, wantCN = "subscription", "时长(订阅)"
case "balance", "":
want, wantCN = "balance", "余额"
default:
return nil
}
if rechargeType != want {
gotCN := "余额"
if rechargeType == "subscription" {
gotCN = "时长(订阅)"
}
return fmt.Errorf("该应用按「%s」计费,卡型也必须是%s型;当前选的是「%s」型,"+
"用它充进去的额度不会被任何逻辑读取", wantCN, wantCN, gotCN)
}
return nil
}
// normalizeCardPurpose 卡型用途白名单:recharge(充值卡) / credential(登录卡)
func normalizeCardPurpose(v string) string {
switch v {
@@ -1113,7 +1160,6 @@ func normalizeCardPurpose(v string) string {
}
}
// handleReissueCard 作废旧卡密并补发一张新卡:主体、余额、到期、设备全部保留,
// 只是换了一把钥匙 —— 卡密泄露时用这个,不要让用户重新买/重新绑定。
func handleReissueCard(c *gin.Context) {
@@ -1129,10 +1175,8 @@ func handleReissueCard(c *gin.Context) {
response.Error(c, 404, "卡密不存在")
return
}
if card.Purpose != "credential" {
response.Error(c, 400, "只有登录卡需要补发,充值卡直接作废即可")
return
}
// 换钥匙只对「已经激活、绑了主体」的卡有意义:作废旧卡、发张新卡、
// 主体/余额/到期/设备全都保留。没激活的卡直接作废就行,不需要补发。
if card.SubjectID == nil {
response.Error(c, 400, "这张卡还没有被激活,直接作废就行")
return
@@ -1160,7 +1204,7 @@ func handleReissueCard(c *gin.Context) {
ApplicationID: card.ApplicationID,
CardTypeID: card.CardTypeID,
CardKey: newKey,
Purpose: "credential",
Purpose: card.Purpose, // 字段保留但不参与任何判断,跟着原卡走
CreatorID: card.CreatorID,
AgentID: card.AgentID,
SubjectID: card.SubjectID, // 同一个主体,换钥匙不换人
@@ -1185,10 +1229,10 @@ func handleReissueCard(c *gin.Context) {
fmt.Sprintf("作废卡密 %s 并补发 %s", card.CardKey, newKey), "", nil)
response.Success(c, gin.H{
"message": "已作废旧卡密并补发新卡密",
"old_key": card.CardKey,
"new_key": newKey,
"subject": card.SubjectID,
"message": "已作废旧卡密并补发新卡密",
"old_key": card.CardKey,
"new_key": newKey,
"subject": card.SubjectID,
})
}
@@ -1204,29 +1248,39 @@ func handleCardSecurity(c *gin.Context) {
}
}
type purposeStat struct {
Purpose string `json:"purpose"`
Status string `json:"status"`
Count int64 `json:"count"`
// 口径:卡不再分「登录卡 / 充值卡」,改为按「是否已激活成主体」+ 状态看。
// activated = 已经绑了 subject_id 的卡(就是走完首次登录的钥匙)
// unused = 还没用过的卡
type statusStat struct {
Status string `json:"status"`
Count int64 `json:"count"`
}
var stats []purposeStat
q.Select("purpose, status, count(*) as count").Group("purpose, status").Scan(&stats)
var stats []statusStat
q.Select("status, count(*) as count").Group("status").Scan(&stats)
var credentialTotal, credentialUsed, credentialVoid, rechargeTotal int64
var total, usedCount, unusedCount, voidCount int64
for _, s := range stats {
if s.Purpose == "credential" {
credentialTotal += s.Count
switch s.Status {
case "used":
credentialUsed += s.Count
case "void":
credentialVoid += s.Count
}
} else {
rechargeTotal += s.Count
total += s.Count
switch s.Status {
case "used":
usedCount += s.Count
case "void":
voidCount += s.Count
case "unused":
unusedCount += s.Count
}
}
// 已激活 = 有主体可回;与 status 正交(补发过的旧卡是 void 但仍有主体)
var activatedCount int64
aq := database.DB.Model(&model.Card{}).Where("creator_id = ? AND subject_id IS NOT NULL", userID)
if appID != "" {
if v, err := strconv.Atoi(appID); err == nil {
aq = aq.Where("application_id = ?", v)
}
}
aq.Count(&activatedCount)
// 失败次数直接从验证日志数:卡密分支的失败文案固定以「登录失败: 卡密」开头
since := time.Now().Add(-24 * time.Hour)
var failCount int64
@@ -1261,13 +1315,14 @@ func handleCardSecurity(c *gin.Context) {
tf.Scan(&byType)
response.Success(c, gin.H{
"failed_by_type": byType,
"credential_total": credentialTotal,
"credential_used": credentialUsed,
"credential_void": credentialVoid,
"recharge_total": rechargeTotal,
"failed_24h": failCount,
"breakdown": stats,
"failed_by_type": byType,
"total": total,
"activated": activatedCount,
"used": usedCount,
"unused": unusedCount,
"void": voidCount,
"failed_24h": failCount,
"breakdown": stats,
})
}
@@ -0,0 +1,73 @@
package admin
import (
"fmt"
"testing"
"time"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
)
func setupAdminTestDB(t *testing.T) {
t.Helper()
dsn := fmt.Sprintf("file:a%d?mode=memory&cache=shared", time.Now().UnixNano())
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("打开测试库失败: %v", err)
}
database.DB = db
if err := db.AutoMigrate(&model.Application{}, &model.CardType{}); err != nil {
t.Fatalf("迁移失败: %v", err)
}
}
// TestCheckCardTypeMatchesAppBilling 卡型计费方式必须和应用一致,
// 否则用户充进去的字段没有任何代码读 —— 钱花了、没效果、还不报错。
func TestCheckCardTypeMatchesAppBilling(t *testing.T) {
setupAdminTestDB(t)
subApp := model.Application{AppKey: "sub1", Name: "订阅应用", BillingType: "subscription", Status: "active"}
balApp := model.Application{AppKey: "bal1", Name: "余额应用", BillingType: "balance", Status: "active"}
freeApp := model.Application{AppKey: "free1", Name: "免费应用", BillingType: "free", Status: "active"}
for _, a := range []*model.Application{&subApp, &balApp, &freeApp} {
if err := database.DB.Create(a).Error; err != nil {
t.Fatalf("建应用失败: %v", err)
}
}
cases := []struct {
name string
appID uint
rechargeType string
wantErr bool
}{
{"订阅应用 + 订阅卡型", subApp.ID, "subscription", false},
{"订阅应用 + 余额卡型(应拦)", subApp.ID, "balance", true},
{"余额应用 + 余额卡型", balApp.ID, "balance", false},
{"余额应用 + 订阅卡型(应拦)", balApp.ID, "subscription", true},
{"免费应用不限制", freeApp.ID, "subscription", false},
{"免费应用不限制(余额)", freeApp.ID, "balance", false},
{"应用不存在时放行(交给上层校验)", 99999, "balance", false},
{"未指定应用时放行", 0, "balance", false},
}
for _, c := range cases {
err := checkCardTypeMatchesAppBilling(c.appID, c.rechargeType)
if c.wantErr && err == nil {
t.Errorf("%s: 期望报错,实际通过", c.name)
}
if !c.wantErr && err != nil {
t.Errorf("%s: 期望通过,实际报错 %v", c.name, err)
}
if err != nil {
t.Logf("%s → %v", c.name, err)
}
}
}
+370 -264
View File
@@ -2,13 +2,17 @@ package admin
import (
"fmt"
"sort"
"strconv"
"strings"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/service"
"verification-platform-backend/pkg/response"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type FinanceRecordResponse struct {
@@ -38,6 +42,7 @@ func SetupFinanceRoutes(r *gin.RouterGroup) {
finance.GET("/recharge-records", handleGetRechargeRecords)
finance.GET("/consumption-records", handleGetConsumptionRecords)
finance.GET("/records", handleGetFinanceRecords)
finance.GET("/export", handleExportFinanceRecords)
finance.DELETE("/records/:id", handleDeleteFinanceRecord)
finance.POST("/records/batch-delete", handleBatchDeleteFinanceRecords)
}
@@ -89,10 +94,20 @@ func handleGetFinanceStatistics(c *gin.Context) {
Select("COALESCE(SUM(amount), 0)").
Scan(&totalExpense)
// 本月流水条数:两个空数据分支都在返回它,正常分支以前漏了
monthStart := time.Now().Format("2006-01") + "-01 00:00:00"
var monthly int64
database.DB.Model(&model.RechargeRecord{}).
Where("user_id IN ? AND created_at >= ?", appUserIDs, monthStart).Count(&monthly)
var monthlyCons int64
database.DB.Model(&model.ConsumptionRecord{}).
Where("user_id IN ? AND created_at >= ?", appUserIDs, monthStart).Count(&monthlyCons)
response.Success(c, gin.H{
"total_income": totalIncome,
"total_expense": totalExpense,
"net_profit": totalIncome - totalExpense,
"total_income": totalIncome,
"total_expense": totalExpense,
"net_profit": totalIncome - totalExpense,
"monthly_transactions": monthly + monthlyCons,
})
}
@@ -132,8 +147,7 @@ func handleGetRechargeRecords(c *gin.Context) {
status := c.Query("status")
startDate := c.Query("start_date")
endDate := c.Query("end_date")
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
page, pageSize := parsePageParams(c)
if search != "" {
query = query.Where("order_no LIKE ? OR card_code LIKE ?", "%"+search+"%", "%"+search+"%")
@@ -202,8 +216,7 @@ func handleGetConsumptionRecords(c *gin.Context) {
status := c.Query("status")
startDate := c.Query("start_date")
endDate := c.Query("end_date")
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
page, pageSize := parsePageParams(c)
if search != "" {
query = query.Where("order_no LIKE ? OR content LIKE ?", "%"+search+"%", "%"+search+"%")
@@ -238,308 +251,401 @@ func handleGetConsumptionRecords(c *gin.Context) {
})
}
func handleGetFinanceRecords(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
response.Error(c, 401, "未授权")
return
// 财务查询的公共筛选条件:records(列表)与 export(导出)共用,避免两边口径漂移。
type financeFilter struct {
appUserIDs []uint
recordType string
status string
search string
startDate string
endDate string
}
func (f financeFilter) wantRecharge() bool {
return f.recordType == "" || f.recordType == "all" || f.recordType == "recharge"
}
func (f financeFilter) wantConsumption() bool {
return f.recordType == "" || f.recordType == "all" || f.recordType == "consumption"
}
func (f financeFilter) recharge() *gorm.DB {
q := database.DB.Model(&model.RechargeRecord{}).Where("user_id IN ?", f.appUserIDs)
if f.search != "" {
p := "%" + escapeLike(f.search) + "%"
q = q.Where("order_no LIKE ? OR card_code LIKE ?", p, p)
}
if f.status != "" && f.status != "all" {
q = q.Where("status = ?", f.status)
}
if f.startDate != "" {
q = q.Where("created_at >= ?", f.startDate)
}
if f.endDate != "" {
q = q.Where("created_at <= ?", f.endDate+" 23:59:59")
}
return q
}
func (f financeFilter) consumption() *gorm.DB {
q := database.DB.Model(&model.ConsumptionRecord{}).Where("user_id IN ?", f.appUserIDs)
if f.search != "" {
p := "%" + escapeLike(f.search) + "%"
q = q.Where("order_no LIKE ? OR content LIKE ?", p, p)
}
if f.status != "" && f.status != "all" {
q = q.Where("status = ?", f.status)
}
if f.startDate != "" {
q = q.Where("created_at >= ?", f.startDate)
}
if f.endDate != "" {
q = q.Where("created_at <= ?", f.endDate+" 23:59:59")
}
return q
}
// appUserIDsForFinance 取这批应用下的主体 id。
//
// 关键点:用 Unscoped() 把**已软删的主体**也算进来。
// 否则后台删掉一个用户后,他历史上的充值和消费流水在面板里会凭空消失,
// 累计收入也跟着变少——财务记录必须不受主体删除影响。
func appUserIDsForFinance(appIDs []uint) []uint {
var ids []uint
if len(appIDs) == 0 {
return ids
}
database.DB.Unscoped().Model(&model.AppUser{}).
Where("application_id IN ?", appIDs).Pluck("id", &ids)
return ids
}
// preloadAppUserIncludingDeleted 同一个道理:主体已软删也要把名字读出来,方便对账。
func preloadAppUserIncludingDeleted(db *gorm.DB) *gorm.DB {
return db.Unscoped()
}
// resolveFinanceScope 解析当前账号能看到的主体范围;application_id 只能是自己名下的应用。
func resolveFinanceScope(c *gin.Context, appIDs []uint) (financeFilter, int, string) {
scopeAppIDs := appIDs
if v := c.Query("application_id"); v != "" && v != "all" {
id, err := strconv.ParseUint(v, 10, 64)
owned := false
for _, a := range appIDs {
if a == uint(id) {
owned = true
break
}
}
if err != nil || !owned {
return financeFilter{}, 403, "无权查看该应用"
}
scopeAppIDs = []uint{uint(id)}
}
return financeFilter{
appUserIDs: appUserIDsForFinance(scopeAppIDs),
recordType: c.Query("type"),
status: c.Query("status"),
search: c.Query("search"),
startDate: c.Query("start_date"),
endDate: c.Query("end_date"),
}, 0, ""
}
// 财务汇总:走 SQL 聚合,不受分页影响
func financeSummary(f financeFilter) gin.H {
var rechargeAmount, consumptionAmount float64
var rechargeCount, consumptionCount int64
if f.wantRecharge() {
f.recharge().Where("status = ?", "success").Select("COALESCE(SUM(amount), 0)").Scan(&rechargeAmount)
f.recharge().Count(&rechargeCount)
}
if f.wantConsumption() {
f.consumption().Where("status = ?", "success").Select("COALESCE(SUM(amount), 0)").Scan(&consumptionAmount)
f.consumption().Count(&consumptionCount)
}
return gin.H{
"recharge_amount": rechargeAmount,
"recharge_count": rechargeCount,
"consumption_amount": consumptionAmount,
"consumption_count": consumptionCount,
"profit": rechargeAmount - consumptionAmount,
}
}
// 财务记录:充值表 + 消费表合并成一条时间线。
//
// 之前的实现有两个硬伤:
// 1. 两张表全量 Find 进内存再切片,数据一多就是内存炸弹,total 也只是 len();
// 2. 前端不传分页参数 → 只拿回 10 条,而页面上的「充值总额/消费总额/利润」
// 又是对这 10 条 reduce 出来的,于是库里 40 条只算 10 条。
// 现在分页与汇总都放在 SQL 层:records 是当前页,summary 是全量(同样带筛选条件)。
func handleGetFinanceRecords(c *gin.Context) {
userID := c.GetUint("user_id")
var appIDs []uint
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
page, pageSize := parsePageParams(c)
empty := func() {
response.Success(c, gin.H{
"records": []FinanceRecordResponse{},
"total": 0,
"page": page,
"page_size": pageSize,
"total_page": 0,
"summary": gin.H{
"recharge_amount": 0,
"recharge_count": 0,
"consumption_amount": 0,
"consumption_count": 0,
"profit": 0,
},
})
}
if len(appIDs) == 0 {
response.Success(c, gin.H{
"recharge_records": []FinanceRecordResponse{},
"consumption_records": []FinanceRecordResponse{},
"total": 0,
})
empty()
return
}
var appUserIDs []uint
database.DB.Model(&model.AppUser{}).Where("application_id IN ?", appIDs).Pluck("id", &appUserIDs)
if len(appUserIDs) == 0 {
response.Success(c, gin.H{
"recharge_records": []FinanceRecordResponse{},
"consumption_records": []FinanceRecordResponse{},
"total": 0,
})
f, code, msg := resolveFinanceScope(c, appIDs)
if code != 0 {
response.Error(c, code, msg)
return
}
if len(f.appUserIDs) == 0 {
empty()
return
}
page := c.DefaultQuery("page", "1")
pageSize := c.DefaultQuery("page_size", "10")
search := c.Query("search")
recordType := c.Query("type")
status := c.Query("status")
startDate := c.Query("start_date")
endDate := c.Query("end_date")
summary := financeSummary(f)
total := summary["recharge_count"].(int64) + summary["consumption_count"].(int64)
// 合并分页:两张表各取前 offset+pageSize 条,排序后再切当前页
offset := (page - 1) * pageSize
need := offset + pageSize
if need > 1000 {
need = 1000 // 深翻页保护:最多让前 1000 条参与合并
}
var rechargeRecords []model.RechargeRecord
rechargeQuery := database.DB.Model(&model.RechargeRecord{}).Preload("AppUser").Where("user_id IN ?", appUserIDs)
if search != "" {
rechargeQuery = rechargeQuery.Where("order_no LIKE ? OR card_code LIKE ?", "%"+search+"%", "%"+search+"%")
}
if recordType == "recharge" || recordType == "" || recordType == "all" {
if status != "" && status != "all" {
rechargeQuery = rechargeQuery.Where("status = ?", status)
}
if startDate != "" {
rechargeQuery = rechargeQuery.Where("created_at >= ?", startDate)
}
if endDate != "" {
rechargeQuery = rechargeQuery.Where("created_at <= ?", endDate+" 23:59:59")
}
if err := rechargeQuery.Order("created_at DESC").Find(&rechargeRecords).Error; err != nil {
if f.wantRecharge() {
if err := f.recharge().Preload("AppUser", preloadAppUserIncludingDeleted).
Order("created_at DESC").Limit(need).Find(&rechargeRecords).Error; err != nil {
response.Error(c, 500, "获取充值记录失败")
return
}
}
var consumptionRecords []model.ConsumptionRecord
consumptionQuery := database.DB.Model(&model.ConsumptionRecord{}).Preload("AppUser").Where("user_id IN ?", appUserIDs)
if search != "" {
consumptionQuery = consumptionQuery.Where("order_no LIKE ? OR content LIKE ?", "%"+search+"%", "%"+search+"%")
}
if recordType == "consumption" || recordType == "" || recordType == "all" {
if status != "" && status != "all" {
consumptionQuery = consumptionQuery.Where("status = ?", status)
}
if startDate != "" {
consumptionQuery = consumptionQuery.Where("created_at >= ?", startDate)
}
if endDate != "" {
consumptionQuery = consumptionQuery.Where("created_at <= ?", endDate+" 23:59:59")
}
if err := consumptionQuery.Order("created_at DESC").Find(&consumptionRecords).Error; err != nil {
if f.wantConsumption() {
if err := f.consumption().Preload("AppUser", preloadAppUserIncludingDeleted).
Order("created_at DESC").Limit(need).Find(&consumptionRecords).Error; err != nil {
response.Error(c, 500, "获取消费记录失败")
return
}
}
var allRecords []FinanceRecordResponse
for _, r := range rechargeRecords {
var user *struct {
ID uint `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
}
if r.AppUser != nil && r.AppUser.ID != 0 {
user = &struct {
ID uint `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
}{
ID: r.AppUser.ID,
Username: r.AppUser.Username,
Email: r.AppUser.Email,
}
}
allRecords = append(allRecords, FinanceRecordResponse{
ID: r.ID,
OrderNo: r.OrderNo,
Type: "recharge",
UserID: r.UserID,
AppID: r.AppUser.ApplicationID,
Amount: r.Amount,
Detail: r.CardCode,
Status: r.Status,
PaymentType: r.PaymentType,
Remark: r.Remark,
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
User: user,
})
type mergedRow struct {
at time.Time
resp FinanceRecordResponse
}
for _, r := range consumptionRecords {
var user *struct {
ID uint `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
}
if r.AppUser != nil && r.AppUser.ID != 0 {
user = &struct {
ID uint `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
}{
ID: r.AppUser.ID,
Username: r.AppUser.Username,
Email: r.AppUser.Email,
}
}
allRecords = append(allRecords, FinanceRecordResponse{
ID: r.ID,
OrderNo: r.OrderNo,
Type: "consumption",
UserID: r.UserID,
AppID: r.AppUser.ApplicationID,
Amount: r.Amount,
Detail: r.Content,
Status: r.Status,
PaymentType: r.PaymentType,
Remark: r.Remark,
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
User: user,
})
merged := make([]mergedRow, 0, len(rechargeRecords)+len(consumptionRecords))
for i := range rechargeRecords {
merged = append(merged, mergedRow{rechargeRecords[i].CreatedAt, rechargeToFinanceResponse(&rechargeRecords[i])})
}
total := len(allRecords)
start := 0
end := total
if p, err := parseInt(page); err == nil && p > 0 {
if ps, err := parseInt(pageSize); err == nil && ps > 0 {
start = (p - 1) * ps
end = start + ps
if start > total {
start = total
}
if end > total {
end = total
}
}
for i := range consumptionRecords {
merged = append(merged, mergedRow{consumptionRecords[i].CreatedAt, consumptionToFinanceResponse(&consumptionRecords[i])})
}
sort.SliceStable(merged, func(i, j int) bool { return merged[i].at.After(merged[j].at) })
if start > end {
start = end
startIdx, endIdx := offset, offset+pageSize
if startIdx > len(merged) {
startIdx = len(merged)
}
if endIdx > len(merged) {
endIdx = len(merged)
}
pageRows := make([]FinanceRecordResponse, 0, endIdx-startIdx)
for _, r := range merged[startIdx:endIdx] {
pageRows = append(pageRows, r.resp)
}
response.Success(c, gin.H{
"records": allRecords[start:end],
"total": total,
"records": pageRows,
"total": total,
"page": page,
"page_size": pageSize,
"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
"summary": summary,
})
}
// 财务流水导出(CSV)。删除接口被封掉之后,需要清理/对账就走这里。
func handleExportFinanceRecords(c *gin.Context) {
userID := c.GetUint("user_id")
var appIDs []uint
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
if len(appIDs) == 0 {
response.Error(c, 404, "没有可导出的记录")
return
}
f, code, msg := resolveFinanceScope(c, appIDs)
if code != 0 {
response.Error(c, code, msg)
return
}
if len(f.appUserIDs) == 0 {
response.Error(c, 404, "没有可导出的记录")
return
}
const exportLimit = 100000
var rechargeRecords []model.RechargeRecord
if f.wantRecharge() {
if err := f.recharge().Preload("AppUser", preloadAppUserIncludingDeleted).
Order("created_at DESC").Limit(exportLimit).Find(&rechargeRecords).Error; err != nil {
response.Error(c, 500, "导出失败")
return
}
}
var consumptionRecords []model.ConsumptionRecord
if f.wantConsumption() {
if err := f.consumption().Preload("AppUser", preloadAppUserIncludingDeleted).
Order("created_at DESC").Limit(exportLimit).Find(&consumptionRecords).Error; err != nil {
response.Error(c, 500, "导出失败")
return
}
}
type mergedRow struct {
at time.Time
resp FinanceRecordResponse
}
merged := make([]mergedRow, 0, len(rechargeRecords)+len(consumptionRecords))
for i := range rechargeRecords {
merged = append(merged, mergedRow{rechargeRecords[i].CreatedAt, rechargeToFinanceResponse(&rechargeRecords[i])})
}
for i := range consumptionRecords {
merged = append(merged, mergedRow{consumptionRecords[i].CreatedAt, consumptionToFinanceResponse(&consumptionRecords[i])})
}
sort.SliceStable(merged, func(i, j int) bool { return merged[i].at.After(merged[j].at) })
c.Header("Content-Type", "text/csv; charset=utf-8")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=finance_%s.csv", time.Now().Format("20060102-150405")))
var b strings.Builder
b.WriteString("\xEF\xBB\xBF") // BOM,Excel 打开不乱码
b.WriteString("类型,订单号,金额,用户,详情,状态,支付方式,备注,应用ID,时间\n")
for _, r := range merged {
typ := "充值"
if r.resp.Type == "consumption" {
typ = "消费"
}
user := ""
if r.resp.User != nil {
user = r.resp.User.Username
}
b.WriteString(fmt.Sprintf("%s,%s,%.2f,%s,%s,%s,%s,%s,%d,%s\n",
typ, csvField(r.resp.OrderNo), r.resp.Amount, csvField(user), csvField(r.resp.Detail),
csvField(r.resp.Status), csvField(r.resp.PaymentType), csvField(r.resp.Remark),
r.resp.AppID, r.resp.CreatedAt))
}
c.String(200, b.String())
}
// csvField 简单转义:含逗号/引号/换行就加引号
func csvField(s string) string {
if strings.ContainsAny(s, ",\"\n") {
return "\"" + strings.ReplaceAll(s, "\"", "\"\"") + "\""
}
return s
}
// 主体信息:AppUser 为空(主体被删/记录user_id悬空)时返回 nil,
// 不要像以前那样直接解引用 r.AppUser.ApplicationID —— 那是 nil 指针 panic。
func financeUserBrief(u *model.AppUser) *struct {
ID uint `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
} {
if u == nil || u.ID == 0 {
return nil
}
return &struct {
ID uint `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
}{ID: u.ID, Username: u.Username, Email: u.Email}
}
func rechargeToFinanceResponse(r *model.RechargeRecord) FinanceRecordResponse {
appID := uint(0)
if r.AppUser != nil {
appID = r.AppUser.ApplicationID
}
return FinanceRecordResponse{
ID: r.ID,
OrderNo: r.OrderNo,
Type: "recharge",
UserID: r.UserID,
AppID: appID,
Amount: r.Amount,
Detail: r.CardCode,
Status: r.Status,
PaymentType: r.PaymentType,
Remark: r.Remark,
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
User: financeUserBrief(r.AppUser),
}
}
func consumptionToFinanceResponse(r *model.ConsumptionRecord) FinanceRecordResponse {
appID := r.ApplicationID
if r.AppUser != nil && r.AppUser.ApplicationID != 0 {
appID = r.AppUser.ApplicationID
}
return FinanceRecordResponse{
ID: r.ID,
OrderNo: r.OrderNo,
Type: "consumption",
UserID: r.UserID,
AppID: appID,
Amount: r.Amount,
Detail: r.Content,
Status: r.Status,
PaymentType: r.PaymentType,
Remark: r.Remark,
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
User: financeUserBrief(r.AppUser),
}
}
func parseInt(s string) (int, error) {
var result int
_, err := fmt.Sscanf(s, "%d", &result)
return result, err
}
// 财务流水是审计凭证:删掉之后「流水没了、余额还在」,账面和余额永久对不上,
// 而且删掉的记录(即使软删)在统计里也消失了,事后没法对账。
// 所以这里直接封掉删除,要清理/对账一律走 /finance/export 导出。
// 老前端仍会调到这两个接口,返回可读的 403,而不是静默失败。
const financeDeleteForbidden = "财务流水是审计凭证,不支持删除;需要清理或对账请使用导出"
func handleDeleteFinanceRecord(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
response.Error(c, 401, "未授权")
return
}
recordID := c.Param("id")
recordType := c.Query("type")
var appIDs []uint
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
if len(appIDs) == 0 {
response.Error(c, 404, "记录不存在")
return
}
var appUserIDs []uint
database.DB.Model(&model.AppUser{}).Where("application_id IN ?", appIDs).Pluck("id", &appUserIDs)
if len(appUserIDs) == 0 {
response.Error(c, 404, "记录不存在")
return
}
var deletedType string
var deletedAmount float64
if recordType == "recharge" {
var record model.RechargeRecord
if err := database.DB.Where("id = ? AND user_id IN ?", recordID, appUserIDs).First(&record).Error; err != nil {
response.Error(c, 404, "记录不存在")
return
}
if err := database.DB.Delete(&record).Error; err != nil {
response.Error(c, 500, "删除失败")
return
}
deletedType = "充值记录"
deletedAmount = record.Amount
} else if recordType == "consumption" {
var record model.ConsumptionRecord
if err := database.DB.Where("id = ? AND user_id IN ?", recordID, appUserIDs).First(&record).Error; err != nil {
response.Error(c, 404, "记录不存在")
return
}
if err := database.DB.Delete(&record).Error; err != nil {
response.Error(c, 500, "删除失败")
return
}
deletedType = "消费记录"
deletedAmount = record.Amount
} else {
var rechargeRecord model.RechargeRecord
var consumptionRecord model.ConsumptionRecord
if err := database.DB.Where("id = ? AND user_id IN ?", recordID, appUserIDs).First(&rechargeRecord).Error; err == nil {
database.DB.Delete(&rechargeRecord)
deletedType = "充值记录"
deletedAmount = rechargeRecord.Amount
service.LogOperation(c, "delete", "finance_record", nil, fmt.Sprintf("删除%s: %.2f", deletedType, deletedAmount), nil)
response.Success(c, nil)
return
}
if err := database.DB.Where("id = ? AND user_id IN ?", recordID, appUserIDs).First(&consumptionRecord).Error; err == nil {
database.DB.Delete(&consumptionRecord)
deletedType = "消费记录"
deletedAmount = consumptionRecord.Amount
service.LogOperation(c, "delete", "finance_record", nil, fmt.Sprintf("删除%s: %.2f", deletedType, deletedAmount), nil)
response.Success(c, nil)
return
}
response.Error(c, 404, "记录不存在")
return
}
service.LogOperation(c, "delete", "finance_record", nil, fmt.Sprintf("删除%s: %.2f", deletedType, deletedAmount), nil)
response.Success(c, nil)
service.LogOperation(c, "delete_blocked", "finance_record", nil,
"尝试删除财务记录(已被拒绝): id="+c.Param("id")+" type="+c.Query("type"), nil)
response.Error(c, 403, financeDeleteForbidden)
}
func handleBatchDeleteFinanceRecords(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
response.Error(c, 401, "未授权")
return
}
var req struct {
IDs []uint `json:"ids"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, 400, "参数错误")
return
}
if len(req.IDs) == 0 {
response.Error(c, 400, "请选择要删除的记录")
return
}
var appIDs []uint
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
if len(appIDs) == 0 {
response.Error(c, 404, "记录不存在")
return
}
var appUserIDs []uint
database.DB.Model(&model.AppUser{}).Where("application_id IN ?", appIDs).Pluck("id", &appUserIDs)
if len(appUserIDs) == 0 {
response.Error(c, 404, "记录不存在")
return
}
database.DB.Where("id IN ? AND user_id IN ?", req.IDs, appUserIDs).Delete(&model.RechargeRecord{})
database.DB.Where("id IN ? AND user_id IN ?", req.IDs, appUserIDs).Delete(&model.ConsumptionRecord{})
service.LogOperation(c, "batch_delete", "finance_record", nil, fmt.Sprintf("批量删除财务记录: %d条", len(req.IDs)), nil)
response.Success(c, gin.H{"deleted": len(req.IDs)})
_ = c.ShouldBindJSON(&req)
service.LogOperation(c, "delete_blocked", "finance_record", nil,
fmt.Sprintf("尝试批量删除财务记录(已被拒绝): %d 条", len(req.IDs)), nil)
response.Error(c, 403, financeDeleteForbidden)
}
+139 -52
View File
@@ -1,80 +1,116 @@
package admin
import (
"fmt"
"strconv"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/pkg/response"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func SetupLogRoutes(r *gin.RouterGroup) {
logs := r.Group("/logs")
{
logs.GET("", handleGetLogs)
logs.GET("/export", handleExportLogs)
}
}
func handleGetLogs(c *gin.Context) {
userID := c.GetUint("user_id")
// logFilter 日志列表与导出共用同一套筛选,避免两边口径漂移
type logFilter struct {
userID uint
appIDs []uint
logType string
status string
applicationID string
startDate string
endDate string
search string
}
func newLogFilter(c *gin.Context) logFilter {
userID := c.GetUint("user_id")
var appIDs []uint
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
return logFilter{
userID: userID,
appIDs: appIDs,
logType: c.Query("type"),
status: c.Query("status"),
applicationID: c.Query("application_id"),
startDate: c.Query("start_date"),
endDate: c.Query("end_date"),
search: c.Query("search"),
}
}
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
logType := c.Query("type")
status := c.Query("status")
applicationID := c.Query("application_id")
startDate := c.Query("start_date")
endDate := c.Query("end_date")
search := c.Query("search")
func (f logFilter) query() *gorm.DB {
// 可见范围:自己应用下产生的 + 自己这个账号产生的
q := database.DB.Model(&model.Log{})
if len(f.appIDs) > 0 {
q = q.Where("application_id IN ? OR user_id = ?", f.appIDs, f.userID)
} else {
q = q.Where("user_id = ?", f.userID)
}
// 按应用筛选时必须是自己的应用;不是自己的应用直接查空,别拿它当探测手段
if f.applicationID != "" && f.applicationID != "all" {
owned := false
for _, a := range f.appIDs {
if strconv.FormatUint(uint64(a), 10) == f.applicationID {
owned = true
break
}
}
if owned {
q = q.Where("application_id = ?", f.applicationID)
} else {
q = q.Where("1 = 0")
}
}
if f.logType != "" && f.logType != "all" {
q = q.Where("log_type = ?", f.logType)
}
if f.status != "" && f.status != "all" {
q = q.Where("status = ?", f.status)
}
if f.startDate != "" {
q = q.Where("created_at >= ?", f.startDate+" 00:00:00")
}
if f.endDate != "" {
q = q.Where("created_at <= ?", f.endDate+" 23:59:59")
}
if f.search != "" {
p := "%" + escapeLike(f.search) + "%"
q = q.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", p, p, p)
}
return q
}
func handleGetLogs(c *gin.Context) {
f := newLogFilter(c)
page, pageSize := parsePageParams(c)
var total int64
f.query().Count(&total)
// 三个统计数字必须和列表同源(同一个 Log 表 + 同一套筛选),
// 否则会出现「列表 0 条、顶部写着成功 128」这种对不上的情况。
var successCount, failedCount, operationCount int64
f.query().Where("status = ?", "success").Count(&successCount)
f.query().Where("status = ?", "failed").Count(&failedCount)
f.query().Where("log_type = ?", "operation").Count(&operationCount)
var logs []model.Log
var total int64
query := database.DB.Model(&model.Log{})
if len(appIDs) > 0 {
query = query.Where("application_id IN ? OR user_id = ?", appIDs, userID)
} else {
query = query.Where("user_id = ?", userID)
}
if logType != "" && logType != "all" {
query = query.Where("log_type = ?", logType)
}
if status != "" && status != "all" {
query = query.Where("status = ?", status)
}
if applicationID != "" && applicationID != "all" {
query = query.Where("application_id = ?", applicationID)
}
if startDate != "" {
query = query.Where("created_at >= ?", startDate+" 00:00:00")
}
if endDate != "" {
query = query.Where("created_at <= ?", endDate+" 23:59:59")
}
if search != "" {
query = query.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", "%"+search+"%", "%"+search+"%", "%"+search+"%")
}
query.Count(&total)
var successCount, failedCount, operationCount int64
database.DB.Model(&model.ApiUsage{}).Where("application_id IN ? OR user_id = ?", appIDs, userID).Where("status = ?", "success").Count(&successCount)
database.DB.Model(&model.ApiUsage{}).Where("application_id IN ? OR user_id = ?", appIDs, userID).Where("status = ?", "failed").Count(&failedCount)
database.DB.Model(&model.ApiUsage{}).Where("application_id IN ? OR user_id = ?", appIDs, userID).Where("log_type = ?", "operation").Count(&operationCount)
offset := (page - 1) * pageSize
if err := query.Preload("User").Preload("Application").Preload("AppUser").Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&logs).Error; err != nil {
if err := f.query().Preload("User").Preload("Application").Preload("AppUser").
Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&logs).Error; err != nil {
response.Error(c, 500, "获取日志失败")
return
}
@@ -90,3 +126,54 @@ func handleGetLogs(c *gin.Context) {
"operation_count": operationCount,
})
}
// 日志导出(CSV):和列表同一套筛选,最多 10 万条。
func handleExportLogs(c *gin.Context) {
f := newLogFilter(c)
const exportLimit = 100000
var logs []model.Log
if err := f.query().Preload("User").Preload("Application").Preload("AppUser").
Order("created_at DESC").Limit(exportLimit).Find(&logs).Error; err != nil {
response.Error(c, 500, "导出日志失败")
return
}
c.Header("Content-Type", "text/csv; charset=utf-8")
c.Header("Content-Disposition",
fmt.Sprintf("attachment; filename=logs_%s.csv", time.Now().Format("20060102-150405")))
typeName := map[string]string{"operation": "操作", "verification": "验证", "exception": "异常"}
statusName := map[string]string{"success": "成功", "failed": "失败", "pending": "处理中"}
buf := make([]byte, 0, 64*len(logs)+128)
buf = append(buf, 0xEF, 0xBB, 0xBF) // BOM,Excel 不乱码
buf = append(buf, []byte("时间,类型,级别,动作,资源,状态,用户,应用,主体,IP,设备,详情,错误\n")...)
for _, l := range logs {
typ := typeName[l.LogType]
if typ == "" {
typ = l.LogType
}
st := statusName[l.Status]
if st == "" {
st = l.Status
}
userName, appName, subjectName := "", "", ""
if l.User != nil {
userName = l.User.Username
}
if l.Application != nil {
appName = l.Application.Name
}
if l.AppUser != nil {
subjectName = l.AppUser.Username
}
line := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n",
l.CreatedAt.Format("2006-01-02 15:04:05"),
csvField(typ), csvField(l.Level), csvField(l.Action), csvField(l.Resource), csvField(st),
csvField(userName), csvField(appName), csvField(subjectName),
csvField(l.IPAddress), csvField(l.DeviceID), csvField(l.Details), csvField(l.ErrorMessage))
buf = append(buf, []byte(line)...)
}
c.String(200, string(buf))
}
@@ -0,0 +1,44 @@
package admin
import (
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// 分页参数的统一入口。
//
// 之前每个 handler 都自己 strconv.Atoi 然后用,没有下限也没有上限:
// - page=0 / 负数 → offset 变负数,MySQL 里直接报错或结果诡异
// - page_size=-1 → GORM 的 Limit(-1) 等于「不加 LIMIT」,一次把全表拉出来
// - page_size=100000 → 同样等于导出全表
// 所以统一在这里夹紧:page >= 1,pageSize ∈ [1, maxPageSize],默认 20。
const (
defaultPageSize = 20
maxPageSize = 200
)
func parsePageParams(c *gin.Context) (page, pageSize int) {
page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
if err != nil || page < 1 {
page = 1
}
pageSize, err = strconv.Atoi(c.DefaultQuery("page_size", strconv.Itoa(defaultPageSize)))
if err != nil || pageSize < 1 {
pageSize = defaultPageSize
}
if pageSize > maxPageSize {
pageSize = maxPageSize
}
return page, pageSize
}
// escapeLike 转义 LIKE 里的通配符:用户搜 "100%" 时不该变成"匹配一切"。
// MySQL / SQLite 默认转义符都是反斜杠。
func escapeLike(s string) string {
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, "%", `\%`)
s = strings.ReplaceAll(s, "_", `\_`)
return s
}
+55 -6
View File
@@ -11,6 +11,7 @@ import (
"strings"
"time"
"verification-platform-backend/internal/config"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
@@ -31,8 +32,14 @@ func SetupProtectRoutes(r *gin.RouterGroup) {
}
}
// baseURL 从请求推断站点根地址(面板/应用共用同一域名)
func baseURL(c *gin.Context) string {
// baseURL 推断站点根地址(面板/应用共用同一域名)。
//
// 这里踩过一次真实的坑:AcePanel 默认的反代模板写的是 `proxy_set_header Host $proxy_host`,
// 于是后端看到的 Host 是 `127.0.0.1:9998`,打包出来的每个客户端都会把
// `https://127.0.0.1:9998/api/v1/app/<key>/login` 写进壳 cfg —— 到了客户机上根本连不上。
// 所以:优先 X-Forwarded-Host,其次(配置里的站点地址),最后才是请求 Host;
// 一旦推断出来是本机/内网地址,宁可让加壳任务报错,也不要产出一个连不上服务器的产物。
func baseURL(c *gin.Context) (string, error) {
scheme := c.GetHeader("X-Forwarded-Proto")
if scheme == "" {
if c.Request.TLS != nil {
@@ -41,11 +48,48 @@ func baseURL(c *gin.Context) string {
scheme = "http"
}
}
host := c.GetHeader("X-Forwarded-Host")
// 反代应当带上 X-Forwarded-Host;它才是用户浏览器里那个域名
host := strings.TrimSpace(c.GetHeader("X-Forwarded-Host"))
if host == "" {
host = c.Request.Host
host = strings.TrimSpace(c.Request.Host)
}
return fmt.Sprintf("%s://%s", scheme, host)
// 站点地址可以在 config.yaml 里显式指定(app.public_url),配了就优先用
if pub := strings.TrimRight(config.GetString("app.public_url"), "/"); pub != "" {
return pub, nil
}
if host == "" || isInternalHost(host) {
return "", fmt.Errorf("无法推断站点地址(反向代理没有传 X-Forwarded-Host,Host 为 %q),请在 config.yaml 配置 app.public_url", host)
}
return fmt.Sprintf("%s://%s", scheme, host), nil
}
// isInternalHost 判断 host 是不是只在本机/内网有意义(127.x、localhost、内网网段、无域名端口等)
func isInternalHost(host string) bool {
h := host
if i := strings.LastIndex(h, ":"); i > 0 && !strings.Contains(h[i:], "]") {
h = h[:i] // 去掉端口
}
h = strings.ToLower(strings.Trim(h, "[]"))
switch {
case h == "", h == "localhost", h == "0.0.0.0", h == "::1":
return true
case strings.HasPrefix(h, "127."), strings.HasPrefix(h, "10."), strings.HasPrefix(h, "192.168."):
return true
case strings.HasPrefix(h, "172."):
// 172.16.0.0/12
parts := strings.Split(h, ".")
if len(parts) == 4 {
if n, err := strconv.Atoi(parts[1]); err == nil && n >= 16 && n <= 31 {
return true
}
}
case strings.HasPrefix(h, "169.254."):
return true
}
return false
}
// HandleCreateProtectTask 上传原始程序 → 建任务 → 异步加壳
@@ -227,7 +271,12 @@ func HandleCreateProtectTask(c *gin.Context) {
response.Error(c, 400, "程序版本号只能包含字母、数字、点、下划线和横线,例如 1.2.3")
return
}
task, err := protect.CreateAndRunThemedVer(&app, userID, name, data, baseURL(c), signProfileID, certIdentity, theme, programVer)
siteURL, err := baseURL(c)
if err != nil {
response.Error(c, 400, err.Error())
return
}
task, err := protect.CreateAndRunThemedVer(&app, userID, name, data, siteURL, signProfileID, certIdentity, theme, programVer)
if err != nil {
response.ParamError(c, err.Error())
return
@@ -0,0 +1,80 @@
package admin
import (
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestIsInternalHost(t *testing.T) {
cases := map[string]bool{
"127.0.0.1:9998": true,
"127.0.0.1": true,
"localhost:8080": true,
"localhost": true,
"10.0.0.5": true,
"192.168.1.10:443": true,
"172.16.0.1": true,
"172.31.255.1:8080": true,
"169.254.1.1": true,
"": true,
"[::1]:8080": true,
"0.0.0.0:8080": true,
"v.viaeon.com": false,
"v.viaeon.com:443": false,
"172.32.0.1": false, // 不在 172.16/12 里
"verify.example.com": false,
"8.8.8.8": false,
}
for host, want := range cases {
if got := isInternalHost(host); got != want {
t.Fatalf("isInternalHost(%q) = %v, want %v", host, got, want)
}
}
}
func newCtx(host, xfh, proto string) *gin.Context {
gin.SetMode(gin.TestMode)
req := httptest.NewRequest("POST", "/", nil)
req.Host = host
if xfh != "" {
req.Header.Set("X-Forwarded-Host", xfh)
}
if proto != "" {
req.Header.Set("X-Forwarded-Proto", proto)
}
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = req
return c
}
// 反代把 Host 改写成 127.0.0.1 时必须报错,绝不能把内网地址打进产物
func TestBaseURLRejectsLoopback(t *testing.T) {
u, err := baseURL(newCtx("127.0.0.1:9998", "", "https"))
if err == nil {
t.Fatalf("期望报错,实际返回 %q", u)
}
}
// 反代带了 X-Forwarded-Host 就用它
func TestBaseURLPrefersForwardedHost(t *testing.T) {
u, err := baseURL(newCtx("127.0.0.1:9998", "v.viaeon.com", "https"))
if err != nil {
t.Fatalf("期望成功,实际 %v", err)
}
if want := "https://v.viaeon.com"; u != want {
t.Fatalf("baseURL = %q, want %q", u, want)
}
}
// 直连(无反代)时用请求 Host
func TestBaseURLUsesRequestHost(t *testing.T) {
u, err := baseURL(newCtx("v.viaeon.com", "", "https"))
if err != nil {
t.Fatalf("期望成功,实际 %v", err)
}
if want := "https://v.viaeon.com"; u != want {
t.Fatalf("baseURL = %q, want %q", u, want)
}
}
@@ -200,7 +200,7 @@ func HandleCreateSignProfile(c *gin.Context) {
msg := "证书已加密保存"
if pfx.KeyCount > 1 {
msg = fmt.Sprintf("证书已保存:文件里含 %d 套可签名身份,加壳时可任选其中一套", pfx.KeyCount)
msg = fmt.Sprintf("证书已保存:文件里含 %d 套可签名身份,云端加密时可任选其中一套", pfx.KeyCount)
}
response.SuccessWithMessage(c, msg, gin.H{
"id": made.ID,
+4 -1
View File
@@ -294,9 +294,12 @@ func handleGetUsers(c *gin.Context) {
CardKey string
}
var rows []row
// 主体可能挂过多张卡(换过钥匙),这里只做展示用途,
// 按 id 倒序取最新一张,不再靠 purpose 过滤
database.DB.Model(&model.Card{}).
Select("subject_id, card_key").
Where("subject_id IN ? AND purpose = ?", ids, "credential").
Where("subject_id IN ?", ids).
Order("id DESC").
Scan(&rows)
keyBySubject := make(map[uint]string, len(rows))
for _, r := range rows {
+30 -2
View File
@@ -1,6 +1,7 @@
package app
import (
"fmt"
"log"
"time"
"verification-platform-backend/internal/database"
@@ -105,6 +106,10 @@ func handleAppHeartbeat(c *gin.Context) {
}
now := time.Now()
// 计时扣费必须拿「上一次心跳」来算间隔。下面这行会先把 LastHeartbeatAt
// 改成 now,所以这里必须先把旧值留一份 —— 否则 elapsed 恒为 0,
// timer 模式永远不扣费(曾经就是这个 bug,线上不会报错,只是静默免费)。
prevHeartbeat := user.LastHeartbeatAt
user.LastHeartbeatAt = &now
if app.BillingType != "free" && app.DeductionMode == "auto" && app.DeductionAmount > 0 {
@@ -112,8 +117,8 @@ func handleAppHeartbeat(c *gin.Context) {
switch app.DeductionType {
case "timer":
if user.LastHeartbeatAt != nil {
elapsed := now.Sub(*user.LastHeartbeatAt)
if prevHeartbeat != nil {
elapsed := now.Sub(*prevHeartbeat)
var interval time.Duration
switch app.DeductionUnit {
case "minute":
@@ -151,7 +156,30 @@ func handleAppHeartbeat(c *gin.Context) {
response.Error(c, 403, "余额不足")
return
}
// 重新查库会把 LastHeartbeatAt 拉回旧值,这里补回 now,
// 否则本次心跳时间丢失,下次间隔会被算长
database.DB.Where("id = ?", user.ID).First(&user)
user.LastHeartbeatAt = &now
// 扣了钱就必须留账。consumption_records 原来一直是 0 条:
// 财务页在查这张表,但没有任何代码往里写,等于扣费无法对账。
consumeRecord := model.ConsumptionRecord{
UserID: user.ID,
ApplicationID: app.ID,
OrderNo: generateOrderNo("C"),
Type: "verification",
Content: fmt.Sprintf("心跳扣费:%s", app.Name),
Description: fmt.Sprintf("每 %d %s 扣 %g", app.DeductionInterval,
app.DeductionUnit, app.DeductionAmount),
Amount: app.DeductionAmount,
BalanceAfter: user.Balance,
Status: "success",
}
if err := database.DB.Create(&consumeRecord).Error; err != nil {
// 记账失败不阻断用户使用,但必须留痕,否则就成了静默少账
log.Printf("[WARN] 写消费流水失败 user=%d amount=%.2f: %v", user.ID, app.DeductionAmount, err)
}
log.Printf("[DEBUG] Deducted %.2f from user %d, new balance: %.2f", app.DeductionAmount, user.ID, user.Balance)
}
}
+86 -28
View File
@@ -12,7 +12,6 @@ import (
"verification-platform-backend/internal/service"
"verification-platform-backend/pkg/jwt"
"verification-platform-backend/pkg/response"
"gorm.io/gorm"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
@@ -109,7 +108,7 @@ func handleAppSendEmailCode(c *gin.Context) {
}
} else if req.Purpose == "bind_email" {
// 卡密主体给自己绑邮箱:只在这类应用开启「允许卡密用户设密码」时给发码
if !app.CardLoginAllowPassword && app.LoginMode != "card" && app.LoginMode != "both" {
if !app.CardLoginAllowPassword {
response.Error(c, 400, "该应用未开启卡密绑定邮箱")
return
}
@@ -207,6 +206,19 @@ func handleAppRegister(c *gin.Context) {
return
}
// 卡密直登模式下注册出来的账号没有登录入口,直接挡掉(宽限期内放行,和登录 gate 保持一致)
if service.AppLoginMode(appModel) == "card" && service.AppLoginModeEnforce(appModel) == "strict" && service.LoginModeGraceDaysLeft(appModel) == 0 {
service.LogVerification(c, &appModel.ID, nil, "register_blocked",
"注册被登录方式策略拦截: mode=card", "", fmt.Errorf("该应用仅支持卡密登录"))
c.JSON(403, gin.H{
"code": 403,
"message": "该应用使用卡密登录,无需注册",
"error_code": "LOGIN_MODE_DISABLED",
"data": gin.H{"login_mode": "card", "allowed": []string{"card"}},
})
return
}
var req struct {
Username string `json:"username"`
Email string `json:"email"`
@@ -459,6 +471,40 @@ func handleAppLogin(c *gin.Context) {
}
}
// 登录方式开关(login_mode):这是应用级登录策略,客户端界面只是体验,判定必须在服务端。
// 位置故意放在查询主体、写设备绑定、记失败次数之前——被策略拒绝的请求不产生任何副作用。
loginDeprecated := false
graceDaysLeft := 0
if !service.LoginTypeAllowedByMode(appModel, req.LoginType) {
mode := service.AppLoginMode(appModel)
switch service.AppLoginModeEnforce(appModel) {
case "strict":
if days := service.LoginModeGraceDaysLeft(appModel); days > 0 {
// 宽限期内旧凭证仍然可用,只在响应里提醒用户尽快换钥匙
loginDeprecated, graceDaysLeft = true, days
log.Printf("[INFO] login_mode grace: app=%s mode=%s login_type=%s days_left=%d", appKey, mode, req.LoginType, days)
} else {
service.LogVerification(c, &appModel.ID, nil, "login_mode_blocked",
"登录被登录方式策略拦截: mode="+mode+" login_type="+req.LoginType, req.DeviceID,
fmt.Errorf("该应用仅允许: %s", strings.Join(service.AllowedLoginTypes(mode), ",")))
c.JSON(403, gin.H{
"code": 403,
"message": service.LoginModeBlockMessage(mode),
"error_code": "LOGIN_MODE_DISABLED",
"data": gin.H{
"login_mode": mode,
"allowed": service.AllowedLoginTypes(mode),
},
})
return
}
case "warn":
log.Printf("[WARN] login_mode(warn-only) 会拦截但已放行: app=%s mode=%s login_type=%s", appKey, mode, req.LoginType)
_ = service.LogVerification(c, &appModel.ID, nil, "login_mode_blocked",
"[warn-only] 登录方式与策略不符,已放行: mode="+mode+" login_type="+req.LoginType, req.DeviceID, nil)
}
}
var user model.AppUser
cardAuth := false
if req.LoginType == "card" {
@@ -782,6 +828,14 @@ func handleAppLogin(c *gin.Context) {
loginData["balance"] = user.Balance
}
// 宽限期内的旧凭证登录:明确告诉壳/用户还剩几天,好引导换钥匙
if loginDeprecated {
loginData["deprecated_login"] = true
loginData["grace_days_left"] = graceDaysLeft
loginData["login_mode"] = service.AppLoginMode(appModel)
loginData["allowed_login_types"] = service.AllowedLoginTypes(service.AppLoginMode(appModel))
}
response.SuccessWithMessage(c, "登录成功", loginData)
}
@@ -860,9 +914,13 @@ func resolveCardSubject(app *model.Application, cardKey string) (*model.AppUser,
return nil, fmt.Errorf("卡密不能为空")
}
// 卡就是一把钥匙 + 一份面值(面值多少由卡型的 recharge_type 决定),
// 不再区分「登录卡 / 充值卡」两种物种:
// 已激活(subject_id 有值) → 回到它绑定的主体
// 未激活 → 首次使用就把这张卡激活成一个新主体
var card model.Card
if err := database.DB.Preload("CardType").
Where("card_key = ? AND application_id = ? AND purpose = ?", cardKey, app.ID, "credential").
Where("card_key = ? AND application_id = ?", cardKey, app.ID).
First(&card).Error; err != nil {
return nil, fmt.Errorf("卡密不存在")
}
@@ -926,30 +984,12 @@ func resolveCardSubject(app *model.Application, cardKey string) (*model.AppUser,
}
}
// 按卡型发额度:余额型加余额,订阅型加时长
if card.CardType.ID != 0 {
if card.CardType.RechargeType == "subscription" {
var add time.Duration
switch card.CardType.ValueUnit {
case "day":
add = time.Duration(card.CardType.Value*24) * time.Hour
case "month":
add = time.Duration(card.CardType.Value*24*30) * time.Hour
case "year":
add = time.Duration(card.CardType.Value*24*365) * time.Hour
default:
add = time.Duration(card.CardType.Value) * time.Second
}
base := now
if subject.ExpiryAt != nil && subject.ExpiryAt.After(now) {
base = *subject.ExpiryAt
}
exp := base.Add(add)
subject.ExpiryAt = &exp
tx.Model(&subject).Update("expiry_at", exp)
} else {
tx.Model(&subject).Update("balance", gorm.Expr("balance + ?", card.CardType.Value))
}
// 按卡型发额度:走和「充到已有主体」同一条实现。
// 这里原来是另写一份 switch,而且少了 minute/hour 两个单位 ——
// 按分钟/小时计价的卡走首次激活会被当「秒」算,30 分钟变 30 秒。
if err := service.ApplyCardTypeToSubject(tx, &subject, &card.CardType, now); err != nil {
tx.Rollback()
return nil, fmt.Errorf("激活卡密失败")
}
if err := tx.Model(&model.Card{}).Where("id = ?", card.ID).Updates(map[string]interface{}{
@@ -960,6 +1000,24 @@ func resolveCardSubject(app *model.Application, cardKey string) (*model.AppUser,
tx.Rollback()
return nil, fmt.Errorf("激活卡密失败")
}
// 卡密激活就是一次收入,必须进财务流水 —— 否则「卡密带来多少收入」
// 永远查不出来(充值那条路径 payment.go 是写的,这里原来漏了)。
rechargeRecord := model.RechargeRecord{
UserID: subject.ID,
OrderNo: generateOrderNo("R"),
CardID: &card.ID,
CardCode: card.CardKey,
Amount: card.CardType.Price,
Status: "success",
PaymentType: "card",
Remark: "卡密首次激活 - " + card.CardType.Name,
}
if err := tx.Create(&rechargeRecord).Error; err != nil {
tx.Rollback()
return nil, fmt.Errorf("激活卡密失败")
}
if err := tx.Commit().Error; err != nil {
return nil, fmt.Errorf("激活卡密失败")
}
@@ -978,7 +1036,7 @@ func handleAppCardBind(c *gin.Context) {
response.Error(c, 404, "应用不存在")
return
}
if !app.CardLoginAllowPassword && app.LoginMode != "card" && app.LoginMode != "both" {
if !app.CardLoginAllowPassword {
response.Error(c, 400, "该应用未开启卡密绑定邮箱")
return
}
@@ -0,0 +1,120 @@
package app
import (
"testing"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
)
// TestCardActivationWritesRechargeRecord 卡密首次激活必须产生一条充值流水。
//
// 修复前 resolveCardSubject 只发额度、改卡状态,不写 RechargeRecord,
// 结果「卡密带来多少收入」在财务页永远查不到。
func TestCardActivationWritesRechargeRecord(t *testing.T) {
setupTestDB(t)
app := model.Application{
AppKey: "cardapp", Name: "卡密应用", Status: "active",
BillingType: "subscription", LoginMode: "card", AllowRegister: true,
}
if err := database.DB.Create(&app).Error; err != nil {
t.Fatalf("建应用失败: %v", err)
}
ct := model.CardType{
ApplicationID: app.ID, Name: "月卡",
RechargeType: "subscription", Value: 30, ValueUnit: "day", Price: 100,
Status: "active",
}
if err := database.DB.Create(&ct).Error; err != nil {
t.Fatalf("建卡型失败: %v", err)
}
card := model.Card{
ApplicationID: app.ID, CardTypeID: ct.ID,
CardKey: "TESTCARD0001", Status: "unused", Purpose: "recharge",
}
if err := database.DB.Create(&card).Error; err != nil {
t.Fatalf("建卡失败: %v", err)
}
subject, err := resolveCardSubject(&app, "TESTCARD0001")
if err != nil {
t.Fatalf("卡密激活失败: %v", err)
}
if subject == nil || subject.ID == 0 {
t.Fatal("没有创建出主体")
}
if subject.SubjectType != "card" {
t.Fatalf("主体类型应为 card,实际 %q", subject.SubjectType)
}
// 月卡 = 30 天,到期时间应在 29~31 天之后
if subject.ExpiryAt == nil {
t.Fatal("订阅型卡密没写到期时间")
}
var recs []model.RechargeRecord
database.DB.Find(&recs)
if len(recs) != 1 {
t.Fatalf("卡密激活应写 1 条充值流水,实际 %d 条(修复前是 0 条)", len(recs))
}
r := recs[0]
if r.UserID != subject.ID {
t.Fatalf("流水主体错: %d,期望 %d", r.UserID, subject.ID)
}
if r.CardCode != "TESTCARD0001" {
t.Fatalf("流水卡号错: %q", r.CardCode)
}
if r.Amount != 100 {
t.Fatalf("流水金额应为卡型售价 100,实际 %v", r.Amount)
}
if r.Status != "success" || r.PaymentType != "card" {
t.Fatalf("流水状态/支付方式不对: %+v", r)
}
if r.OrderNo == "" {
t.Fatal("流水缺单号")
}
// 卡本身要变成已使用并绑定主体
var after model.Card
database.DB.First(&after, card.ID)
if after.Status != "used" || after.SubjectID == nil || *after.SubjectID != subject.ID {
t.Fatalf("卡状态不对: status=%q subject=%v", after.Status, after.SubjectID)
}
}
// TestCardRechargeThenLoginReusesSubject 同一张卡第二次登录要回到原主体,不再建新主体
func TestCardRechargeThenLoginReusesSubject(t *testing.T) {
setupTestDB(t)
app := model.Application{AppKey: "cardapp2", Name: "卡密应用2", Status: "active", BillingType: "subscription"}
database.DB.Create(&app)
ct := model.CardType{ApplicationID: app.ID, Name: "天卡", RechargeType: "subscription", Value: 1, ValueUnit: "day", Price: 10, Status: "active"}
database.DB.Create(&ct)
card := model.Card{ApplicationID: app.ID, CardTypeID: ct.ID, CardKey: "REUSE0001", Status: "unused"}
database.DB.Create(&card)
first, err := resolveCardSubject(&app, "REUSE0001")
if err != nil {
t.Fatalf("首次激活失败: %v", err)
}
second, err := resolveCardSubject(&app, "REUSE0001")
if err != nil {
t.Fatalf("再次登录失败: %v", err)
}
if first.ID != second.ID {
t.Fatalf("同卡应回到同一主体: %d vs %d", first.ID, second.ID)
}
var cnt int64
database.DB.Model(&model.AppUser{}).Count(&cnt)
if cnt != 1 {
t.Fatalf("应只有 1 个主体,实际 %d 个", cnt)
}
// 只有首次激活该记账
var recCnt int64
database.DB.Model(&model.RechargeRecord{}).Count(&recCnt)
if recCnt != 1 {
t.Fatalf("只有首次激活应记一笔,实际 %d 笔", recCnt)
}
}
+5 -6
View File
@@ -397,11 +397,10 @@ func handleAppChangePassword(c *gin.Context) {
})
}
// resolveCardOwner 用卡密定位主体(卡密本身就是钥匙,能拿出来就等于持有它)
func resolveCardOwner(app *model.Application, cardKey string) (*model.AppUser, *model.Card, error) {
var card model.Card
if err := database.DB.Where("card_key = ? AND application_id = ? AND purpose = ?", cardKey, app.ID, "credential").
if err := database.DB.Where("card_key = ? AND application_id = ?", cardKey, app.ID).
First(&card).Error; err != nil {
return nil, nil, fmt.Errorf("卡密不存在")
}
@@ -466,11 +465,11 @@ func handleAppCardDevices(c *gin.Context) {
}
response.Success(c, gin.H{
"max_devices": app.MaxDevices,
"max_devices": app.MaxDevices,
"device_count": len(list),
"devices": list,
"expiry_at": subject.ExpiryAt,
"balance": subject.Balance,
"devices": list,
"expiry_at": subject.ExpiryAt,
"balance": subject.Balance,
})
}
+4 -1
View File
@@ -252,7 +252,10 @@ func handleAppGetInfo(c *gin.Context) {
"enable_free_period": app.EnableFreePeriod,
"trial_days": app.TrialDays,
"bind_type": app.BindType,
"login_mode": app.LoginMode,
"login_mode": service.AppLoginMode(&app),
"login_mode_enforce": service.AppLoginModeEnforce(&app),
"login_mode_grace_days": service.LoginModeGraceDaysLeft(&app),
"allowed_login_types": service.AllowedLoginTypes(service.AppLoginMode(&app)),
"card_login_bind_device": app.CardLoginBindDevice,
"card_login_allow_password": app.CardLoginAllowPassword,
})
+8 -47
View File
@@ -54,13 +54,8 @@ func handleAppRecharge(c *gin.Context) {
fmt.Printf("[DEBUG] 卡密信息: ID=%d, CardKey=%s, Status=%s, CardTypeID=%d\n", card.ID, card.CardKey, card.Status, card.CardTypeID)
fmt.Printf("[DEBUG] 卡类信息: ID=%d, Name=%s, Value=%f, Price=%f\n", card.CardType.ID, card.CardType.Name, card.CardType.Value, card.CardType.Price)
// 登录卡是钥匙不是额度:拿它来充值直接拒绝,避免用途混淆
if card.Purpose == "credential" {
service.LogVerification(c, &app.ID, nil, "recharge_failed", fmt.Sprintf("充值失败: 这是登录卡密 - %s", req.CardKey), "", fmt.Errorf("登录卡密不能用于充值"))
response.Error(c, 400, "这是登录卡密,只能用于登录,不能充值")
return
}
// 不再按「登录卡 / 充值卡」区分:卡就是一份面值,能用来给主体加额度。
// 已激活过的卡(status=used)下面会用状态挡住,不需要额外的用途判断。
if card.Status != "unused" {
service.LogVerification(c, &app.ID, nil, "recharge_failed", fmt.Sprintf("充值失败: 卡密已使用 - %s", req.CardKey), "", fmt.Errorf("卡密已使用"))
response.Error(c, 400, "卡密已使用")
@@ -104,46 +99,12 @@ func handleAppRecharge(c *gin.Context) {
user.IsTrialUser = false
if card.CardType.Value == -1 {
if card.CardType.RechargeType == "subscription" {
permanentExpiry := time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
user.ExpiryAt = &permanentExpiry
user.Balance = -1
} else {
user.Balance = -1
user.ExpiryAt = nil
}
} else {
switch card.CardType.RechargeType {
case "subscription":
var baseTime time.Time
if user.ExpiryAt != nil && user.ExpiryAt.After(now) {
baseTime = *user.ExpiryAt
} else {
baseTime = now
}
var duration time.Duration
switch card.CardType.ValueUnit {
case "minute":
duration = time.Duration(card.CardType.Value) * time.Minute
case "hour":
duration = time.Duration(card.CardType.Value) * time.Hour
case "day":
duration = time.Duration(card.CardType.Value) * 24 * time.Hour
case "month":
duration = time.Duration(card.CardType.Value) * 30 * 24 * time.Hour
case "year":
duration = time.Duration(card.CardType.Value) * 365 * 24 * time.Hour
default:
duration = time.Duration(card.CardType.Value) * time.Second
}
newExpiry := baseTime.Add(duration)
user.ExpiryAt = &newExpiry
case "balance":
fallthrough
default:
user.Balance += card.CardType.Value
}
// 和「卡密首次激活」共用同一套加值实现(原来这里另写一份 switch,
// 两边的 value_unit 支持范围不一样,容易算出不同结果)
if err := service.ApplyCardTypeToSubject(tx, &user, &card.CardType, now); err != nil {
tx.Rollback()
response.Error(c, 500, "充值失败")
return
}
fmt.Printf("[DEBUG] 充值后用户信息: Balance=%f, ExpiryAt=%v (CardType.Value=%f, BillingType=%s)\n", user.Balance, user.ExpiryAt, card.CardType.Value, app.BillingType)
@@ -0,0 +1,168 @@
package app
import (
"bytes"
"encoding/json"
"fmt"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
)
// setupTestDB 起一个内存 sqlite 库,只迁移这些用例会碰到的表。
func setupTestDB(t *testing.T) {
t.Helper()
gin.SetMode(gin.TestMode)
dsn := fmt.Sprintf("file:t%d?mode=memory&cache=shared", time.Now().UnixNano())
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("打开测试库失败: %v", err)
}
database.DB = db
if err := db.AutoMigrate(
&model.Application{},
&model.AppUser{},
&model.ConsumptionRecord{},
&model.Card{},
&model.CardType{},
&model.RechargeRecord{},
&model.Log{},
&model.RiskControlRule{},
&model.UserDevice{},
&model.DeviceSession{},
); err != nil {
t.Fatalf("迁移测试表失败: %v", err)
}
}
// heartbeatCtx 构造一个带齐 handler 所需上下文的 gin.Context
func heartbeatCtx(appKey string, userID uint, username, deviceID string) (*gin.Context, *httptest.ResponseRecorder) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
body, _ := json.Marshal(map[string]string{
"device_id": deviceID,
"instance_id": "inst-test-1",
})
req := httptest.NewRequest("POST", "/api/v1/app/"+appKey+"/heartbeat", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
c.Request = req
c.Params = gin.Params{{Key: "appKey", Value: appKey}}
c.Set("user_id", userID)
c.Set("username", username)
c.Set("device_id", deviceID)
c.Set("instance_id", "inst-test-1")
return c, w
}
// TestTimerDeductionActuallyFires 这是回归测试:
// 修复前 handler 先把 LastHeartbeatAt 覆盖成 now,再拿它算 elapsed,
// 结果 elapsed 恒为 0,timer 模式永远不扣费也不报错。
func TestTimerDeductionActuallyFires(t *testing.T) {
setupTestDB(t)
app := model.Application{
AppKey: "timerapp",
Name: "计时应用",
Status: "active",
BillingType: "balance",
DeductionMode: "auto",
DeductionType: "timer",
DeductionInterval: 1,
DeductionUnit: "minute",
DeductionAmount: 1,
}
if err := database.DB.Create(&app).Error; err != nil {
t.Fatalf("建应用失败: %v", err)
}
// 上次心跳在 3 分钟前 —— 超过 1 分钟的扣费间隔,必须扣
past := time.Now().Add(-3 * time.Minute)
user := model.AppUser{
Username: "timeruser",
ApplicationID: app.ID,
Status: "active",
Balance: 100,
LastHeartbeatAt: &past,
}
if err := database.DB.Create(&user).Error; err != nil {
t.Fatalf("建用户失败: %v", err)
}
c, w := heartbeatCtx(app.AppKey, user.ID, user.Username, "dev-timer-1")
handleAppHeartbeat(c)
t.Logf("HTTP %d: %s", w.Code, w.Body.String())
var after model.AppUser
if err := database.DB.First(&after, user.ID).Error; err != nil {
t.Fatalf("回查用户失败: %v", err)
}
if after.Balance != 99 {
t.Fatalf("计时扣费没生效:余额 %v,期望 99(修复前会是 100)", after.Balance)
}
var recs []model.ConsumptionRecord
database.DB.Find(&recs)
if len(recs) != 1 {
t.Fatalf("应写 1 条消费流水,实际 %d 条(修复前是 0 条)", len(recs))
}
if recs[0].Amount != 1 || recs[0].UserID != user.ID || recs[0].ApplicationID != app.ID {
t.Fatalf("流水字段不对: %+v", recs[0])
}
if recs[0].BalanceAfter != 99 {
t.Fatalf("流水里的余额快照错: %v,期望 99", recs[0].BalanceAfter)
}
if recs[0].OrderNo == "" {
t.Fatal("流水缺单号")
}
// 心跳时间必须被更新成本次(修复过程中容易漏:重新查库会把它拉回旧值)
if after.LastHeartbeatAt == nil || time.Since(*after.LastHeartbeatAt) > time.Minute {
t.Fatalf("心跳时间没更新: %v", after.LastHeartbeatAt)
}
}
// TestTimerDeductionSkipsWhenIntervalNotReached 间隔没到就不该扣
func TestTimerDeductionSkipsWhenIntervalNotReached(t *testing.T) {
setupTestDB(t)
app := model.Application{
AppKey: "timerapp2", Name: "计时应用2", Status: "active",
BillingType: "balance", DeductionMode: "auto", DeductionType: "timer",
DeductionInterval: 1, DeductionUnit: "minute", DeductionAmount: 1,
}
database.DB.Create(&app)
justNow := time.Now().Add(-10 * time.Second) // 才 10 秒,不到 1 分钟
user := model.AppUser{
Username: "u2", ApplicationID: app.ID, Status: "active",
Balance: 100, LastHeartbeatAt: &justNow,
}
database.DB.Create(&user)
c, _ := heartbeatCtx(app.AppKey, user.ID, user.Username, "dev-timer-2")
handleAppHeartbeat(c)
var after model.AppUser
database.DB.First(&after, user.ID)
if after.Balance != 100 {
t.Fatalf("间隔未到不该扣费,余额变成了 %v", after.Balance)
}
var cnt int64
database.DB.Model(&model.ConsumptionRecord{}).Count(&cnt)
if cnt != 0 {
t.Fatalf("间隔未到不该写流水,实际 %d 条", cnt)
}
}
+83
View File
@@ -0,0 +1,83 @@
package service
import (
"time"
"gorm.io/gorm"
"verification-platform-backend/internal/model"
)
// CardTypeDuration 把卡型的 value / value_unit 换算成时长。
//
// 这个换算原来在两个地方各写了一遍 switch:
// - router/app/auth.go 的 resolveCardSubject(卡密首次激活)
// - router/app/payment.go 的充值时
//
// 而且两处的单位支持不一致:payment.go 支持 minute/hour/day/month/year,
// resolveCardSubject 只有 day/month/year,按分钟或小时计价的卡型走首次激活
// 会掉进 default 分支按「秒」算,直接把 30 分钟算成 30 秒。
//
// 现在统一走这里,加单位只改一处。
func CardTypeDuration(ct *model.CardType) time.Duration {
if ct == nil {
return 0
}
switch ct.ValueUnit {
case "minute":
return time.Duration(ct.Value) * time.Minute
case "hour":
return time.Duration(ct.Value) * time.Hour
case "day":
return time.Duration(ct.Value*24) * time.Hour
case "month":
return time.Duration(ct.Value*24*30) * time.Hour
case "year":
return time.Duration(ct.Value*24*365) * time.Hour
default:
return time.Duration(ct.Value) * time.Second
}
}
// ApplyCardTypeToSubject 把卡型的额度应用到主体上:余额型加余额,订阅型加时长。
//
// 「卡密首次激活」和「给已有主体充卡密」两条路径都必须走这里,否则同一张卡
// 换个入口进去结果不同(历史上这两处的 value_unit 支持就不一样)。
//
// db 可以是 *gorm.DB,也可以是事务 tx,调用方自己决定在不在事务里。
func ApplyCardTypeToSubject(db *gorm.DB, subject *model.AppUser, ct *model.CardType, now time.Time) error {
if ct == nil || ct.ID == 0 || subject == nil {
return nil
}
// value = -1:永久卡。余额型和订阅型的历史表示不同,别混。
if ct.Value == -1 {
if ct.RechargeType == "subscription" {
permanent := time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
subject.ExpiryAt = &permanent
subject.Balance = -1
return db.Model(&model.AppUser{}).Where("id = ?", subject.ID).
Updates(map[string]interface{}{"expiry_at": permanent, "balance": -1}).Error
}
subject.Balance = -1
subject.ExpiryAt = nil
return db.Model(&model.AppUser{}).Where("id = ?", subject.ID).
Updates(map[string]interface{}{"balance": -1, "expiry_at": nil}).Error
}
if ct.RechargeType == "subscription" {
base := now
if subject.ExpiryAt != nil && subject.ExpiryAt.After(now) {
base = *subject.ExpiryAt // 续期从原到期时间往后加,不是从今天重算
}
exp := base.Add(CardTypeDuration(ct))
subject.ExpiryAt = &exp
return db.Model(&model.AppUser{}).Where("id = ?", subject.ID).
Update("expiry_at", exp).Error
}
// 余额型:累加,不是覆盖
subject.Balance += ct.Value
return db.Model(&model.AppUser{}).Where("id = ?", subject.ID).
Update("balance", gorm.Expr("balance + ?", ct.Value)).Error
}
+104
View File
@@ -0,0 +1,104 @@
package service
import (
"math"
"time"
"verification-platform-backend/internal/model"
)
// 登录方式开关(login_mode)的判定逻辑集中在这里,供 app 侧(登录/注册/信息下发)
// 与 admin 侧(设置、影响面统计)共用。
//
// 设计约定:
// - login_mode 是应用级**策略**,客户端界面只影响体验,真正的判定必须发生在服务端;
// - 判定必须早于任何副作用(建绑定、记失败、改 last_login、触发风控锁定);
// - 空值/非法值一律按 both 处理(fail-open),任何时候都不把用户锁在门外;
// - 生效级别由 LoginModeEnforce 控制:off = 不校验,warn = 只记录,strict = 拦截;
// - 处于宽限期(LoginModeGraceUntil 未过)时旧凭证仍可用,只在响应里带 deprecated 标记。
// AppLoginMode 归一化应用的登录方式;空值/未知值按 both 处理。
func AppLoginMode(app *model.Application) string {
if app == nil {
return "both"
}
switch app.LoginMode {
case "account", "card", "both":
return app.LoginMode
}
return "both"
}
// AllowedLoginTypes 返回该模式下允许的凭证类型。
func AllowedLoginTypes(mode string) []string {
switch mode {
case "account":
return []string{"account"}
case "card":
return []string{"card"}
default:
return []string{"account", "card"}
}
}
// AppLoginModeEnforce 归一化生效级别;空值/未知值按 off 处理,保证升级后行为不变。
func AppLoginModeEnforce(app *model.Application) string {
if app == nil {
return "off"
}
switch app.LoginModeEnforce {
case "off", "warn", "strict":
return app.LoginModeEnforce
}
return "off"
}
// LoginModeLabel 用于错误文案。
func LoginModeLabel(mode string) string {
switch mode {
case "account":
return "账号密码"
case "card":
return "卡密"
default:
return "账号密码或卡密"
}
}
// LoginModeGraceDaysLeft 返回宽限期剩余天数(向上取整);不在宽限期返回 0。
func LoginModeGraceDaysLeft(app *model.Application) int {
if app == nil || app.LoginModeGraceUntil == nil {
return 0
}
d := time.Until(*app.LoginModeGraceUntil)
if d <= 0 {
return 0
}
days := int(math.Ceil(d.Hours() / 24))
if days < 1 {
days = 1
}
return days
}
// LoginTypeAllowedByMode 判断某凭证类型在当前模式下是否允许。
func LoginTypeAllowedByMode(app *model.Application, loginType string) bool {
for _, t := range AllowedLoginTypes(AppLoginMode(app)) {
if t == loginType {
return true
}
}
return false
}
// LoginModeBlockMessage 生成给终端用户看的拒绝文案。
func LoginModeBlockMessage(mode string) string {
switch mode {
case "account":
return "该应用仅支持账号密码登录"
case "card":
return "该应用仅支持卡密登录"
default:
return "该应用当前不支持的登录方式"
}
}
@@ -0,0 +1,98 @@
package service
import (
"testing"
"time"
"verification-platform-backend/internal/model"
)
func TestAppLoginModeNormalize(t *testing.T) {
cases := []struct {
in string
want string
}{
{"account", "account"},
{"card", "card"},
{"both", "both"},
{"", "both"}, // 空值按 both:任何情况下都不把用户锁在门外
{"weird", "both"}, // 非法值同上
}
for _, c := range cases {
app := &model.Application{LoginMode: c.in}
if got := AppLoginMode(app); got != c.want {
t.Fatalf("AppLoginMode(%q) = %q, want %q", c.in, got, c.want)
}
}
if got := AppLoginMode(nil); got != "both" {
t.Fatalf("AppLoginMode(nil) = %q, want both", got)
}
}
func TestAppLoginModeEnforceNormalize(t *testing.T) {
cases := []struct {
in string
want string
}{
{"off", "off"},
{"warn", "warn"},
{"strict", "strict"},
{"", "off"}, // 空值不拦截
{"bogus", "off"}, // 非法值不拦截
}
for _, c := range cases {
app := &model.Application{LoginModeEnforce: c.in}
if got := AppLoginModeEnforce(app); got != c.want {
t.Fatalf("AppLoginModeEnforce(%q) = %q, want %q", c.in, got, c.want)
}
}
}
func TestLoginTypeAllowedByMode(t *testing.T) {
m := func(mode, enforce string) *model.Application {
return &model.Application{LoginMode: mode, LoginModeEnforce: enforce}
}
cases := []struct {
app *model.Application
typ string
allow bool
}{
{m("account", "strict"), "account", true},
{m("account", "strict"), "card", false},
{m("card", "strict"), "card", true},
{m("card", "strict"), "account", false},
{m("both", "strict"), "account", true},
{m("both", "strict"), "card", true},
}
for _, c := range cases {
if got := LoginTypeAllowedByMode(c.app, c.typ); got != c.allow {
t.Fatalf("mode=%s login_type=%s got %v want %v", c.app.LoginMode, c.typ, got, c.allow)
}
}
}
func TestLoginModeGraceDaysLeft(t *testing.T) {
past := time.Now().Add(-1 * time.Hour)
future := time.Now().Add(72 * time.Hour)
if got := LoginModeGraceDaysLeft(&model.Application{LoginModeGraceUntil: nil}); got != 0 {
t.Fatalf("nil grace = %d, want 0", got)
}
if got := LoginModeGraceDaysLeft(&model.Application{LoginModeGraceUntil: &past}); got != 0 {
t.Fatalf("expired grace = %d, want 0", got)
}
if got := LoginModeGraceDaysLeft(&model.Application{LoginModeGraceUntil: &future}); got != 3 {
t.Fatalf("72h grace = %d, want 3", got)
}
}
func TestAllowedLoginTypes(t *testing.T) {
if got := len(AllowedLoginTypes("account")); got != 1 {
t.Fatalf("account should allow 1 type, got %d", got)
}
if got := len(AllowedLoginTypes("card")); got != 1 {
t.Fatalf("card should allow 1 type, got %d", got)
}
if got := len(AllowedLoginTypes("both")); got != 2 {
t.Fatalf("both should allow 2 types, got %d", got)
}
}
+2 -1
View File
@@ -8,7 +8,8 @@ mkdir -p "$DATA_DIR" "$UPLOADS_DIR"
if [ "$(id -u)" = "0" ]; then
chown -R appuser:appgroup "$DATA_DIR" "$UPLOADS_DIR"
exec su-exec appuser "$@"
# 基础镜像是 debian,没有 alpine 的 su-exec,用 util-linux 的 setpriv 降权
exec setpriv --reuid=appuser --regid=appgroup --clear-groups -- "$@"
else
exec "$@"
fi
+6
View File
@@ -0,0 +1,6 @@
[TestLicense]
AcceptedSerialNumber=SerialNumber
UserName=TestUser
EMail=test@example.com
MyHWID=+L7reY1X2iCLr+TKSsVHtQ==
UserData=00
+38
View File
@@ -0,0 +1,38 @@
# DogProtect 加壳器(Linux 版)
`dogprotect_con` 是 DogProtect Ultimate v3.5.1 的命令行加壳器,由 DogProtect 仓库
(`/root/work/vmprotect`)用 `lin_console64.mak` 构建:
```bash
cd /root/work/vmprotect/DogProtectCon
make -f lin_console64.mak # 产物在 ../bin/64/release/dogprotect_con
```
三个文件必须放在同一个目录里(加壳器链接时是 `-Wl,-rpath,$ORIGIN`):
| 文件 | 作用 |
|---|---|
| `dogprotect_con` | 加壳器本体(42M,glibc 动态链接) |
| `libDogProtectSDK64.so` | SDK 运行时库,缺了会报 `DaveProtectSetSerialNumber: symbol not found` |
| `DogProtectLicense.ini` | 授权文件。当前是随源码带的 TestLicense(TestUser),换正式授权直接替换这个文件 |
**glibc 要求 2.38+ / GLIBCXX 3.4.32+** —— 这是容器基础镜像从 alpine 换成
`debian:trixie-slim` 的原因。alpine 的 gcompat 跑不起来,bookworm(glibc 2.36)也差一截。
## 加壳顺序:必须先 DogProtect、后注入验证壳
DogProtect 会把要保护的节打包、把 `SizeOfRawData`/`PointerToRawData` 清零。
如果先注入验证壳的 `.load` 节、再跑 DogProtect,`.load` 的内容会被搬进打包节,
磁盘上只剩一个 raw size = 0 的空节 —— 验证壳运行时读不到自己的配置,
整个验证静默失效(`vfyfix` 只能重算 CRC,救不回被搬走的内容)。
反过来是可行的,`protect.go` 里就是这么串的:
```
源程序 → dogprotect_con → PatchAutoSignedThemed(追加 .load)→ [可选 Authenticode 重签]
```
运行时顺序:`.load` 壳先跑(显示验证界面、校验授权)→ 通过后跳回原入口
→ DogProtect 启动代码解包 → 原程序执行。
实测(wine):先 dog 后 verify 的产物能正常出验证界面、卡密模式正确、无黑块错位。
BIN
View File
Binary file not shown.
Binary file not shown.
+40
View File
@@ -0,0 +1,40 @@
# 财务 / 日志模块检查报告(2026-11-24)
检查方式:读代码 + 在本地起一套干净后端(sqlite)造 40 条流水、61 条日志,用真请求验证。下面标 ✅ 的已经修好并实测,标 ⚠️ 的需要产品上拍板。
## 财务(`/dev/finance/*`)
| # | 问题 | 证据 | 处理 |
|---|---|---|---|
| F1 | **财务页只显示 10 条,且「充值总额/消费总额/利润」是对这 10 条 reduce 出来的** | 前端 `fetchRecords()` 不带 `page_size`,后端默认 10;库里 40 条时页面只拿到 10 条,卡片数字按 10 条算 | ✅ 后端 `/finance/records` 增加 SQL 聚合 `summary`(带全部筛选条件)+ 真分页;前端卡片改用 `summary`,表格改成服务端分页(实测 40 条 / 2 页,卡片 25 笔 ¥250 / 15 笔 ¥45 / 净收益 ¥205,与库一致) |
| F2 | **两张表全量捞进内存再切片**,`total` 是 `len()` | `handleGetFinanceRecords` 用 `Find` 无 limit | ✅ 改成 SQL 层 `Limit(offset+pageSize)` 合并分页,深翻页限制 1000 条 |
| F3 | **分页参数零校验**:`page=0` / `page_size=0/-5` 会一次返回全部记录 | 实测 `page=0&page_size=0` 返回 40 条全量 | ✅ 统一 `parsePageParams()`:page≥1、page_size∈[1,200]、默认 20(实测同样的请求现在返回 20 条) |
| F4 | **接口支持删财务流水**(单条 + 批量),软删后不碰 `app_user.balance` | `DELETE /dev/finance/records/:id`、`POST .../batch-delete` | ✅ **删除已封**:两个接口返回 403「财务流水是审计凭证,不支持删除;需要清理或对账请使用导出」,并写一条 `delete_blocked` 审计(含 id/type/条数)。新增 `GET /dev/finance/export` 导出 CSV(带 BOM,含类型/订单号/金额/用户/详情/状态/支付方式/备注/应用/时间,上限 10 万条)。前端删除列、批量删除按钮全部移除,换成「导出流水」 |
| F5 | **软删一个主体后,它的历史流水在面板里消失**,`/finance/stats` 的累计收入也跟着减少 | 实测软删有流水的主体后,列表从 20 条变 19 条 | ✅ 已修:主体范围用 `Unscoped()` 取(含软删主体),`Preload("AppUser")` 也带 `Unscoped()`。实测软删主体前后总条数 40/40、充值合计 250/250,且该主体流水的 `user` 字段仍显示用户名 |
| F6 | `AppID: r.AppUser.ApplicationID` 对 nil 指针直接解引用 | 代码审查;当前路径被主体过滤挡住,属潜在 panic | ✅ 抽成 `rechargeToFinanceResponse` / `consumptionToFinanceResponse`,nil 安全 |
| F7 | `/finance/stats` 正常分支漏返回 `monthly_transactions`(只有空数据分支有) | 代码审查 | ✅ 正常分支也返回本月流水条数 |
| F8 | `start_date` 直接拼 `" 00:00:00"` | 前端传 ISO 带 T 时会筛选错/500 | ⚠️ 前端目前传的是 `split('T')[0]`,暂无触发;接口层没做容错 |
## 日志(`/dev/logs`)
| # | 问题 | 证据 | 处理 |
|---|---|---|---|
| L1 | **顶部三个统计与列表不同源**:统计查 `api_usages` 表,列表查 `logs` 表,且统计**完全不带筛选** | 实测列表 61 条、`success=0 failed=0 operation=0`(api_usages 空);带 `status=failed` 筛选后统计也不变 | ✅ 统计改成同一张 `logs` 表 + 同一套筛选条件(实测 success=53 / failed=8 / operation=15,带筛选时为 0/0/0 与列表一致) |
| L2 | **分页参数零校验**:`page_size=-1` → GORM `Limit(-1)` 等于不加 LIMIT | 实测 `page=-1&page_size=-1` 返回 59 条 | ✅ 用同一个 `parsePageParams()` |
| L3 | `query.Count(&total)` 忽略错误 | 代码审查 | ✅ 顺带改为新逻辑(count 与统计共用 baseQuery) |
| L4 | `search` 的 LIKE 没转义 `%` `_`,输入 `%` 会命中全部 | 代码审查 | ✅ 已修:`escapeLike()` 转义 `\` `%` `_`,财务与日志共用。实测 `search=%` 返回 0 条(原来返回全部) |
| L5 | 日志表无索引,列表按 `application_id` + `created_at` 排序、按 `log_type`/`status` 过滤都要扫全表 | 代码审查 | ✅ 已加三组复合索引并实测建出:`idx_logs_app_created(application_id, created_at)`、`idx_logs_user_created(user_id, created_at)`、`idx_logs_type_status(log_type, status)`。`details LIKE %x%` 仍会扫,属全文搜索范畴,不在这轮 |
## 待办(下一步可选)
- 财务/日志导出现在只有财务有;日志要不要也加一份导出?
- `details LIKE %x%` 仍是全表扫,量大再考虑全文索引或改用 ES。
## 顺带
- 分页参数统一收口在 `backend/internal/router/admin/pagination.go`,以后新接口直接用 `parsePageParams(c)`,别再各写一遍。
- 财务/日志都还有"无法导出"的问题(前端没有导出按钮,后端没有 export 接口)——要的话可以按现有 `cards/export` 的路子补。
## 复现脚本
`/root/work/audit_finance_logs.py`(对着本地 sqlite 后端跑,打印每一项的实测结果)。
+74
View File
@@ -1,4 +1,9 @@
# 二次加壳(verify 壳 + 其他加壳器)实测结论
> **壳节已改名**:2026-11 起产物里的壳节从 `.vfy` 改为 **`.load`**(`protect.go` 的 `secName`),
> 旧产物的 `.vfy` 仍被识别(`HasVfy` 与 `cmd/vfyfix` 都同时接受两种名字)。
> 原因是引导 blob 里的节名比较已按 `.load` 打补丁(x64 `blob64.bin` 偏移 `0x85/0x8b/0x91`:`76 66 79` → `6c 6f 61`,
> x86 `blob32.bin` 偏移 `0x73/0x79/0x7f` 同理)—— 两者必须一起改,只改 Go 侧产物会启动即退(引导找不到壳节,`return 2`)。
被测组合:`protect.Patch`(离线工具 `cmd/packtest`)打的 verify 壳产物 + DogProtect 加壳。
运行环境 wine;`exit=124` 表示 GUI 起来在等 API(超时被杀),是**正常启动**的表现;
@@ -19,6 +24,59 @@
| 改造前:壳(默认)→ DogProtect | 13 ❌ | 整文件 CRC 与变长后的文件对不上 |
| DogProtect → 壳(不论模式) | 222 ❌ | 引导把控制权交给 DogProtect 的 loader,交不过去 |
### 用当前壳资产(含设备管理页)重测 —— 功能级验证
上面那批是「能不能启动」;下面这批验证**双层产物里的壳功能是否完整**(2026-11 当前资产:
`blob64.bin` 10,000 字节、`shell64_dui.bin` 907,264 字节,dark 皮肤):
```
单层 dp_single.exe 957,440 字节 → wine exit=124
双层 dp_double.exe(DogProtect 外挂)7,326,720 字节 → wine exit=124
```
把双层产物接上 mock 服务端走完整流程,实测请求序列:
```
POST /api/v1/app/dogtest/login {"login_type":"account","username":"123","password":"***",
"device_id":"C36E-0A03-F08D","device_name":"VIAEON","device_type":"windows",
"instance_id":"C36E-0A03-F08D"} ← 被 403 DEVICE_LIMIT 拦下
→ 界面切到独立「设备管理」页(窗口 620×620、标题「设备管理 - dogtest」、3 行设备各带解绑按钮)
点第 2 行「解绑」
POST /api/v1/app/dogtest/unbind-device-with-auth {"username":"123","password":"***",
"device_id":"BBBB-4444-5555-6666"} ← 第 2 台,不是最早那台
POST /api/v1/app/dogtest/login … ← 解绑后自动重试
```
结论:**DogProtect 外层不影响壳内的设备管理页、行内解绑、窗口放大与标题切换**,双层产物功能与单层一致。
### 分层证据(外层 / 内层到底谁在里面)
| 项目 | 单层(verify 壳) | 双层(verify 内 + DogProtect 外) |
|---|---|---|
| 入口 RVA | `0x10030` = `.vfy`(0x10000) + 48 字节头 | `0x4a7ce9` → 落在 DogProtect 新加的 `.UPX3` 段里 |
| 节表 | … `.reloc@0xf000`, `.vfy@0x10000` | … `.UPX0@0xf000`, **`.vfy@0x10000`(原位不动)**, `.UPX1@0xf0000`, `.UPX2`, `.UPX3`, `.reloc` |
| `.vfy` 内容 sha256(前16) | `4f48879143b676a7` | **`4f48879143b676a7`(完全相同)** |
也就是说:**verify 的验证壳(引导 + 壳 DLL + cfg)原封不动留在内层 `.vfy` 里**,
DogProtect 只是把入口接管到自己的 loader 段、把原程序压缩/虚拟化后追加 `.UPX*`,
解包完再把控制权交回「原入口」—— 那个原入口正是 `.vfy+48`,于是壳照常跑。
**注意**:DogProtect 目前虚拟化的是**原始程序里被 `VMProtectBegin/End` 标记的函数**,
`.vfy` 里的验证壳代码本身**没有被虚拟化**(内容 hash 一致即证明)。若要让验证壳也被 DogProtect 保护,
需要给壳函数加标记并在打包后重算 `.vfy` 头的 `crcV`(否则壳会以 `exit=6` 拒绝启动)—— 属另一个课题。
复现命令:
```bash
# 1) 打壳(api 用完整 login URL)
./packthemed sample.exe single.exe cfg.json dark
# 2) 外层再加 DogProtect(项目文件里 InputFileName 指向 single.exe)
LD_LIBRARY_PATH=<vmprotect>/bin <vmprotect>/bin/64/release/dogprotect_con \
single.exe double.exe -pf project.dog
# 3) 跑起来 + mock 服务端(scripts/mock-vfy-device-limit.py)按 docs/shell-device-ui.md 的清单验收
```
## 引导补丁(1 字节,可逆)
引导里整文件 CRC 的比较是 `cmp [hdr+0x28], eax` 紧跟 `je <通过>`;把那个 `je` 改成 `jmp`,
@@ -72,3 +130,19 @@ go build ./cmd/packsigned && ./packsigned <src.exe> <out.exe> <cfg.json>
即 `PatchSigned(..., signed=true)`,`flags.bit1=1`、`crcFile=0`。引导改造后它不再是二次加壳的前提,
但保留给「签名产物」(Authenticode 与整文件 CRC 也互斥)这一路使用。
### 32 位(x86)实测
改名在 32 位链路上同样验证过(`wine32:i386` + 独立 `WINEARCH=win32` prefix):
| 项目 | 结果 |
|---|---|
| 32 位样本 | `GOOS=windows GOARCH=386 go build` 产出的 PE32(无需 i686 mingw 工具链) |
| 产物 | `ld32.exe` 2,198,016 字节,架构 x86(自动选 `blob32.bin` + `shell32.bin`) |
| 节表 | `… .idata, .reloc, .symtab, .load` —— 壳节名已生效 |
| 入口 | RVA `0x212030` = `.load`(0x212000) + 48 ✅ |
| 启动 | `wine` 起窗口,引导阶段标记 `F`(CRC 通过 + 壳 DLL 映射完成),classic 壳登录页正常渲染,exit=124 ✅ |
| 篡改 `.load` 内容 | exit=**6**(节级 `crcV` 拦住)✅ |
注意:64 位 prefix 里跑 32 位产物会 `could not load kernel32.dll`,必须用 `WINEARCH=win32` 的独立 prefix。
+129
View File
@@ -0,0 +1,129 @@
# 登录方式开关(login_mode)
每个应用可以独立决定「用哪种凭证登录」:账号密码 / 卡密直登 / 两者都开。这个开关**在服务端真正生效**,不只是界面藏控件。
## 一句话架构
```
面板配置(login_mode + enforce + 宽限期)
↓
服务端强制(/login、/register 里 gate,早于任何副作用)
↓
客户端呈现(/info 下发 login_mode,壳按它决定显示哪些控件)
```
壳能被破解替换,**判定只在服务端**;壳按 `/info` 只是把不该出现的输入框藏起来,让用户少困惑。
## 三种模式
| login_mode | 语义 | 允许的凭证 |
|---|---|---|
| `account` | 账号密码登录;卡密只用于充值 | `account` |
| `card` | 一张卡就是一个用户,输入卡密即登录 | `card` |
| `both` | 两种都开 | `account` + `card` |
**卡密的两种语义不要混**:①登录凭证(`purpose=credential`,`login_mode` 管这个)②充值手段(`purpose=recharge`,由 `billing_type` 管)。关掉卡密直登不会连带关掉卡密充值。
## 生效级别(login_mode_enforce)
配置改了不会立刻拦人,`enforce` 决定它到底管不管:
| 值 | 行为 | 用途 |
|---|---|---|
| `off` | 完全不校验(升级前的行为) | 回滚 |
| `warn` | 校验但放行,只写一条 `login_mode_blocked` 审计日志(`[warn-only]` 前缀) | 灰度:先看会挡到谁 |
| `strict` | 真正拦截:HTTP 403 + `error_code=LOGIN_MODE_DISABLED` | 上线 |
新建应用默认 `login_mode=both`、`enforce=warn`;存量应用升级时 `enforce` 会被回填成 `warn`(启动时一次性 UPDATE,幂等),所以**升级本身不改变任何行为**。
## 宽限期
`applications.login_mode_grace_until`:切换模式时自动给 7 天(也可以在面板里填 0 = 立即生效)。
宽限期内旧凭证仍可用,但登录成功的响应里会带:
```json
{"deprecated_login": true, "grace_days_left": 7,
"login_mode": "account", "allowed_login_types": ["account"]}
```
壳拿这些字段提示「该登录方式将在 X 天后停用」。这层是给**老客户端**留的活路:老壳不认识新字段、也显示不了提示,但至少不会被一刀切挡在门外。
## 服务端拦截点
`backend/internal/router/app/auth.go` 的 `/login`:`login_type` 归一化(`auto` → `account`/`card`)**之后**、查主体/写设备绑定/记失败次数**之前**。
这样被策略拒绝的请求**不产生任何副作用**:不建绑定行、不加失败计数、不写 `last_login`、不触发「异常登录自动锁定」,只留一条审计日志。
拒绝响应(固定错误码,壳可以按它做文案):
```json
HTTP 403
{"code":403,"error_code":"LOGIN_MODE_DISABLED",
"message":"该应用仅支持账号密码登录",
"data":{"login_mode":"account","allowed":["account"]}}
```
`/register` 同样有一道:`card` + `strict` + 不在宽限期时返回「该应用使用卡密登录,无需注册」(卡密模式下注册出来的账号根本没有登录入口)。
## 影响面预检
`GET /api/v1/dev/applications/:id/login-mode-impact`
```json
{"total_subjects":2,"card_subjects":1,"card_subjects_with_email":0,
"only_card_subjects":1,"only_account_subjects":1,
"blocking":false,"blocked_if_switch":1,
"login_mode":"both","login_mode_enforce":"warn","login_mode_grace_days":0}
```
- `only_card_subjects`:卡密主体的密码是建主体时写进去的**随机散列**(卡密才是它的钥匙),所以不能靠 `password` 是否为空判断,这里用「没绑邮箱」来近似——绑了邮箱才有自助设密码的通道。
- `only_account_subjects`:有账号但没绑任何 `purpose=credential` 的卡 → 切到 `card` 会登不进来。
面板在「登录方式」卡片里直接显示这两个数字,切换模式时给出「约 N 个主体将无法登录」的黄色提示。
## 面板位置
应用详情 → 设置 → **登录方式**卡片:
1. 三选一(账号密码 / 卡密直登 / 两者都开)
2. **生效方式**(关闭校验 / 仅记录 / 已生效)
3. **切换后的宽限期(天)**
4. 影响面提示条(会挡住多少人)
5. 卡密相关两个开关(是否受设备上限约束、是否允许卡密主体再设密码),仅在非 `account` 模式下显示
## 实测矩阵
`/root/work/e2e_login_mode.py`(对着干净 sqlite 后端起真服务跑,不是单测):
| 模式/级别 | 提交 account | 提交 card | auto(卡密塞 username、密码空) | auto(账号+密码) |
|---|---|---|---|---|
| both / off | 200 | 200 | 200 | 200 |
| account / strict | 200 | **403 LOGIN_MODE_DISABLED** | **403** | 200 |
| card / strict | **403** | 200 | 200 | **403** |
| account / warn | 200 | 200(写 `[warn-only]` 日志) | 200 | 200 |
| account / strict + 7 天宽限 | 200 | 200 + `deprecated=7天` | 200 + `deprecated=7天` | 200 |
纯逻辑另有单测:`go test ./internal/service -run "LoginMode|LoginType|Allowed"`。
## 存量用户怎么迁移(本期只做「不锁死人」的部分)
原则:**主体不动,只补另一种钥匙**(`app_users` 是主体,卡密与账号都是它的凭证)。
已经不锁人的三道保险:
1. 存量应用 `enforce` 回填 `warn` → 升级不改行为
2. 切换模式自动给 7 天宽限 → 旧凭证还能用,且壳能提示
3. 影响面接口 + 面板黄色提示 → 管理员切之前就看得到会挡住谁
**还没做**(下一步,按这个顺序):
1. `POST /app/:key/card-to-account`:持有效卡密即可给自己设密码(纯卡密主体唯一的活路)
2. `POST /app/:key/account-to-card`:给已登录账号签发一张 `credential` 卡
3. 管理端批量迁移向导(批量生成初始密码 / 批量签发迁移卡 + 导出清单 + `must_change_password`)
## 已知未做
- **classic 壳**(`shell64.bin` / `shell32.bin`)不读 `login_mode`:界面照旧给「账号或卡密」单框。服务端会拦,并返回可读的 `message`;UI 适配需要二进制补丁或重编源码(二期)。
- **Android 壳**(`shell_smali.tgz`)同样不读 `login_mode`:仍是「账号或卡密 + 密码」两框。server 已保证策略正确。
- DuiLib 壳(7 套皮肤)**已经**按 `login_mode` 自适应:`card` 模式隐藏密码框、输入框改「卡密」、按钮改「卡密登录」;`both` 模式仍是「密码留空走卡密」的隐式判定(后续可以加显式切换)。
+66
View File
@@ -0,0 +1,66 @@
# 加壳产物的服务器地址是怎么来的(`app.public_url` / 反代头)
## 结论
打包时写进壳 cfg 的 `api` 字段 = `<站点根地址>/api/v1/app/<app_key>/login`。
站点根地址按下面的顺序确定(`backend/internal/router/admin/protect.go` 的 `baseURL()`):
1. `config.yaml` 里的 **`app.public_url`**(配了就最优先,推荐生产环境配上)
2. 请求头 **`X-Forwarded-Host`**(反向代理应当传,值就是用户浏览器地址栏里的域名)
3. 请求的 `Host`
4. 上面两者都没有,或者拿到的是本机/内网地址(`127.x` / `localhost` / `10.x` / `172.16-31.x` / `192.168.x` / `169.254.x`)→ **加壳任务直接报错**,不产出连不上服务器的产物
## 为什么这么写(真实事故)
服务器上的站点是 AcePanel 管的,它默认的反向代理模板写的是:
```nginx
proxy_set_header Host $proxy_host; # ← 后端会看到 127.0.0.1:9998
```
于是 `baseURL()` 推断出 `https://127.0.0.1:9998`,产出的每个客户端壳里都写着:
```
{"api":"https://127.0.0.1:9998/api/v1/app/f26091ac.../login"}
```
客户机上的壳去连自己的 127.0.0.1:9998 —— 必然失败。已确认修复前产出的 `data/protect/*/…_protected.exe` 全部带这个错误地址。
## 正确配法
站点反代(AcePanel → 站点 → 反向代理)里应当是:
```nginx
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
```
`$host` 是请求里的域名(经 Cloudflare 到达时是 `v.viaeon.com`),`$proxy_host` 是上游地址(`127.0.0.1:9998`)。
懒得依赖反代的话,直接在部署目录的 `data/config.yaml` 里写死:
```yaml
app:
public_url: "https://v.viaeon.com"
```
改完重启容器生效(`docker compose restart app`)。
## 自查方法
产物里直接能看出来:
```bash
grep -aoE '\{"api":"[^"]*"' 产物.exe
```
应该看到 `"api":"https://v.viaeon.com/api/v1/app/<key>/login"`。
看到 `127.0.0.1` / `localhost` / 内网 IP 就是踩了这个坑,需要重新打包。
## 验收记录(2026-11-24)
- 反代改前:`proxy_set_header Host $proxy_host` → 探针实测后端收到 `Host: 127.0.0.1:9998`
- 反代改后:`Host $host` + `X-Forwarded-Host $host` → 探针实测后端收到
`Host: v.viaeon.com`、`X-Forwarded-Host: v.viaeon.com`、`X-Forwarded-Proto: https`
- 代码单测:`go test ./internal/router/admin -run "BaseURL|IsInternalHost"`(4 例通过,含「本机地址必须报错」)
+150
View File
@@ -0,0 +1,150 @@
# 验证壳的设备管理页(Windows / Android)
这份文档记录 2026-11 这轮壳改动的**最终形态、交互契约、验收方法和踩过的坑**,换人接手不用再从二进制里挖。
涉及资产:
| 资产 | 说明 |
|---|---|
| `backend/internal/protect/assets/shell64_dui.bin` | x64 DuiLib 壳(7 套皮肤:dark/light/industrial/compact/split/card/terminal) |
| `backend/internal/protect/assets/shell32_dui.bin` | x86 DuiLib 壳(同一套皮肤;用 `shell/duilib/build-duilib32.sh` 编) |
| `backend/internal/protect/assets/shell64.bin`、`shell32.bin` | classic(Direct2D 单皮肤)壳 |
| `backend/internal/protect/assets/shell_smali.tgz` | Android 壳(smali 源码,加壳时由 apktool 合并进 APK) |
| `shell/duilib/shell9_v6.cpp` + `skins_v4.h` | DuiLib 壳的完整源码(XML 皮肤在头文件里) |
| `shell/classic/shell6.cpp` | classic 壳源码 |
> 改完源码后:`shell/duilib/build-duilib.sh` → 产物拷进 `assets/shell64_dui.bin` → **必须重编 `cmd/packthemed`**(见坑 1)。
---
## 1. 设备满时:独立「设备管理」页(QQ 式)
触发:登录返回 HTTP 403 + `error_code=DEVICE_LIMIT_EXCEEDED`。
行为:
1. 窗口从登录页尺寸(470×428 一类)**临时放大到 620×620 并居中**
2. 标题栏文字切为 **`设备管理 - <应用名>`**(cfg 的 `name`)
3. 内容区小标题 `设备管理`,副标题 `已绑定 3 / 2 台,解绑一台后即可登录`
4. 登录页的 4 个 tab(登录/注册/卡密充值/忘记密码)与品牌字**隐藏**
5. 每台设备一行卡片:`序号. 名称 设备ID ● 在线 / ○ 离线`,**右侧一个蓝色「解绑」按钮**
6. 底部:`解绑最早一台` / `重试` / `返回`
7. **点哪一行的「解绑」就解绑那一台**;成功后自动重试登录
8. 点「返回 / 重试」→ 标题复原为 `软件授权验证`、tab 回来、窗口缩回原尺寸
### 交互契约(前端 ↔ 后端)
| 步骤 | 请求 | 说明 |
|---|---|---|
| 登录 | `POST /api/v1/app/:appKey/login` `{login_type,username,password,device_id,device_name,device_type,instance_id}` | 设备绑定 + 会话都在这一步完成 |
| 被拦 | HTTP 403 `{error_code:"DEVICE_LIMIT_EXCEEDED", data:{max_devices, device_count, devices:[{id,device_id,device_name,device_type,online_count,created_at}]}}` | 壳解析 `devices` 渲染列表,`online_count>0` → ● 在线 |
| 解绑 | `POST /api/v1/app/:appKey/unbind-device-with-auth` `{username,password,device_id}` | 卡密用户走 `/card-unbind` `{card_key,device_id}` |
| 重试 | 再发一次 login | 解绑成功后自动重试,不用用户再点 |
**注意**:壳只做**解绑**(删绑定行、连带断会话),不做「下线/踢线」(`POST /instances/:instance_id/offline` 未接入)。所以界面文案里不能用「下线」,否则用户会以为能保留授权只断会话。
### 手动选择,不自动解
- 明细行是可点按钮:`devRowN`(信息)+ `devUnbindN`(右侧「解绑」),点击 → `UnbindDeviceIdx(N+1)`
- **序号输入框已整块拿掉**(`devIdx` / `btnUnbind` 在 XML 里 `visible="false"` 兜底保留,代码不再走输入路径)
- 空列表(服务端没返回明细)时只给「重试」,不会默认解绑任何一台
---
## 2. 卡密用户的「我的设备」
同一套面板复用(`g_devManage=1`):卡密就是身份,不需要先登录。
- 列表来源:`POST /api/v1/app/:appKey/card-devices` `{card_key}`
- 解绑:`POST /api/v1/app/:appKey/card-unbind` `{card_key,device_id}`
- 面板里多一个「卡密」输入框(`devCardKey`),未填时提示「先在『登录』里填入卡密,再点这里的『我的设备』」
---
## 3. Android 壳的界面(`shell_smali.tgz`)
没有 XML 布局、没有皮肤,是运行时拼的原生 `AlertDialog`:
```
┌────────────────────────────────────┐
│ <应用名>(cfg.name,缺省「验证」) │
│ 请输入账号或卡密完成验证 │
│ ┌────────────────────────────────┐ │
│ │ 账号或卡密 │ │
│ └────────────────────────────────┘ │
│ ┌────────────────────────────────┐ │
│ │ 密码(留空则用内置) │ │
│ └────────────────────────────────┘ │
│ 通过后自动进入应用 │
│ 验证 退出 │
└────────────────────────────────────┘
```
- 填了密码 → 覆盖 cfg 里的 `password`(`cfg.put("password", ...)`)后调 `verify()`
- 「退出」= `Activity.finish()` + `Process.killProcess(myPid())`
- 设备超限文案:`设备数超限,请先在平台解绑一台设备`
- 设备标识:`ANDROID-` + Android ID
- **手机端没有设备列表/自助解绑页**(只有这一道登录闸),要补就照桌面端的接口接 `/card-devices` + `/card-unbind`
改了 smali 先离线校验语法:
```bash
cd <解开 shell_smali.tgz 的目录>
smali assemble vfy -o /tmp/vfy.dex # 能出 dex 就说明语法与引用都对得上
tar czf shell_smali.tgz vfy # 结构必须是 vfy/*.smali
```
---
## 4. 验收方法(可复现)
需要:`Xvfb :99` + `openbox` + wine + 一个 mock 验证服务端。
```bash
# 1) mock 服务端:/login 一律回 403 DEVICE_LIMIT(3 台/上限 2),其它接口回成功
python3 scripts/mock-vfy-device-limit.py & # 监听 127.0.0.1:9998
# 2) 打一个 dark 主题的壳产物(api 必须是完整的 login URL)
cat > /tmp/cfg.json <<'JSON'
{"api":"http://127.0.0.1:9998/api/v1/app/dogtest/login","name":"dogtest","device_auto":1,"shell_ver":8,"theme":"dark","ver":"1.0.0"}
JSON
go build -o /tmp/packthemed ./cmd/packthemed # 改过 assets 必须重编!
/tmp/packthemed sample.exe /tmp/out.exe /tmp/cfg.json dark
# 3) 跑起来看
DISPLAY=:99 wine /tmp/out.exe
```
验收清单(每项都要肉眼/日志对得上):
- [ ] 单层产物启动 → 登录页(exit=124 = GUI 在等网络)
- [ ] 输入账号+密码点登录 → 服务端收到 login,含 `device_id/device_name/device_type/instance_id`
- [ ] 被 403 拦下 → **窗口放大、标题变「设备管理 - 应用名」、tab 消失、每行右侧有「解绑」**
- [ ] 列表在线状态与 mock 的 `online_count` 一致(● 在线 / ○ 离线)
- [ ] 点**第 2 行**「解绑」→ 服务端收到 `unbind-device-with-auth`,`device_id` = 第 2 台(不是最早那台)
- [ ] 解绑后自动重试登录
- [ ] 点「返回」→ 标题复原、tab 回来、窗口缩回登录尺寸
- [ ] 无「下线/踢线」按钮(当前设计不含该能力)
---
## 5. 踩过的坑(每条都真踩过)
1. **`cmd/packthemed` 是 `//go:embed` 内嵌壳资产的**:改完 `assets/*.bin` 不重编它,打出来的产物还是旧壳。
症状:改了半天什么都没变,字节数一模一样。规矩:**改资产 → `go build ./cmd/packthemed`**。
2. **wine 下 DuiLib 原生 EDIT 点击不转移焦点**:点一下只是激活窗口,输入会打到上一个输入框。
规矩:**同一点位点两次**(第一次激活、第二次聚焦)再输入。
3. **`devBody` 那个多行 Label 的字色在重编产物里压不住**:XML `textcolor`、运行时 `SetTextColor`、`SetAttribute("textcolor")` 都不行;`CListLabelElementUI` 连 `SetTextColor` 都没有;`CButtonUI::SetAttribute` 只吃 `hot/pushed/focusedtextcolor`。
最终解法:设备行做成**按钮**(信息按钮 + 解绑按钮),跟「重试/返回」同一套渲染 → 亮度和它们一致。
4. **`m_pm.SetSize` 不存在**(`CPaintManagerUI` 只有 `SetSizeBox`):窗口尺寸直接 `SetWindowPos`,DuiLib 会在 `WM_SIZE` 里自己重排。
5. **残留 wine 进程会叠窗污染截图**:脚本开头要 `wineserver -k9` + 杀光 `*.exe`,否则截到的是上一轮的窗口。
6. **`pkill -9 -f "themed/"` 会把自己杀掉**(命令行里含 `packthemed` 字样):模式写成 `wine.*themed/dev`。
7. **面板高度改大不能只改 XML**:`panelDevice` 用 `height="-1"` 跟随窗口,否则登录页会被撑出一个空面板。
8. 皮肤里只有 3 套有「软件授权验证」标题 Label(已命名 `lblTitle` 支持动态改),其余 4 套是 `VFY` 品牌栏设计,标题不随页切换属预期。
---
## 6. 已知未做
- 手机端的设备列表 / 自助解绑页(桌面端已有)
- 「下线(踢线)」按钮 —— 按需求方口径**不做**,有解绑即可
- 设备管理页在多语言 skin(industrial/terminal)里标题仍是各自品牌词,未做本地化
+28
View File
@@ -0,0 +1,28 @@
# 皮肤选择卡片的预览图是怎么来的
面板「云端加密 → 验证界面」里 8 张预览图是**真机截图**,不是设计稿:
```
frontend/public/theme-previews/{classic,dark,light,industrial,compact,split,card,terminal}.png
```
统一 560×420(4:3),窗口居中、去掉黑边,单张 14–33KB,合计约 190KB。构建时由 Vite 原样拷进 `dist/theme-previews/`,页面里按 `/theme-previews/<theme>.png` 引用。
## 重新生成(换皮肤/改布局后要重跑)
1. **打 8 个样本**:`packthemed origin64.exe themed/prev_<theme>.exe cfg_prev_<theme>.json <theme>`
- `cfg_prev_<theme>.json` 里的 `name` 用中性值(例如「示例软件」),不要留测试名
- **`cfg` 里的 `theme` 必须和该主题一致**:`PatchSignedThemed` 只按第四个参数挑要嵌的 shell DLL,不会改写 cfg;cfg 里写错皮肤名,8 个产物会渲染成同一套
2. **截图**:`/root/work/shot64.sh prev_classic prev_dark …`
- `Xvfb :99` + `openbox` + `scrot`
- **必须用独立的 64 位 prefix**(`WINEPREFIX=/root/.wine64 WINEARCH=win64`):装了 `wine32:i386` 之后默认 prefix 会报 `could not load kernel32.dll`
- 每轮开始前 `wineserver -k` 并等到可见窗口数归零,否则会截到上一套皮肤的窗口
3. **裁边 + 统一尺寸**:`python3 /root/work/mktheme_previews.py`
- 不依赖 PIL:用 `ffmpeg -f rawvideo -pix_fmt rgb24` 取出像素
- 窗口边界用**逐列/逐行亮像素密度**判定(阈值 + 最小像素数),避免桌面上的零星亮像素把边界撑大导致缩略图偏心
- `scale=W:H:force_original_aspect_ratio=decrease` 后再 `pad`,保证任何宽高比的窗口都不变形
4. **重新构建前端**:`npm run build`,否则页面拿到的还是旧的 `dist/theme-previews/`
## 位宽徽标
卡片右上角的徽标由 `themeBits()` 决定:`classic` 显示「32/64 位」,其余 7 套显示「64 位」—— 因为 DuiLib 皮肤只做了 64 位构建,32 位程序加壳时服务端会自动回落到经典壳。
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

+203
View File
@@ -0,0 +1,203 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { Maximize2, Minus, Plus, RotateCcw, X } from "lucide-vue-next";
const props = defineProps<{
open: boolean;
src: string;
title?: string;
}>();
const emit = defineEmits<{ (e: "update:open", v: boolean): void }>();
const MIN = 1;
const MAX = 6;
const STEP = 1.25;
const scale = ref(1);
const tx = ref(0);
const ty = ref(0);
const dragging = ref(false);
let startX = 0;
let startY = 0;
let baseTx = 0;
let baseTy = 0;
const zoomLabel = computed(() => `${Math.round(scale.value * 100)}%`);
const canPan = computed(() => scale.value > 1);
function close() {
emit("update:open", false);
}
function reset() {
scale.value = 1;
tx.value = 0;
ty.value = 0;
}
function clampScale(v: number) {
return Math.min(MAX, Math.max(MIN, v));
}
function applyScale(next: number) {
scale.value = clampScale(next);
if (scale.value === 1) {
tx.value = 0;
ty.value = 0;
}
}
function zoomIn() {
applyScale(scale.value * STEP);
}
function zoomOut() {
applyScale(scale.value / STEP);
}
function onWheel(e: WheelEvent) {
e.preventDefault();
// 以图片中心为锚点缩放,简单可靠;指针不在中心时也能接受
applyScale(scale.value * (e.deltaY < 0 ? 1.12 : 1 / 1.12));
}
function onPointerDown(e: MouseEvent) {
if (!canPan.value) return;
dragging.value = true;
startX = e.clientX;
startY = e.clientY;
baseTx = tx.value;
baseTy = ty.value;
}
function onPointerMove(e: MouseEvent) {
if (!dragging.value) return;
tx.value = baseTx + (e.clientX - startX);
ty.value = baseTy + (e.clientY - startY);
}
function onPointerUp() {
dragging.value = false;
}
function onKeydown(e: KeyboardEvent) {
if (!props.open) return;
if (e.key === "Escape") close();
else if (e.key === "+" || e.key === "=") zoomIn();
else if (e.key === "-") zoomOut();
else if (e.key === "0") reset();
}
watch(
() => props.open,
(v) => {
if (v) {
reset();
document.body.style.overflow = "hidden";
} else {
document.body.style.overflow = "";
dragging.value = false;
}
},
);
onMounted(() => window.addEventListener("keydown", onKeydown));
onBeforeUnmount(() => {
window.removeEventListener("keydown", onKeydown);
document.body.style.overflow = "";
});
</script>
<template>
<Teleport to="body">
<Transition
enter-active-class="transition duration-150 ease-out"
enter-from-class="opacity-0"
leave-active-class="transition duration-100 ease-in"
leave-to-class="opacity-0"
>
<div
v-if="open"
class="fixed inset-0 z-[200] flex flex-col bg-black/92 backdrop-blur-sm select-none"
@click.self="close"
@mousemove="onPointerMove"
@mouseup="onPointerUp"
@mouseleave="onPointerUp"
>
<!-- 顶部工具栏 -->
<div
class="flex shrink-0 items-center justify-between gap-3 px-4 py-3 text-white/90"
>
<div class="flex min-w-0 items-center gap-3">
<Maximize2 class="size-4 shrink-0 text-white/50" />
<span class="truncate text-sm font-medium">{{
title || "预览"
}}</span>
</div>
<div class="flex items-center gap-1">
<button
type="button"
class="flex size-8 items-center justify-center rounded-md text-white/70 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-35"
:disabled="scale <= MIN"
title="缩小(-)"
@click="zoomOut"
>
<Minus class="size-4" />
</button>
<span class="w-12 text-center text-xs tabular-nums text-white/60">{{
zoomLabel
}}</span>
<button
type="button"
class="flex size-8 items-center justify-center rounded-md text-white/70 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-35"
:disabled="scale >= MAX"
title="放大(+)"
@click="zoomIn"
>
<Plus class="size-4" />
</button>
<button
type="button"
class="flex size-8 items-center justify-center rounded-md text-white/70 transition-colors hover:bg-white/10 hover:text-white"
title="还原(0)"
@click="reset"
>
<RotateCcw class="size-4" />
</button>
<div class="mx-1 h-5 w-px bg-white/15" />
<button
type="button"
class="flex size-8 items-center justify-center rounded-md text-white/70 transition-colors hover:bg-white/10 hover:text-white"
title="关闭(Esc)"
@click="close"
>
<X class="size-4" />
</button>
</div>
</div>
<!-- 图片区 -->
<div
class="relative min-h-0 flex-1 overflow-hidden"
@click.self="close"
>
<img
:src="src"
:alt="title"
class="absolute top-1/2 left-1/2 max-h-full max-w-full origin-center object-contain transition-transform duration-75"
:class="
canPan
? dragging
? 'cursor-grabbing'
: 'cursor-grab'
: 'cursor-zoom-in'
"
:style="{
transform: `translate(-50%, -50%) translate(${tx}px, ${ty}px) scale(${scale})`,
}"
draggable="false"
@wheel.prevent="onWheel"
@mousedown.prevent="onPointerDown"
@dblclick="scale > 1 ? reset() : zoomIn()"
/>
</div>
<!-- 底部提示 -->
<div class="shrink-0 pb-3 text-center text-[11px] text-white/40">
滚轮缩放 · 放大后拖动平移 · 双击切换 · Esc 关闭
</div>
</div>
</Transition>
</Teleport>
</template>
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { Info, Loader2, Upload, X } from 'lucide-vue-next'
import { onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { toast } from 'vue-sonner'
@@ -32,6 +32,8 @@ interface AppData {
billing_type: string
login_policy: string
login_mode: string
login_mode_enforce: string
login_mode_grace_days: number
card_login_bind_device: boolean
card_login_allow_password: boolean
allow_register: boolean
@@ -55,6 +57,49 @@ interface AppData {
}
const app = ref<AppData | null>(null)
const impact = ref<{
total_subjects: number
only_card_subjects: number
only_account_subjects: number
blocking: boolean
} | null>(null)
const enforceOptions = [
{ value: 'off', title: '关闭校验', desc: '不按登录方式拦人,与升级前行为一致' },
{ value: 'warn', title: '仅记录', desc: '只写审计日志不拦截,用来观察会挡到谁' },
{ value: 'strict', title: '已生效', desc: '真正拦截;宽限期内旧方式仍放行并提示' },
]
// 切到当前选中的模式,会被挡住的主体数
const selectedBlocked = computed(() => {
if (!impact.value)
return 0
if (form.value.login_mode === 'account')
return impact.value.only_card_subjects
if (form.value.login_mode === 'card')
return impact.value.only_account_subjects
return 0
})
function modeLabel(mode: string) {
return mode === 'account' ? '账号密码' : mode === 'card' ? '卡密直登' : '两者都开'
}
async function fetchImpact() {
try {
const token = localStorage.getItem('token')
const res = await fetch(`${API_BASE}/dev/applications/${route.params.id}/login-mode-impact`, {
headers: { Authorization: `Bearer ${token}` },
})
const data = await res.json()
if (data.code === 200)
impact.value = data.data
}
catch (error) {
console.error('获取登录方式影响面失败:', error)
}
}
const emailConfigs = ref<EmailConfig[]>([])
const smsConfigs = ref<SmsConfig[]>([])
@@ -66,7 +111,9 @@ const form = ref({
iconPreview: '',
billing_type: 'free',
login_policy: 'loose',
login_mode: 'account',
login_mode: 'both',
login_mode_enforce: 'warn',
login_mode_grace_days: 7,
card_login_bind_device: true,
card_login_allow_password: false,
allow_register: true,
@@ -194,7 +241,9 @@ async function fetchApp() {
iconPreview: getIconUrl(appData.icon_url),
billing_type: appData.billing_type || 'free',
login_policy: appData.login_policy || 'loose',
login_mode: appData.login_mode || 'account',
login_mode: appData.login_mode || 'both',
login_mode_enforce: appData.login_mode_enforce || 'warn',
login_mode_grace_days: appData.login_mode_grace_days ?? 7,
card_login_bind_device: appData.card_login_bind_device !== false,
card_login_allow_password: appData.card_login_allow_password === true,
allow_register: appData.allow_register ?? true,
@@ -245,6 +294,8 @@ async function handleSave() {
formDataToSend.append('billing_type', form.value.billing_type)
formDataToSend.append('login_policy', form.value.login_policy)
formDataToSend.append('login_mode', form.value.login_mode)
formDataToSend.append('login_mode_enforce', form.value.login_mode_enforce)
formDataToSend.append('login_mode_grace_days', String(form.value.login_mode_grace_days ?? 7))
formDataToSend.append('card_login_bind_device', form.value.card_login_bind_device.toString())
formDataToSend.append('card_login_allow_password', form.value.card_login_allow_password.toString())
formDataToSend.append('allow_register', form.value.allow_register.toString())
@@ -307,6 +358,12 @@ onMounted(() => {
fetchApp()
fetchEmailConfigs()
fetchSmsConfigs()
fetchImpact()
})
// 换登录方式时重新算一遍影响面,切换前就能看到会挡住多少人
watch(() => form.value.login_mode, () => {
fetchImpact()
})
function toggleWeekday(index: number) {
@@ -719,6 +776,53 @@ function toggleWeekday(index: number) {
<UiSwitch v-model="form.card_login_allow_password" />
</div>
</div>
<!-- 生效方式:开关只是配置,这里决定它是不是真的拦人 -->
<div class="space-y-3 pt-2 border-t">
<div>
<p class="font-medium">生效方式</p>
<p class="text-sm text-muted-foreground">
配置改了要经过这一步才真正生效。建议先「仅记录」,看几天日志确认拦的都是该拦的,再切「已生效」。
</p>
</div>
<UiRadioGroup v-model="form.login_mode_enforce" class="grid grid-cols-1 md:grid-cols-3 gap-3">
<div
v-for="opt in enforceOptions"
:key="opt.value"
class="flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors"
:class="form.login_mode_enforce === opt.value ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
@click="form.login_mode_enforce = opt.value"
>
<UiRadioGroupItem :value="opt.value" class="mt-0.5" />
<div>
<p class="font-medium">{{ opt.title }}</p>
<p class="text-sm text-muted-foreground">{{ opt.desc }}</p>
</div>
</div>
</UiRadioGroup>
<div class="flex items-center justify-between gap-4">
<div>
<p class="font-medium">切换后的宽限期(天)</p>
<p class="text-sm text-muted-foreground">
宽限期内旧登录方式仍可用,客户端会提示「X 天后停用」,避免存量用户被一刀切挡在门外。填 0 = 立即生效
</p>
</div>
<UiInput v-model.number="form.login_mode_grace_days" type="number" min="0" max="365" class="w-24" />
</div>
<div v-if="impact && selectedBlocked > 0" class="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 space-y-1">
<p class="font-medium text-amber-600 dark:text-amber-400">
切到「{{ modeLabel(form.login_mode) }}」后,约 {{ selectedBlocked }} 个现存在册主体将无法登录
</p>
<p class="text-sm text-muted-foreground">
共 {{ impact.total_subjects }} 个主体:仅能卡密登录 {{ impact.only_card_subjects }} 个,仅能账号登录 {{ impact.only_account_subjects }} 个。
建议先开宽限期,或用「卡密换密码 / 签发登录卡」的迁移通道给他们换钥匙。
</p>
</div>
<div v-else-if="impact" class="rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground">
当前 {{ impact.total_subjects }} 个主体:仅卡密登录 {{ impact.only_card_subjects }} 个,仅账号登录 {{ impact.only_account_subjects }} 个 ——
切到「{{ modeLabel(form.login_mode) }}」不会挡住任何人。
</div>
</div>
</UiCardContent>
</UiCard>
@@ -26,7 +26,6 @@ const form = ref({
application_id: '',
price: 0,
recharge_type: 'balance' as 'balance' | 'subscription',
purpose: 'recharge' as 'recharge' | 'credential',
value: 1,
value_unit: 'day' as 'day' | 'month' | 'year',
is_permanent: false,
@@ -42,12 +41,6 @@ async function fetchApplications() {
}
}
// 卡型用途:充值卡给主体加额度;登录卡是一张能登录的钥匙(首次登录激活成主体)
const purposeOptions = [
{ value: 'recharge', label: '充值卡', desc: '给账号或卡密主体加余额/加时长' },
{ value: 'credential', label: '登录卡', desc: '一张卡就是一个用户,输入卡密即可登录' },
]
const selectedApplication = computed(() => {
if (form.value.application_id) {
return applications.value.find(app => String(app.id) === form.value.application_id)
@@ -106,7 +99,6 @@ async function handleCreate() {
name: form.value.name,
description: form.value.description,
recharge_type: form.value.recharge_type,
purpose: form.value.purpose,
value: form.value.is_permanent ? -1 : form.value.value,
value_unit: form.value.recharge_type === 'subscription' ? form.value.value_unit : '',
price: form.value.price,
@@ -191,29 +183,6 @@ onMounted(() => {
<UiCardDescription>{{ t('admin.cardTypes.create.rechargeConfigDesc') }}</UiCardDescription>
</UiCardHeader>
<UiCardContent class="space-y-6">
<div class="space-y-2">
<UiLabel>卡型用途</UiLabel>
<UiRadioGroup v-model="form.purpose" class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div
v-for="opt in purposeOptions"
:key="opt.value"
class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
:class="form.purpose === opt.value ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
@click="form.purpose = opt.value as 'recharge' | 'credential'"
>
<UiRadioGroupItem :value="opt.value" class="mt-0.5" />
<div>
<p class="font-medium">{{ opt.label }}</p>
<p class="text-sm text-muted-foreground">{{ opt.desc }}</p>
</div>
</div>
</UiRadioGroup>
<p class="text-xs text-muted-foreground">
登录卡的卡密本身就是一把钥匙:用户第一次用它登录时会自动激活成一个用户主体,
之后这张卡的余额、到期时间、设备都跟着这个主体走。
</p>
</div>
<div class="space-y-2">
<UiLabel>{{ t('admin.cardTypes.create.rechargeType') }}</UiLabel>
<UiRadioGroup v-model="form.recharge_type" class="grid grid-cols-1 md:grid-cols-2 gap-4">
@@ -36,16 +36,6 @@ export function getColumns(actions: {
])
},
},
{
accessorKey: 'purpose',
header: () => '用途',
cell: ({ row }) => {
const purpose = row.getValue('purpose') as string
const isCard = purpose === 'credential'
return h(Badge, { variant: isCard ? 'default' : 'secondary' },
() => (isCard ? '登录卡' : '充值卡'))
},
},
{
accessorKey: 'application.name',
header: () => t('admin.cards.columns.application'),
@@ -196,14 +186,14 @@ export function getColumns(actions: {
isBanned ? t('admin.cards.enable') : t('admin.cards.disable'),
]),
h(DropdownMenuSeparator),
// 只有登录卡能补发:换一把钥匙,主体/余额/设备都不动
card.purpose === 'credential' && actions.onReissue
// 只有已激活(绑了主体)的卡才补发:换一把钥匙,主体/余额/设备都不动
card.subject_id && actions.onReissue
? h(DropdownMenuItem, { onClick: () => actions.onReissue!(card) }, () => [
h(KeyRound, { class: 'mr-2 h-4 w-4' }),
'作废并补发新卡密',
])
: null,
card.purpose === 'credential' && actions.onReissue ? h(DropdownMenuSeparator) : null,
card.subject_id && actions.onReissue ? h(DropdownMenuSeparator) : null,
h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onDelete(card) }, () => [
h(Trash2, { class: 'mr-2 h-4 w-4' }),
t('admin.cards.delete'),
@@ -59,7 +59,6 @@ const columnLabels: Record<string, string> = {
card_type_price: 'admin.cards.columns.faceValue',
card_type_value: 'admin.cards.columns.duration',
status: 'admin.cards.columns.status',
purpose: '用途',
app_user_username: 'admin.cards.columns.usedUser',
used_at: 'admin.cards.columns.usedTime',
creator_username: 'admin.cards.columns.creator',
+11 -10
View File
@@ -167,8 +167,9 @@ async function toggleStatus(card: Card) {
// 作废并补发:卡密泄露时换一把钥匙,主体、余额、到期、设备全保留
async function reissueCard(row: Card) {
if (row.purpose !== 'credential') {
toast.warning('只有登录卡需要补发,充值卡直接作废即可')
// 换钥匙只对「已经激活、绑了主体」的卡有意义:没激活的卡直接作废就行
if (!row.subject_id) {
toast.warning('这张卡还没有被激活,直接作废就行')
return
}
const ok = window.confirm(`作废卡密「${row.card_key}」并补发一张新的?\n用户的主体、余额、到期时间、已绑设备都不会变,只是换了一把钥匙。`)
@@ -185,7 +186,7 @@ async function reissueCard(row: Card) {
}
}
// 卡密安全概览:登录卡/充值卡分布 + 24 小时内的卡密登录失败次数(爆破迹象)
// 卡密安全概览:按状态与「是否已激活」分布 + 24 小时内的卡密登录失败次数(爆破迹象)
const secStats = ref<any>(null)
async function fetchSecurity() {
try {
@@ -327,19 +328,19 @@ const serverPagination = computed(() => ({
</template>
<div class="space-y-6">
<!-- 卡密安全概览:登录卡与充值卡分开看,失败次数突增就是有人在刷卡密 -->
<!-- 卡密安全概览:按「是否已激活成主体」看,失败次数突增就是有人在刷卡密 -->
<div v-if="secStats" class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<div class="rounded-lg border p-3">
<p class="text-xs text-muted-foreground">登录卡(已激活 / 总数)</p>
<p class="text-xl font-semibold">{{ secStats.credential_used }} / {{ secStats.credential_total }}</p>
<p class="text-xs text-muted-foreground">已激活(有主体的卡 / 总数)</p>
<p class="text-xl font-semibold">{{ secStats.activated }} / {{ secStats.total }}</p>
</div>
<div class="rounded-lg border p-3">
<p class="text-xs text-muted-foreground">已作废登录卡</p>
<p class="text-xl font-semibold">{{ secStats.credential_void }}</p>
<p class="text-xs text-muted-foreground">未使用</p>
<p class="text-xl font-semibold">{{ secStats.unused }}</p>
</div>
<div class="rounded-lg border p-3">
<p class="text-xs text-muted-foreground">充值卡总数</p>
<p class="text-xl font-semibold">{{ secStats.recharge_total }}</p>
<p class="text-xs text-muted-foreground">已作废</p>
<p class="text-xl font-semibold">{{ secStats.void }}</p>
</div>
<div class="rounded-lg border p-3">
<p class="text-xs text-muted-foreground">24 小时卡密登录失败</p>
+98 -173
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ArrowDownLeft, ArrowUpRight, CreditCard, DollarSign, Inbox, Loader2, Trash2, TrendingUp } from 'lucide-vue-next'
import { ArrowDownLeft, ArrowUpRight, CreditCard, DollarSign, Download, Inbox, Loader2, TrendingUp } from 'lucide-vue-next'
import type {
ColumnDef,
ColumnFiltersState,
@@ -20,6 +20,7 @@ import { useI18n } from 'vue-i18n'
import { toast } from 'vue-sonner'
import ConfirmDialog from '@/components/confirm-dialog.vue'
import type { ServerPagination } from '@/components/data-table/types'
import DataTablePagination from '@/components/data-table/table-pagination.vue'
import { BasicPage } from '@/components/global-layout'
import { Badge } from '@/components/ui/badge'
@@ -35,7 +36,7 @@ import {
TableRow,
} from '@/components/ui/table'
import { valueUpdater } from '@/lib/utils'
import api from '@/services/api'
import api, { BASE_URL } from '@/services/api'
interface Application {
id: number
@@ -66,6 +67,18 @@ const loading = ref(true)
const records = ref<FinanceRecord[]>([])
const applications = ref<Application[]>([])
// 服务端分页 + 服务端汇总:records 只是当前页,卡片数字用后端算好的 summary
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const summary = ref({
recharge_amount: 0,
recharge_count: 0,
consumption_amount: 0,
consumption_count: 0,
profit: 0,
})
const appFilter = ref<string>('all')
const statusFilter = ref<string>('all')
const dateRange = ref<{ from: string, to: string }>({ from: '', to: '' })
@@ -93,48 +106,17 @@ function setQuickRange(range: 'today' | 'week' | 'month') {
}
}
const filteredRecords = computed(() => {
let result = records.value
// 筛选条件全部交给后端(客户端只有当前页,过滤等于筛一小撮数据)
const filteredRecords = computed(() => records.value)
if (appFilter.value !== 'all') {
result = result.filter(r => r.app_id === Number(appFilter.value))
}
if (statusFilter.value !== 'all') {
result = result.filter(r => r.status === statusFilter.value)
}
if (dateRange.value.from) {
const fromDateTime = dateRange.value.from.includes('T')
? dateRange.value.from.replace('T', ' ')
: `${dateRange.value.from} 00:00`
result = result.filter(r => r.created_at >= fromDateTime)
}
if (dateRange.value.to) {
const toDateTime = dateRange.value.to.includes('T')
? dateRange.value.to.replace('T', ' ')
: `${dateRange.value.to} 23:59`
result = result.filter(r => r.created_at <= toDateTime)
}
return result
})
const stats = computed(() => {
const rechargeRecords = filteredRecords.value.filter(r => r.type === 'recharge' && r.status === 'success')
const consumptionRecords = filteredRecords.value.filter(r => r.type === 'consumption' && r.status === 'success')
const totalRecharge = rechargeRecords.reduce((sum, r) => sum + r.amount, 0)
const totalConsumption = consumptionRecords.reduce((sum, r) => sum + r.amount, 0)
return {
rechargeCount: rechargeRecords.length,
rechargeAmount: totalRecharge,
consumptionCount: consumptionRecords.length,
consumptionAmount: totalConsumption,
profit: totalRecharge - totalConsumption,
}
})
// 卡片数字直接取后端的全量聚合(带上当前所有筛选条件),不再 reduce 当前页
const stats = computed(() => ({
rechargeCount: summary.value.recharge_count,
rechargeAmount: summary.value.recharge_amount,
consumptionCount: summary.value.consumption_count,
consumptionAmount: summary.value.consumption_amount,
profit: summary.value.profit,
}))
function formatTime(time: string) {
if (!time)
@@ -157,50 +139,49 @@ function formatTime(time: string) {
const sorting = ref<SortingState>([])
const columnFilters = ref<ColumnFiltersState>([])
const columnVisibility = ref<VisibilityState>({})
const rowSelection = ref({})
const deleteDialogOpen = ref(false)
const deleteTarget = ref<FinanceRecord | null>(null)
const batchDeleteDialogOpen = ref(false)
async function confirmDelete(record: FinanceRecord) {
deleteTarget.value = record
deleteDialogOpen.value = true
async function fetchApplications() {
try {
const data = await api.get<{ applications: Application[] }>('/dev/applications')
applications.value = data?.applications || []
}
catch (error) {
console.error('获取应用列表失败:', error)
}
}
async function handleDelete() {
if (!deleteTarget.value)
return
async function fetchRecords() {
loading.value = true
try {
await api.delete(`/dev/finance/records/${deleteTarget.value.id}?type=${deleteTarget.value.type}`)
toast.success(t('admin.finance.deleteSuccess'))
fetchRecords()
const params = new URLSearchParams()
params.append('page', String(currentPage.value))
params.append('page_size', String(pageSize.value))
if (appFilter.value !== 'all')
params.append('application_id', appFilter.value)
if (statusFilter.value !== 'all')
params.append('status', statusFilter.value)
if (dateRange.value.from)
params.append('start_date', dateRange.value.from.split('T')[0])
if (dateRange.value.to)
params.append('end_date', dateRange.value.to.split('T')[0])
const data = await api.get<{ records: FinanceRecord[], total: number, summary?: typeof summary.value }>(
`/dev/finance/records?${params.toString()}`,
)
records.value = data?.records || []
total.value = data?.total || 0
if (data?.summary)
summary.value = data.summary
}
catch (error: any) {
toast.error(error.message || t('admin.finance.deleteFailed'))
catch (error) {
console.error('获取财务记录失败:', error)
}
finally {
deleteTarget.value = null
loading.value = false
}
}
const columns: ColumnDef<FinanceRecord>[] = [
{
id: 'select',
header: ({ table }) => h(Checkbox, {
'checked': table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && 'indeterminate'),
'onUpdate:checked': (value: boolean | 'indeterminate') => table.toggleAllPageRowsSelected(!!value),
'ariaLabel': 'Select all',
}),
cell: ({ row }) => h(Checkbox, {
'checked': row.getIsSelected(),
'onUpdate:checked': (value: boolean | 'indeterminate') => row.toggleSelected(!!value),
'ariaLabel': 'Select row',
}),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: 'type',
header: () => t('admin.finance.columns.type'),
@@ -256,18 +237,6 @@ const columns: ColumnDef<FinanceRecord>[] = [
return h('span', { class: 'text-muted-foreground whitespace-nowrap' }, formatTime(row.getValue('created_at')))
},
},
{
id: 'actions',
header: () => t('admin.finance.columns.actions'),
cell: ({ row }) => {
return h(Button, {
variant: 'ghost',
size: 'sm',
class: 'h-8 w-8 p-0',
onClick: () => confirmDelete(row.original),
}, () => h(Trash2, { class: 'size-4 text-muted-foreground hover:text-destructive' }))
},
},
]
const table = useVueTable({
@@ -277,64 +246,50 @@ const table = useVueTable({
get sorting() { return sorting.value },
get columnFilters() { return columnFilters.value },
get columnVisibility() { return columnVisibility.value },
get rowSelection() { return rowSelection.value },
},
enableRowSelection: true,
onSortingChange: updaterOrValue => valueUpdater(updaterOrValue, sorting),
onColumnFiltersChange: updaterOrValue => valueUpdater(updaterOrValue, columnFilters),
onColumnVisibilityChange: updaterOrValue => valueUpdater(updaterOrValue, columnVisibility),
onRowSelectionChange: updaterOrValue => valueUpdater(updaterOrValue, rowSelection),
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
manualPagination: true,
get pageCount() { return Math.ceil(total.value / pageSize.value) || 1 },
})
async function confirmBatchDelete() {
const selectedRows = table.getSelectedRowModel().rows
if (selectedRows.length === 0) {
toast.error(t('admin.finance.delete'))
return
}
batchDeleteDialogOpen.value = true
// 导出当前筛选结果(财务流水不支持删除,清理/对账一律走导出)
function handleExport() {
const token = localStorage.getItem('token')
const params = new URLSearchParams()
if (appFilter.value !== 'all')
params.append('application_id', appFilter.value)
if (statusFilter.value !== 'all')
params.append('status', statusFilter.value)
if (dateRange.value.from)
params.append('start_date', dateRange.value.from.split('T')[0])
if (dateRange.value.to)
params.append('end_date', dateRange.value.to.split('T')[0])
window.open(`${BASE_URL}/dev/finance/export?${params.toString()}&token=${token}`, '_blank')
}
async function handleBatchDelete() {
const selectedRows = table.getSelectedRowModel().rows
const ids = selectedRows.map(row => row.original.id)
try {
await api.post('/dev/finance/records/batch-delete', { ids })
toast.success(t('admin.finance.deleteSuccess'))
const serverPagination = computed<ServerPagination>(() => ({
page: currentPage.value,
pageSize: pageSize.value,
total: total.value,
onPageChange: (page: number) => {
currentPage.value = page
fetchRecords()
}
catch (error: any) {
toast.error(error.message || t('admin.finance.deleteFailed'))
}
}
},
onPageSizeChange: (size: number) => {
pageSize.value = size
currentPage.value = 1
fetchRecords()
},
}))
async function fetchApplications() {
try {
const data = await api.get<{ applications: Application[] }>('/dev/applications')
applications.value = data?.applications || []
}
catch (error) {
console.error('获取应用列表失败:', error)
}
}
async function fetchRecords() {
loading.value = true
try {
const data = await api.get<{ records: FinanceRecord[] }>('/dev/finance/records')
records.value = data?.records || []
}
catch (error) {
console.error('获取财务记录失败:', error)
}
finally {
loading.value = false
}
}
watch([appFilter, statusFilter, dateRange], () => {
currentPage.value = 1
fetchRecords()
}, { deep: true })
onMounted(() => {
fetchApplications()
@@ -431,14 +386,9 @@ onMounted(() => {
<UiCardContent>
<div class="space-y-3 mb-4">
<div class="flex items-center justify-end">
<UiButton
v-if="table.getSelectedRowModel().rows.length > 0"
variant="destructive"
size="sm"
@click="confirmBatchDelete"
>
<Trash2 class="mr-2 size-4" />
{{ t('admin.finance.batchDeleteBtn') }}
<UiButton variant="outline" size="sm" :disabled="loading" @click="handleExport">
<Download class="mr-2 size-4" />
{{ t('admin.finance.exportBtn') }}
</UiButton>
</div>
<div class="flex flex-wrap items-center justify-between gap-2">
@@ -542,39 +492,14 @@ onMounted(() => {
</Table>
</div>
<DataTablePagination v-if="!loading && table.getRowModel().rows?.length" :table="table" class="mt-4" />
<DataTablePagination
v-if="!loading && table.getRowModel().rows?.length"
:table="table"
:server-pagination="serverPagination"
class="mt-4"
/>
</UiCardContent>
</UiCard>
</div>
</BasicPage>
<ConfirmDialog
v-model:open="deleteDialogOpen"
destructive
:confirm-button-text="t('admin.finance.delete')"
:cancel-button-text="t('admin.finance.cancel')"
@confirm="handleDelete"
>
<template #title>
{{ t('admin.finance.delete') }}
</template>
<template #description>
{{ t('admin.finance.deleteConfirm') }}
</template>
</ConfirmDialog>
<ConfirmDialog
v-model:open="batchDeleteDialogOpen"
destructive
:confirm-button-text="t('admin.finance.delete')"
:cancel-button-text="t('admin.finance.cancel')"
@confirm="handleBatchDelete"
>
<template #title>
{{ t('admin.finance.batchDeleteBtn') }}
</template>
<template #description>
{{ t('admin.finance.batchDeleteConfirm', { count: table.getSelectedRowModel().rows.length }) }}
</template>
</ConfirmDialog>
</template>
-224
View File
@@ -1,224 +0,0 @@
<script setup lang="ts">
import { Activity, CheckCircle, FileText, XCircle } from 'lucide-vue-next'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { Log } from '@/pages/admin/logs/data/schema'
import DateRangeFilter from '@/components/data-table/date-range-filter.vue'
import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/admin/logs/components/data-table.vue'
import api from '@/services/api'
const { t } = useI18n()
interface Application {
id: number
name: string
}
const loading = ref(true)
const logs = ref<Log[]>([])
const applications = ref<Application[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const successCount = ref(0)
const failedCount = ref(0)
const operationCount = ref(0)
const appFilter = ref<string>('')
const typeFilter = ref<string>('')
const statusFilter = ref<string>('')
const startDate = ref<string>('')
const endDate = ref<string>('')
const applicationOptions = computed(() => {
return applications.value.map(app => ({
label: app.name,
value: String(app.id),
}))
})
const typeOptions = computed(() => [
{ label: t('admin.logs.types.operation'), value: 'operation' },
{ label: t('admin.logs.types.verification'), value: 'verification' },
{ label: t('admin.logs.types.exception'), value: 'exception' },
])
const statusOptions = computed(() => [
{ label: t('admin.success'), value: 'success' },
{ label: t('admin.failed'), value: 'failed' },
])
async function fetchApplications() {
try {
const data = await api.get<{ applications: Application[] }>('/dev/applications')
applications.value = data?.applications || []
}
catch (error) {
console.error('获取应用列表失败:', error)
}
}
async function fetchLogs() {
loading.value = true
try {
const params = new URLSearchParams()
params.append('page', String(currentPage.value))
params.append('page_size', String(pageSize.value))
if (appFilter.value) {
params.append('application_id', appFilter.value)
}
if (typeFilter.value) {
params.append('type', typeFilter.value)
}
if (statusFilter.value) {
params.append('status', statusFilter.value)
}
if (startDate.value) {
params.append('start_date', startDate.value.split('T')[0])
}
if (endDate.value) {
params.append('end_date', endDate.value.split('T')[0])
}
const data = await api.get<any>(`/dev/logs?${params.toString()}`)
logs.value = data?.logs || []
total.value = data?.total || 0
successCount.value = data?.success_count || 0
failedCount.value = data?.failed_count || 0
operationCount.value = data?.operation_count || 0
}
catch (error) {
console.error('获取日志记录失败:', error)
logs.value = []
}
finally {
loading.value = false
}
}
onMounted(() => {
fetchApplications()
fetchLogs()
})
watch([appFilter, typeFilter, statusFilter, startDate, endDate], () => {
currentPage.value = 1
fetchLogs()
})
const serverPagination = computed(() => ({
currentPage: currentPage.value,
pageSize: pageSize.value,
total: total.value,
onChange: (page: number) => {
currentPage.value = page
fetchLogs()
},
}))
</script>
<template>
<BasicPage
:title="t('admin.logs.title')"
:description="t('admin.logs.description')"
sticky
>
<div class="space-y-6">
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('admin.logs.totalLogs') }}
</UiCardTitle>
<FileText class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ total }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('admin.logs.successCount') }}
</UiCardTitle>
<CheckCircle class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ successCount }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('admin.logs.failedCount') }}
</UiCardTitle>
<XCircle class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ failedCount }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('admin.logs.operationCount') }}
</UiCardTitle>
<Activity class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ operationCount }}
</div>
</UiCardContent>
</UiCard>
</div>
<UiCard>
<UiCardContent class="p-6">
<DataTable
:loading
:data="logs"
:server-pagination="serverPagination"
@refresh="fetchLogs"
>
<template #filters>
<SingleFilter
v-model="appFilter"
:title="t('admin.logs.columns.application')"
:options="applicationOptions"
/>
<SingleFilter
v-model="typeFilter"
:title="t('admin.logs.columns.type')"
:options="typeOptions"
/>
<SingleFilter
v-model="statusFilter"
:title="t('admin.logs.columns.status')"
:options="statusOptions"
/>
<DateRangeFilter
v-model:start-model-value="startDate"
v-model:end-model-value="endDate"
/>
</template>
</DataTable>
</UiCardContent>
</UiCard>
</div>
</BasicPage>
</template>
+25 -2
View File
@@ -1,12 +1,12 @@
<script setup lang="ts">
import { Activity, CheckCircle, FileText, XCircle } from 'lucide-vue-next'
import { Activity, CheckCircle, Download, FileText, XCircle } from 'lucide-vue-next'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { BasicPage } from '@/components/global-layout'
import SingleFilter from '@/components/data-table/single-filter.vue'
import DateRangeFilter from '@/components/data-table/date-range-filter.vue'
import api from '@/services/api'
import api, { BASE_URL } from '@/services/api'
import type { Log } from '@/pages/admin/logs/data/schema'
@@ -112,6 +112,23 @@ async function fetchLogs() {
}
}
// 导出当前筛选结果(后端 /dev/logs/export,与列表同一套筛选条件)
function handleExport() {
const token = localStorage.getItem('token')
const params = new URLSearchParams()
if (appFilter.value && appFilter.value !== 'all')
params.append('application_id', appFilter.value)
if (typeFilter.value && typeFilter.value !== 'all')
params.append('type', typeFilter.value)
if (statusFilter.value && statusFilter.value !== 'all')
params.append('status', statusFilter.value)
if (startDate.value)
params.append('start_date', startDate.value.split('T')[0])
if (endDate.value)
params.append('end_date', endDate.value.split('T')[0])
window.open(`${BASE_URL}/dev/logs/export?${params.toString()}&token=${token}`, '_blank')
}
watch([appFilter, typeFilter, statusFilter, startDate, endDate], () => {
currentPage.value = 1
fetchLogs()
@@ -202,6 +219,12 @@ onMounted(() => {
@page-change="currentPage = $event; fetchLogs()"
@page-size-change="pageSize = $event; currentPage = 1; fetchLogs()"
>
<template #actions>
<UiButton variant="outline" size="sm" :disabled="loading" @click="handleExport">
<Download class="mr-2 size-4" />
{{ t('admin.logs.exportBtn') }}
</UiButton>
</template>
<template #filters>
<SingleFilter
v-model="appFilter"
@@ -0,0 +1,385 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
/**
* 验证界面的网页预览:照着壳里的 DuiLib 皮肤用 HTML/CSS 重画一遍。
*
* 为什么不用截图:截图要维护 8~9 张 PNG,改一点配色就得重新跑壳、截、对;
* 而且放大了发虚、tab 点不动。组件化之后配色直接从壳的皮肤表来,
* tab 能点、输入框能聚焦,任意尺寸都清晰。
*
* 布局和壳一致:标题栏 + 4 个 tab + 卡密输入 + 主按钮 + 设备号。
* 各套皮肤的窗口宽高不同(470×436 / 680×452 / 720×460 / 600×452 / 620×446 / 760×392),
* 这里用 aspect-ratio 保留比例,内部全部百分比布局,缩放不变形。
*/
interface Palette {
win: string // 窗口底
bar: string // 标题栏
border: string // 分隔线 / 边框
input: string // 输入框底
inputBorder: string
accent: string // 主按钮
accentText: string
text: string // 主文字
text2: string // 次要文字
radius: number // 窗口圆角
mono?: boolean // terminal 用等宽
w: number
h: number
}
const PALETTES: Record<string, Palette> = {
dark: {
win: '#141418', bar: '#1D1D24', border: '#2A2A33',
input: '#2A2A33', inputBorder: '#565672',
accent: '#4EA3E8', accentText: '#0B1016',
text: '#F0F0F4', text2: '#9A9AA6',
radius: 8, w: 470, h: 436,
},
classic: {
win: '#1E1E1E', bar: '#252527', border: '#3F3F46',
input: '#252526', inputBorder: '#3F3F46',
accent: '#0E639C', accentText: '#FFFFFF',
text: '#E6E6E6', text2: '#9D9D9D',
radius: 6, w: 470, h: 436,
},
light: {
win: '#FAFAFC', bar: '#FFFFFF', border: '#E2E6EE',
input: '#F1F3F7', inputBorder: '#C3CBD8',
accent: '#1B6FD6', accentText: '#FFFFFF',
text: '#1F1F24', text2: '#4B5563',
radius: 8, w: 470, h: 436,
},
split: {
win: '#12151A', bar: '#1A1F27', border: '#2E343D',
input: '#1A1F27', inputBorder: '#2E343D',
accent: '#2C7BE5', accentText: '#FFFFFF',
text: '#F2F6FA', text2: '#8794A3',
radius: 10, w: 680, h: 452,
},
card: {
win: '#F5F6F9', bar: '#FFFFFF', border: '#DDE3EC',
input: '#FFFFFF', inputBorder: '#C9D1DC',
accent: '#3B2BD6', accentText: '#FFFFFF',
text: '#1F2430', text2: '#4B5563',
radius: 14, w: 720, h: 460,
},
industrial: {
win: '#0A1520', bar: '#14304A', border: '#23567F',
input: '#14304A', inputBorder: '#23567F',
accent: '#1F6FB2', accentText: '#EAF6FF',
text: '#EAF6FF', text2: '#9FC0D8',
radius: 3, w: 600, h: 452,
},
terminal: {
win: '#0B0F0C', bar: '#16211A', border: '#2B3A2D',
input: '#16211A', inputBorder: '#2B3A2D',
accent: '#1B7A4E', accentText: '#D7F5DF',
text: '#D7F5DF', text2: '#7FAE90',
radius: 2, mono: true, w: 620, h: 446,
},
compact: {
win: '#11151A', bar: '#1B232B', border: '#32404E',
input: '#1B232B', inputBorder: '#32404E',
accent: '#2E9E6B', accentText: '#0A1410',
text: '#E8EEF4', text2: '#95A7B8',
radius: 6, w: 760, h: 392,
},
}
const props = withDefaults(
defineProps<{ theme: string; appName?: string; device?: string }>(),
{ appName: '游戏盒子打包器', device: '7BCD-EBE2-F08D' },
)
/** 深浅底色判定:决定阴影、tab 选中态用亮还是暗 */
const isDark = computed(() => {
const hex = PALETTES[props.theme]?.win || PALETTES.dark.win
const n = Number.parseInt(hex.slice(1, 3), 16)
return n < 128
})
const pal = computed<Palette>(() => PALETTES[props.theme] || PALETTES.dark)
/** 皮肤里的 tab 顺序(和壳一致) */
const TABS = ['登录', '我的设备', '卡密充值', '找回/绑定'] as const
const activeTab = ref(0)
/** 主按钮文案跟着 tab 变,贴近壳里的实际行为 */
const primaryLabel = computed(() => {
switch (activeTab.value) {
case 1: return '绑定本机'
case 2: return '卡密充值'
case 3: return '找回密码'
default: return '卡密登录'
}
})
const fontFamily = computed(() =>
pal.value.mono
? 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace'
: 'system-ui, -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif',
)
</script>
<template>
<div
class="preview-shell"
:style="{
'--win': pal.win,
'--bar': pal.bar,
'--bd': pal.border,
'--inp': pal.input,
'--inpbd': pal.inputBorder,
'--acc': pal.accent,
'--acctxt': pal.accentText,
'--txt': pal.text,
'--txt2': pal.text2,
'--radius': `${pal.radius}px`,
'--ff': fontFamily,
aspectRatio: `${pal.w} / ${pal.h}`,
fontFamily: 'var(--ff)',
borderRadius: 'var(--radius)',
background: 'var(--win)',
border: '1px solid var(--bd)',
boxShadow: isDark
? '0 1px 0 rgba(255,255,255,.04) inset, 0 12px 32px -12px rgba(0,0,0,.75)'
: '0 1px 0 rgba(255,255,255,.9) inset, 0 12px 32px -14px rgba(15,23,42,.28)',
}"
>
<!-- 标题栏 -->
<div class="bar">
<span class="title">软件授权验证</span>
<span class="winbtns">
<span class="wb">—</span>
<span class="wb">×</span>
</span>
</div>
<!-- tab 行:真能点,和壳里一样切内容 -->
<div class="tabs">
<button
v-for="(tb, i) in TABS"
:key="tb"
type="button"
class="tab"
:class="{ on: activeTab === i }"
@click="activeTab = i"
>
{{ tb }}
</button>
</div>
<!-- 内容区 -->
<div class="body">
<div class="appname">{{ appName }}</div>
<template v-if="activeTab === 0">
<div class="flabel">卡密</div>
<div class="input"><span class="caret" /></div>
<button type="button" class="primary">{{ primaryLabel }}</button>
</template>
<template v-else-if="activeTab === 1">
<div class="flabel">已绑定设备</div>
<div class="rowlist">
<div class="row"><span class="dot" />本机 · {{ device }}</div>
<div class="row muted"><span class="dot dim" />其他设备未绑定</div>
</div>
<button type="button" class="primary">{{ primaryLabel }}</button>
</template>
<template v-else-if="activeTab === 2">
<div class="flabel">卡密</div>
<div class="input"><span class="caret" /></div>
<div class="flabel">当前余额 <b>0 天</b></div>
<button type="button" class="primary">{{ primaryLabel }}</button>
</template>
<template v-else>
<div class="flabel">邮箱 / 手机号</div>
<div class="input"><span class="caret" /></div>
<div class="flabel">验证码</div>
<div class="input"><span class="caret" /></div>
<button type="button" class="primary">{{ primaryLabel }}</button>
</template>
<div class="device">设备 {{ device }}</div>
</div>
</div>
</template>
<style scoped>
.preview-shell {
position: relative;
display: flex;
flex-direction: column;
overflow: hidden;
width: 100%;
user-select: none;
}
.bar {
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 4.2%;
height: 7.4%;
background: var(--bar);
border-bottom: 1px solid var(--bd);
}
.title {
font-size: 0.72em;
color: var(--txt);
letter-spacing: 0.02em;
}
.winbtns {
display: flex;
gap: 0.9em;
color: var(--txt2);
font-size: 0.78em;
}
.wb {
line-height: 1;
}
.tabs {
flex: 0 0 auto;
display: flex;
gap: 3.6%;
padding: 0 4.2%;
height: 8.6%;
align-items: stretch;
border-bottom: 1px solid var(--bd);
}
.tab {
position: relative;
background: none;
border: 0;
padding: 0;
cursor: pointer;
font-size: 0.68em;
color: var(--txt2);
font-family: inherit;
transition: color 0.15s;
}
.tab:hover {
color: var(--txt);
}
.tab.on {
color: var(--txt);
}
.tab.on::after {
content: '';
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 2px;
background: var(--acc);
border-radius: 2px 2px 0 0;
}
.body {
flex: 1 1 auto;
display: flex;
flex-direction: column;
padding: 5.2% 4.2% 3.4%;
min-height: 0;
}
.appname {
font-size: 0.86em;
font-weight: 600;
color: var(--acc);
margin-bottom: 4.6%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.flabel {
font-size: 0.62em;
color: var(--txt2);
margin: 0 0 1.6%;
}
.flabel b {
color: var(--txt);
font-weight: 600;
}
.input {
height: 9.2%;
min-height: 18px;
background: var(--inp);
border: 1px solid var(--inpbd);
border-radius: calc(var(--radius) * 0.6);
margin-bottom: 3.2%;
display: flex;
align-items: center;
padding: 0 3%;
}
.caret {
width: 1px;
height: 44%;
background: var(--acc);
opacity: 0.65;
}
.rowlist {
display: flex;
flex-direction: column;
gap: 0.42em;
margin-bottom: 3.4%;
font-size: 0.64em;
}
.row {
display: flex;
align-items: center;
gap: 0.5em;
color: var(--txt);
background: var(--inp);
border: 1px solid var(--inpbd);
border-radius: calc(var(--radius) * 0.6);
padding: 0.5em 0.7em;
}
.row.muted {
color: var(--txt2);
}
.dot {
width: 0.42em;
height: 0.42em;
border-radius: 50%;
background: var(--acc);
flex: 0 0 auto;
}
.dot.dim {
background: var(--txt2);
opacity: 0.5;
}
.primary {
margin-top: auto;
height: 9.6%;
min-height: 20px;
border: 0;
border-radius: calc(var(--radius) * 0.6);
background: var(--acc);
color: var(--acctxt);
font-size: 0.7em;
font-weight: 600;
font-family: inherit;
cursor: pointer;
transition: filter 0.15s;
}
.primary:hover {
filter: brightness(1.12);
}
.device {
margin-top: 3.2%;
font-size: 0.56em;
color: var(--txt2);
opacity: 0.85;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
@@ -7,6 +7,7 @@ import type { ProtectTask } from '@/pages/admin/protect/data/schema'
import Badge from '@/components/ui/badge/Badge.vue'
import Button from '@/components/ui/button/Button.vue'
import Progress from '@/components/ui/progress/Progress.vue'
interface ColumnOptions {
appName: (id: number) => string
@@ -106,15 +107,41 @@ export function getColumns(options: ColumnOptions, t: (key: string) => string):
accessorKey: 'status',
header: () => t('admin.protect.status'),
cell: ({ row }) => {
const status = row.original.status
const task = row.original
const status = task.status
// 进行中:不显示干巴巴的「加密中」,改画进度条 + 当前阶段,
// 让用户看得出卡在哪一步(注入壳 / DogProtect / 签名 耗时差很多)
if (status === 'running') {
const pct = Math.max(0, Math.min(100, task.progress ?? 0))
const stageKey = task.stage ? `admin.protect.stage${task.stage.charAt(0).toUpperCase()}${task.stage.slice(1)}` : ''
const stageLabel = stageKey ? t(stageKey) : ''
return h('div', { class: 'flex w-full flex-col gap-1' }, [
h(Progress, { modelValue: pct, class: 'h-1.5' }),
h('div', { class: 'flex items-baseline justify-between gap-2 text-[11px] leading-none text-muted-foreground' }, [
h('span', { class: 'truncate' }, stageLabel || t('admin.protect.statusRunning')),
h('span', { class: 'shrink-0 tabular-nums' }, `${pct}%`),
]),
])
}
// 排队中:也画一条空槽,列表对齐不会跳
if (status === 'pending') {
const Icon = STATUS_ICON[status] as never
return h('div', { class: 'flex w-full flex-col gap-1' }, [
h(Progress, { modelValue: 0, class: 'h-1.5' }),
h('div', { class: 'flex items-center gap-1 text-[11px] leading-none text-muted-foreground' }, [
h(Icon, { class: 'h-3 w-3' }),
h('span', {}, t('admin.protect.statusPending')),
]),
])
}
const Icon = STATUS_ICON[status] as never
const label = t(`admin.protect.status${status.charAt(0).toUpperCase()}${status.slice(1)}`)
return h(Badge, { variant: 'outline', class: `gap-1 ${STATUS_STYLE[status] || ''}` }, () => [
h(Icon, { class: `h-3 w-3 ${status === 'running' ? 'animate-spin' : ''}` }),
h(Icon, { class: 'h-3 w-3' }),
h('span', {}, label),
])
},
size: 120,
size: 160,
},
{
id: 'crc',
@@ -6,6 +6,10 @@ export interface ProtectTask {
kind: string
arch: string
status: 'pending' | 'running' | 'done' | 'failed'
/** 加壳进度 0-100:注入验证壳 → DogProtect 加壳 → 证书签名 → 写出产物 */
progress: number
/** 当前阶段 key:prepare/shell/dogprotect/sign/writing/done */
stage: string
message: string
output_name: string
output_size: number
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -437,7 +437,7 @@ onMounted(() => {
</div>
<div v-else class="space-y-6">
<!-- 加壳来源提示 -->
<!-- 云端加密来源提示 -->
<div
v-if="protectInfo.protected"
class="flex flex-wrap items-center gap-3 rounded-lg border border-emerald-500/30 bg-emerald-500/5 px-4 py-3 text-sm"
+35 -20
View File
@@ -1550,13 +1550,13 @@
"fetchFailed": "Failed to fetch version information",
"fetchAppsFailed": "Failed to fetch application list"
},
"protectedBadge": "Protected",
"protectedHint": "This version is a protected artifact with the verification shell",
"protectedBanner": "This version was generated by the protect tool",
"protectedBadge": "Encrypted",
"protectedHint": "This version is a cloud-encrypted artifact with the verification shell",
"protectedBanner": "This version was generated by cloud encryption",
"derivedFrom": "derived from",
"sourceUnknown": "source version removed",
"viewProtectTask": "View protect task #{id}",
"sourceDirect": "uploaded & protected"
"viewProtectTask": "View cloud-encryption task #{id}",
"sourceDirect": "uploaded & cloud-encrypted"
},
"cardTypes": {
"title": "Card Type Management",
@@ -1825,7 +1825,8 @@
"types": {
"recharge": "Recharge",
"consumption": "Consumption"
}
},
"exportBtn": "Export"
},
"logs": {
"title": "Log Records",
@@ -1952,7 +1953,8 @@
"create_card_type": "Create Card Type: {name}",
"update_card_type": "Update Card Type: {name}",
"delete_card_type": "Delete Card Type: {name}"
}
},
"exportBtn": "Export logs"
},
"cloudConstants": {
"title": "Cloud Constants",
@@ -2577,7 +2579,7 @@
}
},
"protect": {
"title": "Protection",
"title": "Cloud Encryption",
"description": "Inject a verification shell into your program: entry rewrite + in-memory DLL + dual CRC32, single-file output",
"totalTasks": "Total tasks",
"inProgress": "In progress",
@@ -2586,16 +2588,16 @@
"uploadTitle": "Upload program",
"uploadHint": "Supports Windows PE and Android APK: PE gets an entry rewrite + in-memory shell, APK gets a shell class injected and is re-signed. IPA is detected and asks for signing certs",
"app": "Application",
"dropHint": "Click to choose or drop an .exe file",
"dropHint": "Click to choose or drop a program file (exe / dll / apk / ipa / elf)",
"onlyExe": "Supported: .exe / .dll / .apk / .ipa / Linux ELF",
"tooLarge": "File too large (max 200MB)",
"pickApp": "Choose an application first",
"pickFile": "Choose a program first",
"queued": "Submitted, protecting…",
"queued": "Submitted, encrypting…",
"uploading": "Uploading",
"start": "Start",
"clear": "Clear",
"tasks": "Protection tasks",
"tasks": "Cloud Encryption tasks",
"source": "Source / output",
"arch": "Arch",
"status": "Status",
@@ -2604,10 +2606,10 @@
"download": "Download",
"refresh": "Refresh",
"loading": "Loading…",
"empty": "No protection tasks yet",
"empty": "No cloud-encryption tasks yet",
"allStatus": "All status",
"statusPending": "Queued",
"statusRunning": "Protecting",
"statusRunning": "Encrypting",
"statusDone": "Completed",
"statusFailed": "Failed",
"busy": "Task is running, try later",
@@ -2616,7 +2618,7 @@
"loadFailed": "Failed to load tasks",
"loadAppsFailed": "Failed to load applications",
"makeVersion": "Create version",
"makeVersionHint": "Write the protected artifact as a new version record: clients decide updates by increasing version-record id, so replacing an already-published file in place never propagates.",
"makeVersionHint": "Write the cloud-encrypted artifact as a new version record: clients decide updates by increasing version-record id, so replacing an already-published file in place never propagates.",
"versionLabel": "Version",
"versionPlaceholder": "Leave empty to auto-bump the source version",
"strategy": "Update strategy",
@@ -2658,22 +2660,35 @@
"crossCertReady": "Cross-cert configured",
"usageMismatchWarn": "This certificate's usage does not match the file type; the signature is written but the target may reject it.",
"themeLabel": "Verification UI",
"themeClassic": "Classic (original Direct2D)",
"themeClassic": "Classic · Direct2D (original)",
"themeDark": "Dark · card key login",
"themeLight": "Light · office style",
"themeIndustrial": "Industrial blue · device licensing",
"themeHint": "DuiLib skins apply to 64-bit builds; 32-bit binaries keep the classic shell.",
"themeHint": "After choosing, encrypt in the cloud and the produced shell renders with this skin. 32-bit and 64-bit programs share the same set of skins.",
"themeCompact": "Compact banner · single row",
"themeSplit": "Split · brand sidebar",
"themeCard": "Wide card · two columns",
"themeTerminal": "Terminal style",
"programVersionLabel": "Program version",
"programVersionPlaceholder": "e.g. 1.2.3 (leave empty to skip update check)",
"programVersionHint": "When set, the packaged program asks the platform for updates on startup. Publishing a newer version shows an update prompt; forced updates cannot be skipped."
"programVersionHint": "When set, the packaged program asks the platform for updates on startup. Publishing a newer version shows an update prompt; forced updates cannot be skipped.",
"themeGridHint": "Click a skin to apply it to the build — screenshots are from the real client",
"themeBits64": "64-bit",
"themeBits32": "32/64-bit",
"themeZoom": "Preview",
"themeView": "View",
"themeZoomHint": "Actual rendering of the produced verification dialog (raw screenshot)",
"themeUseThis": "Use this skin",
"stagePrepare": "Preparing",
"stageShell": "Injecting shell",
"stageDogprotect": "DogProtect packing",
"stageSign": "Signing",
"stageWriting": "Writing output",
"stageDone": "Finishing"
},
"signProfiles": {
"title": "Signing certificates",
"description": "Upload Windows pfx / iOS p12+provision; protected artifacts are re-signed with them. Certs and passwords are encrypted at rest and never sent back",
"description": "Upload Windows pfx / iOS p12+provision; cloud-encrypted artifacts are re-signed with them. Certs and passwords are encrypted at rest and never sent back",
"uploadTitle": "Upload certificate",
"uploadHint": "Windows uses .pfx/.p12; iOS needs both .p12 and .mobileprovision",
"platform": "Platform",
@@ -2717,7 +2732,7 @@
"expired": "Expired",
"daysLeft": "days left",
"colCerts": "Certificates",
"uploadedSplit": "Parsed {n} identities from this file; {n} records created. Pick any one when protecting.",
"uploadedSplit": "Parsed {n} identities from this file; {n} records created. Pick any one when cloud-encrypting.",
"colSubject": "Certificate name (CN)",
"identities": "Identities",
"identitiesTitle": "Certificate identities",
@@ -3415,7 +3430,7 @@
"storage": "Storage",
"admin": "Admin",
"agent": "Agent",
"protect": "Protection",
"protect": "Cloud Encryption",
"signProfiles": "Certificates"
},
"footer": {
+37 -22
View File
@@ -1546,13 +1546,13 @@
"fetchFailed": "获取版本信息失败",
"fetchAppsFailed": "获取应用列表失败"
},
"protectedBadge": "已加固",
"protectedHint": "此版本是加壳产物,入口文件带验证壳",
"protectedBanner": "此版本由加壳工具生成",
"protectedBadge": "已加密",
"protectedHint": "此版本是云端加密产物,入口文件带验证壳",
"protectedBanner": "此版本由云端加密服务生成",
"derivedFrom": "派生自",
"sourceUnknown": "来源版本已删除",
"viewProtectTask": "查看加壳任务 #{id}",
"sourceDirect": "直接上传加壳"
"viewProtectTask": "查看云端加密任务 #{id}",
"sourceDirect": "直接上传云端加密"
},
"cardTypes": {
"title": "卡类管理",
@@ -1842,7 +1842,8 @@
"types": {
"recharge": "充值",
"consumption": "消费"
}
},
"exportBtn": "导出流水"
},
"logs": {
"title": "日志记录",
@@ -1969,7 +1970,8 @@
"create_card_type": "创建卡密类型: {name}",
"update_card_type": "更新卡密类型: {name}",
"delete_card_type": "删除卡密类型: {name}"
}
},
"exportBtn": "导出日志"
},
"cloudConstants": {
"title": "云端常量",
@@ -2596,7 +2598,7 @@
}
},
"protect": {
"title": "加壳加固",
"title": "云端加密",
"description": "给程序注入验证壳:改入口 + 内存加载壳 DLL + 双层 CRC32,产物单文件、免安装依赖",
"totalTasks": "任务总数",
"inProgress": "进行中",
@@ -2605,16 +2607,16 @@
"uploadTitle": "上传程序",
"uploadHint": "支持 Windows PE 与 Android APK:PE 改入口+内存加载壳,APK 注入壳类并自动重签(内嵌证书)。IPA 会被识别并提示需上传签名证书",
"app": "应用",
"dropHint": "点击选择或拖入 .exe 文件",
"dropHint": "点击选择或拖入程序文件(exe / dll / apk / ipa / elf)",
"onlyExe": "支持 .exe / .dll / .apk / .ipa / Linux ELF",
"tooLarge": "文件过大(上限 200MB)",
"pickApp": "请先选择应用",
"pickFile": "请先选择要加壳的程序",
"queued": "已提交,正在加壳",
"pickFile": "请先选择要加密的程序",
"queued": "已提交,正在云端加密",
"uploading": "上传中",
"start": "开始加壳",
"start": "开始云端加密",
"clear": "清除",
"tasks": "加壳任务",
"tasks": "云端加密任务",
"source": "源文件 / 产物",
"arch": "架构",
"status": "状态",
@@ -2623,10 +2625,10 @@
"download": "下载",
"refresh": "刷新",
"loading": "加载中…",
"empty": "还没有加壳任务",
"empty": "还没有云端加密任务",
"allStatus": "全部状态",
"statusPending": "排队中",
"statusRunning": "加壳中",
"statusRunning": "加密中",
"statusDone": "已完成",
"statusFailed": "失败",
"busy": "任务执行中,稍后再删",
@@ -2635,7 +2637,7 @@
"loadFailed": "加载任务失败",
"loadAppsFailed": "加载应用失败",
"makeVersion": "生成版本",
"makeVersionHint": "把加壳产物写成一条新的版本记录:客户端按版本记录 ID 递增判定更新,原地换包推不下去。其余资源文件沿用来源版本。",
"makeVersionHint": "把云端加密产物写成一条新的版本记录:客户端按版本记录 ID 递增判定更新,原地换包推不下去。其余资源文件沿用来源版本。",
"versionLabel": "版本号",
"versionPlaceholder": "留空则按来源版本末段 +1",
"strategy": "更新策略",
@@ -2677,22 +2679,35 @@
"crossCertReady": "已配交叉证书",
"usageMismatchWarn": "所选证书的用途和这个文件类型不匹配(见上方标签):签名能写进去,但目标机可能不认。驱动建议配交叉签名证书。",
"themeLabel": "验证界面",
"themeClassic": "经典(原版 Direct2D)",
"themeClassic": "经典 · Direct2D 原版",
"themeDark": "深色 · 卡密登录",
"themeLight": "浅色 · 办公风",
"themeIndustrial": "工业蓝 · 设备授权",
"themeHint": "DuiLib 皮肤目前 64 位生效;32 位程序仍用经典壳。选好皮肤后加壳,产物弹窗就按该皮肤渲染。",
"themeHint": "选好后云端加密,产物验证弹窗就按这套皮肤渲染。32 位与 64 位程序共用同一套皮肤,效果一致。",
"themeCompact": "极简横幅 · 单行激活",
"themeSplit": "左右分栏 · 品牌竖栏",
"themeCard": "宽扁卡片 · 双列说明",
"themeTerminal": "终端风 · 命令行",
"programVersionLabel": "程序版本",
"programVersionPlaceholder": "例如 1.2.3(留空则不检查更新)",
"programVersionHint": "填了版本号后,程序启动时会向平台查询是否有更新;平台里发布更高版本就会弹出更新提示,设为强制更新时不允许跳过。"
"programVersionHint": "填了版本号后,程序启动时会向平台查询是否有更新;平台里发布更高版本就会弹出更新提示,设为强制更新时不允许跳过。",
"themeGridHint": "点一套直接套用到产物,下面是各套界面实拍",
"themeBits64": "64 位",
"themeBits32": "32/64 位",
"themeZoom": "看大图",
"themeView": "查看",
"themeZoomHint": "这是产物验证弹窗的实际渲染效果(截图,未做任何美化)",
"themeUseThis": "用这套皮肤",
"stagePrepare": "准备源文件",
"stageShell": "注入验证壳",
"stageDogprotect": "DogProtect 加壳",
"stageSign": "证书签名",
"stageWriting": "写出产物",
"stageDone": "即将完成"
},
"signProfiles": {
"title": "签名证书",
"description": "上传 Windows pfx / iOS p12+描述文件,加壳产物用它们重签;证书与口令一律加密存储,永不下发前端",
"description": "上传 Windows pfx / iOS p12+描述文件,云端加密产物用它们重签;证书与口令一律加密存储,永不下发前端",
"uploadTitle": "上传证书",
"uploadHint": "Windows 用 .pfx/.p12;iOS 需要 .p12 + .mobileprovision 两件套",
"platform": "平台",
@@ -2736,7 +2751,7 @@
"expired": "已过期",
"daysLeft": "天后过期",
"colCerts": "证书数",
"uploadedSplit": "已从该文件解析出 {n} 套证书,分别建了 {n} 条记录,加壳时可任选一套",
"uploadedSplit": "已从该文件解析出 {n} 套证书,分别建了 {n} 条记录,云端加密时可任选一套",
"colSubject": "证书名称(CN)",
"identities": "身份列表",
"identitiesTitle": "证书身份",
@@ -3434,7 +3449,7 @@
"storage": "存储",
"admin": "管理员",
"agent": "代理商",
"protect": "加壳加固",
"protect": "云端加密",
"signProfiles": "签名证书"
},
"footer": {
+1 -1
View File
@@ -111,7 +111,7 @@ const routes: RouteRecordRaw[] = [
path: 'protect',
name: 'AdminProtect',
component: () => import('@/pages/admin/protect/index.vue'),
meta: { title: '加壳加固 - 管理后台' },
meta: { title: '云端加密 - 管理后台' },
},
{
path: 'sign-profiles',
+2
View File
@@ -46,6 +46,7 @@ declare module 'vue' {
GlobalLayoutBasicPage: typeof import('./../components/global-layout/basic-page.vue')['default']
GlobalLayoutTwoCol: typeof import('./../components/global-layout/two-col.vue')['default']
GlobalLayoutTwoColAside: typeof import('./../components/global-layout/two-col-aside.vue')['default']
ImageLightbox: typeof import('./../components/image-lightbox.vue')['default']
InspiraUiFlickeringGrid: typeof import('./../components/inspira-ui/flickering-grid.vue')['default']
InspiraUiGlowingEffect: typeof import('./../components/inspira-ui/glowing-effect.vue')['default']
InspiraUiMarquee: typeof import('./../components/inspira-ui/marquee/index.vue')['default']
@@ -449,6 +450,7 @@ declare global {
const GlobalLayoutBasicPage: typeof import('./../components/global-layout/basic-page.vue')['default']
const GlobalLayoutTwoCol: typeof import('./../components/global-layout/two-col.vue')['default']
const GlobalLayoutTwoColAside: typeof import('./../components/global-layout/two-col-aside.vue')['default']
const ImageLightbox: typeof import('./../components/image-lightbox.vue')['default']
const InspiraUiFlickeringGrid: typeof import('./../components/inspira-ui/flickering-grid.vue')['default']
const InspiraUiGlowingEffect: typeof import('./../components/inspira-ui/glowing-effect.vue')['default']
const InspiraUiMarquee: typeof import('./../components/inspira-ui/marquee/index.vue')['default']
+3 -14
View File
@@ -14,6 +14,9 @@ import type {
ParamValueZeroOrMore,
ParamValueZeroOrOne,
} from 'vue-router'
import type {
_ExtractParamParserType,
} from 'vue-router/experimental'
declare module 'vue-router' {
interface TypesConfig {
@@ -304,13 +307,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/admin/logs': RouteRecordInfo<
'/admin/logs',
'/admin/logs',
Record<never, never>,
Record<never, never>,
| '/admin/logs/'
>,
'/admin/logs/': RouteRecordInfo<
'/admin/logs/',
'/admin/logs',
@@ -928,13 +924,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/admin/logs.vue': {
routes:
| '/admin/logs'
| '/admin/logs/'
views:
| 'default'
}
'src/pages/admin/logs/index.vue': {
routes:
| '/admin/logs/'
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""财务/日志接口审查:用真请求验证可疑点(本地 sqlite 后端)。"""
import json
import sqlite3
import urllib.error
import urllib.request
B = "http://127.0.0.1:8080"
DB = "/root/work/vfy_e2e/verification_platform.db"
def call(method, path, data=None, tok=None):
body = json.dumps(data).encode() if data is not None else None
req = urllib.request.Request(B + path, data=body, method=method,
headers={"Content-Type": "application/json"})
if tok:
req.add_header("Authorization", "Bearer " + tok)
try:
resp = urllib.request.urlopen(req, timeout=30)
return resp.status, json.loads(resp.read().decode())
except urllib.error.HTTPError as e:
return e.code, {"_raw": e.read().decode()[:300]}
except Exception as e:
return 0, {"_err": str(e)}
def login():
_, r = call("POST", "/api/v1/auth/login", {"username": "e2eadmin", "password": "admin123456"})
return r["data"]["token"]
def db():
con = sqlite3.connect(DB)
return con, con.cursor()
def main():
tok = login()
con, cur = db()
total_recharge = cur.execute("SELECT COUNT(*) FROM recharge_records").fetchone()[0]
total_cons = cur.execute("SELECT COUNT(*) FROM consumption_records").fetchone()[0]
print(f"库里实际: 充值 {total_recharge} 条 / 消费 {total_cons} 条")
st, r = call("GET", "/api/v1/dev/finance/records", None, tok)
d = r.get("data") or {}
recs = d.get("records") or []
got_r = len([x for x in recs if x["type"] == "recharge"])
got_c = len([x for x in recs if x["type"] == "consumption"])
print(f"[1] 前端原样请求 /finance/records(无 page_size): HTTP {st} 返回 {len(recs)} 条"
f"(充值{got_r}/消费{got_c})data.total={d.get('total')}")
print(f" → 前端按这 {len(recs)} 条算总额,库里实有 {total_recharge + total_cons} 条")
st, r = call("GET", "/api/v1/dev/finance/records?page=2&page_size=10", None, tok)
d = r.get("data") or {}
print(f"[2] 翻到第 2 页: HTTP {st} 返回 {len(d.get('records') or [])} 条, total={d.get('total')}")
st, r = call("GET", "/api/v1/dev/finance/records?page=0&page_size=0", None, tok)
d = r.get("data") or {}
print(f"[3] page=0&page_size=0: HTTP {st} 返回 {len(d.get('records') or [])} 条")
st, r = call("GET", "/api/v1/dev/finance/records?page=-1&page_size=-5", None, tok)
d = r.get("data") or {}
print(f"[4] page=-1&page_size=-5: HTTP {st} 返回 {len(d.get('records') or [])} 条")
# 主体被软删(正常业务操作)后,它的财务流水还能不能查
victim = cur.execute("SELECT user_id FROM recharge_records GROUP BY user_id ORDER BY COUNT(*) DESC LIMIT 1").fetchone()[0]
cur.execute("UPDATE app_users SET deleted_at = '2026-11-24 12:00:00' WHERE id = ?", (victim,))
con.commit()
st, r = call("GET", "/api/v1/dev/finance/records", None, tok)
d = r.get("data") or {}
print(f"[5] 把一个有流水的主体软删后 /finance/records: HTTP {st} "
f"返回 {len(d.get('records') or [])} 条 {'⚠ panic/500' if st >= 500 else ''} {r.get('_raw','')[:120]}")
st, r = call("GET", "/api/v1/dev/finance/recharge-records", None, tok)
print(f"[6] 同场景 /finance/recharge-records: HTTP {st} {r.get('_raw','')[:120]}")
cur.execute("UPDATE app_users SET deleted_at = NULL WHERE id = ?", (victim,))
con.commit()
# 日志
st, r = call("GET", "/api/v1/dev/logs?page_size=5", None, tok)
d = r.get("data") or {}
print(f"[7] /logs?page_size=5: HTTP {st} 列表 {len(d.get('logs') or [])} 条, total={d.get('total')}, "
f"success={d.get('success_count')} failed={d.get('failed_count')} operation={d.get('operation_count')}")
st, r = call("GET", "/api/v1/dev/logs?status=failed&type=exception&page_size=5", None, tok)
d = r.get("data") or {}
print(f"[8] /logs?status=failed&type=exception: 列表 {len(d.get('logs') or [])} 条, total={d.get('total')}, "
f"success={d.get('success_count')} failed={d.get('failed_count')} operation={d.get('operation_count')}")
print(" → 筛选条件对上面三个统计数字没有影响(统计走的是 ApiUsage,且没带任何筛选)")
st, r = call("GET", "/api/v1/dev/logs?page=-1&page_size=-1", None, tok)
d = r.get("data") or {}
print(f"[9] /logs?page=-1&page_size=-1: HTTP {st} 返回 {len(d.get('logs') or [])} 条(负数未校验)")
st, r = call("GET", "/api/v1/dev/logs?page_size=100000", None, tok)
d = r.get("data") or {}
print(f"[10] /logs?page_size=100000: HTTP {st} 返回 {len(d.get('logs') or [])} 条(无上限)")
if __name__ == "__main__":
main()
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""登录方式开关(login_mode)端到端验证。
前置:一个干净的后端(sqlite)已经装好管理员,环境变量按需覆盖:
VFY_BASE=http://127.0.0.1:8080 VFY_DB=<sqlite 文件> VFY_STATE=<状态文件>
跑法:
python3 scripts/e2e-login-mode.py setup # 建应用 / 账号用户 / credential 卡
python3 scripts/e2e-login-mode.py matrix # 跑 5 组模式×凭证的登录矩阵
"""
import json
import os
import sqlite3
import sys
import urllib.error
import urllib.request
BASE = os.environ.get("VFY_BASE", "http://127.0.0.1:8080")
DB = os.environ.get("VFY_DB", "/root/work/vfy_e2e/verification_platform.db")
ADMIN = {"username": "e2eadmin", "password": "admin123456"}
APP_NAME = "e2e-loginmode"
STATE = os.environ.get("VFY_STATE", "/root/work/e2e_state.json")
def call(method, path, data=None, tok=None):
body = json.dumps(data).encode() if data is not None else None
req = urllib.request.Request(BASE + path, data=body, method=method,
headers={"Content-Type": "application/json"})
if tok:
req.add_header("Authorization", "Bearer " + tok)
try:
return json.loads(urllib.request.urlopen(req, timeout=25).read())
except urllib.error.HTTPError as e:
raw = e.read().decode()
try:
j = json.loads(raw)
j["_http"] = e.code
return j
except Exception:
return {"_http": e.code, "_raw": raw[:400]}
def admin_token():
r = call("POST", "/api/v1/auth/login", ADMIN)
return r["data"]["token"]
def setup():
tok = admin_token()
r = call("POST", "/api/v1/dev/applications",
{"name": APP_NAME, "description": "e2e 登录方式验证", "billing_type": "free"}, tok)
print("建应用:", json.dumps(r, ensure_ascii=False)[:300])
app = r.get("data", {})
if isinstance(app.get("application"), dict):
app = app["application"]
app_id, app_key = app.get("id"), app.get("app_key")
if not app_id:
print("拿不到应用 ID,终止")
return
# 打开注册、关闭各种验证,方便造数据
call("PUT", f"/api/v1/dev/applications/{app_id}",
{"allow_register": True, "enable_register_verify": False, "enable_login_verify": False,
"bind_type": "none", "max_devices": 5}, tok)
reg = call("POST", f"/api/v1/app/{app_key}/register",
{"username": "e2euser", "password": "user123456", "device_id": "DEV-E2E-0001",
"device_name": "e2e-pc", "device_type": "windows", "instance_id": "DEV-E2E-0001"})
print("注册账号用户:", json.dumps(reg, ensure_ascii=False)[:300])
# 直接插一张 credential 卡(管理端建卡接口在这个版本里是桩)
con = sqlite3.connect(DB)
cur = con.cursor()
cur.execute("SELECT id FROM card_types WHERE application_id=? LIMIT 1", (app_id,))
row = cur.fetchone()
if row:
ct_id = row[0]
else:
cols = [r[1] for r in cur.execute("PRAGMA table_info(card_types)")]
vals = {"application_id": app_id, "name": "e2e登录卡", "purpose": "credential",
"recharge_type": "balance", "value": 0, "value_unit": "day", "price": 0,
"status": "active", "created_at": "2026-11-24 00:00:00", "updated_at": "2026-11-24 00:00:00"}
use = {k: v for k, v in vals.items() if k in cols}
cur.execute("INSERT INTO card_types (%s) VALUES (%s)" % (
",".join(use), ",".join("?" * len(use))), list(use.values()))
ct_id = cur.lastrowid
cols = [r[1] for r in cur.execute("PRAGMA table_info(cards)")]
vals = {"application_id": app_id, "card_type_id": ct_id, "card_key": "E2E-CARD-0001",
"purpose": "credential", "status": "unused", "creator_id": 1,
"created_at": "2026-11-24 00:00:00", "updated_at": "2026-11-24 00:00:00"}
use = {k: v for k, v in vals.items() if k in cols}
cur.execute("INSERT INTO cards (%s) VALUES (%s)" % (",".join(use), ",".join("?" * len(use))),
list(use.values()))
con.commit()
con.close()
print(f"已插入 credential 卡 E2E-CARD-0001(card_type_id={ct_id})")
json.dump({"app_id": app_id, "app_key": app_key, "token": tok}, open(STATE, "w"))
print(f"state 已保存: app_id={app_id} app_key={app_key}")
def set_mode(tok, app_id, mode=None, enforce=None, grace=None):
body = {}
if mode is not None:
body["login_mode"] = mode
if enforce is not None:
body["login_mode_enforce"] = enforce
if grace is not None:
body["login_mode_grace_days"] = grace
r = call("PUT", f"/api/v1/dev/applications/{app_id}", body, tok)
return r
def login(app_key, payload):
r = call("POST", f"/api/v1/app/{app_key}/login", payload)
code = r.get("code") or r.get("_http")
return code, r.get("error_code"), r.get("message") or r.get("msg"), r.get("data")
def matrix():
st = json.load(open(STATE))
tok, app_id, app_key = st["token"], st["app_id"], st["app_key"]
acc = {"username": "e2euser", "password": "user123456", "login_type": "account",
"device_id": "DEV-E2E-0001", "device_name": "e2e-pc", "device_type": "windows",
"instance_id": "DEV-E2E-0001"}
crd = {"card_key": "E2E-CARD-0001", "login_type": "card",
"device_id": "DEV-E2E-0002", "device_name": "e2e-pc2", "device_type": "windows",
"instance_id": "DEV-E2E-0002"}
# auto:把卡密塞进 username、密码留空 → 归一化成 card
auto_card = {"username": "E2E-CARD-0001", "password": "", "login_type": "auto",
"device_id": "DEV-E2E-0003", "device_name": "e2e-pc3", "device_type": "windows",
"instance_id": "DEV-E2E-0003"}
auto_acc = {"username": "e2euser", "password": "user123456", "login_type": "auto",
"device_id": "DEV-E2E-0004", "device_name": "e2e-pc4", "device_type": "windows",
"instance_id": "DEV-E2E-0004"}
cases = [
("both/off", "both", "off", 0),
("account/strict", "account", "strict", 0),
("card/strict", "card", "strict", 0),
("account/warn", "account", "warn", 0),
("account/strict+7天宽限", "account", "strict", 7),
]
rows = []
for label, mode, enforce, grace in cases:
set_mode(tok, app_id, mode, enforce, grace)
for tname, payload in (("account", acc), ("card", crd), ("auto→card", auto_card), ("auto→account", auto_acc)):
code, ecode, msg, data = login(app_key, payload)
extra = ""
if isinstance(data, dict):
if data.get("deprecated_login"):
extra = f" deprecated={data.get('grace_days_left')}天"
rows.append((label, tname, code, ecode or "", (msg or "")[:22], extra))
print(f"--- {label} ---")
for r in rows[-4:]:
print(f" {r[1]:<14} code={r[2]} error_code={r[3]:<20} {r[4]}{r[5]}")
# 恢复默认,别把环境留成 strict
set_mode(tok, app_id, "both", "warn", 0)
# impact 接口
imp = call("GET", f"/api/v1/dev/applications/{app_id}/login-mode-impact", None, tok)
print("影响面:", json.dumps(imp.get("data"), ensure_ascii=False))
return rows
if __name__ == "__main__":
cmd = sys.argv[1] if len(sys.argv) > 1 else "setup"
if cmd == "setup":
setup()
elif cmd == "matrix":
matrix()
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""mock 验证服务端(仅开发/验收用)
/login 一律回 HTTP 403 + error_code=DEVICE_LIMIT_EXCEEDED(带 3 台设备明细,上限 2),
/unbind-device-with-auth、/card-devices、/info、/check-update、/announcements 回成功 JSON。
用途:不需要真数据库就能把壳的「设备管理页 / 每行解绑 / 在线状态」全程跑一遍。
用法:python3 scripts/mock-vfy-device-limit.py (监听 127.0.0.1:9998)
配套验收步骤见 docs/shell-device-ui.md
"""
import json
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
DEVICES = [
{"id": 11, "device_id": "AAAA-1111-2222-3333", "device_name": "工作室-PC01", "device_type": "windows", "online_count": 1, "created_at": "2026-11-01T10:00:00+08:00"},
{"id": 12, "device_id": "BBBB-4444-5555-6666", "device_name": "笔记本-Liu", "device_type": "windows", "online_count": 0, "created_at": "2026-11-10T21:12:00+08:00"},
{"id": 13, "device_id": "CCCC-7777-8888-9999", "device_name": "ANDROID-9f3c", "device_type": "android", "online_count": 1, "created_at": "2026-11-20T08:30:00+08:00"},
]
class H(BaseHTTPRequestHandler):
def _log(self, body=b""):
sys.stderr.write("[mock] %s %s %s\n" % (self.command, self.path, body[:200].decode("utf-8", "replace")))
sys.stderr.flush()
def do_GET(self):
self._log()
if "info" in self.path:
return self._json(200, {"code": 200, "data": {
"allow_register": 1, "enable_register_verify": 1, "enable_password_reset": 1,
"password_reset_method": "email", "billing_type": "card", "max_devices": 2,
"name": "dogtest"}})
if "devices" in self.path or "instances" in self.path:
return self._json(200, {"code": 200, "data": {"devices": DEVICES, "max_devices": 2, "device_count": 3}})
return self._json(200, {"code": 200, "data": {}})
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n) if n else b""
self._log(body)
if self.path.rstrip("/").endswith("/login"):
# 与真实后端一致:error_code 放在 data 里;顶层也带一份,壳只按 "DEVICE_LIMIT" 字符串判断
return self._json(403, {"code": 403, "error_code": "DEVICE_LIMIT_EXCEEDED",
"message": "设备绑定数量已达上限,请解绑后再试",
"data": {"error_code": "DEVICE_LIMIT_EXCEEDED",
"max_devices": 2, "device_count": 3, "devices": DEVICES}})
if "unbind" in self.path:
return self._json(200, {"code": 200, "message": "解绑成功"})
if "card-devices" in self.path:
return self._json(200, {"code": 200, "data": {"devices": DEVICES, "max_devices": 2, "device_count": 3}})
return self._json(200, {"code": 200, "data": {}})
def _json(self, code, obj):
raw = json.dumps(obj, ensure_ascii=False, separators=(",", ":")).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def log_message(self, *a):
pass
if __name__ == "__main__":
ThreadingHTTPServer(("127.0.0.1", 9998), H).serve_forever()
+29
View File
@@ -90,3 +90,32 @@ open(p, 'wb').write(bytes(d))
- 壳 DLL 的日志走 `logf_`(本仓库资产里已禁用)。要排查界面/网络问题时,用未打补丁的 DLL
或在源码里给 `logf_` 加重定向,别直接改 `%TEMP%` 路径——那是唯一能落盘的取证点。
- 验证界面需要窗口管理器:`Xvfb :99` + `openbox`,否则 wine 窗口不映射、截图全是黑屏。
## 设备已满页 / 我的设备页(2026-11 改版)
- **设备页做成独立页(QQ 那种观感)**:设备满时窗口从登录尺寸临时放大到 **620×620** 并居中,内容标题变「设备管理」、
登录页的 4 个 tab 与品牌字隐藏;点「返回/重试」时窗口尺寸与 tab 自动还原。
- 列表每行 = `HorizontalLayout(rowBoxN)` 里「信息按钮(devRowN) + 右侧蓝色『解绑』按钮(devUnbindN)」,行高 40、行间 6px;
文字 `序号. 名称 设备ID ● 在线 / ○ 离线`(`online_count > 0` 判在线)。
- **点哪行的『解绑』就解绑哪台**,不再需要输入序号(序号输入框整块隐藏,`devIdx`/`btnUnbind` 在 XML 里 `visible="false"` 兜底保留);
解绑成功后自动重试登录。实测:点第 2 行的解绑 → `POST /unbind-device-with-auth` 带的是第 2 台的 `device_id`。
- 文案:「设备数量已达上限,请先在平台**解绑**一台设备」「超出设备上限时请先**解绑**一台」——原来写「下线」,与按钮实际动作不一致。
- 踩坑:`packthemed` 用 `//go:embed` 内嵌壳资产,**改完 assets 必须重编 packthemed**,否则测的还是旧壳(我在这上面浪费过几轮)。
- 踩坑:wine 下 DuiLib 的原生 EDIT 子窗口点击不转移焦点,**要点两次**(第一次激活窗口、第二次才聚焦),否则输入会打到上一个输入框。
## 手机端壳(Android,`assets/shell_smali.tgz`)
- 用 `smali assemble vfy -o /tmp/x.dex` 可离线校验语法;平台侧走 apktool 合并 smali 后重建 APK。
- 界面是**运行时拼的原生 AlertDialog**(没有 XML 布局、没有皮肤):标题取 `cfg.name`,内容为竖向 LinearLayout(padding 16dp):
说明「请输入账号或卡密完成验证」+ 输入框「账号或卡密」+ 密码框(留空则用 cfg 里的 password)+ 提示「通过后自动进入应用」;
按钮「验证」(走 `verify()`)与「退出」(`finish()` + `killProcess`)。
- 设备超限文案:「设备数超限,请先在平台解绑一台设备」。手机端目前**没有**设备列表/自助解绑页(只有这一道登录闸)。
## 壳节名:.load(2026-11 起)
产物里的壳节原名 `.vfy`,现改为 **`.load`**;旧产物仍可识别。改名必须成对做:
1. `backend/internal/protect/protect.go` 的 `secName = ".load"`(`HasVfy` 同时识别旧 `.vfy`)
2. 引导 blob 的节名比较补丁:`blob64.bin` 偏移 `0x85/0x8b/0x91`、`blob32.bin` 偏移 `0x73/0x79/0x7f`,
把 `76 66 79`(`vfy`)改成 `6c 6f 61`(`loa`,按前 4 字节匹配 `.load`)
只改 Go 侧不改 blob → 引导找不到节头,产物启动即 `return 2`;只改 blob 不改 Go → 写进去的还是 `.vfy`,同样对不上。
+7 -3
View File
@@ -444,11 +444,13 @@ static int http_login(const char *user, const char *pass, char *msg, int cap) {
snprintf(path, sizeof(path), "%s", g_api);
char *p = strstr(path, "://");
if (!p) return 0;
bool https = (p > path && p[-1] == 's');
p += 3;
char *slash = strchr(p, '/');
if (slash) { *slash = 0; snprintf(path, sizeof(path), "%s", slash + 1); }
snprintf(host, sizeof(host), "%s", p);
unsigned short port = 80;
// 原来写死 80:https 的 api 被当成明文 HTTP 发到 443,服务端回 400,登录恒失败。
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
MultiByteToWideChar(CP_UTF8, 0, host, -1, wHost, 256);
@@ -459,7 +461,8 @@ static int http_login(const char *user, const char *pass, char *msg, int cap) {
HINTERNET hS = WinHttpOpen(L"vfy/5.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) return 0;
HINTERNET hC = WinHttpConnect(hS, wHost, port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath, NULL, NULL, NULL, 0) : NULL;
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath, NULL, NULL, NULL,
https ? WINHTTP_FLAG_SECURE : 0) : NULL;
if (hR) {
const wchar_t *hdr = L"Content-Type: application/json\r\n";
WinHttpSendRequest(hR, hdr, (DWORD)-1L, body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
@@ -736,7 +739,8 @@ static int shell_main(PFN_OEP oep) {
RegisterClassExW(&wc);
int w = (int)((CARD_W + PAD * 2) * g_S), h = (int)((CARD_H + PAD * 2) * g_S);
HWND hwnd = CreateWindowExW(WS_EX_LAYERED | WS_EX_APPWINDOW | WS_EX_TOPMOST, CLS_NAME, L"\x9A8C\x8BC1\x767B\x5F55",
// 不带 WS_EX_TOPMOST:验证窗常驻最前会压住用户所有窗口,像卡死。
HWND hwnd = CreateWindowExW(WS_EX_LAYERED | WS_EX_APPWINDOW, CLS_NAME, L"\x9A8C\x8BC1\x767B\x5F55",
WS_POPUP, 0, 0, w, h, NULL, NULL, wc.hInstance, NULL);
if (!hwnd) return -1;
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, w, h, SWP_NOMOVE | SWP_NOACTIVATE);
+9 -3
View File
@@ -530,6 +530,8 @@ static int api_call(const char *suffix, const char *body, char *resp, int cap) {
snprintf(full, sizeof(full), "%s", g_api);
char *p = strstr(full, "://");
if (!p) return 0;
// 判断 scheme:p 指向 "://" 的冒号,p[-1] 就是 http/https 的最后一个字母
bool https = (p > full && p[-1] == 's');
p += 3;
char *slash = strchr(p, '/');
char dir[400] = {0};
@@ -541,7 +543,9 @@ static int api_call(const char *suffix, const char *body, char *resp, int cap) {
}
char host[256];
snprintf(host, sizeof(host), "%s", p);
unsigned short port = 80;
// 原来写死 80:https 的 api 会被当成明文 HTTP 发到 443,服务端直接回
// 400 "The plain HTTP request was sent to HTTPS port",登录恒失败。
unsigned short port = https ? 443 : 80;
char *colon = strrchr(host, ':');
if (colon) { *colon = 0; port = (unsigned short)atoi(colon + 1); }
char path[512];
@@ -553,7 +557,8 @@ static int api_call(const char *suffix, const char *body, char *resp, int cap) {
HINTERNET hS = WinHttpOpen(L"vfy/6.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) return 0;
HINTERNET hC = WinHttpConnect(hS, wHost, port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath, NULL, NULL, NULL, 0) : NULL;
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath, NULL, NULL, NULL,
https ? WINHTTP_FLAG_SECURE : 0) : NULL;
int ok = 0;
if (hR) {
const wchar_t *hdr = L"Content-Type: application/json\r\n";
@@ -962,7 +967,8 @@ static int shell_main(PFN_OEP oep) {
RegisterClassExW(&wc);
int w = (int)((CARD_W + PAD * 2) * g_S), h = (int)((CARD_H + PAD * 2) * g_S);
HWND hwnd = CreateWindowExW(WS_EX_LAYERED | WS_EX_APPWINDOW | WS_EX_TOPMOST, CLS_NAME, L"\x9A8C\x8BC1\x767B\x5F55",
// 不带 WS_EX_TOPMOST:验证窗常驻最前会压住用户所有窗口,像卡死。
HWND hwnd = CreateWindowExW(WS_EX_LAYERED | WS_EX_APPWINDOW, CLS_NAME, L"\x9A8C\x8BC1\x767B\x5F55",
WS_POPUP, 0, 0, w, h, NULL, NULL, wc.hInstance, NULL);
if (!hwnd) return -1;
+1 -1
View File
@@ -23,7 +23,7 @@ mkdir -p "$OUTDIR"
# 导入表按实测产物取:ADVAPI32/bcrypt/COMCTL32/GDI32/gdiplus/KERNEL32/msvcrt/ole32/SHELL32/USER32/WINHTTP
x86_64-w64-mingw32-g++ -std=c++17 -O2 -shared -s \
-DUNICODE -D_UNICODE -D_WIN32_WINNT=0x0601 -D_WIN32_LEAN_AND_MEAN \
-I"$DUILIB_DIR" -I"$DUILIB_DIR/DuiLib" -include "$DUILIB_DIR/shim/compat.h" -fpermissive -w \
-I"$DUILIB_DIR/shim" -I"$DUILIB_DIR" -I"$DUILIB_DIR/DuiLib" -I"$DUILIB_DIR/DuiLib/Core" -I"$DUILIB_DIR/DuiLib/Control" -I"$DUILIB_DIR/DuiLib/Layout" -I"$DUILIB_DIR/DuiLib/Utils" -include "$DUILIB_DIR/shim/compat.h" -fpermissive -w \
-o "$OUTDIR/shell64_dui.dll" "$SRC" "$LIBDUILIB" \
-static -lcomctl32 -lgdiplus -lole32 -loleaut32 -luuid -lshlwapi -limm32 -lwinmm -lversion \
-lgdi32 -luser32 -lwinhttp -ladvapi32 -lbcrypt -Wl,--kill-at
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# 交叉编译 32 位 DuiLib 多皮肤壳 → shell32_dui.dll(x86 对应 shell64_dui.dll)
# 用法: DUILIB_DIR=/path/to/duilib ./build-duilib32.sh [源码] [输出目录]
#
# 与 64 位同源、同皮肤、同交互,只是工具链换成 i686。
#
# 前置:
# 1. apt install g++-mingw-w64-i686
# 2. 编 32 位 libduilib.a(见本文件末尾的说明,老 DuiLib 需要那几处改动)
#
# 产物拷进 backend/internal/protect/assets/shell32_dui.bin,
# 然后 **必须重编 cmd/packthemed 与主服务**(资产是 //go:embed 进去的,
# 不重编的话改了半天什么都没变,字节数一模一样)。
set -euo pipefail
DIR=$(cd "$(dirname "$0")" && pwd)
SRC=${1:-$DIR/shell9_v6.cpp}
DUILIB_DIR=${DUILIB_DIR:-/root/work/duilib-src}
OUTDIR=${2:-$DIR/out}
LIBDUILIB=${LIBDUILIB:-$OUTDIR/libduilib32.a}
[ -f "$LIBDUILIB" ] || {
echo "缺少 $LIBDUILIB(32 位 libduilib.a)。"
echo "先按下面步骤编:"
echo " 1) 用 i686-w64-mingw32-g++ -c 逐个编 $DUILIB_DIR/DuiLib 下的 cpp,"
echo " 排除 UIWebBrowser / UIRichEdit / UIActiveX / UIFlash"
echo " (前三个 mingw 没有对应头,UIFlash 要 atlcomcli.h)"
echo " 2) stb_image.c 必须用 i686-w64-mingw32-gcc 按 C 编(header-only,"
echo " 否则链接时 stbi_load_from_memory 未定义)"
echo " 3) i686-w64-mingw32-ar rcs libduilib32.a *.o"
exit 1
}
mkdir -p "$OUTDIR"
i686-w64-mingw32-g++ -std=c++17 -O2 -shared -s \
-DUNICODE -D_UNICODE -D_WIN32_WINNT=0x0601 -D_WIN32_LEAN_AND_MEAN \
-I"$DUILIB_DIR/shim" -I"$DUILIB_DIR" -I"$DUILIB_DIR/DuiLib" \
-I"$DUILIB_DIR/DuiLib/Core" -I"$DUILIB_DIR/DuiLib/Control" \
-I"$DUILIB_DIR/DuiLib/Layout" -I"$DUILIB_DIR/DuiLib/Utils" \
-include "$DUILIB_DIR/shim/compat.h" -fpermissive -w \
-o "$OUTDIR/shell32_dui.dll" "$SRC" "$LIBDUILIB" \
-static -lcomctl32 -lgdiplus -lole32 -loleaut32 -luuid -lshlwapi -limm32 \
-lwinmm -lversion -lgdi32 -luser32 -lwinhttp -ladvapi32 -lbcrypt -Wl,--kill-at
echo "生成 $OUTDIR/shell32_dui.dll($(stat -c%s "$OUTDIR/shell32_dui.dll") 字节)"
echo "下一步:cp 到 backend/internal/protect/assets/shell32_dui.bin,再 go build ./cmd/packthemed"
@@ -0,0 +1,65 @@
diff --git a/DuiLib/Control/UIEdit.cpp b/DuiLib/Control/UIEdit.cpp
index 4cd3cf8..655f96d 100644
--- a/DuiLib/Control/UIEdit.cpp
+++ b/DuiLib/Control/UIEdit.cpp
@@ -84,14 +84,17 @@ namespace DuiLib
CDuiRect rcPos = m_pOwner->GetPos();
RECT rcInset = m_pOwner->GetTextPadding();
rcPos.left += rcInset.left;
- rcPos.top += rcInset.top;
rcPos.right -= rcInset.right;
- rcPos.bottom -= rcInset.bottom;
- LONG lEditHeight = m_pOwner->GetManager()->GetFontInfo(m_pOwner->GetFont())->tm.tmHeight;
- if( lEditHeight < rcPos.GetHeight() ) {
- rcPos.top += (rcPos.GetHeight() - lEditHeight) / 2;
- rcPos.bottom = rcPos.top + lEditHeight;
- }
+ // 【verify 壳改造】原生 EDIT 的高度仍然取字体行高并垂直居中 ——
+ // 单行 EDIT 不会自己居中文字(我一开始以为会,结果文字贴顶了)。
+ // 高度压成行高带来的「上下露出父窗口底色」问题不在这里解决,
+ // 而是让原生窗口背景透明(见 HandleMessage 的 WM_CTLCOLOREDIT),
+ // 由 DuiLib 自绘的 bkcolor 透上来。
+ LONG lEditHeight = m_pOwner->GetManager()->GetFontInfo(m_pOwner->GetFont())->tm.tmHeight;
+ if( lEditHeight < rcPos.GetHeight() ) {
+ rcPos.top += (rcPos.GetHeight() - lEditHeight) / 2;
+ rcPos.bottom = rcPos.top + lEditHeight;
+ }
CControlUI* pParent = m_pOwner;
RECT rcParent;
@@ -157,24 +160,20 @@ namespace DuiLib
if (m_pOwner->GetManager()->IsLayered() && !m_pOwner->GetManager()->IsPainting()) {
m_pOwner->GetManager()->AddNativeWindow(m_pOwner, m_hWnd);
}
- DWORD clrColor = m_pOwner->GetNativeEditBkColor();
- if( clrColor == 0xFFFFFFFF ) return 0;
+ // 【verify 壳改造】原生 EDIT 一律透明,背景交给 DuiLib 自绘。
+ //
+ // 原生 EDIT 的高度只等于字体行高(CalPos 里做垂直居中 —— 单行 EDIT
+ // 自己不会居中文字),它的背景刷也就只能覆盖中间那一条,上下露出
+ // 父窗口底色。深色皮肤上输入框 #252526、窗口底 #1E1E1E,看着就是
+ // 「输入框里嵌了一条更黑的带子、还占不满」。
+ //
+ // 所以不给原生窗口刷背景,返回 HOLLOW_BRUSH 让它完全透明:底下是
+ // CEditUI 自己画的 bkcolor,颜色跟皮肤永远一致,文字也仍垂直居中。
::SetBkMode((HDC)wParam, TRANSPARENT);
DWORD dwTextColor = m_pOwner->GetTextColor();
::SetTextColor((HDC)wParam, RGB(GetBValue(dwTextColor),GetGValue(dwTextColor),GetRValue(dwTextColor)));
- if (clrColor < 0xFF000000) {
- if (m_hBkBrush != NULL) ::DeleteObject(m_hBkBrush);
- RECT rcWnd = m_pOwner->GetManager()->GetNativeWindowRect(m_hWnd);
- HBITMAP hBmpEditBk = CRenderEngine::GenerateBitmap(m_pOwner->GetManager(), rcWnd, m_pOwner, clrColor);
- m_hBkBrush = ::CreatePatternBrush(hBmpEditBk);
- ::DeleteObject(hBmpEditBk);
- }
- else {
- if (m_hBkBrush == NULL) {
- m_hBkBrush = ::CreateSolidBrush(RGB(GetBValue(clrColor), GetGValue(clrColor), GetRValue(clrColor)));
- }
- }
- return (LRESULT)m_hBkBrush;
+ if (m_hBkBrush != NULL) { ::DeleteObject(m_hBkBrush); m_hBkBrush = NULL; }
+ return (LRESULT)::GetStockObject(HOLLOW_BRUSH);
}
else if( uMsg == WM_PAINT) {
if (m_pOwner->GetManager()->IsLayered()) {
+92
View File
@@ -0,0 +1,92 @@
# DuiLib 本地改动
这份 DuiLib 的完整源码在 Gitea:**`admin/duilib`**(私有),分支 `master`。
```bash
git clone https://git.viaeon.com/admin/duilib.git
```
上游是 `github.com/duilib/duilib`。仓库里多了 mingw 交叉编译适配(`shim/`、控件裁剪)
和下面这个输入框修复。
## 0001-UIEdit-native-edit-centering-and-transparent-bg.patch
修 `<Edit>` 聚焦后的两个现象:**输入框里嵌一条更黑的带子** + **那条带子占不满输入框**。
### 背景:`<Edit>` 是「真 EDIT 子窗口」
老 DuiLib 的 `<Edit>` 不聚焦时由 DuiLib 自绘,**聚焦后在上面叠一个真正的 Windows
EDIT 子窗口**。这个子窗口有两件事要管:
1. **位置**:`CEditWnd::CalPos()` 算出它盖住控件的哪一块
2. **背景**:`WM_CTLCOLOREDIT` 返回的刷子决定它自己怎么刷底色
两个都要对,否则就是上面那两个症状。
### CalPos:高度必须等于字体行高(保持垂直居中)
```cpp
LONG lEditHeight = GetFontInfo(...)->tm.tmHeight; // ≈16px
if (lEditHeight < rcPos.GetHeight()) {
rcPos.top += (rcPos.GetHeight() - lEditHeight) / 2;
rcPos.bottom = rcPos.top + lEditHeight;
}
```
**这段不能删。** 我曾经为了「让它铺满控件」把这几行去掉,结果**文字贴顶** ——
单行 EDIT 并不会自己垂直居中文字。上下内缩(`rcInset.top/bottom`)倒是可以去掉,
这条改动保留了左右内缩、去掉了上下内缩。
### WM_CTLCOLOREDIT:原生窗口一律透明
原实现按 `nativebkcolor` 造纯色刷或位图刷返回。问题在于:原生窗口只有字体行高那么高,
**它的背景刷只能覆盖中间一条**,上下露出父窗口底色。深色皮肤上输入框 `#252526`、
窗口底 `#1E1E1E`,看着就是「嵌了一条更黑的带子」。
改成:
```cpp
::SetBkMode((HDC)wParam, TRANSPARENT);
DWORD dwTextColor = m_pOwner->GetTextColor();
::SetTextColor((HDC)wParam, RGB(...));
if (m_hBkBrush != NULL) { ::DeleteObject(m_hBkBrush); m_hBkBrush = NULL; }
return (LRESULT)::GetStockObject(HOLLOW_BRUSH);
```
原生窗口完全透明 → 底下是 `CEditUI` 自己绘制的 `bkcolor`,颜色跟皮肤永远一致,
文字位置仍由 `CalPos` 保证垂直居中。**两个要求同时满足。**
### 实测(classic 皮肤)
```
输入框蓝框 y=128~167,框中心 147.5
文字行 y=143~152,文字中心 147.5
偏移 +0.0px → 完全垂直居中
纯黑带子行数: 0
```
### 应用方式(如果不想 clone 整个仓库)
```bash
cd <duilib源码目录>
git apply /path/to/0001-UIEdit-native-edit-centering-and-transparent-bg.patch
```
注意源文件是 **CRLF** 行尾。用脚本改这个文件时务必统一成 CRLF,
否则 `git diff` 会把整个文件当成改动(我踩过两次:65 行 vs 1249 行)。
## 重编 libduilib
64 位和 32 位源码同一份(`/root/work/duilib-src`),只是编译器不同:
```bash
/root/work/duilib-build64/build64.sh # → libduilib.a
/root/work/duilib-build32/build32.sh # → libduilib32.a
```
- 排除 `UIWebBrowser` / `UIRichEdit` / `UIActiveX` / `UIFlash`
- `stb_image.c` 必须用 `gcc`(不是 g++)单独编,否则 `stbi_load_from_memory` 未定义
- **改完源码先 `rm -rf obj`**,否则可能吃到缓存的 .o,表现是「改了没生效」
编完核对 `out/shell*.dll` 与 `backend/internal/protect/assets/*.bin` 的 md5 一致,
再确认产物 `.load` 节里内嵌的 DLL md5 也一致。
+493
View File
@@ -0,0 +1,493 @@
#!/usr/bin/env python3
# 生成 7 套「登录 / 注册 / 卡密充值 / 忘记密码」四 tab 皮肤(老 DuiLib,纯 XML)
# 输出:/root/.hermes/cache/scratch/vfyshell/demo/skins_v4.h
import io
OUT = __file__.rsplit("/scripts/", 1)[0] + "/skins_v4.h"
# ------------------------- 面板片段 -------------------------
def p_login(L, IN_BG, IN_FG, IN_BORDER, REM, PRI, PRI_FG, BTN="登录"):
return f''' <VerticalLayout name="panelLogin" height="248">
<Label name="lblUser" text="账号或卡密" textcolor="{L}" height="18" />
<Edit name="editUser" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="12" />
<Label name="lblPass" text="密码" textcolor="{L}" height="18" />
<Edit name="editPass" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" password="true" />
<Control height="12" />
<HorizontalLayout name="rowRemember" height="22">
<Button name="btnRemember" text="[ ] 记住账号" textcolor="{REM}" bkcolor="#00000000" width="104" height="22" />
</HorizontalLayout>
<Control height="14" />
<Button name="btnLogin" text="{BTN}" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="22" margin="0,8,0,0" />
</VerticalLayout>
'''
def p_register(L, IN_BG, IN_FG, IN_BORDER, PRI, PRI_FG, ACC):
return f''' <VerticalLayout name="panelRegister" height="404" visible="false">
<Label text="用户名" textcolor="{L}" height="18" />
<Edit name="regUser" height="38" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="10" />
<Label text="邮箱" textcolor="{L}" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="38" bkcolor="{ACC}" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="10" />
<Label name="lblRegCode" text="邮箱验证码" textcolor="{L}" height="18" />
<Edit name="regCode" height="38" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="{L}" height="18" />
<Edit name="regPass" height="38" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" password="true" />
<Control height="10" />
<Label text="确认密码" textcolor="{L}" height="18" />
<Edit name="regPass2" height="38" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" password="true" />
<Control height="14" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="22" margin="0,8,0,0" />
</VerticalLayout>
'''
def p_card(L, IN_BG, IN_FG, IN_BORDER, PRI, PRI_FG):
return f''' <VerticalLayout name="panelCard" height="250" visible="false">
<Label text="用户名" textcolor="{L}" height="18" />
<Edit name="cardUser" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="12" />
<Label text="卡密" textcolor="{L}" height="18" />
<Edit name="cardKey" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="10" />
<Label text="卡密充入该账号余额,充值后请用账号密码登录" textcolor="{L}" height="18" />
<Control height="14" />
<Button name="btnRecharge" text="立即充值" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Label name="cardTip" text="" textcolor="#FFE08A8A" height="22" margin="0,8,0,0" />
</VerticalLayout>
'''
def p_reset(L, IN_BG, IN_FG, IN_BORDER, PRI, PRI_FG, ACC):
return f''' <VerticalLayout name="panelReset" height="322" visible="false">
<Label name="lblResetCard" text="卡密" textcolor="{L}" height="18" visible="false" />
<Edit name="resetCardKey" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" visible="false" />
<Control name="spResetCard" height="12" visible="false" />
<Label text="邮箱" textcolor="{L}" height="18" />
<HorizontalLayout height="40">
<Edit name="resetEmail" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode2" text="发送验证码" width="104" height="40" bkcolor="{ACC}" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="12" />
<Label text="邮箱验证码" textcolor="{L}" height="18" />
<Edit name="resetCode" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="12" />
<Label text="新密码" textcolor="{L}" height="18" />
<Edit name="resetPass" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" password="true" />
<Control height="14" />
<Button name="btnReset" text="重置密码" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Label name="resetTip" text="" textcolor="#FFE08A8A" height="22" margin="0,8,0,0" />
</VerticalLayout>
'''
def p_overlays(L, IN_BG, IN_FG, IN_BD, PRI, PRI_FG, MUTED):
"""公告 / 更新 / 设备超限 三个覆盖面板:和四个 tab 面板同级,显示时先隐藏它们。"""
return f''' <VerticalLayout name="panelNotice" height="322" visible="false">
<Label text="公 告" textcolor="{PRI}" font="1" height="30" />
<Label name="noticeTitle" text="" textcolor="{IN_FG}" height="26" />
<Control height="6" />
<Label name="noticeBody" text="" textcolor="{L}" height="150" multiline="true" endellipsis="true" />
<HorizontalLayout height="34">
<Button name="btnNoticePrev" text="上一条" width="86" height="32" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
<Control width="8" />
<Button name="btnNoticeNext" text="下一条" width="86" height="32" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
<Control />
<Label name="noticeIdx" text="" textcolor="{MUTED}" width="54" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnNoticeOk" text="我知道了" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
</VerticalLayout>
<VerticalLayout name="panelUpdate" height="300" visible="false">
<Label text="版本更新" textcolor="{PRI}" font="1" height="28" />
<Label name="updTitle" text="" textcolor="{IN_FG}" height="26" />
<Control height="6" />
<Label name="updNotes" text="" textcolor="{L}" height="130" multiline="true" endellipsis="true" />
<Label name="updTip" text="" textcolor="{MUTED}" height="24" />
<HorizontalLayout height="44">
<Button name="btnUpdLater" text="稍后提醒" width="112" height="44" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
<Control width="10" />
<Button name="btnUpdate" text="立即更新" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
</HorizontalLayout>
</VerticalLayout>
<VerticalLayout name="panelDevice" height="386" visible="false">
<Label name="devHead" text="设备数量已满" textcolor="{PRI}" font="1" height="28" />
<Label name="devTitle" text="" textcolor="{IN_FG}" height="24" />
<Control height="6" />
<Label name="lblDevCard" text="卡密" textcolor="{L}" height="18" visible="false" />
<Edit name="devCardKey" height="36" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BD}" inset="10,0,0,0" visible="false" />
<Control name="spDevCard" height="6" visible="false" />
<Control height="6" />
<Label name="devBody" text="" textcolor="{L}" height="150" multiline="true" endellipsis="true" />
<Control height="6" />
<Label text="输入要解绑的设备序号" textcolor="{MUTED}" height="18" />
<Edit name="devIdx" height="36" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BD}" inset="10,0,0,0" />
<Label name="devTip" text="" textcolor="{MUTED}" height="22" />
<HorizontalLayout height="44">
<Button name="btnUnbind" text="解绑该设备" width="118" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Control width="8" />
<Button name="btnUnbindOld" text="解绑最早一台" width="118" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" />
<Control width="8" />
<Button name="btnRetryLogin" text="重试" width="72" height="44" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
<Control width="8" />
<Button name="btnBack" text="返回" width="72" height="44" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
</HorizontalLayout>
</VerticalLayout>
'''
def footer(L, LINK, dev_prefix="设备"):
return f''' <Label name="lblDevice" text="{dev_prefix}" textcolor="{L}" height="18" margin="0,6,0,0" />
'''
# ------------------------- 皮肤 1:dark(下划线 tab) -------------------------
def skin_dark():
T = dict(BG="#FF141418", TITLE_BG="#FF1D1D24", TITLE="#FFF0F0F4", CLOSE="#FF9A9AA6",
TAB_ACT="#FF4EA3E8", TAB_IDLE="#FF9A9AA6", L="#FFB4B4BE",
IN_BG="#FF2A2A33", IN_FG="#FFF4F4F8", IN_BD="#FF474755", REM="#FFB4B4BE",
PRI="#FF146FB8", PRI_FG="#FFFFFFFF", ACC="#FF2F6E4E", DEV="#FF5C5C68")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="470,436" caption="0,0,-1,44" mininfo="470,380" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FF32323A" bordersize="1">
<HorizontalLayout height="44" bkcolor="{T['TITLE_BG']}">
<Label name="lblTitle" text="软件授权验证" textcolor="{T['TITLE']}" font="1" width="260" textpadding="20,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="40" height="44" textcolor="{T['CLOSE']}" bkcolor="{T['TITLE_BG']}" hotbkcolor="#33FFFFFF" pushedbkcolor="#55FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="44" inset="20,0,20,0">
<VerticalLayout width="84">
<Button name="tabLogin" text="登录" height="42" bkcolor="#00000000" textcolor="{T['TAB_ACT']}" font="1" />
<Control name="lineLogin" height="2" bkcolor="{T['TAB_ACT']}" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabRegister" text="注册" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineRegister" height="2" bkcolor="#00000000" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabCard" text="卡密充值" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineCard" height="2" bkcolor="#00000000" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabReset" text="忘记密码" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineReset" height="2" bkcolor="#00000000" />
</VerticalLayout>
<Control />
</HorizontalLayout>
<VerticalLayout inset="24,14,24,16">
<Label name="lblApp" text="演示程序" textcolor="{T['TAB_ACT']}" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['REM'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['TAB_ACT'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 2:light(分段按钮 tab) -------------------------
def skin_classic():
# classic:照搬原 Direct2D 壳的 VS Code 暗色(#1E1E1E 卡片 / #0E639C 主色)
T = dict(BG="#FF1E1E1E", TITLE_BG="#FF252527", TITLE="#FFE6E6E6", CLOSE="#FF9D9D9D",
TAB_ACT="#FF0E639C", TAB_IDLE="#FF9D9D9D", L="#FFB4B4BE",
IN_BG="#FF252526", IN_FG="#FFE6E6E6", IN_BD="#FF3F3F46", REM="#FFB4B4BE",
PRI="#FF0E639C", PRI_FG="#FFFFFFFF", ACC="#FF0F7B4F", DEV="#FF9D9D9D")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="470,436" caption="0,0,-1,44" mininfo="470,380" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FF32323A" bordersize="1">
<HorizontalLayout height="44" bkcolor="{T['TITLE_BG']}">
<Label name="lblTitle" text="软件授权验证" textcolor="{T['TITLE']}" font="1" width="260" textpadding="20,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="40" height="44" textcolor="{T['CLOSE']}" bkcolor="{T['TITLE_BG']}" hotbkcolor="#33FFFFFF" pushedbkcolor="#55FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="44" inset="20,0,20,0">
<VerticalLayout width="84">
<Button name="tabLogin" text="登录" height="42" bkcolor="#00000000" textcolor="{T['TAB_ACT']}" font="1" />
<Control name="lineLogin" height="2" bkcolor="{T['TAB_ACT']}" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabRegister" text="注册" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineRegister" height="2" bkcolor="#00000000" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabCard" text="卡密充值" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineCard" height="2" bkcolor="#00000000" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabReset" text="忘记密码" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineReset" height="2" bkcolor="#00000000" />
</VerticalLayout>
<Control />
</HorizontalLayout>
<VerticalLayout inset="24,14,24,16">
<Label name="lblApp" text="演示程序" textcolor="{T['TAB_ACT']}" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['REM'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['TAB_ACT'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 2:light(分段按钮 tab) -------------------------
def skin_light():
T = dict(BG="#FFFAFAFC", TITLE="#FF1F1F24", CLOSE="#FF6B6B75", L="#FF4B5563",
IN_BG="#FFF1F3F7", IN_FG="#FF1F2430", IN_BD="#FFC3CBD8", REM="#FF4B5563",
PRI="#FF1B6FD6", PRI_FG="#FFFFFFFF", ACC="#FF128A5B", SEG_ACT="#FF1B6FD6",
SEG_IDLE="#FFEBEFF6", SEG_ACT_FG="#FFFFFFFF", SEG_IDLE_FG="#FF5B6270", DEV="#FF8A8F99")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="470,436" caption="0,0,-1,44" mininfo="470,380" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FFDCDCE3" bordersize="1">
<HorizontalLayout height="44" bkcolor="#FFFFFFFF">
<Label name="lblTitle" text="软件授权验证" textcolor="{T['TITLE']}" font="1" width="260" textpadding="20,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="40" height="44" textcolor="{T['CLOSE']}" bkcolor="#FFFFFFFF" hotbkcolor="#14000000" pushedbkcolor="#22000000" />
</HorizontalLayout>
<HorizontalLayout height="12" />
<HorizontalLayout height="38" inset="24,0,24,0">
<Button name="tabLogin" text="登录" height="38" bkcolor="{T['SEG_ACT']}" textcolor="{T['SEG_ACT_FG']}" font="1" />
<Control width="6" />
<Button name="tabRegister" text="注册" height="38" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
<Control width="6" />
<Button name="tabCard" text="卡密充值" height="38" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
<Control width="6" />
<Button name="tabReset" text="忘记密码" height="38" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
</HorizontalLayout>
<VerticalLayout inset="24,16,24,16">
<Label name="lblApp" text="演示程序" textcolor="{T['PRI']}" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['REM'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['PRI'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 3:split(左品牌栏 + 右侧文字 tab) -------------------------
def skin_split():
T = dict(BG="#FF12151A", SIDE="#FF1A2230", ACT="#FF4CC2FF", IDLE="#FF97A5B4", L="#FF8794A3",
IN_BG="#FF1A1F27", IN_FG="#FFF2F6FA", IN_BD="#FF2E343D", PRI="#FF2C7BE5",
PRI_FG="#FFFFFFFF", ACC="#FF2B6A50", DEV="#FF7E8B99")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="680,452" caption="0,0,0,0" mininfo="680,400" bkcolor="{T['BG']}">
<HorizontalLayout bkcolor="{T['BG']}" bordercolor="#FF282D35" bordersize="1">
<VerticalLayout width="196" bkcolor="{T['SIDE']}">
<HorizontalLayout height="44" inset="24,0,0,0">
<Label text="VFY" textcolor="{T['ACT']}" font="1" width="120" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="24,4,24,0">
<Label name="lblTitle" text="软件授权验证" textcolor="#FFC8D3E0" height="28" font="1" />
<Label text="SOFTWARE LICENSE" textcolor="#FF63707E" height="20" />
<Label text="登录后绑定本机设备" textcolor="#FF4C5A68" height="20" margin="0,14,0,0" />
</VerticalLayout>
<VerticalLayout />
<HorizontalLayout height="28" inset="24,0,24,16">
<Label text="v9 · DuiLib" textcolor="#FF4A5764" />
</HorizontalLayout>
</VerticalLayout>
<VerticalLayout>
<HorizontalLayout height="44" inset="24,0,16,0">
<Button name="tabLogin" text="登录" width="72" height="44" bkcolor="#00000000" textcolor="{T['ACT']}" font="1" />
<Button name="tabRegister" text="注册" width="72" height="44" bkcolor="#00000000" textcolor="{T['IDLE']}" />
<Button name="tabCard" text="卡密充值" width="92" height="44" bkcolor="#00000000" textcolor="{T['IDLE']}" />
<Button name="tabReset" text="忘记密码" width="92" height="44" bkcolor="#00000000" textcolor="{T['IDLE']}" />
<Button name="btnClose" text="×" font="1" width="40" height="44" textcolor="#FF8E9BAA" bkcolor="{T['BG']}" hotbkcolor="#22FFFFFF" />
</HorizontalLayout>
<VerticalLayout inset="24,4,24,14">
<Label name="lblApp" text="演示程序" textcolor="#FFF6FAFF" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['ACT'])}
</VerticalLayout>
</VerticalLayout>
</HorizontalLayout>
</Window>'''
# ------------------------- 皮肤 4:card(顶部色条 + 卡片内段按钮) -------------------------
def skin_card():
T = dict(BG="#FFF5F6F9", BAR="#FF3B2BD6", L="#FF4B5563", IN_BG="#FFFFFFFF", IN_FG="#FF1F2430",
IN_BD="#FFC9D1DC", PRI="#FF3B2BD6", PRI_FG="#FFFFFFFF", ACC="#FF128A5B",
SEG_IDLE="#FFE8E6FF", SEG_IDLE_FG="#FF5B56A8", DEV="#FF8A8F99")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="720,460" caption="0,0,-1,88" mininfo="720,400" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FFD7DBE3" bordersize="1">
<HorizontalLayout height="88" bkcolor="{T['BAR']}">
<VerticalLayout inset="28,16,0,0">
<Label name="lblTitle" text="软件授权验证" textcolor="#FFFFFFFF" font="1" height="32" />
<Label name="lblApp" text="演示程序" textcolor="#FFD9D4FF" height="22" />
</VerticalLayout>
<Control />
<Button name="btnClose" text="×" font="1" width="46" height="88" textcolor="#FFEDEBFF" bkcolor="{T['BAR']}" hotbkcolor="#22000000" />
</HorizontalLayout>
<HorizontalLayout height="50" inset="28,12,28,0">
<Button name="tabLogin" text="登录" height="36" bkcolor="#FFFFFFFF" textcolor="{T['PRI']}" font="1" />
<Control width="8" />
<Button name="tabRegister" text="注册" height="36" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
<Control width="8" />
<Button name="tabCard" text="卡密充值" height="36" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
<Control width="8" />
<Button name="tabReset" text="忘记密码" height="36" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
</HorizontalLayout>
<HorizontalLayout inset="28,14,28,16">
<VerticalLayout width="248">
<Label text="账号安全" textcolor="#FF1F2430" height="24" font="1" />
<Label text="登录后账号与本机设备绑定," textcolor="{T['L']}" height="20" />
<Label text="超出设备上限时请先下线一台。" textcolor="{T['L']}" height="20" />
<Control height="12" />
{footer(T['DEV'], T['PRI'])}
</VerticalLayout>
<Control width="24" />
<Control width="1" bkcolor="#FFE3E6EC" />
<Control width="24" />
<VerticalLayout>
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
</VerticalLayout>
</HorizontalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 5:industrial(标题栏内 tab) -------------------------
def skin_industrial():
T = dict(BG="#FF0A1520", BAR="#FF10304C", ACT="#FF1A5A8C", L="#FF9FC0D8",
IN_BG="#FF14304A", IN_FG="#FFEAF6FF", IN_BD="#FF23567F", PRI="#FF1F6FB2",
PRI_FG="#FFFFFFFF", ACC="#FF1B4A3C", DEV="#FF5F89A6")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="600,452" caption="0,0,-1,46" mininfo="600,400" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FF1F4E79" bordersize="1">
<HorizontalLayout height="46" bkcolor="{T['BAR']}">
<Label name="lblTitle" text="软件授权验证" textcolor="#FF7FD1FF" font="1" width="200" textpadding="18,0,0,0" />
<Control />
<Button name="tabLogin" text="LOGIN" width="76" height="46" bkcolor="{T['ACT']}" textcolor="#FFFFFFFF" />
<Button name="tabRegister" text="SIGN UP" width="84" height="46" bkcolor="#00000000" textcolor="#FF9FC8E6" />
<Button name="tabCard" text="CARD" width="66" height="46" bkcolor="#00000000" textcolor="#FF9FC8E6" />
<Button name="tabReset" text="RESET" width="70" height="46" bkcolor="#00000000" textcolor="#FF9FC8E6" />
<Button name="btnClose" text="×" font="1" width="44" height="46" textcolor="#FFBEE3FF" bkcolor="{T['BAR']}" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<VerticalLayout inset="24,14,24,14">
<Label name="lblApp" text="演示程序" textcolor="#FFA8D4F0" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['PRI'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 6:terminal(命令式 tab) -------------------------
def skin_terminal():
T = dict(BG="#FF0B0F0C", BAR="#FF101710", ACT="#FF7FE39B", L="#FF7FAE90",
IN_BG="#FF16211A", IN_FG="#FFD7F5DF", IN_BD="#FF2B3A2D", PRI="#FF1B7A4E",
PRI_FG="#FFFFFFFF", ACC="#FF234A33", DEV="#FF6F9E80")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="620,446" caption="0,0,-1,38" mininfo="620,400" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="{T['IN_BD']}" bordersize="1">
<HorizontalLayout height="38" bkcolor="{T['BAR']}" inset="0,0,8,0">
<Label name="lblTitle" text="软件授权验证" textcolor="{T['ACT']}" width="220" textpadding="14,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="38" height="38" textcolor="#FF7FB08C" bkcolor="{T['BAR']}" hotbkcolor="#22FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="34" bkcolor="#FF0E150F" inset="8,0,8,0">
<Button name="tabLogin" text="login" width="76" height="34" bkcolor="#00000000" textcolor="{T['ACT']}" font="1" />
<Button name="tabRegister" text="register" width="92" height="34" bkcolor="#00000000" textcolor="{T['L']}" />
<Button name="tabCard" text="card" width="66" height="34" bkcolor="#00000000" textcolor="{T['L']}" />
<Button name="tabReset" text="reset" width="70" height="34" bkcolor="#00000000" textcolor="{T['L']}" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="16,10,16,12">
<Label name="lblApp" text="# 演示程序" textcolor="{T['ACT']}" height="28" font="2" />
<Control height="6" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'], "[ 执行登录 ]")}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['ACT'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 7:compact(左列竖排 tab) -------------------------
def skin_compact():
T = dict(BG="#FF11151A", BAR="#FF161C22", ACT="#FF2E9E6B", L="#FF95A7B8",
IN_BG="#FF1B232B", IN_FG="#FFFFFFFF", IN_BD="#FF32404E", PRI="#FF2E9E6B",
PRI_FG="#FFFFFFFF", ACC="#FF234A33", SEL="#FF1C6142", DEV="#FF8698A8")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="760,392" caption="0,0,-1,38" mininfo="760,300" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FF2A3440" bordersize="1">
<HorizontalLayout height="38" bkcolor="{T['BAR']}">
<Label name="lblTitle" text="软件授权验证" textcolor="#FFA8BCCE" width="160" textpadding="16,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="38" height="38" textcolor="#FFA8BCCE" bkcolor="{T['BAR']}" hotbkcolor="#22FFFFFF" />
</HorizontalLayout>
<HorizontalLayout inset="16,12,16,12">
<VerticalLayout width="176">
<Label name="lblApp" text="演示程序" textcolor="#FFF2F8FF" height="28" font="2" />
<Control height="10" />
<Button name="tabLogin" text="登录" width="100" height="32" bkcolor="{T['SEL']}" textcolor="#FFFFFFFF" />
<Control height="6" />
<Button name="tabRegister" text="注册" width="100" height="32" bkcolor="{T['BAR']}" textcolor="#FF9FB3C8" />
<Control height="6" />
<Button name="tabCard" text="卡密充值" width="100" height="32" bkcolor="{T['BAR']}" textcolor="#FF9FB3C8" />
<Control height="6" />
<Button name="tabReset" text="忘记密码" width="100" height="32" bkcolor="{T['BAR']}" textcolor="#FF9FB3C8" />
<VerticalLayout />
{footer(T['DEV'], T['ACT'])}
</VerticalLayout>
<Control width="14" />
<Control width="1" bkcolor="#FF2A3440" />
<Control width="14" />
<VerticalLayout>
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
</VerticalLayout>
</HorizontalLayout>
</VerticalLayout>
</Window>'''
SKINS = [("classic", skin_classic(), 470, 436),
("dark", skin_dark(), 470, 436), ("light", skin_light(), 470, 436),
("split", skin_split(), 680, 452), ("card", skin_card(), 720, 460),
("industrial", skin_industrial(), 600, 452), ("terminal", skin_terminal(), 620, 446),
("compact", skin_compact(), 760, 392)]
with io.open(OUT, "w", encoding="utf-8") as f:
f.write("// 由 gen_skins_v4.py 生成,不要手改\n#pragma once\n\n")
for name, xml, w, h in SKINS:
f.write(f'static const char *kSkin_{name} = R"SKIN({xml})SKIN";\n\n')
f.write('struct SkinDef { const char *name; const char *xml; int w, h; };\n')
f.write('static const SkinDef kSkins[] = {\n')
for name, xml, w, h in SKINS:
f.write(f' {{ "{name}", kSkin_{name}, {w}, {h} }},\n')
f.write(' { NULL, NULL, 0, 0 }\n};\n')
print("skins_v4.h 已生成(4 tab × 7 皮肤)")
for name, xml, w, h in SKINS:
print(f" {name:11s} {w}x{h} {len(xml)} 字节")
+24
View File
@@ -0,0 +1,24 @@
# 历史皮肤生成脚本(已废弃)
`gen_skins.py` / `gen_skins_v3.py` / `gen_skins_v4.py` 是最早那几版皮肤生成器,
从 Python 拼 XML 输出成 `skins_v*.h`。留在这里只为参考它们当时的写法。
**不要再用它们生成 `skins_v4.h`。**
原因:这些副本停在 2026-11-23,而仓库里的 `skins_v4.h` 是 11-24 更晚一版生成的
(Button 多 112 个、多了 `lblTitle`,设备管理页/公告页都是后加的 UI)。
生成最终版的那个脚本已经丢了,用这些旧脚本重新生成会**丢掉后面所有改动**。
现在的做法:`skins_v4.h` 就是**源文件**,直接改它。
改完记得同步到产物:
```bash
cd shell/duilib
LIBDUILIB=/tmp/duilib/libduilib.a ./build-duilib.sh # 64 位
LIBDUILIB=/root/work/duilib-build32/libduilib32.a ./build-duilib32.sh # 32 位
cp out/shell64_dui.dll ../backend/internal/protect/assets/shell64_dui.bin
cp out/shell32_dui.dll ../backend/internal/protect/assets/shell32_dui.bin
```
两个 `LIBDUILIB` 不能搞混:64 位用 `/tmp/duilib/libduilib.a`,32 位用
`/root/work/duilib-build32/libduilib32.a`。混了会报满屏
`undefined reference to DuiLib::CPaintManagerUI::*`,看着像 DuiLib 没编。
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
"""生成 NIM DuiLib 壳用的 6 套皮肤:XML + 透明 PNG → C++ 头文件 skins_data.h"""
import os, io
PNG_DIR = "/tmp/skingen/out"
OUT_H = "/root/.hermes/cache/scratch/vfyshell/demo/skins_data.h"
SKIN_DIR = "/tmp/vfyskin" # 本地预览用(Wine 里直接指这里也行)
GLOBAL_XML = '''<?xml version="1.0" encoding="UTF-8"?>
<Global>
<Font id="f12" name="Microsoft YaHei UI" size="12" default="true"/>
<Font id="f13" name="Microsoft YaHei UI" size="13"/>
<Font id="f14" name="Microsoft YaHei UI" size="14"/>
<Font id="f18" name="Microsoft YaHei UI" size="18" bold="true"/>
<Font id="f22" name="Microsoft YaHei UI" size="22" bold="true"/>
<TextColor name="white" value="#FFFFFFFF"/>
<TextColor name="gray" value="#FF8A8A8A"/>
</Global>
'''
# ---------------- 纯 XML 皮肤(无图片) ----------------
DARK = '''<?xml version="1.0" encoding="UTF-8"?>
<Window size="470,330" caption="0,0,-1,40" mininfo="470,330" bkcolor="#FF1B1B1B">
<VBox bkcolor="#FF1B1B1B">
<HBox height="40" bkcolor="#FF252526">
<Label name="lblTitle" text="软件授权验证" textcolor="#FFE8E8E8" font="f14" padding="16,0,0,0" valign="center"/>
<Control />
<Button name="btnClose" width="40" height="40" text="X" textcolor="#FFCCCCCC" bkcolor="#FF252526" font="f14"/>
</HBox>
<VBox padding="26,18,26,16">
<Label name="lblApp" height="26" text="演示程序" textcolor="#FF7FB8E0" font="f18" valign="center"/>
<Label height="22" text="请输入卡密激活本机" textcolor="#FF9A9A9A" font="f12" valign="center"/>
<Control height="10"/>
<RichEdit name="editCard" height="38" bkcolor="#FF2D2D30" textcolor="#FFFFFFFF" font="f13" padding="10,0,0,0" valign="center"/>
<Control height="14"/>
<Button name="btnLogin" height="40" text="登 录" textcolor="#FFFFFFFF" bkcolor="#FF0E639C" font="f14"/>
<Label name="lblTip" height="22" margin="0,12,0,0" text="设备指纹:" textcolor="#FF8A8A8A" font="f12" valign="center"/>
</VBox>
</VBox>
</Window>
'''
LIGHT = '''<?xml version="1.0" encoding="UTF-8"?>
<Window size="470,330" caption="0,0,-1,40" mininfo="470,330" bkcolor="#FFF7F7F7">
<VBox bkcolor="#FFF7F7F7">
<HBox height="40" bkcolor="#FFFFFFFF">
<Label name="lblTitle" text="软件授权验证" textcolor="#FF1F1F1F" font="f14" padding="16,0,0,0" valign="center"/>
<Control />
<Button name="btnClose" width="40" height="40" text="X" textcolor="#FF666666" bkcolor="#FFFFFFFF" font="f14"/>
</HBox>
<VBox padding="26,18,26,16">
<Label name="lblApp" height="26" text="演示程序" textcolor="#FF0067B8" font="f18" valign="center"/>
<Label height="22" text="请输入卡密激活本机" textcolor="#FF666666" font="f12" valign="center"/>
<Control height="10"/>
<RichEdit name="editCard" height="38" bkcolor="#FFFFFFFF" textcolor="#FF1F1F1F" font="f13" padding="10,0,0,0" valign="center"/>
<Control height="14"/>
<Button name="btnLogin" height="40" text="登录" textcolor="#FFFFFFFF" bkcolor="#FF0078D4" font="f14"/>
<Label name="lblTip" height="22" margin="0,12,0,0" text="设备指纹:" textcolor="#FF8A8A8A" font="f12" valign="center"/>
</VBox>
</VBox>
</Window>
'''
INDUSTRIAL = '''<?xml version="1.0" encoding="UTF-8"?>
<Window size="520,350" caption="0,0,-1,44" mininfo="520,350" bkcolor="#FF0A1622">
<VBox bkcolor="#FF0A1622">
<HBox height="44" bkcolor="#FF113250">
<Label name="lblTitle" text="DEVICE AUTHORIZATION" textcolor="#FF7FD1FF" font="f14" padding="16,0,0,0" valign="center"/>
<Control />
<Button name="btnClose" width="44" height="44" text="X" textcolor="#FFBEE3FF" bkcolor="#FF113250" font="f14"/>
</HBox>
<VBox padding="28,20,28,18">
<Label name="lblApp" height="26" text="演示程序 / DEVICE LICENSING" textcolor="#FF6FA8C8" font="f18" valign="center"/>
<Control height="12"/>
<HBox height="42" bkcolor="#FF0E2438">
<Label width="64" text="卡密" textcolor="#FF8FC4E6" font="f13" padding="12,0,0,0" valign="center"/>
<RichEdit name="editCard" textcolor="#FFFFFFFF" bkcolor="#FF0E2438" font="f13" valign="center"/>
</HBox>
<Control height="16"/>
<HBox height="44">
<Button name="btnLogin" text="激活本机" textcolor="#FFFFFFFF" bkcolor="#FF1F6FB2" font="f14"/>
<Control width="12"/>
<Button name="btnQuit" text="退出" textcolor="#FFBEE3FF" bkcolor="#FF22384F" font="f14"/>
</HBox>
<Label name="lblTip" height="22" margin="0,12,0,0" text="设备指纹:" textcolor="#FF5F89A6" font="f12" valign="center"/>
</VBox>
</VBox>
</Window>
'''
# ---------------- PNG 皮肤(整窗像素 alpha) ----------------
def png_skin(theme, title, title_color, app_color, tip_color, prompt, btn_text, btn_color, has_quit, title_font="f14"):
quit_btn = ('<Control width="10"/>\n <Button name="btnQuit" width="120" height="44" text="退出" '
'textcolor="#FFD8D8D8" bkcolor="#33FFFFFF" font="f13"/>') if has_quit else ""
return f'''<?xml version="1.0" encoding="UTF-8"?>
<Window size="520,356" caption="0,0,520,46" mininfo="520,356" bktrans="true" bkimage="file='{theme}_bg.png'">
<VBox>
<HBox height="46">
<Label name="lblTitle" text="{title}" textcolor="{title_color}" font="{title_font}" padding="20,0,0,0" valign="center"/>
<Control />
<Button name="btnClose" width="34" height="22" margin="0,12,16,0" bkimage="file='{theme}_close.png'"/>
</HBox>
<VBox padding="34,12,34,20">
<Label name="lblApp" height="28" text="演示程序" textcolor="{app_color}" font="f18" valign="center"/>
<Label height="20" text="{prompt}" textcolor="{tip_color}" font="f12" valign="center"/>
<Control height="12"/>
<RichEdit name="editCard" height="42" bkimage="file='{theme}_edit.png'" textcolor="#FFFFFFFF" font="f13" padding="12,0,0,0" valign="center"/>
<Control height="16"/>
<HBox height="44">
<Button name="btnLogin" width="240" height="44" text="{btn_text}" textcolor="{btn_color}" font="f14"
bkimage="file='{theme}_btn.png'" hotbkimage="file='{theme}_btn_hot.png'" pushedbkimage="file='{theme}_btn_down.png'"/>
{quit_btn}
</HBox>
<Label name="lblTip" height="22" margin="0,14,0,0" text="设备指纹:" textcolor="{tip_color}" font="f12" valign="center"/>
</VBox>
</VBox>
</Window>
'''
NEBULA = png_skin("nebula", "NEBULA · 授权验证", "#FFD9CCFF", "#FFB9A6FF", "#FF9C8FC7",
"请输入卡密激活本机", "激活授权", "#FFFFFFFF", True)
ONYX = png_skin("onyx", "ONYX · 授权验证", "#FFE6C55C", "#FFE6C55C", "#FF9C8A5A",
"请输入卡密激活本机", "激 活", "#FF12100A", True)
AURORA = png_skin("aurora", "AURORA · 授权验证", "#FFA8F0DC", "#FF7FF0CC", "#FF6FA898",
"请输入卡密激活本机", "激活授权", "#FF04231F", True)
THEMES = {
"dark": (DARK, []),
"light": (LIGHT, []),
"industrial": (INDUSTRIAL, []),
"nebula": (NEBULA, ["nebula_bg.png", "nebula_btn.png", "nebula_btn_hot.png", "nebula_btn_down.png", "nebula_edit.png", "nebula_close.png"]),
"onyx": (ONYX, ["onyx_bg.png", "onyx_btn.png", "onyx_btn_hot.png", "onyx_btn_down.png", "onyx_edit.png", "onyx_close.png"]),
"aurora": (AURORA, ["aurora_bg.png", "aurora_btn.png", "aurora_btn_hot.png", "aurora_btn_down.png", "aurora_edit.png", "aurora_close.png"]),
}
# ---------------- 输出 C++ 头 ----------------
files = [] # (name, bytes)
files.append(("global.xml", GLOBAL_XML.encode("utf-8")))
for theme, (xml, pngs) in THEMES.items():
files.append((f"{theme}.xml", xml.encode("utf-8")))
for p in pngs:
path = os.path.join(PNG_DIR, p)
if not os.path.exists(path):
raise SystemExit(f"缺图片: {path}")
files.append((p, open(path, "rb").read()))
def c_array(name, data):
lines = [f"static const unsigned char {name}[] = {{"]
for i in range(0, len(data), 20):
lines.append(" " + ",".join(str(b) for b in data[i:i+20]) + ",")
lines.append("};")
return "\n".join(lines)
with io.open(OUT_H, "w", encoding="utf-8") as f:
f.write("// 由 gen_skins.py 自动生成,不要手改\n")
f.write("#pragma once\n\n")
for idx, (name, data) in enumerate(files):
var = "s" + str(idx)
f.write(c_array(var, data) + "\n")
f.write(f"// {name} ({len(data)} B)\n\n")
f.write("struct SkinFile { const char *name; const unsigned char *data; unsigned int size; };\n")
f.write("static const SkinFile kSkins[] = {\n")
for idx, (name, data) in enumerate(files):
f.write(f' {{ "{name}", s{idx}, {len(data)} }},\n')
f.write(" { NULL, NULL, 0 },\n};\n\n")
f.write(f'static const char *kThemeList[] = {{ "dark","light","industrial","nebula","onyx","aurora", NULL }};\n')
# ---------------- 同时铺一份到本地目录,方便 Wine 里直接看 ----------------
for theme, (xml, pngs) in THEMES.items():
d = os.path.join(SKIN_DIR, theme)
os.makedirs(d, exist_ok=True)
open(os.path.join(d, "global.xml"), "w", encoding="utf-8").write(GLOBAL_XML)
open(os.path.join(d, theme + ".xml"), "w", encoding="utf-8").write(xml)
for p in pngs:
open(os.path.join(d, p), "wb").write(open(os.path.join(PNG_DIR, p), "rb").read())
total = sum(len(d) for _, d in files)
print(f"skins_data.h: {len(files)} 个文件 / {total/1024:.0f} KB")
for n, d in files:
print(f" {n:22s} {len(d):>7} B")
@@ -0,0 +1,358 @@
#!/usr/bin/env python3
# 生成 7 套「登录 / 注册」双面板皮肤(老 DuiLib,纯 XML 属性,不依赖图片)
# 输出:/root/.hermes/cache/scratch/vfyshell/demo/skins_v3.h
import io
OUT = "/root/.hermes/cache/scratch/vfyshell/demo/skins_v3.h"
# ---------- 公共片段 ----------
def titlebar(bg, title_color, btn_color, height=44, inset=20, close_w=38):
return f''' <HorizontalLayout height="{height}" bkcolor="{bg}">
<Label text="软件授权验证" textcolor="{title_color}" font="1" inset="{inset},0,0,0" />
<Control />
<Button name="btnClose" text="X" width="{close_w}" height="{height}" textcolor="{btn_color}"
bkcolor="{bg}" hotbkcolor="#33FFFFFF" pushedbkcolor="#66FFFFFF" />
</HorizontalLayout>
'''
def tab_underline(idle, active, bg, y=0):
"""下划线式 tab:当前项下方一条主色线"""
return f''' <HorizontalLayout height="42" bkcolor="{bg}">
<VerticalLayout width="86">
<Button name="tabLogin" text="登录" textcolor="{active}" bkcolor="#00000000" height="40" />
<Control height="2" bkcolor="{active}" />
</VerticalLayout>
<VerticalLayout width="86">
<Button name="tabRegister" text="注册" textcolor="{idle}" bkcolor="#00000000" height="40" />
<Control height="2" bkcolor="#00000000" name="tabRegLine" />
</VerticalLayout>
</HorizontalLayout>
'''
def login_fields(label, inp_bg, inp_fg, inp_native, inp_border, remember_color, primary, btn_text_color, hint, tab_hint=""):
return f''' <Label text="账号或卡密" textcolor="{label}" height="18" />
<Edit name="editUser" height="40" bkcolor="{inp_bg}" nativebkcolor="{inp_native}" textcolor="{inp_fg}" bordercolor="{inp_border}" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="{label}" height="18" />
<Edit name="editPass" height="40" bkcolor="{inp_bg}" nativebkcolor="{inp_native}" textcolor="{inp_fg}" bordercolor="{inp_border}" inset="10,0,0,0" password="true" />
<Control height="10" />
<HorizontalLayout height="22">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="{remember_color}" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="{remember_color}" bkcolor="#00000000" width="78" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnLogin" text="{hint}" height="44" bkcolor="{primary}" textcolor="{btn_text_color}" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
'''
def reg_fields(label, inp_bg, inp_fg, inp_native, inp_border, primary, btn_text_color, accent):
return f''' <Label text="用户名" textcolor="{label}" height="18" />
<Edit name="regUser" height="34" bkcolor="{inp_bg}" nativebkcolor="{inp_native}" textcolor="{inp_fg}" bordercolor="{inp_border}" inset="10,0,0,0" />
<Control height="6" />
<Label text="邮箱" textcolor="{label}" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="{inp_bg}" nativebkcolor="{inp_native}" textcolor="{inp_fg}" bordercolor="{inp_border}" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="34" bkcolor="{accent}" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<Label text="邮箱验证码" textcolor="{label}" height="18" />
<Edit name="regCode" height="34" bkcolor="{inp_bg}" nativebkcolor="{inp_native}" textcolor="{inp_fg}" bordercolor="{inp_border}" inset="10,0,0,0" />
<Control height="6" />
<Label text="密码" textcolor="{label}" height="18" />
<Edit name="regPass" height="34" bkcolor="{inp_bg}" nativebkcolor="{inp_native}" textcolor="{inp_fg}" bordercolor="{inp_border}" inset="10,0,0,0" password="true" />
<Control height="6" />
<Label text="确认密码" textcolor="{label}" height="18" />
<Edit name="regPass2" height="34" bkcolor="{inp_bg}" nativebkcolor="{inp_native}" textcolor="{inp_fg}" bordercolor="{inp_border}" inset="10,0,0,0" password="true" />
<Control height="12" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="{primary}" textcolor="{btn_text_color}" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
'''
def footer(dev_color, link_color):
return f''' <Control height="6" />
<Label name="lblDevice" text="设备" textcolor="{dev_color}" height="18" />
<HorizontalLayout height="24">
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="{link_color}" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="{link_color}" bkcolor="#00000000" />
<Control />
</HorizontalLayout>
'''
# ---------------- 1. dark:下划线 tab,竖排 ----------------
DARK = f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="452,548" caption="0,0,-1,44" mininfo="452,548" bkcolor="#FF141418">
<VerticalLayout bkcolor="#FF141418" bordercolor="#FF32323A" bordersize="1">
{titlebar("#FF1D1D24", "#FFF0F0F4", "#FF9A9AA6")}
{tab_underline("#FF85858F", "#FF4EA3E8", "#FF1D1D24")}
<VerticalLayout inset="26,14,26,14">
<Label name="lblApp" text="演示程序" textcolor="#FF6FB6E8" height="26" font="1" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
{login_fields("#FFB4B4BE", "#FF2A2A33", "#FFF4F4F8", "#FF2A2A33", "#FF474755", "#FFB4B4BE", "#FF146FB8", "#FFFFFFFF", "登 录")}
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
{reg_fields("#FFB4B4BE", "#FF2A2A33", "#FFF4F4F8", "#FF2A2A33", "#FF474755", "#FF1F8A5B", "#FFFFFFFF", "#FF2F6E4E")}
</VerticalLayout>
{footer("#FF5C5C68", "#FF7FA5CC")}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ---------------- 2. light:分段按钮 tab,竖排 ----------------
LIGHT = f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="452,548" caption="0,0,-1,44" mininfo="452,548" bkcolor="#FFFAFAFC">
<VerticalLayout bkcolor="#FFFAFAFC" bordercolor="#FFDCDCE3" bordersize="1">
{titlebar("#FFFFFFFF", "#FF1F1F24", "#FF6B6B75")}
<HorizontalLayout height="20" />
<HorizontalLayout height="42" inset="26,0,26,0">
<Button name="tabLogin" text="登录" width="100" height="40" bkcolor="#FF1B6FD6" textcolor="#FFFFFFFF" font="1" />
<Control width="8" />
<Button name="tabRegister" text="注册" width="100" height="40" bkcolor="#FFEDF0F5" textcolor="#FF5B6270" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="26,16,26,14">
<Label name="lblApp" text="演示程序" textcolor="#FF1B6FD6" height="26" font="1" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
{login_fields("#FF4B5563", "#FFF1F3F7", "#FF1F2430", "#FFF1F3F7", "#FFC3CBD8", "#FF4B5563", "#FF1B6FD6", "#FFFFFFFF", "登录")}
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
{reg_fields("#FF4B5563", "#FFF1F3F7", "#FF1F2430", "#FFF1F3F7", "#FFC3CBD8", "#FF128A5B", "#FFFFFFFF", "#FFD8EAE0")}
</VerticalLayout>
{footer("#FF8A8F99", "#FF3B62B8")}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ---------------- 3. split:左品牌栏 + 右 tab ----------------
SPLIT = f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="660,548" caption="0,0,0,0" mininfo="660,548" bkcolor="#FF12151A">
<HorizontalLayout bkcolor="#FF12151A" bordercolor="#FF282D35" bordersize="1">
<VerticalLayout width="200" bkcolor="#FF1A2230">
<HorizontalLayout height="44" inset="24,0,0,0">
<Label text="VFY" textcolor="#FF4CC2FF" font="1" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="24,4,24,0">
<Label text="软件授权" textcolor="#FFC8D3E0" height="28" font="1" />
<Label text="SOFTWARE LICENSE" textcolor="#FF63707E" height="20" />
<Label text="账号登录后可绑定本机设备" textcolor="#FF4C5A68" height="20" margin="0,14,0,0" />
</VerticalLayout>
<VerticalLayout />
<HorizontalLayout height="28" inset="24,0,24,16">
<Label text="v9 · DuiLib" textcolor="#FF4A5764" />
</HorizontalLayout>
</VerticalLayout>
<VerticalLayout>
<HorizontalLayout height="46" inset="28,0,0,0">
<VerticalLayout width="80">
<Button name="tabLogin" text="登录" height="44" bkcolor="#00000000" textcolor="#FF4CC2FF" font="1" />
<Control height="2" bkcolor="#FF4CC2FF" />
</VerticalLayout>
<VerticalLayout width="80">
<Button name="tabRegister" text="注册" height="44" bkcolor="#00000000" textcolor="#FF7A8794" />
<Control name="tabRegLine" height="2" bkcolor="#00000000" />
</VerticalLayout>
<Control />
</HorizontalLayout>
<VerticalLayout inset="28,8,28,16">
<Label name="lblApp" text="演示程序" textcolor="#FFF0F5FA" height="26" font="1" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
{login_fields("#FF8794A3", "#FF1A1F27", "#FFF2F6FA", "#FF1A1F27", "#FF2E343D", "#FF8794A3", "#FF2C7BE5", "#FFFFFFFF", "登录")}
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
{reg_fields("#FF8794A3", "#FF1A1F27", "#FFF2F6FA", "#FF1A1F27", "#FF2E343D", "#FF1F8A5B", "#FFFFFFFF", "#FF2B6A50")}
</VerticalLayout>
{footer("#FF5E6B78", "#FF6FA8DC")}
</VerticalLayout>
</VerticalLayout>
</HorizontalLayout>
</Window>'''
# ---------------- 4. card:顶部色条 + 卡片内 tab ----------------
CARD = f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="700,564" caption="0,0,-1,92" mininfo="700,564" bkcolor="#FFF5F6F9">
<VerticalLayout bkcolor="#FFF5F6F9" bordercolor="#FFD7DBE3" bordersize="1">
<HorizontalLayout height="92" bkcolor="#FF3B2BD6">
<VerticalLayout inset="28,16,0,0">
<Label text="软件授权验证" textcolor="#FFFFFFFF" font="1" height="34" />
<Label name="lblApp" text="演示程序" textcolor="#FFD9D4FF" height="22" />
</VerticalLayout>
<Control />
<Button name="btnClose" text="X" width="46" height="92" textcolor="#FFEDEBFF" bkcolor="#FF3B2BD6" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="54" inset="28,14,28,0">
<Button name="tabLogin" text="登录" width="112" height="38" bkcolor="#FFFFFFFF" textcolor="#FF3B2BD6" font="1" />
<Control width="8" />
<Button name="tabRegister" text="注册" width="112" height="38" bkcolor="#FFE8E6FF" textcolor="#FF5B56A8" />
<Control />
</HorizontalLayout>
<HorizontalLayout inset="28,16,28,18">
<VerticalLayout width="260">
<Label text="账号安全" textcolor="#FF1F2430" height="26" font="1" />
<Label text="登录后账号与本机设备绑定," textcolor="#FF4B5563" height="20" />
<Label text="超出设备上限时请先下线一台。" textcolor="#FF4B5563" height="20" />
<Control height="12" />
<Label name="lblDevice" text="设备" textcolor="#FF8A8F99" height="20" />
<VerticalLayout />
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF3B2BD6" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF3B2BD6" bkcolor="#00000000" />
</VerticalLayout>
<Control width="28" />
<VerticalLayout>
<VerticalLayout name="panelLogin" height="auto">
{login_fields("#FF4B5563", "#FFFFFFFF", "#FF1F2430", "#FFFFFFFF", "#FFC9D1DC", "#FF4B5563", "#FF3B2BD6", "#FFFFFFFF", "登录")}
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
{reg_fields("#FF4B5563", "#FFF1F3F7", "#FF1F2430", "#FFF1F3F7", "#FFC3CBD8", "#FF128A5B", "#FFFFFFFF", "#FFD8EAE0")}
</VerticalLayout>
</VerticalLayout>
</HorizontalLayout>
</VerticalLayout>
</Window>'''
# ---------------- 5. industrial:标题栏内 tab ----------------
INDUSTRIAL = f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="580,548" caption="0,0,-1,46" mininfo="580,548" bkcolor="#FF0A1520">
<VerticalLayout bkcolor="#FF0A1520" bordercolor="#FF1F4E79" bordersize="1">
<HorizontalLayout height="46" bkcolor="#FF10304C">
<Label text="AUTHORIZATION" textcolor="#FF7FD1FF" font="1" inset="18,0,0,0" />
<Control />
<Button name="tabLogin" text="LOGIN" width="80" height="46" bkcolor="#FF1A5A8C" textcolor="#FFFFFFFF" />
<Button name="tabRegister" text="REGISTER" width="96" height="46" bkcolor="#00000000" textcolor="#FF9FC8E6" />
<Button name="btnClose" text="X" width="46" height="46" textcolor="#FFBEE3FF" bkcolor="#FF10304C" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<VerticalLayout inset="24,16,24,16">
<Label name="lblApp" text="演示程序" textcolor="#FF8FC4E6" height="26" font="1" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
{login_fields("#FF9FC0D8", "#FF14304A", "#FFEAF6FF", "#FF14304A", "#FF23567F", "#FF9FC0D8", "#FF1F6FB2", "#FFFFFFFF", "登录")}
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
{reg_fields("#FF9FC0D8", "#FF14304A", "#FFEAF6FF", "#FF14304A", "#FF23567F", "#FF1F7A5E", "#FFFFFFFF", "#FF1B4A3C")}
</VerticalLayout>
{footer("#FF5F89A6", "#FF6FA8C8")}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ---------------- 6. terminal:命令式 tab ----------------
TERMINAL = f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="600,548" caption="0,0,-1,38" mininfo="600,548" bkcolor="#FF0B0F0C">
<VerticalLayout bkcolor="#FF0B0F0C" bordercolor="#FF2B3A2D" bordersize="1">
<HorizontalLayout height="38" bkcolor="#FF101710">
<Label text="vfy@local:~$" textcolor="#FF54C97A" inset="14,0,0,0" />
<Control />
<Button name="btnClose" text="X" width="38" height="38" textcolor="#FF7FB08C" bkcolor="#FF101710" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="34" bkcolor="#FF0E150F">
<Button name="tabLogin" text="[ login ]" width="96" height="34" bkcolor="#00000000" textcolor="#FF7FE39B" />
<Button name="tabRegister" text="[ register ]" width="108" height="34" bkcolor="#00000000" textcolor="#FF4E7A5C" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="16,10,16,12">
<Label name="lblApp" text="# 演示程序" textcolor="#FF7FE39B" height="24" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
{login_fields("#FF5E8A6C", "#FF16211A", "#FFD7F5DF", "#FF16211A", "#FF2B3A2D", "#FF5E8A6C", "#FF1B7A4E", "#FFFFFFFF", "[ 执行登录 ]")}
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
{reg_fields("#FF5E8A6C", "#FF16211A", "#FFD7F5DF", "#FF16211A", "#FF2B3A2D", "#FF1B7A4E", "#FFFFFFFF", "#FF234A33")}
</VerticalLayout>
{footer("#FF4E7A5C", "#FF6FA08A")}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ---------------- 7. compact:横向紧凑,tab 在左列 ----------------
COMPACT = f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="760,206" caption="0,0,-1,38" mininfo="760,206" bkcolor="#FF11151A">
<VerticalLayout bkcolor="#FF11151A" bordercolor="#FF2A3440" bordersize="1">
<HorizontalLayout height="38" bkcolor="#FF161C22">
<Label text="账号" textcolor="#FFA8BCCE" inset="16,0,0,0" />
<Control />
<Button name="btnClose" text="X" width="38" height="38" textcolor="#FFA8BCCE" bkcolor="#FF161C22" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<HorizontalLayout inset="16,12,16,10">
<VerticalLayout width="200">
<Label name="lblApp" text="演示程序" textcolor="#FFEAF2FA" height="26" font="1" />
<Label name="lblDevice" text="设备" textcolor="#FF6B7C8C" height="20" />
<Control height="12" />
<Button name="tabLogin" text="登录" width="90" height="32" bkcolor="#FF2E9E6B" textcolor="#FFFFFFFF" />
<Control height="6" />
<Button name="tabRegister" text="注册" width="90" height="32" bkcolor="#FF1B232B" textcolor="#FF9FB3C8" />
</VerticalLayout>
<Control width="16" />
<VerticalLayout>
<VerticalLayout name="panelLogin" height="auto">
<HorizontalLayout height="40">
<HorizontalLayout width="214" bkcolor="#FF1B232B">
<Label text="账号" width="46" textcolor="#FF7E90A2" inset="10,0,0,0" />
<Edit name="editUser" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" inset="0,0,0,0" />
</HorizontalLayout>
<Control width="10" />
<HorizontalLayout width="214" bkcolor="#FF1B232B">
<Label text="密码" width="46" textcolor="#FF7E90A2" inset="10,0,0,0" />
<Edit name="editPass" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" inset="0,0,0,0" password="true" />
</HorizontalLayout>
<Control width="10" />
<Button name="btnLogin" text="登录" width="110" height="40" bkcolor="#FF2E9E6B" textcolor="#FFFFFFFF" font="1" />
</HorizontalLayout>
<HorizontalLayout height="26">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="#FF6B7C8C" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="#FF6B7C8C" bkcolor="#00000000" width="120" />
<Label name="lblTip" text="" textcolor="#FFD98A8A" />
</HorizontalLayout>
<Control height="6" />
<HorizontalLayout height="24">
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF7FA5CC" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF7FA5CC" bkcolor="#00000000" />
<Control />
</HorizontalLayout>
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
<HorizontalLayout height="36">
<Edit name="regUser" width="160" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" />
<Control width="8" />
<Edit name="regEmail" width="200" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="100" height="36" bkcolor="#FF234A33" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<HorizontalLayout height="36">
<Edit name="regCode" width="160" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" />
<Control width="8" />
<Edit name="regPass" width="150" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" password="true" />
<Control width="8" />
<Edit name="regPass2" width="150" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" password="true" />
<Control width="8" />
<Button name="btnRegister" text="注册" width="90" height="36" bkcolor="#FF2E9E6B" textcolor="#FFFFFFFF" font="1" />
</HorizontalLayout>
<Label name="regTip" text="" textcolor="#FFD98A8A" height="22" />
</VerticalLayout>
</VerticalLayout>
</HorizontalLayout>
</VerticalLayout>
</Window>'''
SKINS = [("dark", DARK, 452, 548), ("light", LIGHT, 452, 548), ("split", SPLIT, 660, 548),
("card", CARD, 700, 564), ("industrial", INDUSTRIAL, 580, 548),
("terminal", TERMINAL, 600, 548), ("compact", COMPACT, 760, 206)]
with io.open(OUT, "w", encoding="utf-8") as f:
f.write("// 由 gen_skins_v3.py 生成,不要手改\n#pragma once\n\n")
for name, xml, w, h in SKINS:
f.write(f'static const char *kSkin_{name} = R"SKIN({xml})SKIN";\n\n')
f.write('struct SkinDef { const char *name; const char *xml; int w, h; };\n')
f.write('static const SkinDef kSkins[] = {\n')
for name, xml, w, h in SKINS:
f.write(f' {{ "{name}", kSkin_{name}, {w}, {h} }},\n')
f.write(' { NULL, NULL, 0, 0 }\n};\n')
print("skins_v3.h 已生成")
for name, xml, w, h in SKINS:
print(f" {name:11s} {w}x{h} {len(xml)} 字节")
@@ -0,0 +1,445 @@
#!/usr/bin/env python3
# 生成 7 套「登录 / 注册 / 卡密充值 / 忘记密码」四 tab 皮肤(老 DuiLib,纯 XML)
# 输出:/root/.hermes/cache/scratch/vfyshell/demo/skins_v4.h
import io
OUT = "/root/.hermes/cache/scratch/vfyshell/demo/skins_v4.h"
# ------------------------- 面板片段 -------------------------
def p_login(L, IN_BG, IN_FG, IN_BORDER, REM, PRI, PRI_FG, BTN="登录"):
return f''' <VerticalLayout name="panelLogin" height="248">
<Label name="lblUser" text="账号或卡密" textcolor="{L}" height="18" />
<Edit name="editUser" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="12" />
<Label name="lblPass" text="密码" textcolor="{L}" height="18" />
<Edit name="editPass" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" password="true" />
<Control height="12" />
<HorizontalLayout name="rowRemember" height="22">
<Button name="btnRemember" text="[ ] 记住账号" textcolor="{REM}" bkcolor="#00000000" width="104" height="22" />
</HorizontalLayout>
<Control height="14" />
<Button name="btnLogin" text="{BTN}" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="22" margin="0,8,0,0" />
</VerticalLayout>
'''
def p_register(L, IN_BG, IN_FG, IN_BORDER, PRI, PRI_FG, ACC):
return f''' <VerticalLayout name="panelRegister" height="404" visible="false">
<Label text="用户名" textcolor="{L}" height="18" />
<Edit name="regUser" height="38" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="10" />
<Label text="邮箱" textcolor="{L}" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="38" bkcolor="{ACC}" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="10" />
<Label name="lblRegCode" text="邮箱验证码" textcolor="{L}" height="18" />
<Edit name="regCode" height="38" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="{L}" height="18" />
<Edit name="regPass" height="38" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" password="true" />
<Control height="10" />
<Label text="确认密码" textcolor="{L}" height="18" />
<Edit name="regPass2" height="38" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" password="true" />
<Control height="14" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="22" margin="0,8,0,0" />
</VerticalLayout>
'''
def p_card(L, IN_BG, IN_FG, IN_BORDER, PRI, PRI_FG):
return f''' <VerticalLayout name="panelCard" height="250" visible="false">
<Label text="用户名" textcolor="{L}" height="18" />
<Edit name="cardUser" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="12" />
<Label text="卡密" textcolor="{L}" height="18" />
<Edit name="cardKey" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="10" />
<Label text="卡密充入该账号余额,充值后请用账号密码登录" textcolor="{L}" height="18" />
<Control height="14" />
<Button name="btnRecharge" text="立即充值" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Label name="cardTip" text="" textcolor="#FFE08A8A" height="22" margin="0,8,0,0" />
</VerticalLayout>
'''
def p_reset(L, IN_BG, IN_FG, IN_BORDER, PRI, PRI_FG, ACC):
return f''' <VerticalLayout name="panelReset" height="322" visible="false">
<Label name="lblResetCard" text="卡密" textcolor="{L}" height="18" visible="false" />
<Edit name="resetCardKey" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" visible="false" />
<Control name="spResetCard" height="12" visible="false" />
<Label text="邮箱" textcolor="{L}" height="18" />
<HorizontalLayout height="40">
<Edit name="resetEmail" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode2" text="发送验证码" width="104" height="40" bkcolor="{ACC}" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="12" />
<Label text="邮箱验证码" textcolor="{L}" height="18" />
<Edit name="resetCode" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" />
<Control height="12" />
<Label text="新密码" textcolor="{L}" height="18" />
<Edit name="resetPass" height="40" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BORDER}" inset="10,0,0,0" password="true" />
<Control height="14" />
<Button name="btnReset" text="重置密码" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Label name="resetTip" text="" textcolor="#FFE08A8A" height="22" margin="0,8,0,0" />
</VerticalLayout>
'''
def p_overlays(L, IN_BG, IN_FG, IN_BD, PRI, PRI_FG, MUTED):
"""公告 / 更新 / 设备超限 三个覆盖面板:和四个 tab 面板同级,显示时先隐藏它们。"""
return f''' <VerticalLayout name="panelNotice" height="322" visible="false">
<Label text="公 告" textcolor="{PRI}" font="1" height="30" />
<Label name="noticeTitle" text="" textcolor="{IN_FG}" height="26" />
<Control height="6" />
<Label name="noticeBody" text="" textcolor="{L}" height="150" multiline="true" endellipsis="true" />
<HorizontalLayout height="34">
<Button name="btnNoticePrev" text="上一条" width="86" height="32" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
<Control width="8" />
<Button name="btnNoticeNext" text="下一条" width="86" height="32" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
<Control />
<Label name="noticeIdx" text="" textcolor="{MUTED}" width="54" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnNoticeOk" text="我知道了" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
</VerticalLayout>
<VerticalLayout name="panelUpdate" height="300" visible="false">
<Label text="版本更新" textcolor="{PRI}" font="1" height="28" />
<Label name="updTitle" text="" textcolor="{IN_FG}" height="26" />
<Control height="6" />
<Label name="updNotes" text="" textcolor="{L}" height="130" multiline="true" endellipsis="true" />
<Label name="updTip" text="" textcolor="{MUTED}" height="24" />
<HorizontalLayout height="44">
<Button name="btnUpdLater" text="稍后提醒" width="112" height="44" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
<Control width="10" />
<Button name="btnUpdate" text="立即更新" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
</HorizontalLayout>
</VerticalLayout>
<VerticalLayout name="panelDevice" height="386" visible="false">
<Label name="devHead" text="设备数量已满" textcolor="{PRI}" font="1" height="28" />
<Label name="devTitle" text="" textcolor="{IN_FG}" height="24" />
<Control height="6" />
<Label name="lblDevCard" text="卡密" textcolor="{L}" height="18" visible="false" />
<Edit name="devCardKey" height="36" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BD}" inset="10,0,0,0" visible="false" />
<Control name="spDevCard" height="6" visible="false" />
<Control height="6" />
<Label name="devBody" text="" textcolor="{L}" height="150" multiline="true" endellipsis="true" />
<Control height="6" />
<Label text="输入要解绑的设备序号" textcolor="{MUTED}" height="18" />
<Edit name="devIdx" height="36" bkcolor="{IN_BG}" nativebkcolor="{IN_BG}" textcolor="{IN_FG}" bordercolor="{IN_BD}" inset="10,0,0,0" />
<Label name="devTip" text="" textcolor="{MUTED}" height="22" />
<HorizontalLayout height="44">
<Button name="btnUnbind" text="解绑该设备" width="118" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" font="1" />
<Control width="8" />
<Button name="btnUnbindOld" text="解绑最早一台" width="118" height="44" bkcolor="{PRI}" textcolor="{PRI_FG}" />
<Control width="8" />
<Button name="btnRetryLogin" text="重试" width="72" height="44" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
<Control width="8" />
<Button name="btnBack" text="返回" width="72" height="44" bkcolor="{IN_BG}" textcolor="{IN_FG}" />
</HorizontalLayout>
</VerticalLayout>
'''
def footer(L, LINK, dev_prefix="设备"):
return f''' <Label name="lblDevice" text="{dev_prefix}" textcolor="{L}" height="18" margin="0,6,0,0" />
'''
# ------------------------- 皮肤 1:dark(下划线 tab) -------------------------
def skin_dark():
T = dict(BG="#FF141418", TITLE_BG="#FF1D1D24", TITLE="#FFF0F0F4", CLOSE="#FF9A9AA6",
TAB_ACT="#FF4EA3E8", TAB_IDLE="#FF9A9AA6", L="#FFB4B4BE",
IN_BG="#FF2A2A33", IN_FG="#FFF4F4F8", IN_BD="#FF474755", REM="#FFB4B4BE",
PRI="#FF146FB8", PRI_FG="#FFFFFFFF", ACC="#FF2F6E4E", DEV="#FF5C5C68")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="470,436" caption="0,0,-1,44" mininfo="470,380" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FF32323A" bordersize="1">
<HorizontalLayout height="44" bkcolor="{T['TITLE_BG']}">
<Label text="软件授权验证" textcolor="{T['TITLE']}" font="1" width="260" textpadding="20,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="40" height="44" textcolor="{T['CLOSE']}" bkcolor="{T['TITLE_BG']}" hotbkcolor="#33FFFFFF" pushedbkcolor="#55FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="44" inset="20,0,20,0">
<VerticalLayout width="84">
<Button name="tabLogin" text="登录" height="42" bkcolor="#00000000" textcolor="{T['TAB_ACT']}" font="1" />
<Control height="2" bkcolor="{T['TAB_ACT']}" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabRegister" text="注册" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineRegister" height="2" bkcolor="#00000000" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabCard" text="卡密充值" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineCard" height="2" bkcolor="#00000000" />
</VerticalLayout>
<VerticalLayout width="84">
<Button name="tabReset" text="忘记密码" height="42" bkcolor="#00000000" textcolor="{T['TAB_IDLE']}" />
<Control name="lineReset" height="2" bkcolor="#00000000" />
</VerticalLayout>
<Control />
</HorizontalLayout>
<VerticalLayout inset="24,14,24,16">
<Label name="lblApp" text="演示程序" textcolor="{T['TAB_ACT']}" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['REM'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['TAB_ACT'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 2:light(分段按钮 tab) -------------------------
def skin_light():
T = dict(BG="#FFFAFAFC", TITLE="#FF1F1F24", CLOSE="#FF6B6B75", L="#FF4B5563",
IN_BG="#FFF1F3F7", IN_FG="#FF1F2430", IN_BD="#FFC3CBD8", REM="#FF4B5563",
PRI="#FF1B6FD6", PRI_FG="#FFFFFFFF", ACC="#FF128A5B", SEG_ACT="#FF1B6FD6",
SEG_IDLE="#FFEBEFF6", SEG_ACT_FG="#FFFFFFFF", SEG_IDLE_FG="#FF5B6270", DEV="#FF8A8F99")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="470,436" caption="0,0,-1,44" mininfo="470,380" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FFDCDCE3" bordersize="1">
<HorizontalLayout height="44" bkcolor="#FFFFFFFF">
<Label text="软件授权验证" textcolor="{T['TITLE']}" font="1" width="260" textpadding="20,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="40" height="44" textcolor="{T['CLOSE']}" bkcolor="#FFFFFFFF" hotbkcolor="#14000000" pushedbkcolor="#22000000" />
</HorizontalLayout>
<HorizontalLayout height="12" />
<HorizontalLayout height="38" inset="24,0,24,0">
<Button name="tabLogin" text="登录" height="38" bkcolor="{T['SEG_ACT']}" textcolor="{T['SEG_ACT_FG']}" font="1" />
<Control width="6" />
<Button name="tabRegister" text="注册" height="38" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
<Control width="6" />
<Button name="tabCard" text="卡密充值" height="38" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
<Control width="6" />
<Button name="tabReset" text="忘记密码" height="38" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
</HorizontalLayout>
<VerticalLayout inset="24,16,24,16">
<Label name="lblApp" text="演示程序" textcolor="{T['PRI']}" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['REM'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['PRI'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 3:split(左品牌栏 + 右侧文字 tab) -------------------------
def skin_split():
T = dict(BG="#FF12151A", SIDE="#FF1A2230", ACT="#FF4CC2FF", IDLE="#FF97A5B4", L="#FF8794A3",
IN_BG="#FF1A1F27", IN_FG="#FFF2F6FA", IN_BD="#FF2E343D", PRI="#FF2C7BE5",
PRI_FG="#FFFFFFFF", ACC="#FF2B6A50", DEV="#FF7E8B99")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="680,452" caption="0,0,0,0" mininfo="680,400" bkcolor="{T['BG']}">
<HorizontalLayout bkcolor="{T['BG']}" bordercolor="#FF282D35" bordersize="1">
<VerticalLayout width="196" bkcolor="{T['SIDE']}">
<HorizontalLayout height="44" inset="24,0,0,0">
<Label text="VFY" textcolor="{T['ACT']}" font="1" width="120" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="24,4,24,0">
<Label text="软件授权" textcolor="#FFC8D3E0" height="28" font="1" />
<Label text="SOFTWARE LICENSE" textcolor="#FF63707E" height="20" />
<Label text="登录后绑定本机设备" textcolor="#FF4C5A68" height="20" margin="0,14,0,0" />
</VerticalLayout>
<VerticalLayout />
<HorizontalLayout height="28" inset="24,0,24,16">
<Label text="v9 · DuiLib" textcolor="#FF4A5764" />
</HorizontalLayout>
</VerticalLayout>
<VerticalLayout>
<HorizontalLayout height="44" inset="24,0,16,0">
<Button name="tabLogin" text="登录" width="72" height="44" bkcolor="#00000000" textcolor="{T['ACT']}" font="1" />
<Button name="tabRegister" text="注册" width="72" height="44" bkcolor="#00000000" textcolor="{T['IDLE']}" />
<Button name="tabCard" text="卡密充值" width="92" height="44" bkcolor="#00000000" textcolor="{T['IDLE']}" />
<Button name="tabReset" text="忘记密码" width="92" height="44" bkcolor="#00000000" textcolor="{T['IDLE']}" />
<Button name="btnClose" text="×" font="1" width="40" height="44" textcolor="#FF8E9BAA" bkcolor="{T['BG']}" hotbkcolor="#22FFFFFF" />
</HorizontalLayout>
<VerticalLayout inset="24,4,24,14">
<Label name="lblApp" text="演示程序" textcolor="#FFF6FAFF" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['ACT'])}
</VerticalLayout>
</VerticalLayout>
</HorizontalLayout>
</Window>'''
# ------------------------- 皮肤 4:card(顶部色条 + 卡片内段按钮) -------------------------
def skin_card():
T = dict(BG="#FFF5F6F9", BAR="#FF3B2BD6", L="#FF4B5563", IN_BG="#FFFFFFFF", IN_FG="#FF1F2430",
IN_BD="#FFC9D1DC", PRI="#FF3B2BD6", PRI_FG="#FFFFFFFF", ACC="#FF128A5B",
SEG_IDLE="#FFE8E6FF", SEG_IDLE_FG="#FF5B56A8", DEV="#FF8A8F99")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="720,460" caption="0,0,-1,88" mininfo="720,400" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FFD7DBE3" bordersize="1">
<HorizontalLayout height="88" bkcolor="{T['BAR']}">
<VerticalLayout inset="28,16,0,0">
<Label text="软件授权验证" textcolor="#FFFFFFFF" font="1" height="32" />
<Label name="lblApp" text="演示程序" textcolor="#FFD9D4FF" height="22" />
</VerticalLayout>
<Control />
<Button name="btnClose" text="×" font="1" width="46" height="88" textcolor="#FFEDEBFF" bkcolor="{T['BAR']}" hotbkcolor="#22000000" />
</HorizontalLayout>
<HorizontalLayout height="50" inset="28,12,28,0">
<Button name="tabLogin" text="登录" height="36" bkcolor="#FFFFFFFF" textcolor="{T['PRI']}" font="1" />
<Control width="8" />
<Button name="tabRegister" text="注册" height="36" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
<Control width="8" />
<Button name="tabCard" text="卡密充值" height="36" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
<Control width="8" />
<Button name="tabReset" text="忘记密码" height="36" bkcolor="{T['SEG_IDLE']}" textcolor="{T['SEG_IDLE_FG']}" />
</HorizontalLayout>
<HorizontalLayout inset="28,14,28,16">
<VerticalLayout width="248">
<Label text="账号安全" textcolor="#FF1F2430" height="24" font="1" />
<Label text="登录后账号与本机设备绑定," textcolor="{T['L']}" height="20" />
<Label text="超出设备上限时请先下线一台。" textcolor="{T['L']}" height="20" />
<Control height="12" />
{footer(T['DEV'], T['PRI'])}
</VerticalLayout>
<Control width="24" />
<Control width="1" bkcolor="#FFE3E6EC" />
<Control width="24" />
<VerticalLayout>
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
</VerticalLayout>
</HorizontalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 5:industrial(标题栏内 tab) -------------------------
def skin_industrial():
T = dict(BG="#FF0A1520", BAR="#FF10304C", ACT="#FF1A5A8C", L="#FF9FC0D8",
IN_BG="#FF14304A", IN_FG="#FFEAF6FF", IN_BD="#FF23567F", PRI="#FF1F6FB2",
PRI_FG="#FFFFFFFF", ACC="#FF1B4A3C", DEV="#FF5F89A6")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="600,452" caption="0,0,-1,46" mininfo="600,400" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FF1F4E79" bordersize="1">
<HorizontalLayout height="46" bkcolor="{T['BAR']}">
<Label text="AUTHORIZATION" textcolor="#FF7FD1FF" font="1" width="200" textpadding="18,0,0,0" />
<Control />
<Button name="tabLogin" text="LOGIN" width="76" height="46" bkcolor="{T['ACT']}" textcolor="#FFFFFFFF" />
<Button name="tabRegister" text="SIGN UP" width="84" height="46" bkcolor="#00000000" textcolor="#FF9FC8E6" />
<Button name="tabCard" text="CARD" width="66" height="46" bkcolor="#00000000" textcolor="#FF9FC8E6" />
<Button name="tabReset" text="RESET" width="70" height="46" bkcolor="#00000000" textcolor="#FF9FC8E6" />
<Button name="btnClose" text="×" font="1" width="44" height="46" textcolor="#FFBEE3FF" bkcolor="{T['BAR']}" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<VerticalLayout inset="24,14,24,14">
<Label name="lblApp" text="演示程序" textcolor="#FFA8D4F0" height="30" font="2" />
<Control height="8" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['PRI'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 6:terminal(命令式 tab) -------------------------
def skin_terminal():
T = dict(BG="#FF0B0F0C", BAR="#FF101710", ACT="#FF7FE39B", L="#FF7FAE90",
IN_BG="#FF16211A", IN_FG="#FFD7F5DF", IN_BD="#FF2B3A2D", PRI="#FF1B7A4E",
PRI_FG="#FFFFFFFF", ACC="#FF234A33", DEV="#FF6F9E80")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="620,446" caption="0,0,-1,38" mininfo="620,400" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="{T['IN_BD']}" bordersize="1">
<HorizontalLayout height="38" bkcolor="{T['BAR']}" inset="0,0,8,0">
<Label text="vfy@local:~$ auth" textcolor="{T['ACT']}" width="220" textpadding="14,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="38" height="38" textcolor="#FF7FB08C" bkcolor="{T['BAR']}" hotbkcolor="#22FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="34" bkcolor="#FF0E150F" inset="8,0,8,0">
<Button name="tabLogin" text="login" width="76" height="34" bkcolor="#00000000" textcolor="{T['ACT']}" font="1" />
<Button name="tabRegister" text="register" width="92" height="34" bkcolor="#00000000" textcolor="{T['L']}" />
<Button name="tabCard" text="card" width="66" height="34" bkcolor="#00000000" textcolor="{T['L']}" />
<Button name="tabReset" text="reset" width="70" height="34" bkcolor="#00000000" textcolor="{T['L']}" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="16,10,16,12">
<Label name="lblApp" text="# 演示程序" textcolor="{T['ACT']}" height="28" font="2" />
<Control height="6" />
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'], "[ 执行登录 ]")}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
{footer(T['DEV'], T['ACT'])}
</VerticalLayout>
</VerticalLayout>
</Window>'''
# ------------------------- 皮肤 7:compact(左列竖排 tab) -------------------------
def skin_compact():
T = dict(BG="#FF11151A", BAR="#FF161C22", ACT="#FF2E9E6B", L="#FF95A7B8",
IN_BG="#FF1B232B", IN_FG="#FFFFFFFF", IN_BD="#FF32404E", PRI="#FF2E9E6B",
PRI_FG="#FFFFFFFF", ACC="#FF234A33", SEL="#FF1C6142", DEV="#FF8698A8")
return f'''<?xml version="1.0" encoding="utf-8"?>
<Window size="760,392" caption="0,0,-1,38" mininfo="760,300" bkcolor="{T['BG']}">
<VerticalLayout bkcolor="{T['BG']}" bordercolor="#FF2A3440" bordersize="1">
<HorizontalLayout height="38" bkcolor="{T['BAR']}">
<Label text="账号中心" textcolor="#FFA8BCCE" width="160" textpadding="16,0,0,0" />
<Control />
<Button name="btnClose" text="×" font="1" width="38" height="38" textcolor="#FFA8BCCE" bkcolor="{T['BAR']}" hotbkcolor="#22FFFFFF" />
</HorizontalLayout>
<HorizontalLayout inset="16,12,16,12">
<VerticalLayout width="176">
<Label name="lblApp" text="演示程序" textcolor="#FFF2F8FF" height="28" font="2" />
<Control height="10" />
<Button name="tabLogin" text="登录" width="100" height="32" bkcolor="{T['SEL']}" textcolor="#FFFFFFFF" />
<Control height="6" />
<Button name="tabRegister" text="注册" width="100" height="32" bkcolor="{T['BAR']}" textcolor="#FF9FB3C8" />
<Control height="6" />
<Button name="tabCard" text="卡密充值" width="100" height="32" bkcolor="{T['BAR']}" textcolor="#FF9FB3C8" />
<Control height="6" />
<Button name="tabReset" text="忘记密码" width="100" height="32" bkcolor="{T['BAR']}" textcolor="#FF9FB3C8" />
<VerticalLayout />
{footer(T['DEV'], T['ACT'])}
</VerticalLayout>
<Control width="14" />
<Control width="1" bkcolor="#FF2A3440" />
<Control width="14" />
<VerticalLayout>
{p_login(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['L'], T['PRI'], T['PRI_FG'])}
{p_register(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_card(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'])}
{p_reset(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['ACC'])}
{p_overlays(T['L'], T['IN_BG'], T['IN_FG'], T['IN_BD'], T['PRI'], T['PRI_FG'], T['DEV'])}
</VerticalLayout>
</HorizontalLayout>
</VerticalLayout>
</Window>'''
SKINS = [("dark", skin_dark(), 470, 436), ("light", skin_light(), 470, 436),
("split", skin_split(), 680, 452), ("card", skin_card(), 720, 460),
("industrial", skin_industrial(), 600, 452), ("terminal", skin_terminal(), 620, 446),
("compact", skin_compact(), 760, 392)]
with io.open(OUT, "w", encoding="utf-8") as f:
f.write("// 由 gen_skins_v4.py 生成,不要手改\n#pragma once\n\n")
for name, xml, w, h in SKINS:
f.write(f'static const char *kSkin_{name} = R"SKIN({xml})SKIN";\n\n')
f.write('struct SkinDef { const char *name; const char *xml; int w, h; };\n')
f.write('static const SkinDef kSkins[] = {\n')
for name, xml, w, h in SKINS:
f.write(f' {{ "{name}", kSkin_{name}, {w}, {h} }},\n')
f.write(' { NULL, NULL, 0, 0 }\n};\n')
print("skins_v4.h 已生成(4 tab × 7 皮肤)")
for name, xml, w, h in SKINS:
print(f" {name:11s} {w}x{h} {len(xml)} 字节")
+275 -37
View File
@@ -42,9 +42,11 @@ static char g_lastResp[8192] = ""; // 上一次 /login 原始响应(设备
static int g_overlay = 0; // 0=正常 1=公告 2=更新 3=设备
static int g_devManage = 0; // 1 = 设备面板处于「我的设备」自助模式
struct DevItem { char id[64]; char name[64]; char created[32]; };
struct DevItem { char id[64]; char name[64]; char created[32]; int online; };
static DevItem g_devs[16];
static int g_devCount = 0, g_devMax = 0;
static int g_selIdx = 0; // 设备页手动选中的那台(1 起;0=未选)
static int g_baseW = 0, g_baseH = 0; // 登录页原始窗口尺寸(设备管理页会临时放大)
struct Notice { int id; char title[128]; char body[1024]; };
static Notice g_notices[8];
@@ -204,6 +206,29 @@ static const SkinDef *skin_for(const char *theme) {
}
/* ---------------------------- 接口请求 ---------------------------- */
// 最近一次请求的 HTTP 状态码。0 = 没取到(连接失败 / 不是合法响应)。
// 只做记录、不参与界面判断:没有它,接口失败时界面上只会看到「操作失败」,
// 到底是 DNS 挂了、证书不对、还是服务端 5xx,全无线索。
static DWORD g_lastHttpStatus = 0;
// 取 HTTP 状态码。WinHttpQueryHeaders 失败时返回 0。
static DWORD http_status(HINTERNET hR) {
DWORD code = 0, len = sizeof(code);
if (!WinHttpQueryHeaders(hR, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &code, &len,
WINHTTP_NO_HEADER_INDEX))
return 0;
return code;
}
// 2xx 视为成功。取不到状态码时返回 true —— 交回调用方按响应体自行判断,
// 保持补丁前对老服务端(不走标准状态码)的兼容。
static bool http_ok(DWORD st) {
if (st == 0) return true;
return st >= 200 && st < 300;
}
// 平台接口:POST /api/v1/app/<appKey>/login
// {"username","password","device_id","device_name","device_type","instance_id"}
static int api_login(const char *user, const char *pass, char *msg, int cap) {
@@ -251,12 +276,14 @@ static int api_login(const char *user, const char *pass, char *msg, int cap) {
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, cap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, https ? WINHTTP_FLAG_SECURE : 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
DWORD httpSt = http_status(hR);
g_lastHttpStatus = httpSt;
char resp[4096] = {0};
DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, resp + total, sizeof(resp) - 1 - total, &cl) && cl > 0) {
@@ -266,9 +293,9 @@ static int api_login(const char *user, const char *pass, char *msg, int cap) {
resp[total] = 0;
// 设备超限的 403 里带整份设备列表,留给「设备已满」页展示与解绑
snprintf(g_lastResp, sizeof(g_lastResp), "%s", resp);
if (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true")) ok = 1;
if (http_ok(httpSt) && (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true"))) ok = 1;
if (!json_str(resp, "message", msg, cap) || !msg[0]) {
if (strstr(resp, "DEVICE_LIMIT")) snprintf(msg, cap, "设备数量已达上限,请先在平台下线一台设备");
if (strstr(resp, "DEVICE_LIMIT")) snprintf(msg, cap, "设备数量已达上限,请先在平台解绑一台设备");
else if (strstr(resp, "IP_LIMIT")) snprintf(msg, cap, "IP 绑定已达上限,请解绑后再试");
else if (ok) snprintf(msg, cap, "登录成功");
else snprintf(msg, cap, "账号或密码错误");
@@ -318,18 +345,20 @@ static int api_register(const char *user, const char *email, const char *code,
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, cap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, https ? WINHTTP_FLAG_SECURE : 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
DWORD httpSt = http_status(hR);
g_lastHttpStatus = httpSt;
char resp[4096] = {0}; DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, resp + total, sizeof(resp) - 1 - total, &cl) && cl > 0) {
total += cl; if (total >= sizeof(resp) - 1) break;
}
resp[total] = 0;
if (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true")) ok = 1;
if (http_ok(httpSt) && (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true"))) ok = 1;
if (!json_str(resp, "message", msg, cap) || !msg[0])
snprintf(msg, cap, ok ? "注册成功,正在登录…" : "注册失败,请检查邮箱验证码");
} else {
@@ -367,16 +396,18 @@ static int api_send_code(const char *email, const char *purpose, char *msg, int
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, cap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, https ? WINHTTP_FLAG_SECURE : 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
DWORD httpSt = http_status(hR);
g_lastHttpStatus = httpSt;
char resp[2048] = {0}; DWORD cl = 0;
WinHttpReadData(hR, resp, sizeof(resp) - 1, &cl);
resp[cl < sizeof(resp) ? cl : sizeof(resp) - 1] = 0;
if (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true")) ok = 1;
if (http_ok(httpSt) && (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true"))) ok = 1;
if (!json_str(resp, "message", msg, cap) || !msg[0])
snprintf(msg, cap, ok ? "验证码已发送" : "发送失败");
} else {
@@ -413,18 +444,20 @@ static int api_post_sibling(const char *sibling, const char *body, char *msg, in
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) { snprintf(msg, cap, "网络初始化失败"); return 0; }
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"POST", wPath.c_str(), NULL, NULL, NULL, https ? WINHTTP_FLAG_SECURE : 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
DWORD httpSt = http_status(hR);
g_lastHttpStatus = httpSt;
char resp[4096] = {0}; DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, resp + total, sizeof(resp) - 1 - total, &cl) && cl > 0) {
total += cl; if (total >= sizeof(resp) - 1) break;
}
resp[total] = 0;
if (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true")) ok = 1;
if (http_ok(httpSt) && (strstr(resp, "\"code\":0") || strstr(resp, "\"code\":200") || strstr(resp, "\"success\":true"))) ok = 1;
if (!json_str(resp, "message", msg, cap) || !msg[0]) {
if (ok) snprintf(msg, cap, "操作成功");
else snprintf(msg, cap, "操作失败");
@@ -462,7 +495,7 @@ static int api_get_sibling(const char *sibling, char *resp, int cap) {
HINTERNET hS = WinHttpOpen(L"vfy/9.0", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0);
if (!hS) return 0;
HINTERNET hC = WinHttpConnect(hS, wHost.c_str(), port, 0);
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"GET", wPath.c_str(), NULL, NULL, NULL, 0) : NULL;
HINTERNET hR = hC ? WinHttpOpenRequest(hC, L"GET", wPath.c_str(), NULL, NULL, NULL, https ? WINHTTP_FLAG_SECURE : 0) : NULL;
int ok = 0;
if (hR) {
WinHttpSendRequest(hR, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, 0, 0);
@@ -473,7 +506,13 @@ static int api_get_sibling(const char *sibling, char *resp, int cap) {
if ((int)total >= cap) break;
}
resp[total] = 0;
ok = total > 0;
// 原来只看 total > 0,服务端的 4xx/5xx 错误页也算「读到了」,
// 于是调用方拿 HTML 去解 JSON,全部字段静默回落到默认值
// (曾经表现为:应用配了卡密登录,客户端却显示账号密码登录、
// 没有充值入口,而且应用名还是对的,因为名字来自本地 cfg)。
DWORD st = http_status(hR);
g_lastHttpStatus = st;
ok = (total > 0 && http_ok(st)) ? 1 : 0;
WinHttpCloseHandle(hR);
}
if (hC) WinHttpCloseHandle(hC);
@@ -552,6 +591,8 @@ static int api_post_sibling_raw(const char *sibling, const char *body, char *res
WinHttpSendRequest(hR, L"Content-Type: application/json\r\n", (DWORD)-1,
(LPVOID)body, (DWORD)strlen(body), (DWORD)strlen(body), 0);
WinHttpReceiveResponse(hR, NULL);
DWORD httpSt = http_status(hR);
g_lastHttpStatus = httpSt;
char tmp[8192] = {0};
DWORD cl = 0, total = 0;
while (WinHttpReadData(hR, tmp + total, sizeof(tmp) - 1 - total, &cl) && cl > 0) {
@@ -560,7 +601,7 @@ static int api_post_sibling_raw(const char *sibling, const char *body, char *res
}
tmp[total] = 0;
if (respOut) snprintf(respOut, cap, "%s", tmp);
if (strstr(tmp, "\"code\":200") || strstr(tmp, "\"code\":0")) ok = 1;
if (http_ok(httpSt) && (strstr(tmp, "\"code\":200") || strstr(tmp, "\"code\":0"))) ok = 1;
if (!json_str(tmp, "message", msg, msgCap) || !msg[0])
snprintf(msg, msgCap, ok ? "操作成功" : "操作失败");
} else {
@@ -901,6 +942,11 @@ public:
if (!_tcsicmp(nm, _T("btnNoticeOk"))) { SaveNoticeSeen(); HideOverlays(); return; }
if (!_tcsicmp(nm, _T("btnUpdate"))) { DoUpdate(); return; }
if (!_tcsicmp(nm, _T("btnUpdLater"))) { HideOverlays(); return; }
if (!_tcsnicmp(nm, _T("devUnbind"), 9) || !_tcsnicmp(nm, _T("devRow"), 6)) {
int sel = _ttoi(nm + (!_tcsnicmp(nm, _T("devUnbind"), 9) ? 9 : 6)) + 1;
if (sel >= 1 && sel <= g_devCount) UnbindDeviceIdx(sel);
return;
}
if (!_tcsicmp(nm, _T("btnUnbind"))) { UnbindByIndex(); return; }
if (!_tcsicmp(nm, _T("btnUnbindOld"))) { UnbindOldest(); return; }
if (!_tcsicmp(nm, _T("btnRetryLogin"))) { HideOverlays(); DoLogin(); return; }
@@ -946,7 +992,15 @@ public:
// ---------------- 四个 tab:登录 / 注册 / 卡密充值 / 忘记密码 ----------------
void SwitchTab(int tab) {
if (!strcmp(g_loginMode, "card") && tab == 1) { ShowManageDevices(); return; }
if (!strcmp(g_loginMode, "card") && tab == 1) {
// 卡密模式下「我的设备」不复用注册面板,直接进设备管理。
// 但 g_tab 必须先更新 + 刷新 tab 样式,否则点完「我的设备」,
// 高亮还留在「登录」上(用户看到的就是「切过去了但焦点没跟过来」)。
g_tab = 1;
UpdateTabStyle();
ShowManageDevices();
return;
}
int old = g_tab;
g_tab = tab;
// 从覆盖页回到 tab 时把覆盖层收掉
@@ -984,15 +1038,26 @@ public:
std::string th(g_theme);
DWORD actBg = 0, idleBg = 0, actFg = 0, idleFg = 0;
// 下划线指示条的颜色必须跟皮肤走:原来写死 0xFF4EA3E8(dark 的蓝),
// 结果 classic 的下划线也变成浅蓝,和它的 #0E639C 主色不是一个色系。
DWORD lineColor = 0xFF4EA3E8;
bool bgMode = true;
if (th == "dark") { bgMode = false; actFg = 0xFF4EA3E8; idleFg = 0xFF85858F; }
else if (th == "light") { actBg = 0xFF1B6FD6; idleBg = 0xFFEBEFF6; actFg = 0xFFFFFFFF; idleFg = 0xFF5B6270; }
else if (th == "split") { bgMode = false; actFg = 0xFF4CC2FF; idleFg = 0xFF7A8794; }
else if (th == "card") { actBg = 0xFFFFFFFF; idleBg = 0xFFE8E6FF; actFg = 0xFF3B2BD6; idleFg = 0xFF5B56A8; }
else if (th == "industrial") { actBg = 0xFF1A5A8C; idleBg = 0x00000000; actFg = 0xFFFFFFFF; idleFg = 0xFF9FC8E6; }
else if (th == "terminal") { bgMode = false; actFg = 0xFF7FE39B; idleFg = 0xFF4E7A5C; }
else if (th == "compact") { actBg = 0xFF2E9E6B; idleBg = 0xFF161C22; actFg = 0xFFFFFFFF; idleFg = 0xFF9FB3C8; }
// classic 必须有分支:它是 VS Code 暗色系,走「无底色 + 下划线」方案。
// 原来没有这一支,落到默认的 bgMode=true / 全 0 色 → tab 文字会被设成透明。
if (th == "classic") { bgMode = false; actFg = 0xFF0E639C; idleFg = 0xFF9D9D9D; lineColor = 0xFF0E639C; }
else if (th == "dark") { bgMode = false; actFg = 0xFF4EA3E8; idleFg = 0xFF85858F; lineColor = 0xFF4EA3E8; }
else if (th == "light") { actBg = 0xFF1B6FD6; idleBg = 0xFFEBEFF6; actFg = 0xFFFFFFFF; idleFg = 0xFF5B6270; lineColor = 0xFF1B6FD6; }
// split 的 XML 里 tab 本来就有底色(SEG_ACT / SEG_IDLE 分段按钮),
// 原来这里写 bgMode=false,只改文字色不改底色 —— 切 tab 时底色永远停在
// 「登录」那格,只有文字从白变浅蓝,几乎看不出切换。改回底色方案。
else if (th == "split") { actBg = 0xFF1B6FD6; idleBg = 0xFFEBEFF6; actFg = 0xFFFFFFFF; idleFg = 0xFF5B6270; lineColor = 0xFF4CC2FF; }
else if (th == "card") { actBg = 0xFFFFFFFF; idleBg = 0xFFE8E6FF; actFg = 0xFF3B2BD6; idleFg = 0xFF5B56A8; lineColor = 0xFF3B2BD6; }
else if (th == "industrial") { actBg = 0xFF1A5A8C; idleBg = 0x00000000; actFg = 0xFFFFFFFF; idleFg = 0xFF9FC8E6; lineColor = 0xFF7FD1FF; }
// terminal 的 tab 是横排透明底,原来只改文字色(亮绿 vs 暗绿),选中态太弱。
// 改成底色方案:选中那格给深绿底 + 亮绿字,未选透明 + 暗绿字。
else if (th == "terminal") { actBg = 0xFF1B7A4E; idleBg = 0x00000000; actFg = 0xFFD7F5DF; idleFg = 0xFF7FAE90; lineColor = 0xFF7FE39B; }
else if (th == "compact") { actBg = 0xFF2E9E6B; idleBg = 0xFF161C22; actFg = 0xFFFFFFFF; idleFg = 0xFF9FB3C8; lineColor = 0xFF2E9E6B; }
for (int i = 0; i < 4; i++) {
if (!btns[i]) continue;
@@ -1001,11 +1066,15 @@ public:
btns[i]->SetTextColor(on ? actFg : idleFg);
btns[i]->Invalidate();
}
// dark 皮肤用下划线指示条
// 「无底色」皮肤(classic / dark / split / terminal)才用下划线指示器。
// 其余皮肤靠 tab 自身的底色区分,下划线一律清掉。
const char *lines[4] = { "lineLogin", "lineRegister", "lineCard", "lineReset" };
for (int i = 0; i < 4; i++) {
if (CControlUI *l = m_pm.FindControl(U8(lines[i]).c_str()))
l->SetBkColor(i == g_tab ? 0xFF4EA3E8 : 0x00000000);
if (CControlUI *l = m_pm.FindControl(U8(lines[i]).c_str())) {
bool on = !bgMode && (i == g_tab);
l->SetBkColor(on ? lineColor : 0x00000000);
l->Invalidate();
}
}
}
@@ -1191,7 +1260,32 @@ public:
}
}
void ShowTabsAgain() {
// 只恢复四个 tab。lblApp / lblBrand 是旧布局里正文那行应用名,
// 现在应用名统一显示在标题栏,别再把它放出来。
const TCHAR *names[] = {_T("tabLogin"), _T("tabRegister"), _T("tabCard"), _T("tabReset")};
for (int i = 0; i < 4; i++) {
if (CControlUI *c = static_cast<CControlUI *>(m_pm.FindControl(names[i]))) c->SetVisible(true);
}
HideByName("lblApp");
HideByName("lblBrand");
if (CLabelUI *h = static_cast<CLabelUI *>(m_pm.FindControl(_T("devHead")))) h->SetText(L"设备数量已满");
// 标题恢复成应用名(不是固定的「软件授权验证」)
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblTitle"))))
t->SetText((g_name[0] ? U8(g_name) : std::wstring(L"软件授权验证")).c_str());
}
void RestoreWindowSize() {
if (g_baseW > 0) {
RECT rc; ::GetWindowRect(m_hWnd, &rc);
int sw = ::GetSystemMetrics(SM_CXSCREEN), sh = ::GetSystemMetrics(SM_CYSCREEN);
::SetWindowPos(m_hWnd, NULL, (sw - g_baseW) / 2, (sh - g_baseH) / 2, g_baseW, g_baseH, SWP_NOZORDER | SWP_NOACTIVATE);
}
}
void HideOverlays() {
RestoreWindowSize();
ShowTabsAgain();
HideByName("panelNotice"); HideByName("panelUpdate"); HideByName("panelDevice");
g_overlay = 0;
SwitchTab(g_tab);
@@ -1366,6 +1460,7 @@ public:
// 把 g_lastResp 里的设备数组解析到 g_devs/后面统一渲染
void ParseDevicesInto() {
g_devCount = 0;
g_selIdx = 0;
g_devMax = json_int(g_lastResp, "max_devices", g_maxDevices);
const char *p = g_lastResp;
while ((p = strstr(p, "\"device_id\":\"")) && g_devCount < 16) {
@@ -1379,13 +1474,51 @@ public:
}
snprintf(g_devs[g_devCount].id, sizeof(g_devs[0].id), "%s", id);
snprintf(g_devs[g_devCount].name, sizeof(g_devs[0].name), "%s", name[0] ? name : "未命名设备");
g_devs[g_devCount].online = 0;
if (const char *oc = strstr(p, "\"online_count\":")) g_devs[g_devCount].online = atoi(oc + 15);
g_devCount++;
p++;
}
}
// 设备列表渲染:每行 = 信息按钮 + 右侧「解绑」按钮;每行点哪个解哪台
void RenderDeviceList() {
for (int i = 0; i < 8; i++) {
TCHAR nm[16];
_stprintf(nm, _T("devRow%d"), i);
CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(nm));
TCHAR bn[16];
_stprintf(bn, _T("rowBox%d"), i);
CControlUI *box = static_cast<CControlUI *>(m_pm.FindControl(bn));
if (!b) continue;
if (i < g_devCount) {
wchar_t line[320];
swprintf(line, 320, L"%d. %ls %ls %ls", i + 1,
U8(g_devs[i].name).c_str(), U8(g_devs[i].id).c_str(),
g_devs[i].online > 0 ? L"\u25cf \u5728\u7ebf" : L"\u25cb \u79bb\u7ebf");
b->SetText(line);
if (box) box->SetVisible(true);
} else {
b->SetText(L"");
if (box) box->SetVisible(false);
}
}
}
void ShowDevicePanel() {
ParseDevicesInto();
g_selIdx = 0;
// 设备管理页比登录页大:临时放大窗口(QQ 那种独立设备页的观感)
if (g_baseW == 0) {
RECT rc; ::GetClientRect(m_hWnd, &rc);
g_baseW = rc.right - rc.left; g_baseH = rc.bottom - rc.top;
}
{
int nw = 620, nh = 620;
RECT rc; ::GetWindowRect(m_hWnd, &rc);
int sw = ::GetSystemMetrics(SM_CXSCREEN), sh = ::GetSystemMetrics(SM_CYSCREEN);
::SetWindowPos(m_hWnd, NULL, (sw - nw) / 2, (sh - nh) / 2, nw, nh, SWP_NOZORDER | SWP_NOACTIVATE);
}
std::wstring body;
for (int i = 0; i < g_devCount; i++) {
wchar_t line[256];
@@ -1393,6 +1526,7 @@ public:
body += line;
}
if (body.empty()) body = L"(服务器没有返回设备明细,可直接重试登录)";
else body = L"点选下面要解绑的那台设备,再按「解绑该设备」";
#ifdef VFY_DEBUG
{ HANDLE f = ::CreateFileW(L"C:\\vfy_dev.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (f != INVALID_HANDLE_VALUE) { std::string dump; char tmp[2048];
@@ -1400,11 +1534,22 @@ public:
dump = tmp; for (int i2 = 0; i2 < g_devCount; i2++) { snprintf(tmp, sizeof(tmp), "ITEM[%d] name=<%s> id=<%s>\n", i2, g_devs[i2].name, g_devs[i2].id); dump += tmp; }
DWORD wr = 0; ::WriteFile(f, dump.c_str(), (DWORD)dump.size(), &wr, NULL); ::CloseHandle(f); } }
#endif
if (CLabelUI *b = static_cast<CLabelUI *>(m_pm.FindControl(_T("devBody")))) b->SetText(body.c_str());
RenderDeviceList(); // 列表正文由它写进 devBody
wchar_t title[160];
swprintf(title, 160, L"已绑定 %d / %d 台,解绑一台后即可登录", g_devCount, g_devMax > 0 ? g_devMax : g_maxDevices);
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTitle")))) t->SetText(title);
ShowOverlay("panelDevice");
if (CLabelUI *h = static_cast<CLabelUI *>(m_pm.FindControl(_T("devHead")))) h->SetText(L"设备管理");
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblTitle")))) {
// 标题栏格式:应用名 · 设备管理(应用名在前,用户先看到自己在管哪个程序)
std::wstring wt = g_name[0] ? (U8(g_name) + L" · 设备管理") : L"设备管理";
t->SetText(wt.c_str());
}
HideByName("tabLogin"); HideByName("tabRegister"); HideByName("tabCard"); HideByName("tabReset");
HideByName("lblApp"); HideByName("lblBrand");
if (CLabelUI *tp = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTip"))))
tp->SetText(L"点任一行右侧的「解绑」即解绑那一台设备");
if (CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(_T("devIdx")))) { e->SetText(L""); e->SetVisible(false); }
}
// 一键解绑最早绑定的一台(服务器按 created_at DESC 返回,最后一台最老)
@@ -1465,7 +1610,7 @@ public:
text += line;
}
if (text.empty()) text = L"当前没有已绑定设备";
if (CLabelUI *b = static_cast<CLabelUI *>(m_pm.FindControl(_T("devBody")))) b->SetText(text.c_str());
RenderDeviceList(); // 列表正文由它写进 devBody
wchar_t title[160];
swprintf(title, 160, L"已绑定 %d / %d 台,解绑一台即可换设备登录", g_devCount, g_devMax > 0 ? g_devMax : g_maxDevices);
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTitle")))) t->SetText(title);
@@ -1476,7 +1621,14 @@ public:
CLabelUI *tip = static_cast<CLabelUI *>(m_pm.FindControl(_T("devTip")));
if (!e || !tip) return;
int idx = _wtoi(e->GetText().GetData());
if (idx < 1 || idx > g_devCount) { tip->SetText(L"请输入列表里的序号,例如 1"); return; }
if (idx < 1) idx = g_selIdx; // 没填序号时用列表里点选的那台
if (idx < 1 || idx > g_devCount) { tip->SetText(L"请先在「输入要解绑的设备序号」里填上列表中的序号(例如 1),再按「解绑该设备」"); return; }
{
wchar_t conf[256];
swprintf(conf, 256, L"正在解绑第 %d 台:%ls(%ls)", idx,
U8(g_devs[idx - 1].name).c_str(), g_devs[idx - 1].online > 0 ? L"在线" : L"离线");
tip->SetText(conf);
}
UnbindDeviceIdx(idx);
}
@@ -1537,9 +1689,16 @@ public:
void ApplyAppInfo() {
if (!g_infoLoaded) return;
// 应用名以服务器为准
if (CLabelUI *p = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblApp"))))
p->SetText(U8(g_name).c_str());
SyncNativeEditBg();
// 应用名以服务器为准 —— 显示在标题栏,不占界面正文。
// 原来标题栏固定写「软件授权验证」,正文再单起一行蓝色大字写应用名,
// 等于同一个信息说了两遍,正文还被挤掉一行高度。
if (!g_name[0]) return;
if (CLabelUI *t = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblTitle"))))
t->SetText(U8(g_name).c_str());
// 旧布局里的正文应用名标签统一藏掉(有的皮肤叫 lblApp,有的叫 lblBrand)
HideByName("lblApp");
HideByName("lblBrand");
// 注册:后台关掉就整条 tab 拿掉
if (!g_allowRegister) {
@@ -1650,9 +1809,16 @@ public:
if (!c) continue;
bool on = (CControlUI *)c == focused;
DWORD want = on ? accent : m_editBorder[i]; // 失焦时还原皮肤原本的边框色
if (c->GetBorderColor() != want) {
// 原来失焦硬编码 SetBorderSize(1),而皮肤 Edit 的原始边框宽度是 0,
// 于是每次聚焦再失焦都会在输入框里留下一圈 1px 深灰边(看着像黑框)。
// 改成还原各自原始的 RECT,没边框的就回到没边框。
RECT wantSize = on ? RECT{2, 2, 2, 2} : m_editBorderSize[i];
RECT cur = c->GetBorderSize();
bool sameSize = cur.left == wantSize.left && cur.top == wantSize.top &&
cur.right == wantSize.right && cur.bottom == wantSize.bottom;
if (c->GetBorderColor() != want || !sameSize) {
c->SetBorderColor(want);
c->SetBorderSize(on ? 2 : 1);
c->SetBorderSize(wantSize);
c->Invalidate();
}
}
@@ -1667,9 +1833,46 @@ public:
for (int i = 0; i < 15; i++) {
CControlUI *c = m_pm.FindControl(U8(names[i]).c_str());
m_editBorder[i] = c ? c->GetBorderColor() : 0;
m_editBorderSize[i] = c ? c->GetBorderSize() : RECT{0, 0, 0, 0};
}
}
// 把 DuiLib 自绘用的 bkcolor 同步给原生 EDIT 子窗口。
//
// 老 DuiLib 的 <Edit> 是「真 EDIT 子窗口」,聚焦时它自己的背景刷来自
// nativebkcolor(XML 属性)。一旦这个属性没解析成功(或皮肤忘了写),
// GetNativeEditBkColor() 就保持默认 0xFFFFFFFF,WM_CTLCOLOREDIT 里
// `if (clrColor == 0xFFFFFFFF) return 0;` 直接返回 0 —— 不设背景刷,
// EDIT 就透明,露出父窗口底色。深色皮肤上就是「输入框里嵌了一条更黑的带子」。
//
// 这里不去赌 XML,直接把控件自己的 bkcolor 灌给原生窗口,两套颜色永远一致。
void SyncNativeEditBg() {
static const char *names[] = {
"editUser", "editPass", "regUser", "regEmail", "regCode", "regPass", "regPass2",
"cardUser", "cardKey", "resetEmail", "resetCode", "resetPass", "resetCardKey",
"devIdx", "devCardKey"
};
const int n = (int)(sizeof(names) / sizeof(names[0]));
int synced = 0;
for (int i = 0; i < n; i++) {
CEditUI *e = static_cast<CEditUI *>(m_pm.FindControl(U8(names[i]).c_str()));
if (!e) continue;
DWORD bk = e->GetBkColor();
// 完全透明(0x00000000)的原生窗口会露出父窗口底色,退回到窗口底色
if ((bk & 0xFF000000) == 0) continue;
if (e->GetNativeEditBkColor() != bk) {
e->SetNativeEditBkColor(bk);
synced++;
}
}
#ifdef VFY_DEBUG_APPLY
{ HANDLE f = ::CreateFileW(L"C:\\vfy_editbg.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (f != INVALID_HANDLE_VALUE) { char b[128]; int m = snprintf(b, sizeof(b), "synced=%d/n", synced);
DWORD wr = 0; ::WriteFile(f, b, m, &wr, NULL); ::CloseHandle(f); } }
#endif
}
void UpdateRememberButton() {
if (CButtonUI *b = static_cast<CButtonUI *>(m_pm.FindControl(_T("btnRemember"))))
b->SetText(g_remember ? L"[ ✓ ] 记住账号" : L"[ ] 记住账号");
@@ -1739,6 +1942,8 @@ public:
m_pm.SetDefaultFont(L"Microsoft YaHei UI", 12, false, false, false);
m_pm.AddFont(1, L"Microsoft YaHei UI", 14, true, false, false);
m_pm.AddFont(2, L"Microsoft YaHei UI", 19, true, false, false);
// 3 号专给关闭按钮的 ×:默认 12/14/19 三档在大按钮里都显得小而细
m_pm.AddFont(3, L"Microsoft YaHei UI", 24, true, false, false);
CDialogBuilder builder;
std::wstring xml = U8(m_skin);
CControlUI *pRoot = builder.Create(xml.c_str(), (UINT)0, NULL, &m_pm);
@@ -1746,8 +1951,13 @@ public:
m_pm.AttachDialog(pRoot);
m_pm.AddNotifier(this);
if (CLabelUI *p = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblApp"))))
p->SetText(U8(g_name).c_str());
// 应用名显示在标题栏,不再单独占正文一行(原来写进 lblApp,就是那个
// 蓝色大字,既和标题栏重复、又白占一行高度)。cfg 里加壳时已经带了 name,
// 这里立刻就能用,不用等 /info。
if (CLabelUI *p = static_cast<CLabelUI *>(m_pm.FindControl(_T("lblTitle"))))
p->SetText((g_name[0] ? U8(g_name) : std::wstring(L"软件授权验证")).c_str());
HideByName("lblApp");
HideByName("lblBrand");
std::wstring devText = L"设备 ";
devText += U8(g_device);
@@ -1789,6 +1999,7 @@ public:
if (loginH > 0) m_chromeH = (rc.bottom - rc.top) - loginH;
SwitchTab(0);
CaptureBorders();
SyncNativeEditBg(); // 原生 EDIT 背景跟输入框底色对齐
::SetTimer(m_hWnd, 4, 150, NULL); // 焦点描边轮询
FetchAppInfo(); // 按后台设置裁剪界面(注册/重置/充值 tab、注册验证码)
CheckUpdate(); // 有强制更新就先拦更新页
@@ -1823,6 +2034,24 @@ public:
}
if (uMsg == WM_DESTROY) { ::KillTimer(m_hWnd, 4); ::PostQuitMessage(0); return 0; }
// WS_POPUP 的无边框窗口没有系统标题栏,不自己答 NCHITTEST 就完全拖不动。
// 把顶部 44px(各皮肤 btnClose 的高度)当标题栏交给系统原生拖动;
// 关闭按钮那块必须排除,否则它收不到点击。
// 必须在 m_pm.MessageHandler 之前处理,否则 DuiLib 先答 HTCLIENT 就没机会了。
if (uMsg == WM_NCHITTEST) {
POINT pt = { (short)LOWORD(lParam), (short)HIWORD(lParam) };
::ScreenToClient(m_hWnd, &pt);
if (CControlUI *pClose = m_pm.FindControl(_T("btnClose"))) {
if (pClose->IsVisible()) {
RECT r = pClose->GetPos();
if (pt.x >= r.left && pt.x < r.right && pt.y >= r.top && pt.y < r.bottom)
return HTCLIENT;
}
}
if (pt.y >= 0 && pt.y < 44) return HTCAPTION;
return HTCLIENT;
}
LRESULT lr = 0;
if (m_pm.MessageHandler(uMsg, wParam, lParam, lr)) return lr;
return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
@@ -1831,6 +2060,10 @@ public:
CPaintManagerUI m_pm;
const char *m_skin;
DWORD m_editBorder[15] = {0};
// 皮肤里 Edit 不写 bordersize,默认就是 0(不画边框)。
// 聚焦时为了突出,代码会临时把边框加到 2px;失焦时必须还原成各自原始的
// RECT,否则会凭空留下一圈 1px 深灰边 —— 深色皮肤上看着就是「输入框里有黑框」。
RECT m_editBorderSize[15] = {0};
int m_chromeH = 0; // 除面板外的固定高度(标题栏 + tab 行 + 页脚)
int m_iWidth = 0;
int m_iMinH = 380;
@@ -1845,9 +2078,13 @@ static int RunShell(void *oep) {
CVerifyWnd wnd(sk->xml);
UINT style = WS_POPUP | WS_CLIPCHILDREN;
UINT exstyle = WS_EX_TOPMOST | WS_EX_APPWINDOW;
// 不带 WS_EX_TOPMOST:验证窗压在用户所有窗口上面,切出去回个消息它还在最前,
// 只有一个窗口时看着像卡死。WS_EX_APPWINDOW 保留,任务栏上仍然有它。
UINT exstyle = WS_EX_APPWINDOW;
wnd.Create(NULL, L"软件授权验证", style, exstyle, 0, 0, sk->w, sk->h);
// 窗口标题同样用应用名:任务栏、Alt-Tab、截图工具的窗口名都会显示它
std::wstring wtitle = g_name[0] ? U8(g_name) : std::wstring(L"软件授权验证");
wnd.Create(NULL, wtitle.c_str(), style, exstyle, 0, 0, sk->w, sk->h);
wnd.CenterWindow();
::ShowWindow(wnd, SW_SHOW);
@@ -1903,7 +2140,8 @@ extern "C" __declspec(dllexport) int VerifyMain(void *oep, const char *cfgjson)
}
extern "C" __declspec(dllexport) int VerifyShellVersion(void) { return 9; }
extern "C" __declspec(dllexport) const char *VerifyShellThemes(void) {
return "dark,light,split,card,industrial,terminal,compact";
// 和 kSkins 里的顺序无关,只是给外部查询用;classic 现在也是 DuiLib 皮肤
return "dark,light,split,card,industrial,terminal,compact,classic";
}
BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) DisableThreadLibraryCalls(h);
File diff suppressed because it is too large Load Diff
+533
View File
@@ -0,0 +1,533 @@
// 由 gen_skins_v3.py 生成,不要手改
#pragma once
static const char *kSkin_dark = R"SKIN(<?xml version="1.0" encoding="utf-8"?>
<Window size="452,548" caption="0,0,-1,44" mininfo="452,548" bkcolor="#FF141418">
<VerticalLayout bkcolor="#FF141418" bordercolor="#FF32323A" bordersize="1">
<HorizontalLayout height="44" bkcolor="#FF1D1D24">
<Label text="软件授权验证" textcolor="#FFF0F0F4" font="1" inset="20,0,0,0" />
<Control />
<Button name="btnClose" text="X" width="38" height="44" textcolor="#FF9A9AA6"
bkcolor="#FF1D1D24" hotbkcolor="#33FFFFFF" pushedbkcolor="#66FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="42" bkcolor="#FF1D1D24">
<VerticalLayout width="86">
<Button name="tabLogin" text="登录" textcolor="#FF4EA3E8" bkcolor="#00000000" height="40" />
<Control height="2" bkcolor="#FF4EA3E8" />
</VerticalLayout>
<VerticalLayout width="86">
<Button name="tabRegister" text="注册" textcolor="#FF85858F" bkcolor="#00000000" height="40" />
<Control height="2" bkcolor="#00000000" name="tabRegLine" />
</VerticalLayout>
</HorizontalLayout>
<VerticalLayout inset="26,14,26,14">
<Label name="lblApp" text="演示程序" textcolor="#FF6FB6E8" height="26" font="1" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
<Label text="账号或卡密" textcolor="#FFB4B4BE" height="18" />
<Edit name="editUser" height="40" bkcolor="#FF2A2A33" nativebkcolor="#FF2A2A33" textcolor="#FFF4F4F8" bordercolor="#FF474755" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="#FFB4B4BE" height="18" />
<Edit name="editPass" height="40" bkcolor="#FF2A2A33" nativebkcolor="#FF2A2A33" textcolor="#FFF4F4F8" bordercolor="#FF474755" inset="10,0,0,0" password="true" />
<Control height="10" />
<HorizontalLayout height="22">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="#FFB4B4BE" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="#FFB4B4BE" bkcolor="#00000000" width="78" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnLogin" text="登 录" height="44" bkcolor="#FF146FB8" textcolor="#FFFFFFFF" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
<Label text="用户名" textcolor="#FFB4B4BE" height="18" />
<Edit name="regUser" height="34" bkcolor="#FF2A2A33" nativebkcolor="#FF2A2A33" textcolor="#FFF4F4F8" bordercolor="#FF474755" inset="10,0,0,0" />
<Control height="6" />
<Label text="邮箱" textcolor="#FFB4B4BE" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="#FF2A2A33" nativebkcolor="#FF2A2A33" textcolor="#FFF4F4F8" bordercolor="#FF474755" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="34" bkcolor="#FF2F6E4E" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<Label text="邮箱验证码" textcolor="#FFB4B4BE" height="18" />
<Edit name="regCode" height="34" bkcolor="#FF2A2A33" nativebkcolor="#FF2A2A33" textcolor="#FFF4F4F8" bordercolor="#FF474755" inset="10,0,0,0" />
<Control height="6" />
<Label text="密码" textcolor="#FFB4B4BE" height="18" />
<Edit name="regPass" height="34" bkcolor="#FF2A2A33" nativebkcolor="#FF2A2A33" textcolor="#FFF4F4F8" bordercolor="#FF474755" inset="10,0,0,0" password="true" />
<Control height="6" />
<Label text="确认密码" textcolor="#FFB4B4BE" height="18" />
<Edit name="regPass2" height="34" bkcolor="#FF2A2A33" nativebkcolor="#FF2A2A33" textcolor="#FFF4F4F8" bordercolor="#FF474755" inset="10,0,0,0" password="true" />
<Control height="12" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="#FF1F8A5B" textcolor="#FFFFFFFF" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<Control height="6" />
<Label name="lblDevice" text="设备" textcolor="#FF5C5C68" height="18" />
<HorizontalLayout height="24">
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF7FA5CC" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF7FA5CC" bkcolor="#00000000" />
<Control />
</HorizontalLayout>
</VerticalLayout>
</VerticalLayout>
</Window>)SKIN";
static const char *kSkin_light = R"SKIN(<?xml version="1.0" encoding="utf-8"?>
<Window size="452,548" caption="0,0,-1,44" mininfo="452,548" bkcolor="#FFFAFAFC">
<VerticalLayout bkcolor="#FFFAFAFC" bordercolor="#FFDCDCE3" bordersize="1">
<HorizontalLayout height="44" bkcolor="#FFFFFFFF">
<Label text="软件授权验证" textcolor="#FF1F1F24" font="1" inset="20,0,0,0" />
<Control />
<Button name="btnClose" text="X" width="38" height="44" textcolor="#FF6B6B75"
bkcolor="#FFFFFFFF" hotbkcolor="#33FFFFFF" pushedbkcolor="#66FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="20" />
<HorizontalLayout height="42" inset="26,0,26,0">
<Button name="tabLogin" text="登录" width="100" height="40" bkcolor="#FF1B6FD6" textcolor="#FFFFFFFF" font="1" />
<Control width="8" />
<Button name="tabRegister" text="注册" width="100" height="40" bkcolor="#FFEDF0F5" textcolor="#FF5B6270" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="26,16,26,14">
<Label name="lblApp" text="演示程序" textcolor="#FF1B6FD6" height="26" font="1" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
<Label text="账号或卡密" textcolor="#FF4B5563" height="18" />
<Edit name="editUser" height="40" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="#FF4B5563" height="18" />
<Edit name="editPass" height="40" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" password="true" />
<Control height="10" />
<HorizontalLayout height="22">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="#FF4B5563" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="#FF4B5563" bkcolor="#00000000" width="78" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnLogin" text="登录" height="44" bkcolor="#FF1B6FD6" textcolor="#FFFFFFFF" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
<Label text="用户名" textcolor="#FF4B5563" height="18" />
<Edit name="regUser" height="34" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" />
<Control height="6" />
<Label text="邮箱" textcolor="#FF4B5563" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="34" bkcolor="#FFD8EAE0" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<Label text="邮箱验证码" textcolor="#FF4B5563" height="18" />
<Edit name="regCode" height="34" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" />
<Control height="6" />
<Label text="密码" textcolor="#FF4B5563" height="18" />
<Edit name="regPass" height="34" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" password="true" />
<Control height="6" />
<Label text="确认密码" textcolor="#FF4B5563" height="18" />
<Edit name="regPass2" height="34" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" password="true" />
<Control height="12" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="#FF128A5B" textcolor="#FFFFFFFF" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<Control height="6" />
<Label name="lblDevice" text="设备" textcolor="#FF8A8F99" height="18" />
<HorizontalLayout height="24">
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF3B62B8" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF3B62B8" bkcolor="#00000000" />
<Control />
</HorizontalLayout>
</VerticalLayout>
</VerticalLayout>
</Window>)SKIN";
static const char *kSkin_split = R"SKIN(<?xml version="1.0" encoding="utf-8"?>
<Window size="660,548" caption="0,0,0,0" mininfo="660,548" bkcolor="#FF12151A">
<HorizontalLayout bkcolor="#FF12151A" bordercolor="#FF282D35" bordersize="1">
<VerticalLayout width="200" bkcolor="#FF1A2230">
<HorizontalLayout height="44" inset="24,0,0,0">
<Label text="VFY" textcolor="#FF4CC2FF" font="1" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="24,4,24,0">
<Label text="软件授权" textcolor="#FFC8D3E0" height="28" font="1" />
<Label text="SOFTWARE LICENSE" textcolor="#FF63707E" height="20" />
<Label text="账号登录后可绑定本机设备" textcolor="#FF4C5A68" height="20" margin="0,14,0,0" />
</VerticalLayout>
<VerticalLayout />
<HorizontalLayout height="28" inset="24,0,24,16">
<Label text="v9 · DuiLib" textcolor="#FF4A5764" />
</HorizontalLayout>
</VerticalLayout>
<VerticalLayout>
<HorizontalLayout height="46" inset="28,0,0,0">
<VerticalLayout width="80">
<Button name="tabLogin" text="登录" height="44" bkcolor="#00000000" textcolor="#FF4CC2FF" font="1" />
<Control height="2" bkcolor="#FF4CC2FF" />
</VerticalLayout>
<VerticalLayout width="80">
<Button name="tabRegister" text="注册" height="44" bkcolor="#00000000" textcolor="#FF7A8794" />
<Control name="tabRegLine" height="2" bkcolor="#00000000" />
</VerticalLayout>
<Control />
</HorizontalLayout>
<VerticalLayout inset="28,8,28,16">
<Label name="lblApp" text="演示程序" textcolor="#FFF0F5FA" height="26" font="1" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
<Label text="账号或卡密" textcolor="#FF8794A3" height="18" />
<Edit name="editUser" height="40" bkcolor="#FF1A1F27" nativebkcolor="#FF1A1F27" textcolor="#FFF2F6FA" bordercolor="#FF2E343D" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="#FF8794A3" height="18" />
<Edit name="editPass" height="40" bkcolor="#FF1A1F27" nativebkcolor="#FF1A1F27" textcolor="#FFF2F6FA" bordercolor="#FF2E343D" inset="10,0,0,0" password="true" />
<Control height="10" />
<HorizontalLayout height="22">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="#FF8794A3" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="#FF8794A3" bkcolor="#00000000" width="78" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnLogin" text="登录" height="44" bkcolor="#FF2C7BE5" textcolor="#FFFFFFFF" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
<Label text="用户名" textcolor="#FF8794A3" height="18" />
<Edit name="regUser" height="34" bkcolor="#FF1A1F27" nativebkcolor="#FF1A1F27" textcolor="#FFF2F6FA" bordercolor="#FF2E343D" inset="10,0,0,0" />
<Control height="6" />
<Label text="邮箱" textcolor="#FF8794A3" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="#FF1A1F27" nativebkcolor="#FF1A1F27" textcolor="#FFF2F6FA" bordercolor="#FF2E343D" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="34" bkcolor="#FF2B6A50" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<Label text="邮箱验证码" textcolor="#FF8794A3" height="18" />
<Edit name="regCode" height="34" bkcolor="#FF1A1F27" nativebkcolor="#FF1A1F27" textcolor="#FFF2F6FA" bordercolor="#FF2E343D" inset="10,0,0,0" />
<Control height="6" />
<Label text="密码" textcolor="#FF8794A3" height="18" />
<Edit name="regPass" height="34" bkcolor="#FF1A1F27" nativebkcolor="#FF1A1F27" textcolor="#FFF2F6FA" bordercolor="#FF2E343D" inset="10,0,0,0" password="true" />
<Control height="6" />
<Label text="确认密码" textcolor="#FF8794A3" height="18" />
<Edit name="regPass2" height="34" bkcolor="#FF1A1F27" nativebkcolor="#FF1A1F27" textcolor="#FFF2F6FA" bordercolor="#FF2E343D" inset="10,0,0,0" password="true" />
<Control height="12" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="#FF1F8A5B" textcolor="#FFFFFFFF" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<Control height="6" />
<Label name="lblDevice" text="设备" textcolor="#FF5E6B78" height="18" />
<HorizontalLayout height="24">
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF6FA8DC" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF6FA8DC" bkcolor="#00000000" />
<Control />
</HorizontalLayout>
</VerticalLayout>
</VerticalLayout>
</HorizontalLayout>
</Window>)SKIN";
static const char *kSkin_card = R"SKIN(<?xml version="1.0" encoding="utf-8"?>
<Window size="700,564" caption="0,0,-1,92" mininfo="700,564" bkcolor="#FFF5F6F9">
<VerticalLayout bkcolor="#FFF5F6F9" bordercolor="#FFD7DBE3" bordersize="1">
<HorizontalLayout height="92" bkcolor="#FF3B2BD6">
<VerticalLayout inset="28,16,0,0">
<Label text="软件授权验证" textcolor="#FFFFFFFF" font="1" height="34" />
<Label name="lblApp" text="演示程序" textcolor="#FFD9D4FF" height="22" />
</VerticalLayout>
<Control />
<Button name="btnClose" text="X" width="46" height="92" textcolor="#FFEDEBFF" bkcolor="#FF3B2BD6" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="54" inset="28,14,28,0">
<Button name="tabLogin" text="登录" width="112" height="38" bkcolor="#FFFFFFFF" textcolor="#FF3B2BD6" font="1" />
<Control width="8" />
<Button name="tabRegister" text="注册" width="112" height="38" bkcolor="#FFE8E6FF" textcolor="#FF5B56A8" />
<Control />
</HorizontalLayout>
<HorizontalLayout inset="28,16,28,18">
<VerticalLayout width="260">
<Label text="账号安全" textcolor="#FF1F2430" height="26" font="1" />
<Label text="登录后账号与本机设备绑定," textcolor="#FF4B5563" height="20" />
<Label text="超出设备上限时请先下线一台。" textcolor="#FF4B5563" height="20" />
<Control height="12" />
<Label name="lblDevice" text="设备" textcolor="#FF8A8F99" height="20" />
<VerticalLayout />
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF3B2BD6" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF3B2BD6" bkcolor="#00000000" />
</VerticalLayout>
<Control width="28" />
<VerticalLayout>
<VerticalLayout name="panelLogin" height="auto">
<Label text="账号或卡密" textcolor="#FF4B5563" height="18" />
<Edit name="editUser" height="40" bkcolor="#FFFFFFFF" nativebkcolor="#FFFFFFFF" textcolor="#FF1F2430" bordercolor="#FFC9D1DC" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="#FF4B5563" height="18" />
<Edit name="editPass" height="40" bkcolor="#FFFFFFFF" nativebkcolor="#FFFFFFFF" textcolor="#FF1F2430" bordercolor="#FFC9D1DC" inset="10,0,0,0" password="true" />
<Control height="10" />
<HorizontalLayout height="22">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="#FF4B5563" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="#FF4B5563" bkcolor="#00000000" width="78" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnLogin" text="登录" height="44" bkcolor="#FF3B2BD6" textcolor="#FFFFFFFF" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
<Label text="用户名" textcolor="#FF4B5563" height="18" />
<Edit name="regUser" height="34" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" />
<Control height="6" />
<Label text="邮箱" textcolor="#FF4B5563" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="34" bkcolor="#FFD8EAE0" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<Label text="邮箱验证码" textcolor="#FF4B5563" height="18" />
<Edit name="regCode" height="34" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" />
<Control height="6" />
<Label text="密码" textcolor="#FF4B5563" height="18" />
<Edit name="regPass" height="34" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" password="true" />
<Control height="6" />
<Label text="确认密码" textcolor="#FF4B5563" height="18" />
<Edit name="regPass2" height="34" bkcolor="#FFF1F3F7" nativebkcolor="#FFF1F3F7" textcolor="#FF1F2430" bordercolor="#FFC3CBD8" inset="10,0,0,0" password="true" />
<Control height="12" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="#FF128A5B" textcolor="#FFFFFFFF" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
</VerticalLayout>
</HorizontalLayout>
</VerticalLayout>
</Window>)SKIN";
static const char *kSkin_industrial = R"SKIN(<?xml version="1.0" encoding="utf-8"?>
<Window size="580,548" caption="0,0,-1,46" mininfo="580,548" bkcolor="#FF0A1520">
<VerticalLayout bkcolor="#FF0A1520" bordercolor="#FF1F4E79" bordersize="1">
<HorizontalLayout height="46" bkcolor="#FF10304C">
<Label text="AUTHORIZATION" textcolor="#FF7FD1FF" font="1" inset="18,0,0,0" />
<Control />
<Button name="tabLogin" text="LOGIN" width="80" height="46" bkcolor="#FF1A5A8C" textcolor="#FFFFFFFF" />
<Button name="tabRegister" text="REGISTER" width="96" height="46" bkcolor="#00000000" textcolor="#FF9FC8E6" />
<Button name="btnClose" text="X" width="46" height="46" textcolor="#FFBEE3FF" bkcolor="#FF10304C" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<VerticalLayout inset="24,16,24,16">
<Label name="lblApp" text="演示程序" textcolor="#FF8FC4E6" height="26" font="1" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
<Label text="账号或卡密" textcolor="#FF9FC0D8" height="18" />
<Edit name="editUser" height="40" bkcolor="#FF14304A" nativebkcolor="#FF14304A" textcolor="#FFEAF6FF" bordercolor="#FF23567F" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="#FF9FC0D8" height="18" />
<Edit name="editPass" height="40" bkcolor="#FF14304A" nativebkcolor="#FF14304A" textcolor="#FFEAF6FF" bordercolor="#FF23567F" inset="10,0,0,0" password="true" />
<Control height="10" />
<HorizontalLayout height="22">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="#FF9FC0D8" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="#FF9FC0D8" bkcolor="#00000000" width="78" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnLogin" text="登录" height="44" bkcolor="#FF1F6FB2" textcolor="#FFFFFFFF" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
<Label text="用户名" textcolor="#FF9FC0D8" height="18" />
<Edit name="regUser" height="34" bkcolor="#FF14304A" nativebkcolor="#FF14304A" textcolor="#FFEAF6FF" bordercolor="#FF23567F" inset="10,0,0,0" />
<Control height="6" />
<Label text="邮箱" textcolor="#FF9FC0D8" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="#FF14304A" nativebkcolor="#FF14304A" textcolor="#FFEAF6FF" bordercolor="#FF23567F" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="34" bkcolor="#FF1B4A3C" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<Label text="邮箱验证码" textcolor="#FF9FC0D8" height="18" />
<Edit name="regCode" height="34" bkcolor="#FF14304A" nativebkcolor="#FF14304A" textcolor="#FFEAF6FF" bordercolor="#FF23567F" inset="10,0,0,0" />
<Control height="6" />
<Label text="密码" textcolor="#FF9FC0D8" height="18" />
<Edit name="regPass" height="34" bkcolor="#FF14304A" nativebkcolor="#FF14304A" textcolor="#FFEAF6FF" bordercolor="#FF23567F" inset="10,0,0,0" password="true" />
<Control height="6" />
<Label text="确认密码" textcolor="#FF9FC0D8" height="18" />
<Edit name="regPass2" height="34" bkcolor="#FF14304A" nativebkcolor="#FF14304A" textcolor="#FFEAF6FF" bordercolor="#FF23567F" inset="10,0,0,0" password="true" />
<Control height="12" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="#FF1F7A5E" textcolor="#FFFFFFFF" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<Control height="6" />
<Label name="lblDevice" text="设备" textcolor="#FF5F89A6" height="18" />
<HorizontalLayout height="24">
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF6FA8C8" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF6FA8C8" bkcolor="#00000000" />
<Control />
</HorizontalLayout>
</VerticalLayout>
</VerticalLayout>
</Window>)SKIN";
static const char *kSkin_terminal = R"SKIN(<?xml version="1.0" encoding="utf-8"?>
<Window size="600,548" caption="0,0,-1,38" mininfo="600,548" bkcolor="#FF0B0F0C">
<VerticalLayout bkcolor="#FF0B0F0C" bordercolor="#FF2B3A2D" bordersize="1">
<HorizontalLayout height="38" bkcolor="#FF101710">
<Label text="vfy@local:~$" textcolor="#FF54C97A" inset="14,0,0,0" />
<Control />
<Button name="btnClose" text="X" width="38" height="38" textcolor="#FF7FB08C" bkcolor="#FF101710" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<HorizontalLayout height="34" bkcolor="#FF0E150F">
<Button name="tabLogin" text="[ login ]" width="96" height="34" bkcolor="#00000000" textcolor="#FF7FE39B" />
<Button name="tabRegister" text="[ register ]" width="108" height="34" bkcolor="#00000000" textcolor="#FF4E7A5C" />
<Control />
</HorizontalLayout>
<VerticalLayout inset="16,10,16,12">
<Label name="lblApp" text="# 演示程序" textcolor="#FF7FE39B" height="24" />
<Control height="6" />
<VerticalLayout name="panelLogin" height="auto">
<Label text="账号或卡密" textcolor="#FF5E8A6C" height="18" />
<Edit name="editUser" height="40" bkcolor="#FF16211A" nativebkcolor="#FF16211A" textcolor="#FFD7F5DF" bordercolor="#FF2B3A2D" inset="10,0,0,0" />
<Control height="10" />
<Label text="密码" textcolor="#FF5E8A6C" height="18" />
<Edit name="editPass" height="40" bkcolor="#FF16211A" nativebkcolor="#FF16211A" textcolor="#FFD7F5DF" bordercolor="#FF2B3A2D" inset="10,0,0,0" password="true" />
<Control height="10" />
<HorizontalLayout height="22">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="#FF5E8A6C" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="#FF5E8A6C" bkcolor="#00000000" width="78" />
</HorizontalLayout>
<Control height="12" />
<Button name="btnLogin" text="[ 执行登录 ]" height="44" bkcolor="#FF1B7A4E" textcolor="#FFFFFFFF" font="1" />
<Label name="lblTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
<Label text="用户名" textcolor="#FF5E8A6C" height="18" />
<Edit name="regUser" height="34" bkcolor="#FF16211A" nativebkcolor="#FF16211A" textcolor="#FFD7F5DF" bordercolor="#FF2B3A2D" inset="10,0,0,0" />
<Control height="6" />
<Label text="邮箱" textcolor="#FF5E8A6C" height="18" />
<HorizontalLayout height="38">
<Edit name="regEmail" bkcolor="#FF16211A" nativebkcolor="#FF16211A" textcolor="#FFD7F5DF" bordercolor="#FF2B3A2D" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="104" height="34" bkcolor="#FF234A33" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<Label text="邮箱验证码" textcolor="#FF5E8A6C" height="18" />
<Edit name="regCode" height="34" bkcolor="#FF16211A" nativebkcolor="#FF16211A" textcolor="#FFD7F5DF" bordercolor="#FF2B3A2D" inset="10,0,0,0" />
<Control height="6" />
<Label text="密码" textcolor="#FF5E8A6C" height="18" />
<Edit name="regPass" height="34" bkcolor="#FF16211A" nativebkcolor="#FF16211A" textcolor="#FFD7F5DF" bordercolor="#FF2B3A2D" inset="10,0,0,0" password="true" />
<Control height="6" />
<Label text="确认密码" textcolor="#FF5E8A6C" height="18" />
<Edit name="regPass2" height="34" bkcolor="#FF16211A" nativebkcolor="#FF16211A" textcolor="#FFD7F5DF" bordercolor="#FF2B3A2D" inset="10,0,0,0" password="true" />
<Control height="12" />
<Button name="btnRegister" text="注册并登录" height="44" bkcolor="#FF1B7A4E" textcolor="#FFFFFFFF" font="1" />
<Label name="regTip" text="" textcolor="#FFE08A8A" height="24" inset="0,6,0,0" />
</VerticalLayout>
<Control height="6" />
<Label name="lblDevice" text="设备" textcolor="#FF4E7A5C" height="18" />
<HorizontalLayout height="24">
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF6FA08A" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF6FA08A" bkcolor="#00000000" />
<Control />
</HorizontalLayout>
</VerticalLayout>
</VerticalLayout>
</Window>)SKIN";
static const char *kSkin_compact = R"SKIN(<?xml version="1.0" encoding="utf-8"?>
<Window size="760,206" caption="0,0,-1,38" mininfo="760,206" bkcolor="#FF11151A">
<VerticalLayout bkcolor="#FF11151A" bordercolor="#FF2A3440" bordersize="1">
<HorizontalLayout height="38" bkcolor="#FF161C22">
<Label text="账号" textcolor="#FFA8BCCE" inset="16,0,0,0" />
<Control />
<Button name="btnClose" text="X" width="38" height="38" textcolor="#FFA8BCCE" bkcolor="#FF161C22" hotbkcolor="#33FFFFFF" />
</HorizontalLayout>
<HorizontalLayout inset="16,12,16,10">
<VerticalLayout width="200">
<Label name="lblApp" text="演示程序" textcolor="#FFEAF2FA" height="26" font="1" />
<Label name="lblDevice" text="设备" textcolor="#FF6B7C8C" height="20" />
<Control height="12" />
<Button name="tabLogin" text="登录" width="90" height="32" bkcolor="#FF2E9E6B" textcolor="#FFFFFFFF" />
<Control height="6" />
<Button name="tabRegister" text="注册" width="90" height="32" bkcolor="#FF1B232B" textcolor="#FF9FB3C8" />
</VerticalLayout>
<Control width="16" />
<VerticalLayout>
<VerticalLayout name="panelLogin" height="auto">
<HorizontalLayout height="40">
<HorizontalLayout width="214" bkcolor="#FF1B232B">
<Label text="账号" width="46" textcolor="#FF7E90A2" inset="10,0,0,0" />
<Edit name="editUser" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" inset="0,0,0,0" />
</HorizontalLayout>
<Control width="10" />
<HorizontalLayout width="214" bkcolor="#FF1B232B">
<Label text="密码" width="46" textcolor="#FF7E90A2" inset="10,0,0,0" />
<Edit name="editPass" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" inset="0,0,0,0" password="true" />
</HorizontalLayout>
<Control width="10" />
<Button name="btnLogin" text="登录" width="110" height="40" bkcolor="#FF2E9E6B" textcolor="#FFFFFFFF" font="1" />
</HorizontalLayout>
<HorizontalLayout height="26">
<Label name="chkBox" width="14" height="14" bkcolor="#00000000" bordercolor="#FF6B7C8C" bordersize="1" />
<Control width="8" />
<Button name="btnRemember" text="记住账号" textcolor="#FF6B7C8C" bkcolor="#00000000" width="120" />
<Label name="lblTip" text="" textcolor="#FFD98A8A" />
</HorizontalLayout>
<Control height="6" />
<HorizontalLayout height="24">
<Button name="btnLinkCard" text="卡密充值" width="96" textcolor="#FF7FA5CC" bkcolor="#00000000" />
<Button name="btnLinkForgot" text="忘记密码" width="96" textcolor="#FF7FA5CC" bkcolor="#00000000" />
<Control />
</HorizontalLayout>
</VerticalLayout>
<VerticalLayout name="panelRegister" height="auto" visible="false">
<HorizontalLayout height="36">
<Edit name="regUser" width="160" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" />
<Control width="8" />
<Edit name="regEmail" width="200" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" />
<Control width="8" />
<Button name="btnSendCode" text="发送验证码" width="100" height="36" bkcolor="#FF234A33" textcolor="#FFFFFFFF" />
</HorizontalLayout>
<Control height="6" />
<HorizontalLayout height="36">
<Edit name="regCode" width="160" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" />
<Control width="8" />
<Edit name="regPass" width="150" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" password="true" />
<Control width="8" />
<Edit name="regPass2" width="150" bkcolor="#FF1B232B" nativebkcolor="#FF1B232B" textcolor="#FFFFFFFF" bordercolor="#FF32404E" inset="10,0,0,0" password="true" />
<Control width="8" />
<Button name="btnRegister" text="注册" width="90" height="36" bkcolor="#FF2E9E6B" textcolor="#FFFFFFFF" font="1" />
</HorizontalLayout>
<Label name="regTip" text="" textcolor="#FFD98A8A" height="22" />
</VerticalLayout>
</VerticalLayout>
</HorizontalLayout>
</VerticalLayout>
</Window>)SKIN";
struct SkinDef { const char *name; const char *xml; int w, h; };
static const SkinDef kSkins[] = {
{ "dark", kSkin_dark, 452, 548 },
{ "light", kSkin_light, 452, 548 },
{ "split", kSkin_split, 660, 548 },
{ "card", kSkin_card, 700, 564 },
{ "industrial", kSkin_industrial, 580, 548 },
{ "terminal", kSkin_terminal, 600, 548 },
{ "compact", kSkin_compact, 760, 206 },
{ NULL, NULL, 0, 0 }
};
File diff suppressed because it is too large Load Diff