Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccd46aafb3 | ||
|
|
88216ce644 | ||
|
|
4ba2b27398 | ||
|
|
2c8a8af514 | ||
|
|
2dbd321ef0 | ||
|
|
ae6093cf23 | ||
|
|
fc80a598c0 | ||
|
|
297f0428cc | ||
|
|
06c26dee87 | ||
|
|
8df62d6486 | ||
|
|
810d72fa04 | ||
|
|
179d1efe01 | ||
|
|
4e62fdc80b | ||
|
|
4520687fbe | ||
|
|
a9b8440731 | ||
|
|
f3bfec04a5 | ||
|
|
168f414cd9 | ||
|
|
b92c8ad881 | ||
|
|
e6a69b05a7 | ||
|
|
f3e0c4e45a | ||
|
|
65e819d96e | ||
|
|
3c2a402b8a | ||
|
|
78101b3512 | ||
|
|
613b2b1e68 | ||
|
|
87bab6666b | ||
|
|
605b5d1104 | ||
|
|
d40c803ed9 | ||
|
|
c15625dbd8 | ||
|
|
fb451ff3e8 | ||
|
|
4391b45c41 | ||
|
|
5fe6b31eb6 | ||
|
|
b3838d204f | ||
|
|
1568942ae6 | ||
|
|
fadc7ce316 | ||
|
|
afa4ccc5e0 | ||
|
|
08ec771234 | ||
|
|
bdb4fce8b8 | ||
|
|
9f212d2f19 | ||
|
|
9bdc6510bd | ||
|
|
5e0cbb026b | ||
|
|
2f8b1c8e68 | ||
|
|
6a1042e33f | ||
|
|
c2d028af2e | ||
|
|
0e3bbc6906 | ||
|
|
0503af2fcc | ||
|
|
f581fab396 | ||
|
|
e224a0c6ea | ||
|
|
cd0466a7e3 | ||
|
|
cce9ab07eb | ||
|
|
bfd00a14db | ||
|
|
5a64acd807 | ||
|
|
897f55c88b | ||
|
|
9e34ebc0d4 | ||
|
|
e842f6128b | ||
|
|
a4bf838bfd | ||
|
|
b4f5e9b71b | ||
|
|
383f6aa818 | ||
|
|
ebd02c3f3d | ||
|
|
6492500158 | ||
|
|
9c61d991bd | ||
|
|
da26d6796f | ||
|
|
e8cb49ced9 | ||
|
|
bd9236e3fa | ||
|
|
ccbee78cc7 | ||
|
|
2fea3ca4d9 | ||
|
|
6a278721b2 | ||
|
|
be05d47dd4 | ||
|
|
f9d251d1fa | ||
|
|
06106d2bd3 | ||
|
|
a3467a8d89 | ||
|
|
21431e525d | ||
|
|
9e60de32fe | ||
|
|
5885187e7d | ||
|
|
51eb1f733d | ||
|
|
216213e102 | ||
|
|
74939da3d7 | ||
|
|
defe15694b | ||
|
|
4d93c727bb | ||
|
|
03aec3b052 | ||
|
|
6f484e06e6 | ||
|
|
939d740beb | ||
|
|
4f175afab5 | ||
|
|
b5452c59e6 | ||
|
|
8cd7d51d80 | ||
|
|
2ae9a47249 | ||
|
|
a824e0b46a | ||
|
|
b53004ee23 | ||
|
|
da04381436 | ||
|
|
c04864dd21 | ||
|
|
a67c95407e | ||
|
|
852004291b | ||
|
|
01688c7567 | ||
|
|
aff6ad9179 | ||
|
|
588fdab8de | ||
|
|
4825434ffa | ||
|
|
9f7f34cd8f | ||
|
|
ffede67aed | ||
|
|
920f75718a | ||
|
|
b7d648ea0f | ||
|
|
bb56030979 | ||
|
|
4425bee612 | ||
|
|
369a82b5e4 | ||
|
|
35958a7fc2 | ||
|
|
3c73d1d5b0 | ||
|
|
b37b17f7d8 | ||
|
|
5e73d69663 | ||
|
|
9b470d0412 | ||
|
|
7ab91c81e9 | ||
|
|
c17fff6e2f | ||
|
|
90f65654c7 | ||
|
|
fbc2aa052b | ||
|
|
b6fb5bd530 | ||
|
|
cd04271b69 | ||
|
|
9914db69e6 | ||
|
|
fc424ab740 | ||
|
|
d984833914 | ||
|
|
c49a5a0aa8 | ||
|
|
4802dfe7aa | ||
|
|
8fbcbd29ff | ||
|
|
1914807770 | ||
|
|
c09c6e0883 | ||
|
|
fd57eb4b6f | ||
|
|
d9dfe513ee | ||
|
|
eda1c32994 | ||
|
|
447b40a259 | ||
|
|
0d4d58605f | ||
|
|
d3d1d2512e | ||
|
|
bfde0daab4 | ||
|
|
852870db59 | ||
|
|
8a7b2413f4 | ||
|
|
d35e276730 | ||
|
|
e86fd707ea | ||
|
|
55c9ee59f5 | ||
|
|
908aaf9dc8 | ||
|
|
b6107e38d8 | ||
|
|
e1e0c6b02f | ||
|
|
ac20956076 | ||
|
|
18d8273f5c | ||
|
|
0e6e2ec51d | ||
|
|
007dfaf6e2 | ||
|
|
8dde7ef8e2 | ||
|
|
5f90cc9b6e | ||
|
|
a4ab4e92b5 | ||
|
|
1b968b9126 | ||
|
|
e83eb80f2c | ||
|
|
0e4d958b5f | ||
|
|
631cc982a0 | ||
|
|
7b91903f80 | ||
|
|
5324e2f014 | ||
|
|
c236bc86ee | ||
|
|
9a6c17cb27 | ||
|
|
efac547d6a | ||
|
|
770b224d58 | ||
|
|
0d03b00643 | ||
|
|
d3eb3bae14 | ||
|
|
5f01c6ab5f | ||
|
|
6cb7f2c6d0 | ||
|
|
07c08ed74d | ||
|
|
b20ed12761 | ||
|
|
c027161a64 | ||
|
|
95b5878456 | ||
|
|
f127e3dc59 | ||
|
|
7b93eb2716 | ||
|
|
abef7973d9 | ||
|
|
7744e24af2 | ||
|
|
884db940df | ||
|
|
3e99d3bb5a | ||
|
|
b5ede95772 | ||
|
|
1f2bf4d3f2 | ||
|
|
c85c510c0b | ||
|
|
99547e847e | ||
|
|
d17381a221 | ||
|
|
a11c684dfd | ||
|
|
72aedbc612 | ||
|
|
63ab7a1846 | ||
|
|
3932958c39 | ||
|
|
ade76d3d2f | ||
|
|
c822c5dab6 | ||
|
|
a8f24b8f13 | ||
|
|
f111ba7129 | ||
|
|
3db89d0bd0 | ||
|
|
298d174640 | ||
|
|
29a792cfdf | ||
|
|
c1d27c5055 | ||
|
|
85ca207279 | ||
|
|
d89b095af5 | ||
|
|
15a6fe3785 | ||
|
|
ae17bc0cf5 | ||
|
|
891a197335 | ||
|
|
b6cde5101d | ||
|
|
9d67630396 | ||
|
|
6f6f372337 | ||
|
|
5be852f394 | ||
|
|
ab45667fdf | ||
|
|
ab40f086ee | ||
|
|
8e173cf7d7 | ||
|
|
f4170b014a | ||
|
|
f424454422 | ||
|
|
5d6ce86b66 | ||
|
|
9ca64bed10 | ||
|
|
2f374ea8c9 | ||
|
|
c90a3954e4 | ||
|
|
397087dc74 | ||
|
|
b807825a09 | ||
|
|
48e2777bc3 | ||
|
|
a8307891fa | ||
|
|
b6c476390f | ||
|
|
fc4d3a9c5d | ||
|
|
1f23e6e9f0 | ||
|
|
0cf9cdd0d7 | ||
|
|
90456def2e | ||
|
|
8fc5917b3b | ||
|
|
65195abbe0 | ||
|
|
d5fbd6fa06 | ||
|
|
383ddb0a5d | ||
|
|
11866caa2f | ||
|
|
c5611ed622 | ||
|
|
a7667f1cd5 | ||
|
|
c839121fdb | ||
|
|
f9900053b0 | ||
|
|
14a61f4ce8 | ||
|
|
7285db1e37 | ||
|
|
369dea582c | ||
|
|
4f0a0f89ae | ||
|
|
01ef98abb6 | ||
|
|
62eb8fd763 | ||
|
|
547640bbfd | ||
|
|
f8caa92333 | ||
|
|
57ff0e69d8 | ||
|
|
053137669a | ||
|
|
37f768dd33 | ||
|
|
5dc3ec88d4 | ||
|
|
688402814c | ||
|
|
7ec74f2928 | ||
|
|
2b15bc6710 | ||
|
|
196f98e97c | ||
|
|
ea1c5ff9eb | ||
|
|
659970077a | ||
|
|
5d39cf5782 | ||
|
|
12b01907bc | ||
|
|
219d60410a | ||
|
|
182df4b0e2 | ||
|
|
6c2a3fc325 | ||
|
|
5eaac0870c | ||
|
|
04591517fa | ||
|
|
e1f5267764 | ||
|
|
85182795b5 | ||
|
|
70fd40e34c | ||
|
|
0e8a194d4f | ||
|
|
d2490787ae | ||
|
|
0163af979a | ||
|
|
75f14540c8 | ||
|
|
5e0d2db8b2 | ||
|
|
18014fb3c5 | ||
|
|
355cce1e52 | ||
|
|
04a9016a7d | ||
|
|
cf7de9f7bd | ||
|
|
a60385c376 | ||
|
|
351db573d8 | ||
|
|
3b023b3275 | ||
|
|
319c7d607d | ||
|
|
9de12db447 | ||
|
|
ecea72df40 | ||
|
|
214287da28 | ||
|
|
81969a4590 | ||
|
|
860848a310 | ||
|
|
39338c3f1d | ||
|
|
02de2acea4 | ||
|
|
3eba2a677c | ||
|
|
78b0e1a124 | ||
|
|
feaa94bec7 | ||
|
|
67f8bf3941 | ||
|
|
7343ae6372 | ||
|
|
41bad7f24c | ||
|
|
19c03eb0ba | ||
|
|
fbc5a3c981 | ||
|
|
1ce7385d1e | ||
|
|
3a4af38842 | ||
|
|
e11601bfec | ||
|
|
a305afbc76 | ||
|
|
84cdd99868 | ||
|
|
bae9f8edb0 | ||
|
|
f9ce49ac7e | ||
|
|
bb752b13a1 | ||
|
|
a9f5f277f1 | ||
|
|
de3bb4817d | ||
|
|
a7522deb82 | ||
|
|
53f68b3945 | ||
|
|
5302341dfc | ||
|
|
fb7675f3cb | ||
|
|
1d2a56bcdb | ||
|
|
74c7e086c7 | ||
|
|
9ad37d4ada | ||
|
|
1bdb8a40c4 | ||
|
|
4e0ec92c23 | ||
|
|
2b3d1c67c2 | ||
|
|
b918450483 | ||
|
|
157cc90397 | ||
|
|
1bd126562f | ||
|
|
e160837f8b | ||
|
|
4593ba3340 | ||
|
|
45aae92af5 | ||
|
|
839de51519 | ||
|
|
11e7584d1c | ||
|
|
f470b7a10c | ||
|
|
8b87f80951 | ||
|
|
b135752577 | ||
|
|
fd2345b772 | ||
|
|
907cfddfa3 | ||
|
|
7f391e065e | ||
|
|
9efe16237d | ||
|
|
c7b7c0b323 | ||
|
|
e2415210cd | ||
|
|
127f2cd2d6 | ||
|
|
ebadfb968b | ||
|
|
bba9b82ce9 | ||
|
|
9d1e39f25f | ||
|
|
b9d8247309 | ||
|
|
95f24ffc4a | ||
|
|
870504ae3a | ||
|
|
d497f1e6c7 | ||
|
|
e406a3bc2b | ||
|
|
4d75dc9ae3 | ||
|
|
a704f12945 | ||
|
|
9e21c3a7ef | ||
|
|
9f2eb37232 | ||
|
|
b00f5ab759 | ||
|
|
5164ba9e39 | ||
|
|
094dc12f0c | ||
|
|
0083a8fb07 | ||
|
|
61b4bd04a6 | ||
|
|
d38a0a4c1b | ||
|
|
258b7e1e72 | ||
|
|
d0498de966 | ||
|
|
67c99e1e32 | ||
|
|
8c7efc34a9 | ||
|
|
f71ed2e4db | ||
|
|
552238fd04 | ||
|
|
e3a04858b4 | ||
|
|
3428d37764 | ||
|
|
7ea1ffb497 | ||
|
|
43cd4a0b99 | ||
|
|
b9a015a4aa | ||
|
|
c572cd498f | ||
|
|
9b787dfdc1 | ||
|
|
36d557e5ea | ||
|
|
261d6596dc | ||
|
|
dfb6aa54c7 | ||
|
|
a9f84a2aa0 | ||
|
|
fac51cd94d | ||
|
|
aee543c7de | ||
|
|
06c8954881 | ||
|
|
c637329884 | ||
|
|
f153781208 | ||
|
|
3655f10a43 | ||
|
|
fae2f75525 | ||
|
|
39864f6e48 | ||
|
|
cde5a22ec8 | ||
|
|
d2e8222886 | ||
|
|
0c20d58a8c | ||
|
|
c0e3bd0cff | ||
|
|
b71aedaa60 | ||
|
|
a38b33c8aa | ||
|
|
675261691f | ||
|
|
a4b226f1d0 | ||
|
|
82d5f782a3 | ||
|
|
7faef1b7c0 | ||
|
|
9a455b30c6 | ||
|
|
ad21e19dc8 | ||
|
|
64c10e2856 | ||
|
|
77b16faebb | ||
|
|
90d3f7c0d6 | ||
|
|
e07090376a | ||
|
|
f936515a59 | ||
|
|
7625c18768 | ||
|
|
07988629f1 | ||
|
|
0ba5eba31c | ||
|
|
dbb5160be7 | ||
|
|
84e5254c3a | ||
|
|
8144dd9c27 | ||
|
|
5d08fc8471 | ||
|
|
16920b4444 | ||
|
|
f014defd54 | ||
|
|
0b7fb0c69d | ||
|
|
c0af18e1c2 | ||
|
|
30bcd97a3f | ||
|
|
34d05f41f5 | ||
|
|
bf5978fb51 | ||
|
|
652a817568 | ||
|
|
fb567177b4 | ||
|
|
2913a7a19b | ||
|
|
7355fe9ea4 | ||
|
|
1a0bc12ec0 | ||
|
|
72e0d6bcca | ||
|
|
60d1f0b04f | ||
|
|
23048894b5 | ||
|
|
754621de04 | ||
|
|
45d651614b | ||
|
|
6d4e8538ea | ||
|
|
636189d7c9 | ||
|
|
5b07f518cc | ||
|
|
e0d5b47488 | ||
|
|
2ffb6192dd | ||
|
|
d5af6b10ef | ||
|
|
300fa70148 | ||
|
|
6003acac56 | ||
|
|
b0bfb9e6a7 | ||
|
|
e5e6d50f2f | ||
|
|
7e59dbf79b | ||
|
|
28633f3c62 | ||
|
|
cf8e62d2ac | ||
|
|
457186419f | ||
|
|
9dfa31bdbc | ||
|
|
8dc4ff48f8 | ||
|
|
58c02d415f | ||
|
|
987ac09896 | ||
|
|
7d90820e19 | ||
|
|
ee8eb928b3 | ||
|
|
8f61b1486e | ||
|
|
44a29c6ee4 | ||
|
|
84021a19dc | ||
|
|
df0b79a87d | ||
|
|
dc26cc93ba | ||
|
|
985dfd4705 | ||
|
|
9dd46198cb | ||
|
|
7d647e0ed7 | ||
|
|
e93a17de78 | ||
|
|
de598242ab | ||
|
|
3d480fb018 | ||
|
|
5b253ea1d5 | ||
|
|
a61e0a253d | ||
|
|
056fff415c | ||
|
|
7c2923dd04 | ||
|
|
3258300539 | ||
|
|
f07f309c51 | ||
|
|
a5335687ec | ||
|
|
69ed8fc722 | ||
|
|
ac1ffc46d3 | ||
|
|
0b5087b410 | ||
|
|
043ce779e6 | ||
|
|
e9ae2ec751 | ||
|
|
69195ced93 | ||
|
|
a3a36718d6 | ||
|
|
d2a67cb560 | ||
|
|
d804a3b2e0 | ||
|
|
14e02bce3c | ||
|
|
d2c56d565b | ||
|
|
d508814dfa | ||
|
|
ac049e5cc1 | ||
|
|
cc27cd1f43 | ||
|
|
515bac4b3c | ||
|
|
6a2fd9e8f3 | ||
|
|
40c65c87bd | ||
|
|
ac39d04170 | ||
|
|
174150c5e1 | ||
|
|
56dc934106 | ||
|
|
28db1d1079 | ||
|
|
966855469d | ||
|
|
9374b8ac64 | ||
|
|
34ea2ce438 | ||
|
|
9dedcf93a8 | ||
|
|
0cc7ef2f30 | ||
|
|
d2097f77c8 | ||
|
|
46cbd29956 | ||
|
|
4fcaba2f3e | ||
|
|
4427ecd569 | ||
|
|
6d92a28e2b | ||
|
|
18f7d847ac | ||
|
|
d3092a1806 | ||
|
|
69c8960ea9 | ||
|
|
fc21d87a9b | ||
|
|
e036e70acc | ||
|
|
92cfaf24b8 | ||
|
|
15e4e261c5 | ||
|
|
7336352cd3 | ||
|
|
9b92f3825d | ||
|
|
74c727b9e3 | ||
|
|
a1f372bc9d | ||
|
|
b23607d51d | ||
|
|
a51bf60d9a | ||
|
|
003e8c2deb | ||
|
|
118bcbe83c | ||
|
|
0d63bf7415 | ||
|
|
f9252fb26d | ||
|
|
e821080ca8 | ||
|
|
b3749560c8 | ||
|
|
c3803e4ba8 | ||
|
|
f2840c7074 | ||
|
|
ad081e2149 | ||
|
|
0e4b881f76 | ||
|
|
90f26ca4f4 | ||
|
|
c4413dabb5 | ||
|
|
71be3ae2e1 | ||
|
|
3cfac51811 | ||
|
|
76c6ebc700 | ||
|
|
74b6fe97e5 | ||
|
|
4a0626f00b | ||
|
|
ba19cee07d | ||
|
|
624959f099 | ||
|
|
0110b71dd3 | ||
|
|
00ca582f1a | ||
|
|
bf932477dd | ||
|
|
f2b7ef0056 | ||
|
|
54c4641a0e | ||
|
|
08b7ab7f15 | ||
|
|
4a92dd71ad | ||
|
|
1bd0cbc359 | ||
|
|
fe567caeec | ||
|
|
231d60411b | ||
|
|
bee1e67c60 | ||
|
|
71b0bda8f4 | ||
|
|
133cfc0c0e | ||
|
|
b959783ded | ||
|
|
463e0ffb5d | ||
|
|
9d55e86b1c | ||
|
|
07449788c6 | ||
|
|
fe4af70562 | ||
|
|
545a732385 | ||
|
|
c2f22d8daf | ||
|
|
9216b54427 | ||
|
|
fd9a239241 | ||
|
|
5a4028d5dc | ||
|
|
d02e7cc3ab | ||
|
|
9938545788 | ||
|
|
7149bc8689 | ||
|
|
9802128421 | ||
|
|
a572d05c25 | ||
|
|
cb06624d12 | ||
|
|
7b93839186 | ||
|
|
d0085ec052 |
No files matched your search
@@ -18,13 +18,15 @@ body:
|
||||
required: true
|
||||
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
|
||||
required: true
|
||||
- label: 我已将日志级别调到 TRACE,并在下方「TRACE 日志」一栏附上了复现期间的完整日志
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: snowluma-version
|
||||
attributes:
|
||||
label: SnowLuma 版本
|
||||
description: 启动日志首行或 `package.json` 里的版本号
|
||||
placeholder: "例如 1.8.5"
|
||||
placeholder: "例如 1.10.2"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -53,6 +55,19 @@ body:
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: deploy
|
||||
attributes:
|
||||
label: 部署方式
|
||||
description: 如何运行 SnowLuma
|
||||
options:
|
||||
- 源码运行(pnpm dev / start)
|
||||
- 预构建包
|
||||
- Docker
|
||||
- 其他 / 不确定
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: node-version
|
||||
attributes:
|
||||
@@ -106,11 +121,21 @@ body:
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 相关日志 / 错误堆栈
|
||||
label: TRACE 日志 / 错误堆栈
|
||||
description: |
|
||||
粘贴控制台日志、SSE 实时日志或错误堆栈。
|
||||
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
|
||||
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
|
||||
|
||||
开启 TRACE 的两种方式(任选其一):
|
||||
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。
|
||||
- **环境变量**:启动前设置 `SNOWLUMA_LOG_LEVEL=trace` 再运行,复现后复制控制台输出。
|
||||
|
||||
贴出的日志里应当能看到 `TRACE` 字样。请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
|
||||
placeholder: |
|
||||
[2026-06-26 12:00:00.000] TRACE [core] ...
|
||||
[2026-06-26 12:00:00.001] DEBUG [bridge] ...
|
||||
render: shell
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: extra
|
||||
|
||||
@@ -66,11 +66,13 @@ body:
|
||||
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
|
||||
- 相关讨论: #xxx
|
||||
|
||||
- type: checkboxes
|
||||
- type: dropdown
|
||||
id: willingness
|
||||
attributes:
|
||||
label: 您是否愿意提交 PR 来实现这个功能?
|
||||
options:
|
||||
- label: 愿意,且需要维护者讨论方案后再动手
|
||||
- label: 愿意,已有大致实现思路
|
||||
- label: 暂时只提建议
|
||||
- 愿意,但需要维护者讨论方案后再动手
|
||||
- 愿意,已有大致实现思路
|
||||
- 暂时只提建议
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,40 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120" width="100%" height="100%" style="background-color: transparent;">
|
||||
<defs>
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@800&display=swap');
|
||||
|
||||
.title-font {
|
||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
||||
font-size: 48px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
text-anchor: middle;
|
||||
}
|
||||
|
||||
.star-fx {
|
||||
animation: floatAnimation 4s ease-in-out infinite;
|
||||
}
|
||||
.star-top { transform-origin: 265px 25px; fill: #cec1e6; }
|
||||
.star-bottom { transform-origin: 45px 95px; animation-delay: 0.5s; fill: #fad6e6; }
|
||||
|
||||
@keyframes floatAnimation {
|
||||
0% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
50% { transform: translateY(-8px) rotate(10deg); opacity: 1; }
|
||||
100% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
}
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<g transform="translate(160, 75)">
|
||||
<text class="title-font" dx="2" dy="2">
|
||||
<tspan fill="#f9d5e7">Snow</tspan><tspan fill="#a5c9ff">Luma</tspan>
|
||||
</text>
|
||||
|
||||
<text class="title-font" dx="0" dy="0">
|
||||
<tspan fill="#a5c9ff">Snow</tspan><tspan fill="#cec1e6">Luma</tspan>
|
||||
</text>
|
||||
</g>
|
||||
|
||||
<path class="star-fx star-top" d="M265,13 L267.8,21.1 L276,24 L267.8,26.9 L265,35 L262.2,26.9 L254,24 L262.2,21.1 Z"/>
|
||||
<path class="star-fx star-bottom" d="M45,84 L47.1,90.2 L53.5,92.2 L47.1,94.2 L45,100 L42.9,94.2 L36.5,92.2 L42.9,90.2 Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,17 @@
|
||||
<!-- 感谢贡献。请填写以下内容,方便评审。 -->
|
||||
|
||||
## 关联 Issue
|
||||
|
||||
<!-- 例如 Closes #123。若无关联 issue,请说明这个 PR 解决什么问题、为何现在做。 -->
|
||||
|
||||
## 变更说明
|
||||
|
||||
<!-- 简述本 PR 做了什么、为什么这样做。 -->
|
||||
|
||||
## 提交前检查
|
||||
|
||||
- [ ] 本 PR 聚焦单一目标,未夹带无关改动
|
||||
- [ ] 已通过 `pnpm lint` 与 `pnpm typecheck`
|
||||
- [ ] 已补充/更新相关测试,且 `pnpm test` 通过
|
||||
- [ ] 文件行尾为 LF(未引入 CRLF)
|
||||
- [ ] PR 描述与实际实现一致
|
||||
@@ -0,0 +1,53 @@
|
||||
# Run the full workspace test suite on every pull request.
|
||||
#
|
||||
# The repo previously had no PR test gate, so broken tests could land on `dev`
|
||||
# unnoticed — and did (protocol's oidb-service rejection path, plus an external
|
||||
# contributor PR). This gates every PR on the whole suite.
|
||||
#
|
||||
# `pnpm -r --no-bail --if-present test` runs each package's `test` script
|
||||
# (skipping packages without one); --no-bail means one failing package still
|
||||
# reports the rest, and the run as a whole still fails if any package fails.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Cancel an in-flight run when the PR gets new commits.
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run all package tests
|
||||
run: pnpm -r --no-bail --if-present test
|
||||
|
||||
# The MCP test suite regenerates the action catalog (catalog.ts + the
|
||||
# catalog.json the docs site consumes). Fail if the committed snapshot
|
||||
# drifted from the live specs — keeps the API docs from going stale.
|
||||
- name: Verify generated action catalog is up to date
|
||||
run: |
|
||||
if ! git diff --exit-code -- packages/mcp/src/generated; then
|
||||
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -7,6 +7,15 @@ on:
|
||||
tags-ignore:
|
||||
- 'v*'
|
||||
|
||||
# Only `dev` gets a shared, self-cancelling group so a newer dev commit
|
||||
# supersedes the in-flight one (and its Docker dispatch) before it publishes.
|
||||
# Every other branch falls back to a unique per-run group (github.run_id), so
|
||||
# their concurrency behavior is unchanged — no shared-group pending-run
|
||||
# replacement, no accidental serialization.
|
||||
concurrency:
|
||||
group: ${{ github.ref == 'refs/heads/dev' && format('{0}-{1}', github.workflow, github.ref) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.ref == 'refs/heads/dev' }}
|
||||
|
||||
jobs:
|
||||
cleanup:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -14,10 +23,20 @@ jobs:
|
||||
actions: write
|
||||
contents: read
|
||||
steps:
|
||||
# Delete only artifacts older than 24h. The dev Docker hand-off relies on
|
||||
# this run's fresh `snowluma-dev-docker-*` artifact still existing when the
|
||||
# downstream (cross-repo) Docker build downloads it; a blanket "delete all"
|
||||
# here — which also runs on every other branch's push — could race-delete
|
||||
# an in-flight hand-off artifact. Age-gating keeps recent ones safe while
|
||||
# still reaping the backlog.
|
||||
- name: Delete old artifacts
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const cutoff = Date.now() - 24 * 60 * 60 * 1000;
|
||||
// Collect every artifact first, THEN delete — deleting mid-pagination
|
||||
// shifts the list and would skip ~a page of old artifacts per delete.
|
||||
const all = [];
|
||||
let page = 1;
|
||||
while (true) {
|
||||
const { data: { artifacts } } = await github.rest.actions.listArtifactsForRepo({
|
||||
@@ -27,16 +46,20 @@ jobs:
|
||||
page,
|
||||
});
|
||||
if (artifacts.length === 0) break;
|
||||
for (const artifact of artifacts) {
|
||||
await github.rest.actions.deleteArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
artifact_id: artifact.id,
|
||||
});
|
||||
console.log(`Deleted artifact: ${artifact.name}`);
|
||||
}
|
||||
all.push(...artifacts);
|
||||
page++;
|
||||
}
|
||||
for (const artifact of all) {
|
||||
if (new Date(artifact.created_at).getTime() >= cutoff) {
|
||||
continue; // keep recent artifacts (may be in-flight dev hand-offs)
|
||||
}
|
||||
await github.rest.actions.deleteArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
artifact_id: artifact.id,
|
||||
});
|
||||
console.log(`Deleted artifact: ${artifact.name}`);
|
||||
}
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -104,12 +127,22 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run native smoke tests
|
||||
run: pnpm test:native
|
||||
|
||||
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||
- name: Build project
|
||||
env:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
# Bundle production node_modules into dist/ before packaging — mirrors
|
||||
# release.yml. Without this the `-lite` tarball has no runtime deps and the
|
||||
# Docker image (which bakes the lite tarball) can't start.
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
@@ -140,3 +173,110 @@ jobs:
|
||||
retention-days: 3
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
|
||||
# Deterministic-name hand-off artifact consumed by the cross-repo dev
|
||||
# Docker build (SnowLuma.Docker.Framework/docker-image.yml downloads it by
|
||||
# this exact name). linux-x64 only — dev images are amd64-only. Just the
|
||||
# lite tarball; the container already ships its own Node runtime.
|
||||
- name: Upload dev Docker hand-off artifact
|
||||
if: matrix.name == 'linux-x64' && github.ref == 'refs/heads/dev'
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: snowluma-dev-docker-linux-x64
|
||||
path: SnowLuma-dev-linux-x64-lite.tar.gz
|
||||
retention-days: 3
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
|
||||
# Fire the "latest dev" Docker build on SnowLuma.Docker.Framework — but only
|
||||
# for `dev`. Mirrors release.yml's dispatch-docker, parameterized for dev:
|
||||
# tag=dev (rolling) + sha_tag=dev-<12sha> (immutable), also_latest=false so it
|
||||
# never touches the stable :latest, platforms=amd64, and artifact_run_id so the
|
||||
# downstream build pulls THIS run's hand-off artifact instead of a Release.
|
||||
dispatch-dev-docker:
|
||||
needs: [build]
|
||||
if: github.ref == 'refs/heads/dev'
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Compute short SHA
|
||||
id: sha
|
||||
run: echo "short=${GITHUB_SHA:0:12}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Dispatch dev Docker build
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
|
||||
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
|
||||
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
|
||||
DOCKER_REF: ${{ vars.DOCKER_REF }}
|
||||
SHA_TAG: dev-${{ steps.sha.outputs.short }}
|
||||
ARTIFACT_RUN_ID: ${{ github.run_id }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
const target = process.env.RELEASE_REPOSITORY;
|
||||
if (!target || !target.includes('/')) {
|
||||
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
|
||||
}
|
||||
const [owner, repo] = target.split('/');
|
||||
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
|
||||
const image = process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
const runId = String(process.env.ARTIFACT_RUN_ID);
|
||||
const shaTag = process.env.SHA_TAG;
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: workflowId,
|
||||
ref,
|
||||
inputs: {
|
||||
image,
|
||||
tag: 'dev',
|
||||
push: 'true',
|
||||
platforms: 'linux/amd64',
|
||||
also_latest: 'false',
|
||||
snowluma_repository: sourceRepo,
|
||||
artifact_run_id: runId,
|
||||
sha_tag: shaTag,
|
||||
},
|
||||
});
|
||||
core.info(`Dispatched ${workflowId}@${ref} on ${target} for dev (image=${image}:dev + :${shaTag}, src run ${runId}).`);
|
||||
|
||||
// Best-effort: resolve the dispatched run by its unique run-name
|
||||
// marker so the summary links straight to it (every dev dispatch is
|
||||
// tag=dev, so we key on the source run id, not the tag).
|
||||
const marker = `(src-run ${runId})`;
|
||||
let runUrl = '';
|
||||
for (let i = 0; i < 6 && !runUrl; i++) {
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
try {
|
||||
const { data } = await github.rest.actions.listWorkflowRuns({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: workflowId,
|
||||
event: 'workflow_dispatch',
|
||||
per_page: 30,
|
||||
});
|
||||
const hit = data.workflow_runs.find(
|
||||
(r) => (r.display_title || r.name || '').includes(marker),
|
||||
);
|
||||
if (hit) runUrl = hit.html_url;
|
||||
} catch (e) {
|
||||
core.warning(`Downstream run lookup failed: ${e.message}`);
|
||||
}
|
||||
}
|
||||
const workflowUrl = `https://github.com/${owner}/${repo}/actions/workflows/${workflowId}`;
|
||||
await core.summary
|
||||
.addHeading('dev Docker dispatch', 3)
|
||||
.addList([
|
||||
`source SHA: ${context.sha}`,
|
||||
`source run id: ${runId}`,
|
||||
`image: ${image}:dev + ${image}:${shaTag}`,
|
||||
`downstream run: ${runUrl || `(not resolved yet — see ${workflowUrl}, look for ${marker})`}`,
|
||||
])
|
||||
.write();
|
||||
@@ -0,0 +1,94 @@
|
||||
name: 校验 Bug 反馈日志
|
||||
|
||||
# 表单只能强制「非空」,强制不了「内容真的是 TRACE 级别」。
|
||||
# 这个 workflow 在 bug issue 打开/编辑时解析正文里的 TRACE 日志小节,
|
||||
# 缺日志就打 needs-logs 标签 + 评论,补齐后自动移除标签。
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
require-trace-logs:
|
||||
runs-on: ubuntu-latest
|
||||
# 只校验 Bug 反馈(表单会自动打 bug 标签)
|
||||
if: contains(join(github.event.issue.labels.*.name, ','), 'bug')
|
||||
steps:
|
||||
- uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const NEEDS = 'needs-logs';
|
||||
const MARKER = '<!-- needs-logs-bot -->';
|
||||
const { owner, repo } = context.repo;
|
||||
const issue = context.payload.issue;
|
||||
const number = issue.number;
|
||||
const body = issue.body || '';
|
||||
|
||||
// 抽取「TRACE 日志 / 错误堆栈」小节(issue form 渲染成 ### 标题)
|
||||
const m = body.match(/###\s*TRACE 日志[^\n]*\n([\s\S]*?)(?:\n###\s|$)/);
|
||||
const section = (m ? m[1] : '').trim();
|
||||
|
||||
// 粘贴的终端日志常带 ANSI 颜色码(如 \x1b[90mTRACE\x1b[0m),
|
||||
// 颜色码结尾的 'm' 紧贴 TRACE 会吃掉 \b 单词边界,先剥掉再判定。
|
||||
const clean = section.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
|
||||
const empty = section === '' || /^_no response_$/i.test(section);
|
||||
const hasTrace = /\bTRACE\b/i.test(clean);
|
||||
// 去掉代码围栏后过短,基本等于没给
|
||||
const stripped = clean.replace(/```[a-z]*|```|`/gi, '').trim();
|
||||
const tooShort = stripped.length < 40;
|
||||
const ok = !empty && hasTrace && !tooShort;
|
||||
|
||||
const hasLabel = (issue.labels || []).some((l) => (l.name || l) === NEEDS);
|
||||
|
||||
if (ok) {
|
||||
if (hasLabel) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: NEEDS });
|
||||
} catch (e) { /* 已被手动移除则忽略 */ }
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 确保标签存在再添加(addLabels 不会自动建标签)
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name: NEEDS });
|
||||
} catch (e) {
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner, repo, name: NEEDS, color: 'd93f0b',
|
||||
description: '缺少有效的 TRACE 日志',
|
||||
});
|
||||
} catch (e2) { /* 并发下可能已被建出 */ }
|
||||
}
|
||||
await github.rest.issues.addLabels({ owner, repo, issue_number: number, labels: [NEEDS] });
|
||||
|
||||
// 已经提示过就不再刷屏
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner, repo, issue_number: number,
|
||||
});
|
||||
if (comments.some((c) => (c.body || '').includes(MARKER))) return;
|
||||
|
||||
const reasons = [];
|
||||
if (empty) reasons.push('- 日志字段为空');
|
||||
else if (!hasTrace) reasons.push('- 日志里没有 `TRACE` 字样(默认级别 `info` 不输出 TRACE,需先开启)');
|
||||
else if (tooShort) reasons.push('- 日志内容过短,疑似未提供完整日志');
|
||||
|
||||
const comment = [
|
||||
MARKER,
|
||||
`@${issue.user.login} 这条反馈缺少有效的 **TRACE 级别日志**,已标记为 \`${NEEDS}\`:`,
|
||||
'',
|
||||
reasons.join('\n'),
|
||||
'',
|
||||
'请按以下任一方式开启 TRACE 后复现,再 **编辑本 issue** 把完整日志补到「TRACE 日志 / 错误堆栈」一栏:',
|
||||
'',
|
||||
'- **WebUI**:「日志」页 → 服务端日志级别切到 `TRACE` → 显示过滤用「开发」预设 → 复现 → 导出当前视图。',
|
||||
'- **环境变量**:`SNOWLUMA_LOG_LEVEL=trace` 启动后复现。',
|
||||
'',
|
||||
'补齐后机器人会自动移除该标记。若你以附件形式上传了 `.log` 文件,请在正文里也贴一段关键日志(机器人只能识别正文)。',
|
||||
].join('\n');
|
||||
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: number, body: comment });
|
||||
@@ -0,0 +1,65 @@
|
||||
name: Issue template guard
|
||||
|
||||
# Blank / free-form issues bypass `blank_issues_enabled: false` (it only hides
|
||||
# the chooser link — the CLI, API and direct URLs still create template-less
|
||||
# issues). This guard enforces the policy after the fact: an issue opened by
|
||||
# someone WITHOUT write access that did not go through a template (no template
|
||||
# label) is commented on and closed. Properly-filed bug reports / feature
|
||||
# requests (which carry `bug` / `enhancement`) and anyone with write access are
|
||||
# left alone.
|
||||
#
|
||||
# Note: workflows for `issues` events run from the file on the DEFAULT branch,
|
||||
# so this only takes effect once it lands on `main`.
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
guard:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const issue = context.payload.issue;
|
||||
|
||||
// Write-access roles are exempt.
|
||||
const privileged = ['OWNER', 'MEMBER', 'COLLABORATOR'];
|
||||
if (privileged.includes(issue.author_association)) {
|
||||
core.info(`author_association=${issue.author_association} — allowed`);
|
||||
return;
|
||||
}
|
||||
|
||||
// A template was used iff it stamped its label.
|
||||
const TEMPLATE_LABELS = ['bug', 'enhancement'];
|
||||
const labels = (issue.labels || []).map((l) => (typeof l === 'string' ? l : l.name));
|
||||
if (labels.some((l) => TEMPLATE_LABELS.includes(l))) {
|
||||
core.info('template label present — allowed');
|
||||
return;
|
||||
}
|
||||
|
||||
// Non-privileged + no template → guide and close.
|
||||
const { owner, repo } = context.repo;
|
||||
const chooser = `https://github.com/${owner}/${repo}/issues/new/choose`;
|
||||
const body = [
|
||||
'感谢你的反馈。',
|
||||
'',
|
||||
'本仓库的 issue 需要通过模板提交:请使用 **Bug 反馈** 或 **功能请求** 模板重新创建,',
|
||||
'以便我们准确、高效地处理。直接创建的空白 / 自定义 issue 会被自动关闭。',
|
||||
'',
|
||||
`- 重新创建:${chooser}`,
|
||||
'- 日常使用、快速交流类问题,可先到 README 中的 QQ 群',
|
||||
'',
|
||||
'本 issue 将自动关闭,感谢理解。',
|
||||
].join('\n');
|
||||
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body });
|
||||
await github.rest.issues.update({
|
||||
owner, repo, issue_number: issue.number,
|
||||
state: 'closed', state_reason: 'not_planned',
|
||||
});
|
||||
core.info(`closed #${issue.number} (author_association=${issue.author_association}, no template label)`);
|
||||
@@ -0,0 +1,109 @@
|
||||
name: Publish MCP to npm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/mcp/**'
|
||||
# The action catalog is generated from @snowluma/onebot's specs, so an
|
||||
# action change must republish the MCP snapshot.
|
||||
- 'packages/onebot/**'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'tsconfig.base.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: mcp-npm-publish-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build, test, and publish MCP
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check MCP
|
||||
run: pnpm --filter @snowluma/mcp typecheck
|
||||
|
||||
- name: Test MCP (regenerates + validates the action catalog)
|
||||
run: pnpm --filter @snowluma/mcp test
|
||||
|
||||
- name: Build MCP
|
||||
run: pnpm --filter @snowluma/mcp build
|
||||
|
||||
- name: Check npm package version
|
||||
id: npm
|
||||
working-directory: packages/mcp
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
|
||||
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
|
||||
|
||||
{
|
||||
echo "package_name=${package_name}"
|
||||
echo "package_version=${package_version}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
|
||||
echo "already_published=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
|
||||
else
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish MCP to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/mcp
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
shell: bash
|
||||
run: |
|
||||
{
|
||||
echo "## MCP npm publish"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -45,6 +45,9 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run native smoke tests
|
||||
run: pnpm test:native
|
||||
|
||||
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||
- name: Build project
|
||||
env:
|
||||
@@ -109,42 +112,42 @@ jobs:
|
||||
tag="${GITHUB_REF_NAME}"
|
||||
previousTag="$(git describe --tags --abbrev=0 "${tag}^" 2>/dev/null || true)"
|
||||
if [[ -n "$previousTag" ]]; then
|
||||
changes="$(git log --pretty=format:'- %s (%h)' "$previousTag..$tag")"
|
||||
range="$previousTag..$tag"
|
||||
comparison="[查看 ${previousTag} → ${tag} 的完整差异](https://github.com/${GITHUB_REPOSITORY}/compare/${previousTag}...${tag})"
|
||||
else
|
||||
changes="$(git log --pretty=format:'- %s (%h)' "$tag")"
|
||||
range="$tag"
|
||||
comparison=""
|
||||
fi
|
||||
changes="$(git log --no-merges --invert-grep --grep='^chore(release):' --pretty=format:"- %s ([%h](https://github.com/${GITHUB_REPOSITORY}/commit/%H))" "$range")"
|
||||
[[ -z "$changes" ]] && changes="- No commit changes detected."
|
||||
cat > release-notes.md <<EOF
|
||||
# SnowLuma ${tag}
|
||||
|
||||
## 发布概览
|
||||
本次发布提供 SnowLuma 的 Windows x64 / Linux x64 / Linux arm64 构建产物,默认包含 WebUI。
|
||||
> **跨平台正式支持:** Windows x64、Linux x64 与 Linux arm64 均可完整运行 SnowLuma,包含 QQ 接入、OneBot v11 与 WebUI 管理能力。
|
||||
|
||||
## 下载说明
|
||||
命名约定:
|
||||
- 无后缀 \`.zip/.tar.gz\`:完整版本,内置 \`node\`/\`node.exe\` 与运行时依赖,解压即可使用。
|
||||
- \`-lite\` 后缀:精简版本,不含 Node.js 运行时,需自行安装 Node.js 22+。
|
||||
## 选择下载
|
||||
|
||||
Windows:
|
||||
- \`SnowLuma-${tag}-win-x64.zip\`
|
||||
- \`SnowLuma-${tag}-win-x64-lite.zip\`
|
||||
| 平台 | 完整版(内置 Node.js,推荐) | Lite(需 Node.js 22+) |
|
||||
| --- | --- | --- |
|
||||
| Windows x64 | \`SnowLuma-${tag}-win-x64.zip\` | \`SnowLuma-${tag}-win-x64-lite.zip\` |
|
||||
| Linux x64 | \`SnowLuma-${tag}-linux-x64.tar.gz\` | \`SnowLuma-${tag}-linux-x64-lite.tar.gz\` |
|
||||
| Linux arm64 | \`SnowLuma-${tag}-linux-arm64.tar.gz\` | \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\` |
|
||||
|
||||
Linux x64:
|
||||
- \`SnowLuma-${tag}-linux-x64.tar.gz\`
|
||||
- \`SnowLuma-${tag}-linux-x64-lite.tar.gz\`
|
||||
完整版适合直接解压运行;Lite 版不包含 Node.js,但其余运行时依赖和 WebUI 静态资源保持一致。
|
||||
|
||||
Linux arm64:
|
||||
- \`SnowLuma-${tag}-linux-arm64.tar.gz\`
|
||||
- \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\`
|
||||
## 快速开始
|
||||
|
||||
1. 解压与你的系统架构匹配的压缩包。
|
||||
2. Windows 运行 \`launcher.bat\`;Linux 运行 \`./launcher.sh\`。
|
||||
3. 浏览器访问 http://localhost:5099,初始账号为 \`admin\`,密码见启动日志。
|
||||
|
||||
无人值守部署可同时设置 \`SNOWLUMA_ACCEPT_EULA=1\` 与 \`SNOWLUMA_ACCEPT_PRIVACY=1\` 完成协议确认。设置这些变量即表示运营者已阅读并同意发行包内的 EULA 与隐私政策;缺少任意一项时仍会显示同意页面。
|
||||
|
||||
## 本次更新
|
||||
|
||||
## 更新内容
|
||||
${changes}
|
||||
|
||||
## 使用说明
|
||||
- Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。
|
||||
- Linux:\`./launcher.sh\` 或 \`node index.mjs\`。
|
||||
- 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:5099。
|
||||
- Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。
|
||||
${comparison}
|
||||
EOF
|
||||
|
||||
- name: Create GitHub Release
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
name: 关闭长期缺日志的反馈
|
||||
|
||||
# needs-logs 的 issue 若长期不补 TRACE 日志,先标 stale,再自动关闭。
|
||||
# 补齐日志后 issue-require-logs 会移除 needs-logs,这里 only-labels 过滤即跳过。
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
only-labels: 'needs-logs'
|
||||
days-before-stale: 7
|
||||
days-before-close: 7
|
||||
stale-issue-label: 'stale'
|
||||
close-issue-reason: 'not_planned'
|
||||
ascending: true
|
||||
# 不处理 PR
|
||||
days-before-pr-stale: -1
|
||||
days-before-pr-close: -1
|
||||
stale-issue-message: >
|
||||
这条反馈因长期缺少有效的 TRACE 日志被标记为 `stale`。
|
||||
若 7 天内仍未补充日志,将自动关闭。补充后请编辑 issue 贴上日志或留言。
|
||||
close-issue-message: >
|
||||
因长期缺少定位所需的 TRACE 日志,已自动关闭。
|
||||
如果问题仍然存在,欢迎补齐 TRACE 日志后重新打开本 issue 或新开一个。
|
||||
@@ -0,0 +1,114 @@
|
||||
name: Sync action catalog to docs
|
||||
|
||||
# Regenerates the OneBot action catalog from @snowluma/onebot's specs and commits
|
||||
# the plain-JSON twin (catalog.json) into the SnowLumaDocs repo, where the docs
|
||||
# build turns it into the API Reference pages. Runs on main (the release/promote
|
||||
# target) so the published docs always describe shipped behavior. Uses the same
|
||||
# SnowLuma bot GitHub App as the promote-dev-to-main flow.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/onebot/src/actions/**'
|
||||
- 'packages/onebot/src/action-kit.ts'
|
||||
- 'packages/onebot/src/action-docs.ts'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sync-docs-catalog
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout SnowLuma
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Generate catalog.json
|
||||
run: pnpm --filter @snowluma/mcp gen
|
||||
|
||||
- name: Validate GitHub App credentials
|
||||
env:
|
||||
APP_ID: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
|
||||
PRIVATE_KEY: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
|
||||
run: |
|
||||
if [ -z "${APP_ID}" ] || [ -z "${PRIVATE_KEY}" ]; then
|
||||
echo 'Missing SNOWLUMA_BOT_APP_ID and/or SNOWLUMA_BOT_PRIVATE_KEY secrets.' >&2
|
||||
echo 'Configure the same GitHub App used by the promote-dev-to-main flow.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Mint GitHub App installation token (scoped to SnowLumaDocs)
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
repositories: SnowLumaDocs
|
||||
|
||||
- name: Resolve bot identity
|
||||
id: bot
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bot_login="${APP_SLUG}[bot]"
|
||||
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
|
||||
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
|
||||
{
|
||||
echo "login=${bot_login}"
|
||||
echo "email=${bot_email}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
- name: Commit catalog.json to docs repo
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
BOT_LOGIN: ${{ steps.bot.outputs.login }}
|
||||
BOT_EMAIL: ${{ steps.bot.outputs.email }}
|
||||
OWNER: ${{ github.repository_owner }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
src="$(pwd)/packages/mcp/src/generated/catalog.json"
|
||||
tmp="$(mktemp -d)"
|
||||
git clone --depth 1 \
|
||||
"https://x-access-token:${GH_TOKEN}@github.com/${OWNER}/SnowLumaDocs.git" "$tmp"
|
||||
mkdir -p "$tmp/docs/public/api"
|
||||
cp "$src" "$tmp/docs/public/api/catalog.json"
|
||||
cd "$tmp"
|
||||
git config user.name "${BOT_LOGIN}"
|
||||
git config user.email "${BOT_EMAIL}"
|
||||
# Stage first: `git diff --quiet` ignores UNTRACKED files, so on the
|
||||
# initial sync (catalog.json not yet in the docs repo) the index diff
|
||||
# is the only reliable change check.
|
||||
git add docs/public/api/catalog.json
|
||||
if git diff --cached --quiet; then
|
||||
echo "::notice::catalog.json unchanged; nothing to sync."
|
||||
exit 0
|
||||
fi
|
||||
git commit -m "chore(api): sync action catalog from SnowLuma@${GITHUB_SHA::7}"
|
||||
# Single writer, but guard against a concurrent docs commit racing the
|
||||
# shallow clone: rebase onto the latest main before pushing.
|
||||
git pull --rebase --depth 1 origin main
|
||||
git push origin HEAD:main
|
||||
@@ -11,7 +11,13 @@ dist/
|
||||
|
||||
/config/
|
||||
/data/
|
||||
# per-package runtime data dirs (e.g. packages/core/data/<uin>/*.db written by
|
||||
# IdentityService during tests) — not just the root /data/
|
||||
**/data/
|
||||
logs/
|
||||
|
||||
# macOS metadata
|
||||
.DS_Store
|
||||
|
||||
# test coverage output
|
||||
coverage/
|
||||
@@ -285,3 +285,13 @@ git push origin v1.7.0 # → 仅触发 release.yml
|
||||
- 如果只是想确认"我这么改 OK 吗",欢迎开 draft PR,先把代码亮出来再讨论。
|
||||
|
||||
感谢你愿意花时间贡献 SnowLuma —— 这个项目能走多远,取决于你们每一个人。❄️
|
||||
|
||||
## 贡献的许可 / Licensing of contributions
|
||||
|
||||
当你提交 PR,即表示你的贡献按本项目的 [`LICENSE`](LICENSE)(SnowLuma 源码可见非商业许可)授权,且你声明你有权这么做、贡献为你的原创(若含第三方材料,请在 PR 中显著标注其来源与许可证)。
|
||||
|
||||
**你保留对自己贡献的版权**,同时**授予 SnowLumaDevs 一项永久、全球、免费、不可撤销、可再许可(sublicensable)的许可**,可使用、复制、修改、分发你的贡献并基于其制作衍生作品,**包括以本项目非商业许可之外的其他条款(含商业条款)再许可与分发**——以便项目方无需逐一回头征求同意,即可在获授权的商业场景中使用社区贡献。
|
||||
|
||||
By opening a PR, you agree your contribution is licensed under the project's [`LICENSE`](LICENSE); you represent that you have the right to submit it and that it is your own work (clearly identify any third-party material in the PR).
|
||||
|
||||
**You retain copyright in your contribution** and additionally grant SnowLumaDevs a **perpetual, worldwide, royalty-free, irrevocable, sublicensable license** to use, reproduce, modify, distribute, and create derivative works of your contribution, **including the right to relicense and distribute it under terms other than this project's non-commercial license (including commercial terms)** — so the project can use community contributions in authorized commercial scenarios without seeking each contributor's consent again.
|
||||
@@ -0,0 +1,90 @@
|
||||
# SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement
|
||||
|
||||
- **生效日期 / Effective date:** 2026-06-19
|
||||
- **版本 / Version:** 1.0
|
||||
- **许可方 / Licensor:** SnowLumaDevs(联系方式 / Contact: motricseven@foxmail.com)
|
||||
|
||||
> 本协议以中文与英文两种语言提供。如两版本有冲突,**以中文版本为准**。
|
||||
> This Agreement is provided in Chinese and English. **In case of any conflict, the Chinese version prevails.**
|
||||
|
||||
---
|
||||
|
||||
## 中文版
|
||||
|
||||
### 1. 定义与接受
|
||||
1.1 "**本软件**"指 SnowLuma 软件及其官方发行包,包括可执行文件、原生模块(`snowluma-*.node`)、文档及相关组件。
|
||||
1.2 "**您**"指下载、安装、运行或以其他方式使用本软件的个人或实体。
|
||||
1.3 下载、安装、运行或使用本软件,即表示您已阅读、理解并同意受本协议约束。**若您不同意本协议,请勿使用本软件并删除其全部副本。**
|
||||
|
||||
### 2. 授权范围
|
||||
2.1 本软件的**源代码**依据 GNU Affero General Public License 第 3 版(AGPL-3.0)及其第 7 条附加许可(原生模块链接例外)授权,详见随附的 `LICENSE` 文件。
|
||||
2.2 本协议是针对**发行包(二进制)**的补充条款,就 AGPL 未涵盖之事项(接受方式、可接受使用、免责、专有组件、争议解决等)作出约定。
|
||||
2.3 **本协议不减损 AGPL 授予您的任何权利。** 对于您依 AGPL 单独获取、使用、修改或分发源代码的行为,本协议不附加任何限制。
|
||||
2.4 专有组件(见第 5 条)不属于 AGPL 授权范围,依其各自条款授权。
|
||||
|
||||
### 3. 免责声明
|
||||
3.1 **非官方、无隶属**:本软件是独立的第三方互操作性项目,与腾讯公司(Tencent)及 QQ **无任何隶属、合作、授权或背书关系**。"QQ""腾讯"等名称及标识为其各自所有者的商标。
|
||||
3.2 **用途**:本软件**仅供学习、研究与技术互操作之目的**提供。
|
||||
3.3 **合规义务**:您须自行确保对本软件的使用符合一切适用法律法规,以及您所接入平台的规定(包括但不限于《QQ 用户协议》与相关服务条款)。
|
||||
3.4 **按"现状"提供**:本软件按"**现状(AS-IS)**"及"**现有(AS-AVAILABLE)**"提供,不附带任何明示或默示的担保,包括但不限于对适销性、特定用途适用性、不侵权、可用性、准确性或不中断的担保。
|
||||
3.5 **责任限制**:在适用法律允许的最大范围内,对于因使用或无法使用本软件而导致的任何直接、间接、偶然、特殊、惩罚性或后果性损害(包括但不限于账号封禁或限制、数据丢失、利润或业务损失、服务中断),SnowLumaDevs **概不承担责任**。
|
||||
3.6 **风险自负**:您理解,使用非官方协议工具接入第三方平台**可能违反该平台条款并导致账号风险**,您**自愿承担**该等风险。
|
||||
|
||||
### 4. 可接受使用
|
||||
您**不得**将本软件用于:(a) 任何违法犯罪活动;(b) 未经授权访问、干扰或破坏任何系统或网络;(c) 发送垃圾信息、实施骚扰、欺诈或传播恶意内容;(d) 侵犯他人隐私、知识产权或其他合法权益;(e) 任何违反所接入平台服务条款的行为。
|
||||
|
||||
### 5. 专有组件
|
||||
5.1 本软件可能包含或依赖**非开源的专有组件**,包括但不限于 **SnowLuma 原生模块**(`snowluma-*.node`),以及其中可能包含的任何授权、激活或技术保护措施。
|
||||
5.2 此类专有组件的**源代码不依 AGPL 提供**,受本条款约束。
|
||||
5.3 除适用法律强制性规定明确允许外,您不得对专有组件进行逆向工程、反编译或反汇编,亦不得规避、破解或绕过其授权或激活机制。
|
||||
5.4 `LICENSE` 第 7 条的链接例外仅允许将本软件与该原生模块**组合并分发**,**并不**向您授予该原生模块本身的源代码权利。
|
||||
|
||||
### 6. 终止
|
||||
若您违反本协议任何条款,本协议项下授予您的权利(**不含**您依 AGPL 单独享有的权利)将自动终止。终止后,您应停止使用并删除发行包中的专有组件。
|
||||
|
||||
### 7. 适用法律与争议解决
|
||||
本协议的订立、效力、解释、履行及争议解决,均适用**中华人民共和国大陆地区法律**(不含其冲突法规则)。因本协议引起或与之相关的任何争议,双方应首先友好协商解决;协商不成的,任何一方可向**有管辖权的人民法院**提起诉讼。
|
||||
|
||||
### 8. 协议的变更
|
||||
SnowLumaDevs 可不时更新本协议。更新后的版本将随发行包发布并注明生效日期。在更新生效后继续使用本软件,即视为您接受更新后的条款。
|
||||
|
||||
---
|
||||
|
||||
## English Version
|
||||
|
||||
### 1. Definitions and Acceptance
|
||||
1.1 "**Software**" means the SnowLuma software and its official distribution packages, including executables, native modules (`snowluma-*.node`), documentation, and related components.
|
||||
1.2 "**You**" means the individual or entity that downloads, installs, runs, or otherwise uses the Software.
|
||||
1.3 By downloading, installing, running, or using the Software, you acknowledge that you have read, understood, and agree to be bound by this Agreement. **If you do not agree, do not use the Software and delete all copies.**
|
||||
|
||||
### 2. Scope of License
|
||||
2.1 The **source code** of the Software is licensed under the GNU Affero General Public License version 3 (AGPL-3.0) together with its Section 7 additional permission (the native-addon linking exception); see the accompanying `LICENSE` file.
|
||||
2.2 This Agreement provides **supplemental terms for the binary distribution packages**, addressing matters not covered by the AGPL (acceptance, acceptable use, disclaimers, proprietary components, dispute resolution).
|
||||
2.3 **This Agreement does not diminish any rights granted to you under the AGPL.** It imposes no additional restriction on your acquisition, use, modification, or distribution of the source code under the AGPL.
|
||||
2.4 Proprietary Components (Section 5) are outside the scope of the AGPL and are licensed under their own terms.
|
||||
|
||||
### 3. Disclaimers
|
||||
3.1 **Not official; no affiliation.** The Software is an independent, third-party interoperability project and has **no affiliation, partnership, authorization, or endorsement relationship** with Tencent or QQ. "QQ", "Tencent", and related marks belong to their respective owners.
|
||||
3.2 **Purpose.** The Software is provided **solely for learning, research, and technical interoperability**.
|
||||
3.3 **Compliance.** You are responsible for ensuring that your use complies with all applicable laws and with the terms of any platform you connect to (including the QQ User Agreement and related terms of service).
|
||||
3.4 **AS-IS.** The Software is provided "**AS IS**" and "**AS AVAILABLE**", without warranties of any kind, express or implied, including merchantability, fitness for a particular purpose, non-infringement, availability, accuracy, or uninterrupted operation.
|
||||
3.5 **Limitation of liability.** To the maximum extent permitted by law, SnowLumaDevs shall **not be liable** for any direct, indirect, incidental, special, punitive, or consequential damages (including account suspension or restriction, data loss, lost profits or business, or service interruption) arising from use of or inability to use the Software.
|
||||
3.6 **Assumption of risk.** You understand that using an unofficial protocol tool to connect to a third-party platform **may violate that platform's terms and carry account risk**, which you **voluntarily assume**.
|
||||
|
||||
### 4. Acceptable Use
|
||||
You shall **not** use the Software for: (a) any unlawful activity; (b) unauthorized access to, interference with, or disruption of any system or network; (c) spam, harassment, fraud, or malicious content; (d) infringement of others' privacy, intellectual-property, or other lawful rights; or (e) any conduct that violates the terms of service of a connected platform.
|
||||
|
||||
### 5. Proprietary Components
|
||||
5.1 The Software may include or depend on **non-free proprietary components**, including but not limited to the **SnowLuma native addon** (`snowluma-*.node`) and any licensing, activation, or technical-protection measures it may contain.
|
||||
5.2 The **source code of such components is not provided under the AGPL** and is governed by these terms.
|
||||
5.3 Except to the extent expressly permitted by mandatory applicable law, you may not reverse engineer, decompile, or disassemble the Proprietary Components, nor circumvent, crack, or bypass their licensing or activation mechanisms.
|
||||
5.4 The Section 7 linking exception in `LICENSE` permits only the **combination and distribution** of the Software with the SnowLuma native addon; it does **not** grant you rights to that addon's own source code.
|
||||
|
||||
### 6. Termination
|
||||
If you breach any term of this Agreement, the rights granted to you hereunder (**excluding** rights you hold separately under the AGPL) terminate automatically. Upon termination you must cease use of and delete the Proprietary Components from the distribution package.
|
||||
|
||||
### 7. Governing Law and Disputes
|
||||
This Agreement is governed by the laws of the **mainland of the People's Republic of China** (excluding its conflict-of-laws rules). Any dispute arising out of or relating to this Agreement shall first be resolved through good-faith negotiation; failing that, either party may bring an action before a **court of competent jurisdiction**.
|
||||
|
||||
### 8. Changes
|
||||
SnowLumaDevs may update this Agreement from time to time. Updated versions will be published with the distribution package and bear an effective date. Continued use after an update takes effect constitutes acceptance of the updated terms.
|
||||
@@ -0,0 +1,131 @@
|
||||
SnowLuma Source-Available Non-Commercial License
|
||||
SnowLuma 源码可见非商业许可
|
||||
|
||||
Version 1.0 · 2026-06-19
|
||||
Copyright (C) 2026 SnowLumaDevs
|
||||
Contact: motricseven@foxmail.com
|
||||
|
||||
中英文如有冲突,以中文为准。
|
||||
In case of any conflict between the Chinese and English text, the Chinese
|
||||
version prevails.
|
||||
|
||||
This is NOT an open-source license as defined by the Open Source Initiative:
|
||||
it restricts commercial use and the public release of modifications. The
|
||||
source is published for transparency, study, and non-commercial self-hosting.
|
||||
本许可不是 OSI 定义的开源许可:它限制商业用途与修改版的公开发布。源码公开
|
||||
仅用于透明、学习与非商业的自托管。
|
||||
|
||||
===============================================================================
|
||||
1. Definitions / 定义
|
||||
===============================================================================
|
||||
- "Software" / "本软件": the SnowLuma source code and assets in this
|
||||
repository, excluding the Native Addon (defined below) and any third-party
|
||||
components.
|
||||
- "You" / "你": any individual or entity exercising rights under this License.
|
||||
- "Commercial Use" / "商业用途": any use primarily intended for or directed
|
||||
toward commercial advantage or monetary compensation. This includes, without
|
||||
limitation, selling or reselling the Software; offering paid hosting,
|
||||
deployment, setup, or operation services based on the Software; bundling it
|
||||
into a paid product or service; or running it to provide a service for a fee.
|
||||
包括但不限于:出售或转售本软件;提供基于本软件的付费托管、部署、代搭、代运营
|
||||
服务;将其并入付费产品或服务;或以收费方式运行本软件对外提供服务。
|
||||
- "Native Addon" / "原生附加组件": the SnowLuma native binary components shipped
|
||||
with the Software (e.g. `snowluma-*.node`, `snowluma-*.dll`, `snowluma-*.so`).
|
||||
These are a separate, proprietary component and are NOT licensed under this
|
||||
License — see Section 5.
|
||||
|
||||
===============================================================================
|
||||
2. Grant / 授权
|
||||
===============================================================================
|
||||
Subject to the conditions and restrictions below, the copyright holder grants
|
||||
You a worldwide, royalty-free, non-exclusive, non-transferable, revocable
|
||||
license to:
|
||||
在下列条件与限制下,著作权人授予你一项全球、免费、非独占、不可转让、可撤销的
|
||||
许可,允许你:
|
||||
(a) view and study the Software; 查看与学习本软件;
|
||||
(b) use and run the Software for personal or other Non-Commercial purposes;
|
||||
为个人或其他非商业目的使用与运行本软件;
|
||||
(c) modify the Software for Your own Non-Commercial use; 为自己的非商业使用
|
||||
修改本软件;
|
||||
(d) redistribute the Software under the conditions in Section 3.
|
||||
在第 3 条的条件下再分发本软件。
|
||||
|
||||
===============================================================================
|
||||
3. Redistribution Conditions / 再分发条件
|
||||
===============================================================================
|
||||
You may redistribute the Software (modified or unmodified) ONLY if ALL of the
|
||||
following are met. 仅当同时满足以下全部条件时,你方可再分发本软件(无论是否修改):
|
||||
(a) it is Non-Commercial; 属非商业性质;
|
||||
(b) the complete text of this License is included; 附带本许可的完整文本;
|
||||
(c) all copyright, attribution, and notices are retained unaltered;
|
||||
保留全部著作权、署名与声明,且不得改动;
|
||||
(d) PUBLIC release of a modified or derivative version requires the prior
|
||||
written permission of the copyright holder. Private, non-public
|
||||
modifications for Your own Non-Commercial use are permitted.
|
||||
公开发布修改版或衍生版,须事先获得著作权人书面许可;为你自己非商业使用
|
||||
而作的、不公开的修改则被允许。
|
||||
|
||||
===============================================================================
|
||||
4. Restrictions / 限制
|
||||
===============================================================================
|
||||
(a) Commercial Use of the Software in any form is PROHIBITED without the
|
||||
prior written authorization of the copyright holder.
|
||||
未经著作权人事先书面授权,禁止以任何形式对本软件进行商业使用。
|
||||
(b) You may not develop, publish, or distribute another project based on the
|
||||
Software without the prior written authorization of the copyright holder.
|
||||
未经著作权人事先书面授权,不得基于本软件开发、发布或分发另一个项目。
|
||||
(c) You may not remove, obscure, or alter any copyright, attribution, license,
|
||||
or notice. 不得移除、遮蔽或更改任何著作权、署名、许可或声明。
|
||||
|
||||
===============================================================================
|
||||
5. Native Addon / 原生附加组件
|
||||
===============================================================================
|
||||
The Native Addon is proprietary and is NOT covered by this License. It is
|
||||
distributed only as a precompiled binary bundled with the Software. No rights
|
||||
are granted to it other than to run it as bundled for the Non-Commercial use
|
||||
permitted above; in particular, no right to reverse engineer, reproduce,
|
||||
modify, redistribute separately, or relicense it is granted.
|
||||
原生附加组件为专有组件,不在本许可范围内,仅以随本软件分发的预编译二进制形式提供。
|
||||
除按上文允许的非商业用途以其随附形式运行外,不授予任何权利;尤其不授予对其进行逆向、
|
||||
复制、修改、单独再分发或再许可的权利。
|
||||
|
||||
===============================================================================
|
||||
6. Additional Permissions / 额外授权
|
||||
===============================================================================
|
||||
Any use not granted by this License — including Commercial Use and the public
|
||||
release of derivative works — requires prior written permission, which must be
|
||||
requested from and granted by the copyright holder (Contact above).
|
||||
本许可未授予的任何用途——包括商业使用及公开发布衍生作品——均须事先取得著作权人的
|
||||
书面许可(见上方联系方式)。
|
||||
|
||||
===============================================================================
|
||||
7. Third-Party Components / 第三方组件
|
||||
===============================================================================
|
||||
Third-party code and components retain their own original licenses, which
|
||||
govern those parts. 第三方代码与组件遵循其各自的原始许可,并以其许可为准。
|
||||
|
||||
===============================================================================
|
||||
8. Termination / 终止
|
||||
===============================================================================
|
||||
Any breach of this License automatically terminates the rights granted to You
|
||||
under it. 任何违反本许可的行为将自动终止你依本许可获得的权利。
|
||||
|
||||
===============================================================================
|
||||
9. Disclaimer / 免责声明
|
||||
===============================================================================
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
|
||||
LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
||||
OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
本软件按“现状”提供,不附带任何明示或默示的担保,包括但不限于适销性、特定用途
|
||||
适用性及不侵权的担保。在任何情况下,作者或著作权人均不对因本软件或其使用所引起
|
||||
的任何索赔、损害或其他责任负责。
|
||||
|
||||
===============================================================================
|
||||
10. Governing Law / 适用法律
|
||||
===============================================================================
|
||||
This License is governed by the laws of the mainland of the People's Republic
|
||||
of China, excluding its conflict-of-laws rules.
|
||||
本许可适用中华人民共和国大陆地区法律(不含其冲突法规则)。
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
# SnowLuma 隐私与数据处理说明 / Privacy & Data Handling Notice
|
||||
|
||||
- **生效日期 / Effective date:** 2026-06-19
|
||||
- **版本 / Version:** 1.0
|
||||
- **责任主体 / Provider:** SnowLumaDevs(联系方式 / Contact: motricseven@foxmail.com)
|
||||
|
||||
> 本说明以中文与英文两种语言提供。如有冲突,**以中文版本为准**。
|
||||
> Provided in Chinese and English. **In case of conflict, the Chinese version prevails.**
|
||||
|
||||
---
|
||||
|
||||
## 中文版
|
||||
|
||||
### 1. 概述
|
||||
SnowLuma 是一款**自托管**软件:它运行在**您自己的设备或服务器**上。**SnowLumaDevs(作者方)默认不收集、不接收、不存储您的任何个人数据**。本软件**不包含**任何需要联网激活、或向作者方回传信息的授权机制。
|
||||
本说明唯一例外的数据外发情形,是第 4、5 条所述的两种,且其中遥测受严格限制(第 5 条)。
|
||||
|
||||
### 2. 本软件在您设备上存储的数据
|
||||
为实现功能,本软件会在您的设备本地(如 SQLite 数据库、配置与日志文件)存储以下类别的数据。**这些数据保存在您本地、由您掌控,作者方无法访问:**
|
||||
- **账号与登录凭据**:所登录的 QQ 账号信息、会话/令牌、WebUI 登录口令(以**加盐 scrypt 哈希**形式存储,不保存明文)。
|
||||
- **关系数据**:好友、群组及成员的列表与资料。
|
||||
- **消息数据**:为实现协议转换而处理或缓存的消息(视您的配置而定)。
|
||||
- **运行配置与日志**:适配器配置、运行日志等。
|
||||
|
||||
> 说明:因 SnowLuma 是 QQ 协议工具,上述本地数据**必然**包含 QQ 账号及联系人信息。这与第 5 条"遥测绝不采集 QQ 账号/联系人"并不矛盾——本地存储 ≠ 对外传输。
|
||||
|
||||
### 3. 您作为数据控制者的责任
|
||||
当您运行本软件处理您 QQ 联系人、群成员等他人的个人信息时,**您是该等个人信息的"数据控制者/处理者"**,须自行就该等处理承担合规责任(包括取得必要同意、保障安全、响应数据主体请求等)。作者方仅提供软件工具,不参与您的数据处理活动。
|
||||
|
||||
### 4. 数据离开您设备的唯一途径
|
||||
除以下两种情形外,本软件不会将您的数据传输至任何外部目的地:
|
||||
1. **您自行配置的通知 / Webhook**:当您主动配置通知渠道(如 Webhook)时,相应内容会按**您填写的地址与设置**外发。目的地与内容由您完全掌控,作者方不经手。
|
||||
2. **匿名遥测**:见第 5 条。
|
||||
|
||||
### 5. 遥测(Telemetry)
|
||||
**模式:默认开启(opt-out)。** 您可随时关闭(见 5.3)。
|
||||
|
||||
#### 5.1 采集内容(仅匿名、聚合,无法定位到个人)
|
||||
- 应用版本、操作系统与 CPU 架构、Node.js 版本;
|
||||
- 启动次数、功能使用计数(例如启用了哪些适配器/命令,**不含其参数或内容**);
|
||||
- 匿名化的崩溃栈与错误类型。
|
||||
|
||||
#### 5.2 绝不采集(显式负面清单)
|
||||
本遥测**在任何情况下都不会**采集或传输:
|
||||
- **QQ 账号 / UIN,及好友、群、成员的身份信息**;
|
||||
- **消息内容或其元数据**、昵称、头像;
|
||||
- 手机号、邮箱或任何联系方式;
|
||||
- 凭据、令牌、密码;
|
||||
- 用于身份画像的精确 IP 地址(若服务端在传输层偶然可见 IP,将即时丢弃、不入库、不进行关联);
|
||||
- 任何可直接或间接定位到自然人的标识。
|
||||
|
||||
#### 5.3 如何关闭与告知
|
||||
- **首次运行提示**:软件首次运行时会在控制台与 WebUI 一次性告知遥测已默认开启及关闭方式。
|
||||
- **一键关闭**:可通过环境变量 `SNOWLUMA_TELEMETRY=0`、配置项或 WebUI 开关随时关闭,关闭后即刻停止采集。
|
||||
|
||||
#### 5.4 用途、共享与保留
|
||||
遥测数据**仅用于改进本软件**,**不向任何第三方出售或共享**,仅以匿名聚合形式保留必要期限。
|
||||
|
||||
#### 5.5 生效状态(重要)
|
||||
本条款完整描述了 SnowLuma 的遥测机制,但**仅对实际包含遥测代码的发行版生效**。
|
||||
> **当前生效状态(截至 2026-06-17)**:公开发行版**尚未包含**遥测代码,故本条款目前**处于未生效状态**。一旦某一发行版引入遥测,将在该版本的发布说明中明确告知,并使本条款对该版本生效。
|
||||
|
||||
### 6. 数据安全与保留
|
||||
本地数据的安全与保留由您(运营者)控制。建议您妥善保护设备访问权限、定期更新 WebUI 口令。
|
||||
|
||||
### 7. 第三方组件
|
||||
本软件可能捆绑第三方组件(如用于音视频处理的 FFmpeg)。此类组件**在您本地运行**、用于处理本地数据,**不向作者方或第三方外发**数据。
|
||||
|
||||
### 8. 未成年人
|
||||
本软件面向开发者与技术用户,**不面向未成年人**,作者方不会有意收集未成年人信息。
|
||||
|
||||
### 9. 您的权利
|
||||
由于作者方默认不持有您的任何个人数据,与您个人信息相关的访问、更正、删除等权利,应在**您本地的数据范围内**由您自行行使。如遥测启用且您有疑问,可通过第 10 条联系我们。
|
||||
|
||||
### 10. 联系方式
|
||||
隐私相关问询:**motricseven@foxmail.com**。
|
||||
|
||||
### 11. 变更
|
||||
本说明可不时更新,更新版本将注明生效日期。涉及遥测的重大变更将在发布说明中显著告知。
|
||||
|
||||
---
|
||||
|
||||
## English Version
|
||||
|
||||
### 1. Overview
|
||||
SnowLuma is **self-hosted**: it runs on **your own device or server**. **By default, SnowLumaDevs (the authors) collect, receive, and store none of your data.** The Software contains **no** activation that requires network access or transmits information back to the authors. The only data that ever leaves your device is described in Sections 4 and 5, and telemetry is strictly limited (Section 5).
|
||||
|
||||
### 2. Data the Software Stores on Your Device
|
||||
To function, the Software stores the following categories of data locally (e.g., in a SQLite database, configuration, and log files). **This data stays on your device under your control; the authors cannot access it:**
|
||||
- **Account & credentials:** the signed-in QQ account, session/tokens, and the WebUI login password (stored as a **salted scrypt hash**, never in plaintext).
|
||||
- **Relationship data:** lists and profiles of friends, groups, and members.
|
||||
- **Message data:** messages processed or cached for protocol conversion (depending on your configuration).
|
||||
- **Runtime configuration & logs.**
|
||||
|
||||
> Note: Because SnowLuma is a QQ protocol tool, this local data **necessarily** includes QQ account and contact information. This does not conflict with Section 5 ("telemetry never collects QQ account/contacts") — local storage ≠ outbound transmission.
|
||||
|
||||
### 3. You Are the Data Controller
|
||||
When you run the Software to process the personal information of your QQ contacts, group members, or other individuals, **you are the data controller/processor** for that information and are responsible for compliance (obtaining any necessary consent, securing the data, responding to data-subject requests). The authors merely provide a software tool and take no part in your processing.
|
||||
|
||||
### 4. The Only Ways Data Leaves Your Device
|
||||
The Software transmits your data to an external destination only in these two cases:
|
||||
1. **Notifications / webhooks you configure:** when you set up a notification channel (e.g., a webhook), the relevant content is sent to **the address and settings you provide**. You fully control the destination and content; the authors are not involved.
|
||||
2. **Anonymous telemetry:** see Section 5.
|
||||
|
||||
### 5. Telemetry
|
||||
**Mode: ON by default (opt-out).** You can disable it at any time (see 5.3).
|
||||
|
||||
#### 5.1 What is collected (anonymous, aggregate, non-identifying only)
|
||||
- Application version, OS and CPU architecture, Node.js version;
|
||||
- Launch counts and feature-usage counts (e.g., which adapters/commands are enabled — **never their arguments or content**);
|
||||
- Anonymized crash stacks and error types.
|
||||
|
||||
#### 5.2 Never collected (explicit negative list)
|
||||
Telemetry will **never, under any circumstances**, collect or transmit:
|
||||
- **QQ account / UIN, or the identity of any friend, group, or member**;
|
||||
- **Message content or metadata**, nicknames, avatars;
|
||||
- Phone numbers, emails, or any contact details;
|
||||
- Credentials, tokens, passwords;
|
||||
- Precise IP addresses used for profiling (any IP incidentally visible at the transport layer is discarded immediately, not stored, not correlated);
|
||||
- Any identifier that could directly or indirectly identify a natural person.
|
||||
|
||||
#### 5.3 How to disable; notice
|
||||
- **First-run notice:** on first run the Software gives a one-time notice in the console and WebUI that telemetry is on by default and how to disable it.
|
||||
- **One switch off:** disable any time via the `SNOWLUMA_TELEMETRY=0` environment variable, a config option, or the WebUI toggle; collection stops immediately.
|
||||
|
||||
#### 5.4 Use, sharing, retention
|
||||
Telemetry is used **only to improve the Software**, is **never sold or shared with any third party**, and is retained only in anonymous aggregate form for as long as necessary.
|
||||
|
||||
#### 5.5 Effective status (important)
|
||||
This Section fully describes SnowLuma's telemetry mechanism but is **effective only for builds that actually contain telemetry code.**
|
||||
> **Current status (as of 2026-06-17):** public releases **do not yet contain** telemetry code, so this Section is currently **not in effect**. If a release introduces telemetry, its release notes will say so and this Section will take effect for that release.
|
||||
|
||||
### 6. Security & Retention
|
||||
Security and retention of local data are under your (the operator's) control. Protect device access and rotate the WebUI password regularly.
|
||||
|
||||
### 7. Third-Party Components
|
||||
The Software may bundle third-party components (such as FFmpeg for media processing). These run **locally** on your device to process local data and **send nothing** to the authors or third parties.
|
||||
|
||||
### 8. Minors
|
||||
The Software targets developers and technical users, is **not directed to minors**, and the authors do not knowingly collect minors' information.
|
||||
|
||||
### 9. Your Rights
|
||||
Because the authors hold none of your personal data by default, rights of access, correction, and deletion are exercised by you **over the data on your own device**. If telemetry is enabled and you have questions, contact us (Section 10).
|
||||
|
||||
### 10. Contact
|
||||
Privacy inquiries: **motricseven@foxmail.com**.
|
||||
|
||||
### 11. Changes
|
||||
This Notice may be updated from time to time; updated versions bear an effective date. Material changes affecting telemetry will be prominently noted in release notes.
|
||||
@@ -1,131 +1,153 @@
|
||||
<h1 align="center">❄️ SnowLuma</h1>
|
||||
|
||||
<p align="center">
|
||||
<i>Next Remote Protocol Framework.</i>
|
||||
<img src="./assets/readme/hero.svg" width="100%" alt="SnowLuma 将 QQ 原生会话桥接到 OneBot、WebUI 与自动化工具" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="最新版本" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions/workflows/dev-build.yml"><img alt="构建状态" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/dev-build.yml?branch=dev&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="SnowLuma SDK 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=287fb8"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/mcp"><img alt="SnowLuma MCP 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fmcp?style=flat-square&label=mcp&color=7658c7"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="GitHub Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases">Releases</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">Issues</a> ·
|
||||
<a href="https://qm.qq.com/q/g3UMLpWALe">QQ 群</a> ·
|
||||
<a href="https://t.me/napcatqq">Telegram</a>
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="#运行链路">运行链路</a> ·
|
||||
<a href="./docs/onebot-actions.md">动作参考</a> ·
|
||||
<a href="./packages/sdk/README.md">SDK</a> ·
|
||||
<a href="./packages/mcp/README.md">MCP</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">问题反馈</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口;每个账号拥有独立会话,适合机器人开发、自动化与协议研究。
|
||||
|
||||
## 简介
|
||||
> [!CAUTION]
|
||||
> **使用边界**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
>
|
||||
> **Disclaimer**: SnowLuma is an independent third-party interoperability project with no affiliation with or endorsement by Tencent / QQ. It is provided for study and research only, “as is” and without warranty. See [`EULA.md`](EULA.md).
|
||||
|
||||
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
|
||||
## 运行链路
|
||||
|
||||
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
|
||||
<p align="center">
|
||||
<img src="./assets/readme/runtime-map.svg" width="100%" alt="QQ 会话经过协议桥接与 OneBot 标准化后连接到 WebSocket、HTTP、WebUI、SDK 和 MCP" />
|
||||
</p>
|
||||
|
||||
## 特性
|
||||
SnowLuma 将会话接入、协议解析、身份映射、OneBot 转换和网络适配拆成清晰边界。多个 QQ 账号可以并行运行,同时保持独立状态、日志与连接配置。
|
||||
|
||||
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
|
||||
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
|
||||
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
|
||||
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
|
||||
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
|
||||
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
|
||||
## 核心能力
|
||||
|
||||
| 场景 | SnowLuma 提供 |
|
||||
| --- | --- |
|
||||
| OneBot 接入 | OneBot v11 动作与事件,支持 WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 |
|
||||
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及 JSON / XML 卡片等常见消息元素 |
|
||||
| 多账号运行 | 每个 QQ 账号独立维护会话、身份映射、消息存储与网络适配器 |
|
||||
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、密码管理与可定制总览 |
|
||||
| 开发者工具 | 提供 [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
|
||||
| 可观察错误 | 关键解析与执行失败会留下明确上下文,不以静默丢弃掩盖问题 |
|
||||
|
||||
## 快速开始
|
||||
|
||||
下载预构建发布包:
|
||||
### 1. 选择发行包
|
||||
|
||||
前往 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载与你的平台匹配的版本:
|
||||
|
||||
| 平台 | 完整版(内置 Node.js,推荐) | Lite(需要 Node.js 22+) |
|
||||
| --- | --- | --- |
|
||||
| Windows x64 | `SnowLuma-vX.Y.Z-win-x64.zip` | `SnowLuma-vX.Y.Z-win-x64-lite.zip` |
|
||||
| Linux x64 | `SnowLuma-vX.Y.Z-linux-x64.tar.gz` | `SnowLuma-vX.Y.Z-linux-x64-lite.tar.gz` |
|
||||
| Linux arm64 | `SnowLuma-vX.Y.Z-linux-arm64.tar.gz` | `SnowLuma-vX.Y.Z-linux-arm64-lite.tar.gz` |
|
||||
|
||||
完整版适合直接解压运行;Lite 版只移除了内置 Node.js,其余运行时依赖与 WebUI 静态资源保持一致。
|
||||
|
||||
### 2. 启动 SnowLuma
|
||||
|
||||
Windows 运行 `launcher.bat`。Linux 在解压目录执行:
|
||||
|
||||
```bash
|
||||
# 从 Releases 下载 zip,解压到任意目录
|
||||
./launcher.bat # Windows
|
||||
chmod +x launcher.sh
|
||||
./launcher.sh
|
||||
```
|
||||
|
||||
或从源码开发:
|
||||
### 3. 打开 WebUI
|
||||
|
||||
浏览器访问 [`http://localhost:5099`](http://localhost:5099)。初始账号为 `admin`,随机密码会显示在启动日志中;登录后即可接入已启动的 QQ 进程并配置 OneBot 连接。
|
||||
|
||||
<details>
|
||||
<summary><strong>无人值守部署:通过环境变量确认协议</strong></summary>
|
||||
|
||||
同时设置以下两个变量可跳过 WebUI 的协议确认页面:
|
||||
|
||||
```bash
|
||||
SNOWLUMA_ACCEPT_EULA=1
|
||||
SNOWLUMA_ACCEPT_PRIVACY=1
|
||||
```
|
||||
|
||||
两项必须同时设置,且环境变量确认不会写入持久化同意记录。设置变量即表示运营者已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。
|
||||
|
||||
</details>
|
||||
|
||||
## 选择接入方式
|
||||
|
||||
| 入口 | 适合场景 | 参考 |
|
||||
| --- | --- | --- |
|
||||
| WebSocket / HTTP | 对接现有 OneBot 机器人框架 | [OneBot 动作参考](docs/onebot-actions.md) |
|
||||
| TypeScript SDK | 编写类型安全的客户端与消息逻辑 | [`packages/sdk`](packages/sdk/README.md) |
|
||||
| MCP | 让支持 MCP 的工具查询或调用 SnowLuma 动作 | [`packages/mcp`](packages/mcp/README.md) |
|
||||
| WebUI | 管理运行状态、日志、账号与连接 | 启动后访问 `http://localhost:5099` |
|
||||
|
||||
## 开发与贡献
|
||||
|
||||
本地开发需要 Node.js 22+ 与项目锁定版本的 pnpm。所有日常开发基于 `dev` 分支:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
cd SnowLuma
|
||||
git checkout dev
|
||||
pnpm install
|
||||
pnpm build
|
||||
pnpm start
|
||||
pnpm typecheck
|
||||
pnpm test
|
||||
```
|
||||
|
||||
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
|
||||
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
|
||||
- 先读 [`CONTEXT.md`](CONTEXT.md) 了解模块边界与项目词汇。
|
||||
- 提交代码前阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md) 与 [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md)。
|
||||
- 开发方向与已完成事项见 [`RoadMap.md`](RoadMap.md)。
|
||||
|
||||
## 工作区
|
||||
<details>
|
||||
<summary><strong>主要目录</strong></summary>
|
||||
|
||||
本仓库使用 pnpm monorepo 管理,各包职责如下:
|
||||
|
||||
| 包 | 说明 |
|
||||
| 路径 | 作用 |
|
||||
| --- | --- |
|
||||
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
|
||||
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
|
||||
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
|
||||
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
|
||||
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
|
||||
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
|
||||
| [`webui`](packages/webui) | Web 管理面板前端。 |
|
||||
| `packages/protocol` | QQ 协议定义、数据包解析、消息推送与 OIDB 服务 |
|
||||
| `packages/onebot` | OneBot 动作执行、事件转换与网络适配 |
|
||||
| `packages/core` | 运行时编排、QQ 会话桥接与 WebUI 服务端 |
|
||||
| `packages/webui` | React 管理界面 |
|
||||
| `packages/sdk` | 对外发布的 TypeScript SDK |
|
||||
| `packages/mcp` | 面向 MCP 客户端的动作目录与执行入口 |
|
||||
|
||||
## 架构
|
||||
</details>
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A([QQ 客户端])
|
||||
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
|
||||
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
|
||||
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
|
||||
E([WS / HTTP / WebUI])
|
||||
## 使用边界与许可
|
||||
|
||||
A --> B --> C --> D --> E
|
||||
```
|
||||
> [!IMPORTANT]
|
||||
> SnowLuma 使用 **源码可见非商业许可**,**不是 OSI 开源许可**。源码可用于查看、学习、非商业自托管及私下修改;任何商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
|
||||
|
||||
## 文档
|
||||
- 完整条款见 [`LICENSE`](LICENSE)。
|
||||
- 随附的原生附加组件为专有组件,不在源码许可范围内。
|
||||
- 二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束。
|
||||
- 商业授权请联系 `motricseven@foxmail.com`。
|
||||
|
||||
- [路线图](RoadMap.md)
|
||||
- [贡献指南](CONTRIBUTING.md)
|
||||
- [行为准则](CODE_OF_CONDUCT.md)
|
||||
SnowLuma is source-available for study and non-commercial self-hosting, but it is **not OSI open source**. Commercial use and public distribution of modified or derivative versions require prior written permission. Bundled native components are proprietary and excluded from the source license.
|
||||
|
||||
## 开发命令
|
||||
## 社区与支持
|
||||
|
||||
```bash
|
||||
pnpm dev # 启动 core dev server
|
||||
pnpm dev:web # 启动 webui dev server
|
||||
pnpm test # 运行 core 测试
|
||||
pnpm typecheck # 全仓库 type check
|
||||
pnpm build:all # 构建 core + sdk + webui
|
||||
```
|
||||
- [提交问题](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
- [QQ 群](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- [Telegram](https://t.me/napcatqq)
|
||||
|
||||
## 鸣谢
|
||||
|
||||
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
|
||||
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
|
||||
项目参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
|
||||
## 贡献者
|
||||
|
||||
感谢每一位为 SnowLuma 提交过代码的伙伴。
|
||||
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
## Star 趋势
|
||||
|
||||
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 社区
|
||||
|
||||
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
|
||||
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="SnowLuma 贡献者" /></a>
|
||||
</p>
|
||||
@@ -0,0 +1,150 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="400" viewBox="0 0 1200 400" role="img" aria-labelledby="hero-title hero-desc">
|
||||
<title id="hero-title">SnowLuma — QQ 到 OneBot 的现代协议桥</title>
|
||||
<desc id="hero-desc">SnowLuma 将多个 QQ 原生会话经过协议、桥接与 OneBot 三层处理,连接到 WebSocket、HTTP、WebUI、SDK 与 MCP。</desc>
|
||||
|
||||
<defs>
|
||||
<linearGradient id="hero-bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#08111f"/>
|
||||
<stop offset="0.58" stop-color="#101b31"/>
|
||||
<stop offset="1" stop-color="#17223d"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="brand-line" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stop-color="#75d2ff"/>
|
||||
<stop offset="0.55" stop-color="#bba7ff"/>
|
||||
<stop offset="1" stop-color="#f4bfd9"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="bridge-fill" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#192c4e"/>
|
||||
<stop offset="1" stop-color="#2a2550"/>
|
||||
</linearGradient>
|
||||
<filter id="soft-glow" x="-40%" y="-40%" width="180%" height="180%">
|
||||
<feGaussianBlur stdDeviation="16"/>
|
||||
</filter>
|
||||
<style>
|
||||
.sans { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; }
|
||||
.mono { font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; }
|
||||
.hero-star { animation: hero-star-float 4s ease-in-out infinite; }
|
||||
.hero-star-main { transform-origin: 16px 14px; }
|
||||
.hero-star-secondary { transform-origin: 38px 38px; animation-delay: 0.5s; }
|
||||
@keyframes hero-star-float {
|
||||
0% { transform: translateY(0) rotate(0deg); opacity: 0.9; }
|
||||
50% { transform: translateY(-8px) rotate(10deg); opacity: 1; }
|
||||
100% { transform: translateY(0) rotate(0deg); opacity: 0.9; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .hero-star { animation: none; } }
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<rect width="1200" height="400" rx="28" fill="url(#hero-bg)"/>
|
||||
<circle cx="1112" cy="28" r="138" fill="#63c9f6" opacity="0.08" filter="url(#soft-glow)"/>
|
||||
<circle cx="705" cy="392" r="120" fill="#b59cff" opacity="0.06" filter="url(#soft-glow)"/>
|
||||
|
||||
<g aria-hidden="true" fill="none" stroke-linecap="round">
|
||||
<path d="M694 28H1154" stroke="#5f7192" stroke-opacity="0.28"/>
|
||||
<path d="M694 372H1154" stroke="#5f7192" stroke-opacity="0.2"/>
|
||||
<path d="M708 14V386" stroke="#5f7192" stroke-opacity="0.16"/>
|
||||
<path d="M1140 14V386" stroke="#5f7192" stroke-opacity="0.16"/>
|
||||
</g>
|
||||
|
||||
<g id="title-block" transform="translate(64 54)">
|
||||
<text class="mono" x="0" y="0" fill="#8da1c0" font-size="14" letter-spacing="2.2">QQ INTEROPERABILITY · ONEBOT V11 · MULTI-ACCOUNT</text>
|
||||
|
||||
<text class="sans" x="0" y="92" font-size="74" font-weight="760" letter-spacing="-3">
|
||||
<tspan fill="#f7fbff">Snow</tspan><tspan fill="#82d7ff">Luma</tspan>
|
||||
</text>
|
||||
<rect x="2" y="110" width="148" height="5" rx="2.5" fill="url(#brand-line)"/>
|
||||
|
||||
<text class="sans" x="0" y="162" fill="#dce7f7" font-size="27" font-weight="590">把 QQ 原生会话,稳定地桥接到</text>
|
||||
<text class="sans" x="0" y="199" fill="#dce7f7" font-size="27" font-weight="590">OneBot、WebUI 与自动化工具。</text>
|
||||
|
||||
<text class="sans" x="0" y="244" fill="#92a6c5" font-size="16">一个运行时,管理多账号、动作调用、事件分发与实时状态。</text>
|
||||
|
||||
<g transform="translate(0 274)">
|
||||
<rect width="128" height="34" rx="17" fill="#172942" stroke="#315173"/>
|
||||
<circle cx="18" cy="17" r="4" fill="#75d2ff"/>
|
||||
<text class="mono" x="31" y="22" fill="#b9dfff" font-size="13">Windows x64</text>
|
||||
|
||||
<g transform="translate(140 0)">
|
||||
<rect width="174" height="34" rx="17" fill="#211f41" stroke="#4d4777"/>
|
||||
<circle cx="18" cy="17" r="4" fill="#bba7ff"/>
|
||||
<text class="mono" x="31" y="22" fill="#d8cdfd" font-size="13">Linux x64 / arm64</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(326 0)">
|
||||
<rect width="120" height="34" rx="17" fill="#302037" stroke="#68435c"/>
|
||||
<circle cx="18" cy="17" r="4" fill="#f4bfd9"/>
|
||||
<text class="mono" x="31" y="22" fill="#f7d7e6" font-size="13">TypeScript</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g id="project-proof" transform="translate(734 58)">
|
||||
<text class="mono" x="0" y="0" fill="#8398b8" font-size="13" letter-spacing="1.8">LIVE SESSION ROUTING</text>
|
||||
|
||||
<g transform="translate(0 24)">
|
||||
<g>
|
||||
<rect width="116" height="45" rx="12" fill="#12253d" stroke="#2d5274"/>
|
||||
<circle cx="19" cy="17" r="5" fill="#74d2ff"/>
|
||||
<text class="mono" x="31" y="21" fill="#c7e9fb" font-size="12">QQ · 01</text>
|
||||
<text class="mono" x="16" y="36" fill="#7189a9" font-size="10">ONLINE</text>
|
||||
</g>
|
||||
<g transform="translate(132 0)">
|
||||
<rect width="116" height="45" rx="12" fill="#1b2342" stroke="#4a4c78"/>
|
||||
<circle cx="19" cy="17" r="5" fill="#bba7ff"/>
|
||||
<text class="mono" x="31" y="21" fill="#ddd4ff" font-size="12">QQ · 02</text>
|
||||
<text class="mono" x="16" y="36" fill="#8186ad" font-size="10">ONLINE</text>
|
||||
</g>
|
||||
<g transform="translate(264 0)">
|
||||
<rect width="116" height="45" rx="12" fill="#292039" stroke="#67445d"/>
|
||||
<circle cx="19" cy="17" r="5" fill="#f4bfd9"/>
|
||||
<text class="mono" x="31" y="21" fill="#f8dbea" font-size="12">QQ · N</text>
|
||||
<text class="mono" x="16" y="36" fill="#a17f95" font-size="10">READY</text>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g aria-hidden="true" fill="none" stroke="url(#brand-line)" stroke-width="2" stroke-linecap="round" opacity="0.85">
|
||||
<path d="M58 69V90C58 102 78 104 94 104H190"/>
|
||||
<path d="M190 69V104"/>
|
||||
<path d="M322 69V90C322 102 302 104 286 104H190"/>
|
||||
</g>
|
||||
|
||||
<g transform="translate(0 104)">
|
||||
<rect x="12" y="16" width="356" height="88" rx="18" fill="#0d1729" stroke="#263853" opacity="0.72"/>
|
||||
<rect x="6" y="8" width="368" height="88" rx="18" fill="#111f35" stroke="#364865" opacity="0.88"/>
|
||||
<rect width="380" height="88" rx="18" fill="url(#bridge-fill)" stroke="#6684ae" stroke-opacity="0.74"/>
|
||||
|
||||
<text class="mono" x="22" y="25" fill="#90a6c6" font-size="11" letter-spacing="1.4">SNOWLUMA RUNTIME</text>
|
||||
<text class="sans" x="22" y="53" fill="#f4f8ff" font-size="20" font-weight="680">Protocol → Bridge → OneBot</text>
|
||||
<text class="sans" x="22" y="74" fill="#93a8c7" font-size="13">独立会话 · 类型化动作 · 可追踪事件</text>
|
||||
|
||||
<g transform="translate(326 13)" aria-hidden="true">
|
||||
<path class="hero-star hero-star-main" d="M16 0L19.5 10.5L30 14L19.5 17.5L16 28L12.5 17.5L2 14L12.5 10.5Z" fill="#c8b7ff"/>
|
||||
<path class="hero-star hero-star-secondary" d="M38 30L40 36L46 38L40 40L38 46L36 40L30 38L36 36Z" fill="#f2c2da" opacity="0.9"/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g aria-hidden="true" fill="none" stroke="#6881a4" stroke-width="1.5" stroke-linecap="round">
|
||||
<path d="M58 208V224"/>
|
||||
<path d="M190 208V224"/>
|
||||
<path d="M322 208V224"/>
|
||||
</g>
|
||||
|
||||
<g transform="translate(0 224)">
|
||||
<g>
|
||||
<rect width="116" height="68" rx="15" fill="#10253b" stroke="#315d7c"/>
|
||||
<text class="sans" x="58" y="29" fill="#bfe8fb" text-anchor="middle" font-size="15" font-weight="650">OneBot v11</text>
|
||||
<text class="mono" x="58" y="50" fill="#6685a3" text-anchor="middle" font-size="10">ACTIONS · EVENTS</text>
|
||||
</g>
|
||||
<g transform="translate(132 0)">
|
||||
<rect width="116" height="68" rx="15" fill="#201f42" stroke="#504d7a"/>
|
||||
<text class="sans" x="58" y="29" fill="#ded5ff" text-anchor="middle" font-size="15" font-weight="650">WebUI</text>
|
||||
<text class="mono" x="58" y="50" fill="#8483ad" text-anchor="middle" font-size="10">STATUS · LOGS</text>
|
||||
</g>
|
||||
<g transform="translate(264 0)">
|
||||
<rect width="116" height="68" rx="15" fill="#2a2038" stroke="#65455e"/>
|
||||
<text class="sans" x="58" y="29" fill="#f6d6e6" text-anchor="middle" font-size="15" font-weight="650">SDK / MCP</text>
|
||||
<text class="mono" x="58" y="50" fill="#9d7e93" text-anchor="middle" font-size="10">TOOLS · STREAMS</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 8.0 KiB |
@@ -0,0 +1,140 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="440" viewBox="0 0 1200 440" role="img" aria-labelledby="map-title map-desc">
|
||||
<title id="map-title">SnowLuma 运行链路</title>
|
||||
<desc id="map-desc">QQ 进程接入后,数据经过协议桥接、OneBot 标准化,再分发到 WebSocket、HTTP、WebUI、SDK 与 MCP。</desc>
|
||||
|
||||
<defs>
|
||||
<linearGradient id="map-rule" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stop-color="#54bde9"/>
|
||||
<stop offset="0.55" stop-color="#9e88ef"/>
|
||||
<stop offset="1" stop-color="#e4a8c6"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="consumer-border" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#54bde9"/>
|
||||
<stop offset="0.5" stop-color="#9e88ef"/>
|
||||
<stop offset="1" stop-color="#e4a8c6"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="consumer-flow" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#a5e7ff"/>
|
||||
<stop offset="0.5" stop-color="#d1c5ff"/>
|
||||
<stop offset="1" stop-color="#ffd4e8"/>
|
||||
</linearGradient>
|
||||
<style>
|
||||
.sans { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; }
|
||||
.mono { font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; }
|
||||
@media (prefers-reduced-motion: reduce) { .consumer-flow { display: none; } }
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<rect width="1200" height="440" rx="28" fill="#f6f9fd"/>
|
||||
<rect x="0.75" y="0.75" width="1198.5" height="438.5" rx="27.25" fill="none" stroke="#cbd8e8" stroke-width="1.5"/>
|
||||
|
||||
<g transform="translate(54 42)">
|
||||
<text class="mono" x="0" y="0" fill="#6e819b" font-size="13" letter-spacing="2">RUNTIME MAP · FROM SESSION TO CONSUMER</text>
|
||||
<text class="sans" x="0" y="45" fill="#14223a" font-size="34" font-weight="720">一条事件如何穿过 SnowLuma</text>
|
||||
<text class="sans" x="0" y="75" fill="#63758e" font-size="16">每层只承担一种职责,多个 QQ 账号各自拥有独立、可追踪的会话链路。</text>
|
||||
</g>
|
||||
|
||||
<g id="connection-labels" class="mono" fill="#7c8ca2" font-size="10" letter-spacing="1.5" text-anchor="middle">
|
||||
<text x="305" y="210">PIPE</text>
|
||||
<text x="577" y="210">MAP</text>
|
||||
<text x="849" y="210">OUT</text>
|
||||
</g>
|
||||
<g aria-hidden="true" fill="none" stroke="url(#map-rule)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M284 225H316L309 218M316 225L309 232"/>
|
||||
<path d="M556 225H588L581 218M588 225L581 232"/>
|
||||
<path d="M828 225H860L853 218M860 225L853 232"/>
|
||||
</g>
|
||||
|
||||
<g id="stage-session" transform="translate(54 138)">
|
||||
<rect width="230" height="218" rx="20" fill="#ffffff" stroke="#c9d8e8" stroke-width="1.5"/>
|
||||
<path d="M20 0H210" fill="none" stroke="#54bde9" stroke-width="4" stroke-linecap="round"/>
|
||||
<text class="mono" x="20" y="32" fill="#5582a0" font-size="11" letter-spacing="1.4">01 · 会话接入</text>
|
||||
|
||||
<g transform="translate(20 48)">
|
||||
<rect width="190" height="54" rx="13" fill="#edf8fd" stroke="#afd9eb"/>
|
||||
<circle cx="25" cy="19" r="5" fill="#47b7e6"/>
|
||||
<circle cx="25" cy="35" r="5" fill="#92d8f3"/>
|
||||
<text class="mono" x="42" y="23" fill="#315a77" font-size="11">QQ · ACCOUNT 01</text>
|
||||
<text class="mono" x="42" y="39" fill="#6d92a8" font-size="11">QQ · ACCOUNT 02</text>
|
||||
</g>
|
||||
|
||||
<text class="sans" x="115" y="132" fill="#15243a" font-size="20" font-weight="680" text-anchor="middle">多个 QQ 进程</text>
|
||||
<text class="sans" x="115" y="158" fill="#687c95" font-size="14" text-anchor="middle">独立接入、独立登录状态</text>
|
||||
<text class="sans" x="115" y="181" fill="#687c95" font-size="14" text-anchor="middle">每个账号单独路由</text>
|
||||
</g>
|
||||
|
||||
<g id="stage-bridge" transform="translate(326 138)">
|
||||
<rect width="230" height="218" rx="20" fill="#ffffff" stroke="#d0c9ed" stroke-width="1.5"/>
|
||||
<path d="M20 0H210" fill="none" stroke="#9e88ef" stroke-width="4" stroke-linecap="round"/>
|
||||
<text class="mono" x="20" y="32" fill="#7163aa" font-size="11" letter-spacing="1.4">02 · 协议桥接</text>
|
||||
|
||||
<g transform="translate(20 42)">
|
||||
<rect x="10" y="14" width="170" height="48" rx="12" fill="#f2effd" stroke="#cfc5f2"/>
|
||||
<rect x="5" y="7" width="180" height="48" rx="12" fill="#eeeafd" stroke="#c3b7ee"/>
|
||||
<rect width="190" height="48" rx="12" fill="#e9e3fb" stroke="#b6a7e9"/>
|
||||
<text class="mono" x="95" y="21" fill="#544584" text-anchor="middle" font-size="11">PACKET → EVENT</text>
|
||||
<text class="mono" x="95" y="37" fill="#77699c" text-anchor="middle" font-size="10">PROTOCOL · BRIDGE</text>
|
||||
</g>
|
||||
|
||||
<text class="sans" x="115" y="132" fill="#15243a" font-size="20" font-weight="680" text-anchor="middle">解析与身份映射</text>
|
||||
<text class="sans" x="115" y="158" fill="#687c95" font-size="14" text-anchor="middle">协议数据转换为内部事件</text>
|
||||
<text class="sans" x="115" y="181" fill="#687c95" font-size="14" text-anchor="middle">异常路径保留可观察信息</text>
|
||||
</g>
|
||||
|
||||
<g id="stage-onebot" transform="translate(598 138)">
|
||||
<rect width="230" height="218" rx="20" fill="#ffffff" stroke="#d9c8e1" stroke-width="1.5"/>
|
||||
<path d="M20 0H210" fill="none" stroke="#cf9bc0" stroke-width="4" stroke-linecap="round"/>
|
||||
<text class="mono" x="20" y="32" fill="#916382" font-size="11" letter-spacing="1.4">03 · 标准化</text>
|
||||
|
||||
<g transform="translate(20 49)">
|
||||
<rect width="190" height="55" rx="13" fill="#faeff6" stroke="#e6bfd5"/>
|
||||
<text class="sans" x="95" y="25" fill="#753e62" text-anchor="middle" font-size="17" font-weight="700">OneBot v11</text>
|
||||
<text class="mono" x="95" y="42" fill="#a37792" text-anchor="middle" font-size="10">ACTIONS ↔ EVENTS</text>
|
||||
</g>
|
||||
|
||||
<text class="sans" x="115" y="132" fill="#15243a" font-size="20" font-weight="680" text-anchor="middle">统一动作与事件</text>
|
||||
<text class="sans" x="115" y="158" fill="#687c95" font-size="14" text-anchor="middle">参数校验、动作执行</text>
|
||||
<text class="sans" x="115" y="181" fill="#687c95" font-size="14" text-anchor="middle">事件转换与消息存储</text>
|
||||
</g>
|
||||
|
||||
<g id="stage-consumers" transform="translate(870 138)">
|
||||
<rect x="2" y="2" width="272" height="214" rx="18" fill="#101a2d" stroke="url(#consumer-border)" stroke-width="4"/>
|
||||
<rect class="consumer-flow" x="2" y="2" width="272" height="214" rx="18" fill="none" stroke="url(#consumer-flow)" stroke-width="5" stroke-linecap="round" stroke-dasharray="108 838" aria-hidden="true">
|
||||
<animate attributeName="stroke-dashoffset" from="0" to="-946" dur="4.8s" repeatCount="indefinite"/>
|
||||
</rect>
|
||||
<text class="mono" x="20" y="32" fill="#91a5c2" font-size="11" letter-spacing="1.4">04 · 消费端</text>
|
||||
<text class="sans" x="20" y="65" fill="#f2f7ff" font-size="20" font-weight="680">按场景自由组合</text>
|
||||
|
||||
<g class="mono" font-size="11" text-anchor="middle">
|
||||
<g transform="translate(20 84)">
|
||||
<rect width="70" height="32" rx="10" fill="#17304a" stroke="#315b7a"/>
|
||||
<text x="35" y="21" fill="#bce8fb">WS</text>
|
||||
</g>
|
||||
<g transform="translate(102 84)">
|
||||
<rect width="70" height="32" rx="10" fill="#242244" stroke="#514e7c"/>
|
||||
<text x="35" y="21" fill="#ddd5ff">HTTP</text>
|
||||
</g>
|
||||
<g transform="translate(184 84)">
|
||||
<rect width="70" height="32" rx="10" fill="#34233c" stroke="#67465e"/>
|
||||
<text x="35" y="21" fill="#f6d9e7">WebUI</text>
|
||||
</g>
|
||||
<g transform="translate(20 128)">
|
||||
<rect width="111" height="32" rx="10" fill="#182a43" stroke="#334f70"/>
|
||||
<text x="55.5" y="21" fill="#c4def5">SDK</text>
|
||||
</g>
|
||||
<g transform="translate(143 128)">
|
||||
<rect width="111" height="32" rx="10" fill="#2b2447" stroke="#554d7e"/>
|
||||
<text x="55.5" y="21" fill="#dfd7ff">MCP</text>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<text class="sans" x="20" y="190" fill="#8196b5" font-size="13">多个适配器可同时启用</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(54 392)">
|
||||
<rect width="1092" height="1" fill="#d4dfeb"/>
|
||||
<circle cx="5" cy="24" r="4" fill="#54bde9"/>
|
||||
<text class="sans" x="18" y="29" fill="#60738c" font-size="14">一次接入,统一管理运行状态、日志、连接与动作调用。</text>
|
||||
<text class="mono" x="1092" y="29" fill="#8191a6" text-anchor="end" font-size="11">SNOWLUMA / RUNTIME MAP</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 8.2 KiB |
+13
-3
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.9.2",
|
||||
"version": "1.12.7",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -8,12 +9,17 @@
|
||||
"build": "pnpm --filter @snowluma/core build",
|
||||
"build:sdk": "pnpm --filter @snowluma/sdk build",
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
|
||||
"build:mcp": "pnpm --filter @snowluma/mcp build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter webui build",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
"test": "pnpm --filter @snowluma/core test",
|
||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||
"test:common": "pnpm --filter @snowluma/common test",
|
||||
"test:all": "pnpm -r --if-present test",
|
||||
"test:native": "pnpm -r --if-present test:native",
|
||||
"coverage": "pnpm --filter @snowluma/common test -- --coverage",
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
@@ -42,7 +48,11 @@
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"better-sqlite3"
|
||||
]
|
||||
],
|
||||
"overrides": {
|
||||
"esbuild@<0.28.1": "^0.28.1",
|
||||
"@babel/core@<7.29.6": "^7.29.6"
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
"engines": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.2",
|
||||
"version": "1.12.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
|
||||
@@ -6,10 +6,12 @@ import { HookSession, type HookSessionDeps } from './hook-session';
|
||||
import {
|
||||
injectHookProcess,
|
||||
listHookProcesses,
|
||||
resolveHookNativePath,
|
||||
unloadHookProcess,
|
||||
type HookProcessBaseInfo,
|
||||
} from './injector';
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
|
||||
import { QqHookClient } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import type { HookProcessInfo } from './types';
|
||||
@@ -27,6 +29,7 @@ export interface BridgeManagerSink {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
|
||||
onPacket(pkt: PacketInfo): void;
|
||||
onPidDisconnected(pid: number): void;
|
||||
onPidReceiveHealthChanged(pid: number, healthy: boolean): void;
|
||||
}
|
||||
|
||||
export type HookManagerDeps = {
|
||||
@@ -49,6 +52,13 @@ export type HookManagerDeps = {
|
||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||
* Failed loads are logged and leave the session in the 'error' state. */
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
/** Optional hook fired whenever the set of HookProcessInfo observable to
|
||||
* `listProcesses()` changes — new process discovered, process gone, or
|
||||
* any session's status mutated. Used by the WebUI SSE wiring to push a
|
||||
* fresh processes snapshot to connected clients without REST polling.
|
||||
* Exceptions thrown by the callback are caught and logged; they do not
|
||||
* break the watcher / session event loops. */
|
||||
onSessionsChanged?: () => void;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
@@ -59,7 +69,7 @@ export type HookManagerDeps = {
|
||||
* Responsibilities:
|
||||
* - Route user commands (load/unload/refresh) to the matching session.
|
||||
* - Route watcher diff events to the matching session.
|
||||
* - Forward session events ('login' / 'disconnected') to BridgeManager.
|
||||
* - Forward session events ('login' / 'disconnected' / receive health) to BridgeManager.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
*
|
||||
@@ -74,8 +84,15 @@ export class HookManager {
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: PipeWatcher;
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
private readonly listProcessesNative: () => HookProcessBaseInfo[];
|
||||
/** Watcher/API process enumeration — isolated + timeout-bounded by default
|
||||
* so a blocked native /proc walk can't freeze the loop (issue #158).
|
||||
* Resolves to `null` (UNKNOWN) on timeout/failure. */
|
||||
private readonly enumerate: () => Promise<HookProcessBaseInfo[] | null>;
|
||||
/** The owned enumerator (worker lifecycle), or null when a custom lister was
|
||||
* injected (tests) — nothing to tear down in that case. */
|
||||
private readonly enumerator: ProcessEnumerator | null;
|
||||
private readonly autoLoadOnDiscovery: boolean;
|
||||
private readonly onSessionsChangedRaw?: () => void;
|
||||
private readonly log: Logger;
|
||||
private readonly sessions = new Map<number, HookSession>();
|
||||
private readonly startPromise: Promise<void>;
|
||||
@@ -85,6 +102,7 @@ export class HookManager {
|
||||
constructor(deps: HookManagerDeps) {
|
||||
this.bridgeManager = deps.bridgeManager;
|
||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
|
||||
this.onSessionsChangedRaw = deps.onSessionsChanged;
|
||||
this.log = deps.log ?? createLogger('Hook');
|
||||
|
||||
this.injector = deps.injector ?? {
|
||||
@@ -95,15 +113,38 @@ export class HookManager {
|
||||
},
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
|
||||
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
|
||||
|
||||
// A custom lister (tests) is used directly — no worker, no isolation, just
|
||||
// an async wrap that maps a throw to the UNKNOWN sentinel. The default path
|
||||
// wraps the native enumerator in a worker with a timeout.
|
||||
if (deps.listProcesses) {
|
||||
const lister = deps.listProcesses;
|
||||
this.enumerator = null;
|
||||
this.enumerate = async () => {
|
||||
try {
|
||||
return await lister();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
} else {
|
||||
this.enumerator = createNativeProcessEnumerator({
|
||||
addonPath: resolveHookNativePath('node'),
|
||||
fallbackSync: listHookProcesses,
|
||||
processName: defaultProcessName(),
|
||||
log: this.log,
|
||||
});
|
||||
this.enumerate = () => this.enumerator!.enumerate();
|
||||
}
|
||||
|
||||
if (deps.pipeWatcher) {
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.ownsPipeWatcher = false;
|
||||
} else {
|
||||
this.pipeWatcher = new PipeWatcher({
|
||||
listProcesses: this.listProcessesNative,
|
||||
listProcesses: this.enumerate,
|
||||
listLivePipes: () => QqHookClient.listLivePipes(),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
@@ -119,12 +160,13 @@ export class HookManager {
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
let processes: HookProcessBaseInfo[];
|
||||
try {
|
||||
processes = this.listProcessesNative();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = [];
|
||||
const processes = await this.enumerate();
|
||||
if (processes === null) {
|
||||
// Enumeration timed out / failed — report the last-known sessions rather
|
||||
// than an empty list (which the WebUI would render as "no QQ").
|
||||
return [...this.sessions.values()]
|
||||
.map((s) => s.toInfo())
|
||||
.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
const result: HookProcessInfo[] = [];
|
||||
for (const proc of processes) {
|
||||
@@ -172,6 +214,7 @@ export class HookManager {
|
||||
session.dispose();
|
||||
}
|
||||
this.sessions.clear();
|
||||
this.enumerator?.dispose();
|
||||
if (this.ownsPipeWatcher) {
|
||||
this.pipeWatcher.dispose();
|
||||
}
|
||||
@@ -193,11 +236,13 @@ export class HookManager {
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
|
||||
});
|
||||
}
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
this.pipeWatcher.on('process-gone', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.notifyProcessGone();
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
@@ -253,6 +298,15 @@ export class HookManager {
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
});
|
||||
session.on('receive-health-changed', (healthy: boolean) => {
|
||||
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
|
||||
});
|
||||
// status-changed fires on EVERY internal status mutation, including the
|
||||
// ones reached via login / disconnected / refresh — subscribing here
|
||||
// alone covers every transition the WebUI processes view cares about.
|
||||
session.on('status-changed', () => {
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
session.on('disposed', () => {
|
||||
this.sessions.delete(pid);
|
||||
});
|
||||
@@ -261,6 +315,19 @@ export class HookManager {
|
||||
return session;
|
||||
}
|
||||
|
||||
/** Fire the optional sessions-changed hook with exceptions isolated.
|
||||
* A throwing subscriber must not abort the watcher's emit loop or break
|
||||
* a HookSession event handler in flight. */
|
||||
private notifySessionsChanged(): void {
|
||||
if (this.disposed) return;
|
||||
if (!this.onSessionsChangedRaw) return;
|
||||
try {
|
||||
this.onSessionsChangedRaw();
|
||||
} catch (err) {
|
||||
this.log.warn('onSessionsChanged threw: %s', errMsg(err));
|
||||
}
|
||||
}
|
||||
|
||||
private assertValidPid(pid: number): void {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
}
|
||||
|
||||
@@ -1,17 +1,37 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
import type { HookInjectResult } from './injector';
|
||||
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import { statusFor } from './hook-status';
|
||||
import type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
|
||||
/** How often to actively re-probe QQ's login state while connected but not yet
|
||||
* logged in — the safety net for a login the native hook never pushed (Docker
|
||||
* auto-login races/bypasses the pushed loginState frame). */
|
||||
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
|
||||
|
||||
/** QQ emits this response periodically while its MSF receive path is healthy.
|
||||
* Seeing it once arms the watchdog; before that, silence is UNKNOWN rather
|
||||
* than unhealthy so QQ versions that do not expose this command cannot be
|
||||
* false-flagged. Any later recv packet proves the same end-to-end path. */
|
||||
const QQ_RECV_HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat';
|
||||
const RECEIVE_STALE_AFTER_MS = 90_000;
|
||||
const RECEIVE_STALE_CONFIRM_MS = 15_000;
|
||||
|
||||
export type HookSessionDeps = {
|
||||
injector: {
|
||||
inject: (pid: number) => HookInjectResult;
|
||||
unload: (pid: number, handle: HookInjectResult['handle']) => void;
|
||||
};
|
||||
makeClient: (pid: number) => QqHookClient;
|
||||
/** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports).
|
||||
* Drives the login-reconcile safety net; injectable for tests. Defaults to
|
||||
* `probeQqLoginInfo`. */
|
||||
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
/** Sync fast-path check used by load() to skip re-injection when a
|
||||
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
|
||||
* fresh poll — used after unload to dodge the up-to-1500ms cache
|
||||
@@ -41,6 +61,7 @@ export type HookSessionDeps = {
|
||||
* Emitted events:
|
||||
* 'login' (uin, packetSender) — real-UIN login detected
|
||||
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
|
||||
* 'receive-health-changed' (healthy) — receive path confirmed stale/recovered
|
||||
* 'status-changed' (status, error) — status field mutated
|
||||
* 'disposed' () — session stopped tracking this PID
|
||||
*/
|
||||
@@ -49,6 +70,7 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly probeLogin: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
|
||||
private readonly onPacket: PacketSink | null;
|
||||
private readonly log: Logger;
|
||||
@@ -69,12 +91,20 @@ export class HookSession extends EventEmitter {
|
||||
private bound = false;
|
||||
private opChain: Promise<unknown> = Promise.resolve();
|
||||
private disposed = false;
|
||||
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private probing = false;
|
||||
private _receiveHealthy = true;
|
||||
private receiveWatchUin = '';
|
||||
private receiveWatchArmed = false;
|
||||
private receiveWatchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private lastReceiveAt = 0;
|
||||
|
||||
constructor(pid: number, deps: HookSessionDeps) {
|
||||
super();
|
||||
this.pid = pid;
|
||||
this.injector = deps.injector;
|
||||
this.makeClient = deps.makeClient;
|
||||
this.probeLogin = deps.probeLogin ?? probeQqLoginInfo;
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.onPacket = deps.onPacket ?? null;
|
||||
this.log = deps.log ?? createLogger('HookSession');
|
||||
@@ -87,6 +117,7 @@ export class HookSession extends EventEmitter {
|
||||
get uin(): string { return this._uin; }
|
||||
get method(): string { return this._method; }
|
||||
get isDisposed(): boolean { return this.disposed; }
|
||||
get receiveHealthy(): boolean { return this._receiveHealthy; }
|
||||
|
||||
attachProcessInfo(info: { name?: string; path?: string }): void {
|
||||
if (info.name) this._name = info.name;
|
||||
@@ -131,17 +162,7 @@ export class HookSession extends EventEmitter {
|
||||
if (this.disposed) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
// Adopt a DLL that survived a SnowLuma restart.
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
if (!this._method) this._method = 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
|
||||
}
|
||||
await this.reconcilePipeUp();
|
||||
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
@@ -149,18 +170,7 @@ export class HookSession extends EventEmitter {
|
||||
if (this.disposed) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (!this.connected) {
|
||||
// Nothing to tear down; just keep status visible.
|
||||
if (this.injected) this.setStatus('connecting', this._error);
|
||||
return;
|
||||
}
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.setStatus(
|
||||
this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available',
|
||||
'',
|
||||
);
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
this.reconcilePipeDown();
|
||||
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
@@ -227,10 +237,7 @@ export class HookSession extends EventEmitter {
|
||||
this._method = this.injectResult.method;
|
||||
}
|
||||
}
|
||||
this.setStatus(
|
||||
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
|
||||
'',
|
||||
);
|
||||
this.applyStatus();
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus('error', this._error);
|
||||
@@ -281,24 +288,14 @@ export class HookSession extends EventEmitter {
|
||||
private async refreshInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
try {
|
||||
const pipeUp = this.pipeWatcher.isPipeLive(this.pid);
|
||||
if (pipeUp) {
|
||||
// Adopt an unknown DLL the same way onPipeUp would.
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
this._method = this._method || 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
|
||||
}
|
||||
// Same pipe-up / pipe-down reconcilers the watcher drives, chosen by
|
||||
// a fresh poll. This collapses what used to be a hand-copied pair of
|
||||
// onPipeUp/onPipeDown bodies — and fixes the drift where the down
|
||||
// branch reported 'disconnected' even for a never-logged-in session.
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
await this.reconcilePipeUp();
|
||||
} else {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.setStatus(this.injected ? 'disconnected' : 'available', '');
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
this.reconcilePipeDown();
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
@@ -308,6 +305,55 @@ export class HookSession extends EventEmitter {
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
// ─────────────── settled-status reconcilers ───────────────
|
||||
|
||||
/** Push the settled status derived from the live flags. `wasLoggedIn`
|
||||
* defaults to the current `loggedIn`; callers that just tore the client
|
||||
* down pass the value captured *before* teardown (teardown clears it). */
|
||||
private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void {
|
||||
this.setStatus(statusFor({
|
||||
injected: this.injected,
|
||||
connected: this.connected,
|
||||
loggedIn: this.loggedIn,
|
||||
wasLoggedIn,
|
||||
}), error);
|
||||
}
|
||||
|
||||
/** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a
|
||||
* stale client, then (re)connect if needed or just settle the status.
|
||||
* Shared by onPipeUp and refresh's pipe-up branch. */
|
||||
private async reconcilePipeUp(): Promise<void> {
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
if (!this._method) this._method = 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
this.applyStatus();
|
||||
}
|
||||
}
|
||||
|
||||
/** Pipe is down (or the client closed): tear down, settle the status,
|
||||
* and emit the disconnect notification iff we owed BridgeManager one
|
||||
* (i.e. we had reached login). Shared by onPipeDown, refresh's pipe-down
|
||||
* branch, and the client 'close' handler. */
|
||||
private reconcilePipeDown(): void {
|
||||
if (!this.connected) {
|
||||
// Nothing live to tear down. A session that never connected can't owe
|
||||
// a disconnect, and we must NOT clobber a diagnostic the failed
|
||||
// connect/load already set — settle the status keeping `_error`, or
|
||||
// (when not even injected) leave the status untouched entirely.
|
||||
if (this.injected) this.applyStatus(this.loggedIn, this._error);
|
||||
return;
|
||||
}
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.applyStatus(wasLoggedIn);
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
}
|
||||
|
||||
// ─────────────── client plumbing ───────────────
|
||||
|
||||
private async attemptConnect(): Promise<void> {
|
||||
@@ -327,15 +373,26 @@ export class HookSession extends EventEmitter {
|
||||
try {
|
||||
await client.connectAll({ recv: true });
|
||||
this.connected = true;
|
||||
this.setStatus(client.isLoggedIn ? 'online' : 'loaded', '');
|
||||
const loginState = client.getLoginState();
|
||||
if (loginState.loggedIn) this.handleLoginState(loginState);
|
||||
// handleLoginState owns the connected+loggedIn → 'online' (+ login
|
||||
// emit) transition; defer to it so the status is set once. Otherwise
|
||||
// we're connected-but-not-logged-in → 'loaded'.
|
||||
if (loginState.loggedIn) {
|
||||
this.handleLoginState(loginState);
|
||||
} else {
|
||||
this.applyStatus();
|
||||
// The native hook only PUSHES a loginState frame on the login edge;
|
||||
// if QQ logged in before/around connect (Docker auto-login) that edge
|
||||
// is missed and we'd wait forever. Actively re-probe until logged in.
|
||||
this.startLoginReconcile();
|
||||
}
|
||||
this.log.info('pipe connected: PID=%d', this.pid);
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
// Drop the client so the next attempt builds a fresh socket pair.
|
||||
// A failed connect was never logged in → 'connecting' (or 'available').
|
||||
this.tearDownClient();
|
||||
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
|
||||
this.applyStatus(false, this._error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,21 +412,14 @@ export class HookSession extends EventEmitter {
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (this.client !== client) return;
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
if (!this.injected) {
|
||||
this.setStatus('available', '');
|
||||
} else if (wasLoggedIn) {
|
||||
this.setStatus('disconnected', '');
|
||||
} else {
|
||||
this.setStatus('connecting', '');
|
||||
}
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
this.reconcilePipeDown();
|
||||
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
});
|
||||
}
|
||||
|
||||
private tearDownClient(): void {
|
||||
this.stopLoginReconcile();
|
||||
this.resetReceiveWatch();
|
||||
const client = this.client;
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
@@ -387,11 +437,25 @@ export class HookSession extends EventEmitter {
|
||||
const previousUin = this._uin;
|
||||
this._uin = state.uin || state.uinNumber.toString();
|
||||
this.loggedIn = state.loggedIn && isRealUin(this._uin);
|
||||
|
||||
// However login was observed (pushed frame or the active probe), the
|
||||
// safety net's job is done.
|
||||
if (this.loggedIn) {
|
||||
this.setStatus('online', '');
|
||||
} else if (this.connected) {
|
||||
this.setStatus('loaded', this._error);
|
||||
this.stopLoginReconcile();
|
||||
// A PID can switch accounts without an intermediate logout edge. Never
|
||||
// carry the previous account's heartbeat deadline into the new epoch.
|
||||
if (this.receiveWatchUin !== this._uin) this.resetReceiveWatch(this._uin);
|
||||
} else {
|
||||
this.resetReceiveWatch();
|
||||
}
|
||||
|
||||
// Only the connected/logged-in states are ours to set here; when fully
|
||||
// down we leave the status the teardown path already settled.
|
||||
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
|
||||
// observed on a live client, and teardown clears `loggedIn` before
|
||||
// `connected`), so statusFor lands 'online' here rather than the
|
||||
// disconnected/connecting branch.
|
||||
if (this.connected || this.loggedIn) {
|
||||
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
|
||||
}
|
||||
|
||||
if (!this.loggedIn || !this.sender) return;
|
||||
@@ -401,9 +465,63 @@ export class HookSession extends EventEmitter {
|
||||
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
|
||||
}
|
||||
|
||||
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
|
||||
// The hook's loginState frame is edge-triggered (pushed only when the native
|
||||
// observes the login transition). When that edge is missed — QQ auto-logged
|
||||
// in before connect, or a silent session-restore path the hook doesn't
|
||||
// intercept — we'd sit at 'loaded'/'connecting' forever. So while connected
|
||||
// but not logged in, actively re-probe QQ's own ports and synthesize the
|
||||
// login once it reports a real uin. Idempotent with the pushed-frame path
|
||||
// (handleLoginState's wasLoggedIn guard dedups the 'login' emit).
|
||||
|
||||
private startLoginReconcile(): void {
|
||||
if (this.loginProbeTimer || this.disposed) return;
|
||||
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
|
||||
this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS);
|
||||
this.loginProbeTimer.unref?.();
|
||||
}
|
||||
|
||||
private stopLoginReconcile(): void {
|
||||
if (this.loginProbeTimer) {
|
||||
clearInterval(this.loginProbeTimer);
|
||||
this.loginProbeTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async probeLoginOnce(): Promise<void> {
|
||||
// A port-scan probe can outlast the interval; skip overlapping ticks so a
|
||||
// slow probe never stacks concurrent subprocess-spawning scans.
|
||||
if (this.probing) return;
|
||||
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
|
||||
this.probing = true;
|
||||
try {
|
||||
let info: QqPortLoginInfo | null;
|
||||
try {
|
||||
info = await this.probeLogin(this.pid);
|
||||
} catch {
|
||||
return; // best-effort; the interval retries
|
||||
}
|
||||
// The await yielded — re-check we still want this before mutating state.
|
||||
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
|
||||
if (info?.loggedIn && isRealUin(info.uin)) {
|
||||
this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin);
|
||||
// isRealUin guarantees a pure non-empty digit string, so BigInt() here
|
||||
// cannot throw (keep that contract if isRealUin's regex is ever changed).
|
||||
this.handleLoginState({ loggedIn: true, uin: info.uin, uinNumber: BigInt(info.uin) });
|
||||
}
|
||||
} finally {
|
||||
this.probing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private handlePacket(packet: QqHookPacket): void {
|
||||
if (!this.loggedIn) return;
|
||||
const uin = packet.uin || this._uin;
|
||||
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
|
||||
// receive hook is alive. Attribute that evidence to the current epoch
|
||||
// without forwarding the malformed packet into BridgeManager.
|
||||
const receiveUin = isRealUin(uin) ? uin : (this.receiveWatchUin || this._uin);
|
||||
if (isRealUin(receiveUin)) this.noteReceiveActivity(packet.cmd, receiveUin);
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!this.onPacket) return;
|
||||
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
|
||||
@@ -427,11 +545,85 @@ export class HookSession extends EventEmitter {
|
||||
this._error = error;
|
||||
this.emit('status-changed', status, error);
|
||||
}
|
||||
}
|
||||
|
||||
function isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
private noteReceiveActivity(cmd: string, uin: string): void {
|
||||
// BridgeManager treats packet.uin as authoritative and may move this PID
|
||||
// before the next loginState edge. Keep the watchdog on that same epoch.
|
||||
if (this.receiveWatchUin !== uin) this.resetReceiveWatch(uin);
|
||||
|
||||
if (!this.receiveWatchArmed) {
|
||||
if (cmd !== QQ_RECV_HEARTBEAT_CMD) return;
|
||||
this.receiveWatchArmed = true;
|
||||
this.log.debug('receive health armed by QQ heartbeat: PID=%d UIN=%s', this.pid, this.receiveWatchUin);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const silentForMs = this.lastReceiveAt > 0 ? now - this.lastReceiveAt : 0;
|
||||
this.lastReceiveAt = now;
|
||||
this.scheduleReceiveStaleCheck();
|
||||
|
||||
if (!this._receiveHealthy) {
|
||||
this.setReceiveHealthy(true);
|
||||
this.log.info(
|
||||
'receive path recovered: PID=%d UIN=%s silentFor=%dms',
|
||||
this.pid,
|
||||
this.receiveWatchUin,
|
||||
silentForMs,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReceiveStaleCheck(): void {
|
||||
if (this.receiveWatchTimer) clearTimeout(this.receiveWatchTimer);
|
||||
this.receiveWatchTimer = setTimeout(() => {
|
||||
this.receiveWatchTimer = null;
|
||||
if (!this.shouldWatchReceive()) return;
|
||||
|
||||
// A delayed event loop (notably system sleep/resume) lands here long
|
||||
// after the nominal 90s deadline. Do not flip health immediately: give
|
||||
// the real QQ heartbeat one short confirmation window to arrive.
|
||||
this.receiveWatchTimer = setTimeout(() => {
|
||||
this.receiveWatchTimer = null;
|
||||
if (!this.shouldWatchReceive()) return;
|
||||
const silentForMs = Date.now() - this.lastReceiveAt;
|
||||
if (silentForMs < RECEIVE_STALE_AFTER_MS + RECEIVE_STALE_CONFIRM_MS) {
|
||||
this.scheduleReceiveStaleCheck();
|
||||
return;
|
||||
}
|
||||
this.setReceiveHealthy(false);
|
||||
this.log.warn(
|
||||
'receive path stale: PID=%d UIN=%s lastRecvAt=%s silentFor=%dms; reporting good=false',
|
||||
this.pid,
|
||||
this.receiveWatchUin,
|
||||
new Date(this.lastReceiveAt).toISOString(),
|
||||
silentForMs,
|
||||
);
|
||||
}, RECEIVE_STALE_CONFIRM_MS);
|
||||
this.receiveWatchTimer.unref?.();
|
||||
}, RECEIVE_STALE_AFTER_MS);
|
||||
this.receiveWatchTimer.unref?.();
|
||||
}
|
||||
|
||||
private shouldWatchReceive(): boolean {
|
||||
return !this.disposed && this.connected && this.loggedIn && this.receiveWatchArmed;
|
||||
}
|
||||
|
||||
private setReceiveHealthy(healthy: boolean): void {
|
||||
if (this._receiveHealthy === healthy) return;
|
||||
this._receiveHealthy = healthy;
|
||||
this.emit('receive-health-changed', healthy);
|
||||
}
|
||||
|
||||
private resetReceiveWatch(uin = ''): void {
|
||||
if (this.receiveWatchTimer) {
|
||||
clearTimeout(this.receiveWatchTimer);
|
||||
this.receiveWatchTimer = null;
|
||||
}
|
||||
this.receiveWatchUin = uin;
|
||||
this.receiveWatchArmed = false;
|
||||
this.lastReceiveAt = 0;
|
||||
this._receiveHealthy = true;
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { HookProcessStatus } from './types';
|
||||
|
||||
/**
|
||||
* The flags that fully determine a HookSession's *settled* status.
|
||||
* `wasLoggedIn` carries the one bit of history the derivation needs:
|
||||
* on ANY injected-but-not-connected path (connect failure, pipe close,
|
||||
* refresh-while-down), the session reads `disconnected` only if it had
|
||||
* reached login, otherwise it's still `connecting`. Capture it from
|
||||
* `loggedIn` *before* tearing the client down, since teardown clears it.
|
||||
*/
|
||||
export interface HookFlags {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
wasLoggedIn: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single source of truth for the five *settled* HookProcessStatus values
|
||||
* — `available` / `connecting` / `loaded` / `online` / `disconnected`.
|
||||
*
|
||||
* Pure: status is a function of the flags alone. The two *out-of-band*
|
||||
* states `loading` (injection in flight) and `error` (carries a message)
|
||||
* are set explicitly by HookSession and are deliberately NOT derivable
|
||||
* here.
|
||||
*/
|
||||
export function statusFor(flags: HookFlags): HookProcessStatus {
|
||||
if (!flags.injected) return 'available';
|
||||
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
|
||||
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import { existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import { listSnowlumaPipePidsSync } from './qq-hook-client';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface ManualMapHandle {
|
||||
@@ -98,6 +100,17 @@ export function getNativeHookLoadError(): string | null {
|
||||
}
|
||||
|
||||
export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
|
||||
// means QQ ran with our dylib already mapped, so the dylib's listener
|
||||
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
|
||||
// in the runtime dir as a known process (the watcher's subsequent
|
||||
// connectable-probe gates the pipe-up emit, so a stale dangling socket
|
||||
// here doesn't drive a false connect).
|
||||
if (process.platform === 'darwin') {
|
||||
return [...listSnowlumaPipePidsSync()]
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) return [];
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
|
||||
@@ -6,8 +6,11 @@ const DEFAULT_INTERVAL_MS = 1500;
|
||||
const MIN_INTERVAL_MS = 250;
|
||||
|
||||
export type PipeWatcherDeps = {
|
||||
/** Native: list QQ.exe processes currently running. */
|
||||
listProcesses: () => HookProcessBaseInfo[];
|
||||
/** Native: list QQ.exe processes currently running. May be async and may
|
||||
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
|
||||
* case this tick keeps the prior process+pipe state instead of treating the
|
||||
* missing data as "everything disappeared" (issue #158). */
|
||||
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
|
||||
/** Native: PIDs that currently have a live SnowLuma named pipe. */
|
||||
listLivePipes: () => Promise<Set<number>>;
|
||||
/** Polling interval in ms. Defaults to 1500, floored to 250. */
|
||||
@@ -138,12 +141,22 @@ export class PipeWatcher extends EventEmitter {
|
||||
}
|
||||
this.ticking = true;
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[];
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
try {
|
||||
processes = this.listProcesses();
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = [];
|
||||
processes = null;
|
||||
}
|
||||
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
|
||||
// Treating missing data as "everything disappeared" would fire
|
||||
// process-gone for every live PID and dispose healthy sessions — the
|
||||
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
|
||||
// the manager's per-tick reconnect retries keep running off last-known
|
||||
// live pipes.
|
||||
if (processes === null) {
|
||||
this.emit('tick');
|
||||
return;
|
||||
}
|
||||
let livePipes: Set<number>;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { Worker } from 'worker_threads';
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
/**
|
||||
* Isolated, timeout-bounded wrapper around the native `getAllMainProcess()`
|
||||
* enumeration.
|
||||
*
|
||||
* Why this exists (issue #158): the watcher polls QQ processes every ~1.5s by
|
||||
* calling the synchronous native enumerator, which walks `/proc` and reads each
|
||||
* candidate's `cmdline`/`maps`. Those reads go through the target's mm and
|
||||
* BLOCK while a process is mid-`exec()` — exactly what happens when QQ runs a
|
||||
* silent hot-update and the process table churns. A blocked synchronous native
|
||||
* call freezes the whole Node event loop: OneBot stops responding, the watcher
|
||||
* stops ticking, reconnect logic never runs. The process stays "alive" so the
|
||||
* supervisor never restarts it — the bot just goes silent.
|
||||
*
|
||||
* The only way to put a real timeout on a synchronous native call is to run it
|
||||
* off the main thread. We run it in a worker; the main thread races the result
|
||||
* against a deadline. On timeout the main loop keeps going (it returns the
|
||||
* UNKNOWN sentinel `null`, which the watcher treats as "no fresh data, keep
|
||||
* prior state" — crucially NOT "all processes gone"). The blocked worker is
|
||||
* abandoned (a fresh one is spawned next time); it exits on its own once the
|
||||
* native call finally returns.
|
||||
*
|
||||
* Graceful degradation: if the native addon can't be loaded in a worker (e.g.
|
||||
* it isn't context-aware) or there's no addon at all (macOS reads sockets, not
|
||||
* `/proc`), we fall back to calling `fallbackSync` on the main thread — i.e.
|
||||
* exactly today's behaviour, no worse.
|
||||
*/
|
||||
export interface ProcessEnumerator {
|
||||
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
|
||||
* out / failed and the caller should keep its prior state. */
|
||||
enumerate(): Promise<HookProcessBaseInfo[] | null>;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface NativeEnumeratorDeps {
|
||||
/** Resolved path to the hook `.node` addon, or null when there is none
|
||||
* (macOS / missing) — in which case we never spawn a worker. */
|
||||
addonPath: string | null;
|
||||
/** Synchronous lister used when worker isolation is unavailable. Returns
|
||||
* today's value (and may itself block — that's the no-worse-than-before
|
||||
* fallback). */
|
||||
fallbackSync: () => HookProcessBaseInfo[];
|
||||
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
|
||||
processName: string;
|
||||
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
|
||||
* enumeration (single-digit ms) but well under a human "is it dead?". */
|
||||
timeoutMs?: number;
|
||||
/** Cap on abandoned (blocked) workers before we stop spawning more and just
|
||||
* return UNKNOWN until they drain. Bounds thread growth across a long
|
||||
* hot-update window. Default 4. */
|
||||
maxOrphans?: number;
|
||||
log?: Logger;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4000;
|
||||
const DEFAULT_MAX_ORPHANS = 4;
|
||||
|
||||
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
|
||||
// `process.dlopen` is a global and needs no module system). Loads the addon
|
||||
// handed in via workerData, then answers each 'enumerate' with the raw pid list
|
||||
// from the blocking native call. All the cheap post-processing stays on main.
|
||||
const WORKER_SOURCE = `
|
||||
const { parentPort, workerData } = require('node:worker_threads');
|
||||
let addon = null;
|
||||
try {
|
||||
const mod = { exports: {} };
|
||||
process.dlopen(mod, workerData.addonPath);
|
||||
addon = mod.exports;
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
|
||||
}
|
||||
if (addon) {
|
||||
parentPort.on('message', (msg) => {
|
||||
if (!msg || msg.type !== 'enumerate') return;
|
||||
try {
|
||||
const pids = addon.getAllMainProcess();
|
||||
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
|
||||
}
|
||||
});
|
||||
parentPort.postMessage({ type: 'ready' });
|
||||
}
|
||||
`;
|
||||
|
||||
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
|
||||
return [...new Set(pids)]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: processName, path: '' }));
|
||||
}
|
||||
|
||||
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
|
||||
const log = deps.log ?? createLogger('ProcessEnumerator');
|
||||
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
|
||||
|
||||
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
|
||||
// fallback there is a cheap socket read, not a /proc walk.
|
||||
if (!deps.addonPath) {
|
||||
return {
|
||||
async enumerate() {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
dispose() { /* nothing to tear down */ },
|
||||
};
|
||||
}
|
||||
|
||||
const addonPath = deps.addonPath;
|
||||
let worker: Worker | null = null;
|
||||
/** Set once we learn the addon can't load in a worker — permanent fallback. */
|
||||
let isolationBroken = false;
|
||||
let orphans = 0;
|
||||
let seq = 0;
|
||||
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
|
||||
let disposed = false;
|
||||
|
||||
const spawnWorker = (): void => {
|
||||
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
|
||||
worker = w;
|
||||
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
|
||||
if (msg.type === 'ready') return;
|
||||
if (msg.type === 'fatal') {
|
||||
// The addon won't load off-thread — give up on isolation for good and
|
||||
// fall back to the synchronous path from here on. Resolve any in-flight
|
||||
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
|
||||
log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? '');
|
||||
isolationBroken = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
pending.clear();
|
||||
teardownWorker();
|
||||
return;
|
||||
}
|
||||
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
|
||||
const entry = pending.get(msg.id);
|
||||
if (!entry) return;
|
||||
pending.delete(msg.id);
|
||||
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
|
||||
}
|
||||
});
|
||||
w.on('error', (err) => {
|
||||
log.warn('enumeration worker error: %s', errMsg(err));
|
||||
if (worker === w) teardownWorker();
|
||||
});
|
||||
};
|
||||
|
||||
const teardownWorker = (): void => {
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (!w) return;
|
||||
// terminate() can't preempt a thread blocked in the native call; it takes
|
||||
// effect once the call returns. Track it as an orphan until it actually
|
||||
// exits so we can bound how many we let pile up.
|
||||
orphans += 1;
|
||||
w.once('exit', () => { orphans = Math.max(0, orphans - 1); });
|
||||
void w.terminate().catch(() => { /* already gone */ });
|
||||
};
|
||||
|
||||
const syncFallback = (): HookProcessBaseInfo[] | null => {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate sync fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) return syncFallback();
|
||||
|
||||
if (!worker) {
|
||||
if (orphans >= maxOrphans) {
|
||||
// Too many blocked workers already piling up (a sustained hang) —
|
||||
// don't spawn more; report UNKNOWN and let them drain.
|
||||
return null;
|
||||
}
|
||||
spawnWorker();
|
||||
}
|
||||
const w = worker;
|
||||
if (!w) return syncFallback();
|
||||
|
||||
const id = ++seq;
|
||||
const resultPromise = new Promise<number[] | null>((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
});
|
||||
try {
|
||||
w.postMessage({ type: 'enumerate', id });
|
||||
} catch (err) {
|
||||
pending.delete(id);
|
||||
log.warn('failed to post enumerate request: %s', errMsg(err));
|
||||
teardownWorker();
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
||||
});
|
||||
const outcome = await Promise.race([resultPromise, timeout]);
|
||||
if (timer) clearTimeout(timer);
|
||||
|
||||
if (outcome === 'timeout') {
|
||||
pending.delete(id);
|
||||
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
|
||||
teardownWorker();
|
||||
return null;
|
||||
}
|
||||
if (outcome === null) {
|
||||
// Native call threw inside the worker — treat as a transient failure,
|
||||
// keep prior state rather than nuking every session.
|
||||
return null;
|
||||
}
|
||||
return mapPids(outcome, deps.processName);
|
||||
},
|
||||
|
||||
dispose() {
|
||||
disposed = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
pending.clear();
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (w) void w.terminate().catch(() => { /* ignore */ });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { promises as fs } from 'fs';
|
||||
import { readdirSync, promises as fs } from 'fs';
|
||||
import net from 'net';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
@@ -85,12 +85,59 @@ interface PendingAck {
|
||||
wantReply: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync directory scan for `mojo.<pid>.control.sock` socket files in the
|
||||
* runtime dir, returning the pid set. Used by the darwin path of
|
||||
* `listHookProcesses()` — on macOS the DYLD_INSERT injection model means
|
||||
* there is no native enumerate-QQ-processes addon; the existence of our
|
||||
* dylib's listener socket IS the proof that a QQ process is hooked. The
|
||||
* sync variant is needed because the watcher's `listProcesses` dep is sync.
|
||||
*
|
||||
* Mirrors `listLiveLinuxPipePids` (the async + connectable-probe variant)
|
||||
* but skips the connectable probe — the existence of the socket file is
|
||||
* sufficient signal for "process exists with our dylib mapped". The async
|
||||
* variant still gates the subsequent `pipe-up` emit via a real connect.
|
||||
*/
|
||||
export function listSnowlumaPipePidsSync(
|
||||
runtimeDir = linuxRuntimeDir(),
|
||||
): Set<number> {
|
||||
const result = new Set<number>();
|
||||
let names: string[];
|
||||
try {
|
||||
names = readdirSync(runtimeDir);
|
||||
} catch {
|
||||
return result;
|
||||
}
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
|
||||
if (!m) continue;
|
||||
const pid = Number(m[1]);
|
||||
if (Number.isInteger(pid) && pid > 0) result.add(pid);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function linuxRuntimeDir(): string {
|
||||
// Name kept for historical reasons (the function predates the macOS port);
|
||||
// applies to every non-win32 platform. The fallback order mirrors each
|
||||
// platform hook's runtime_dir(): explicit override first, then the OS-
|
||||
// native ephemeral-dir convention.
|
||||
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
if (explicit && explicit.length > 0) return explicit;
|
||||
const xdg = process.env.XDG_RUNTIME_DIR;
|
||||
if (xdg && xdg.length > 0) return xdg;
|
||||
// Mirrors hook_stub.cpp runtime_dir() fallback.
|
||||
// macOS: dylib defaults to "$TMPDIR/snowluma-hook" (apps/qq/macos/
|
||||
// qq_hook_dylib.cpp's runtime_dir()). $TMPDIR is per-user on macOS
|
||||
// (under /var/folders/.../T) so this is the right place — Linux's
|
||||
// /tmp/snowluma-<uid> doesn't exist on a stock Mac.
|
||||
if (process.platform === 'darwin') {
|
||||
const tmpdir = process.env.TMPDIR;
|
||||
if (tmpdir && tmpdir.length > 0) {
|
||||
const trimmed = tmpdir.endsWith('/') ? tmpdir.slice(0, -1) : tmpdir;
|
||||
return path.join(trimmed, 'snowluma-hook');
|
||||
}
|
||||
}
|
||||
// Linux fallback: mirrors hook_stub.cpp runtime_dir() last-resort.
|
||||
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
|
||||
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
|
||||
return `/tmp/snowluma-${uid}`;
|
||||
@@ -465,6 +512,12 @@ export class QqHookClient extends EventEmitter {
|
||||
});
|
||||
|
||||
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
|
||||
// Always attach a handler so a rejection can never become "unhandled" (which
|
||||
// crashes Node). When the pipe closes, rejectControlPending() rejects every
|
||||
// pending deferred — but the reply is only `await`ed AFTER the ack, so if the
|
||||
// ack fails first the reply promise is rejected with NO awaiter. The real
|
||||
// `await` below still observes the value/rejection (a separate continuation).
|
||||
ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ });
|
||||
this.pendingAcks.set(requestId, {
|
||||
resolve: ackDeferred.resolve,
|
||||
reject: ackDeferred.reject,
|
||||
@@ -474,6 +527,7 @@ export class QqHookClient extends EventEmitter {
|
||||
let replyDeferred: Deferred<QqHookSendReply> | null = null;
|
||||
if (wantReply) {
|
||||
replyDeferred = createDeferred<QqHookSendReply>();
|
||||
replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ });
|
||||
this.pendingReplies.set(requestId, replyDeferred);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
@@ -8,6 +10,13 @@ const PORT_RANGE_START = 9210;
|
||||
const PORT_RANGE_END = 9219;
|
||||
const PROBE_TIMEOUT_MS = 1000;
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
// QQ's Ptlogin quick-login ports plus its main process mean a single
|
||||
// logged-in client surfaces roughly this many processes. When no usable
|
||||
// probe port is found, a count BELOW this implies the target PID is still at
|
||||
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
|
||||
// unrelated `qq` processes), so we fall through to deep-link probing rather
|
||||
// than guess "logged out".
|
||||
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
@@ -42,6 +51,7 @@ function decodeJwt(token: string): JwtPayload | null {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
@@ -108,6 +118,101 @@ async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
|
||||
* probe reads are modelled; QQ sends more but they're irrelevant here. */
|
||||
interface PtloginUin {
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One `pt_get_uins` call. Returns the parsed account array (possibly empty —
|
||||
* an EMPTY array is a real answer: "0 accounts", NOT an error) or `null` when
|
||||
* the port could not be reached / the body was not a usable pt_get_uins
|
||||
* response (connect refused, timeout, unparseable). Callers MUST distinguish
|
||||
* the two: `[]` feeds the logged-in/out decision, `null` means "network
|
||||
* problem, no answer" and should fall through to the deep-link fallback.
|
||||
*/
|
||||
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
|
||||
return new Promise((resolve) => {
|
||||
const protocol = useHttps ? 'https' : 'http';
|
||||
const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
|
||||
const headers = {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
};
|
||||
|
||||
const handleResponse = (res: http.IncomingMessage) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => { text += chunk.toString(); });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const req = useHttps
|
||||
? https.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, handleResponse)
|
||||
: http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse);
|
||||
|
||||
req.on('error', () => resolve(null));
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
|
||||
const useHttps = port % 2 !== 0;
|
||||
|
||||
const res1 = await fetchPtlogin(port, useHttps);
|
||||
const res2 = await fetchPtlogin(port, useHttps);
|
||||
|
||||
if (res1 === null && res2 === null) return 'fallback';
|
||||
|
||||
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
|
||||
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
|
||||
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
loggedIn: true,
|
||||
};
|
||||
}
|
||||
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
|
||||
async function getQqProcessCount(): Promise<number> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('tasklist /fi "imagename eq QQ.exe" /nh');
|
||||
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq');
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
@@ -119,13 +224,11 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
if (parts.length < 5) continue;
|
||||
const owningPid = parts[parts.length - 1];
|
||||
if (owningPid !== String(pid)) continue;
|
||||
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
if (!portMatch) continue;
|
||||
const port = Number(portMatch[1]);
|
||||
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
|
||||
ports.add(port);
|
||||
}
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
@@ -135,10 +238,7 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
for (const line of lines) {
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
if (match) {
|
||||
const port = Number(match[1]);
|
||||
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
|
||||
ports.add(port);
|
||||
}
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
@@ -148,18 +248,50 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports.length === 0) {
|
||||
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', loggedIn: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
|
||||
|
||||
for (const port of ports) {
|
||||
const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p));
|
||||
const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p));
|
||||
|
||||
let ptPortsToTry: number[] = [];
|
||||
if (matchedOddPorts.length > 0) {
|
||||
ptPortsToTry = matchedOddPorts;
|
||||
} else if (matchedEvenPorts.length > 0) {
|
||||
ptPortsToTry = matchedEvenPorts;
|
||||
}
|
||||
|
||||
if (ptPortsToTry.length > 0) {
|
||||
for (const port of ptPortsToTry) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
if (ptResult !== 'fallback') {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
|
||||
for (const port of deepLinkPorts) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookManager } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
// Regression cover for the WebUI SSE wiring: HookManager must call its
|
||||
// optional `onSessionsChanged` callback every time the observable set of
|
||||
// HookProcessInfo (what `listProcesses()` would return) changes, so the
|
||||
// /api/state/stream handler can push a fresh processes snapshot to the
|
||||
// browser without REST polling.
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
interface Harness {
|
||||
manager: HookManager;
|
||||
pipeWatcher: PipeWatcher;
|
||||
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
setProcesses: (next: number[]) => void;
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
clientFactory: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
|
||||
let pids = opts.processes ?? [];
|
||||
let live = new Set<number>(opts.livePipes ?? []);
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const clientFactory = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { /* succeed without doing anything */ };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
onPidReceiveHealthChanged: vi.fn(),
|
||||
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
const onSessionsChanged = vi.fn();
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: clientFactory,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
onSessionsChanged,
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
pipeWatcher,
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
setProcesses: (next) => { pids = next; },
|
||||
setLivePipes: (next) => { live = new Set(next); },
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.onSessionsChanged', () => {
|
||||
it('fires when the watcher discovers a new QQ process', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
await ctx.pipeWatcher.start();
|
||||
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports a process is gone', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
// Inject so the session is in 'connecting' state; the next pipe-up
|
||||
// makes attemptConnect succeed and status flips to 'loaded'.
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setLivePipes([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
ctx.setProcesses([4242]);
|
||||
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
|
||||
await flush();
|
||||
// A second tick still fires the callback — it wasn't unregistered by
|
||||
// the prior throw.
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
ctx.setProcesses([4242, 5555]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
|
||||
const pids = [4242];
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const manager = new HookManager({
|
||||
bridgeManager: {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: vi.fn(() => {
|
||||
const c = new EventEmitter() as any;
|
||||
c.isClosed = false; c.isLoggedIn = false;
|
||||
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
c.connectAll = async () => undefined;
|
||||
c.close = () => { c.isClosed = true; };
|
||||
return c;
|
||||
}),
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
// onSessionsChanged deliberately omitted
|
||||
});
|
||||
await pipeWatcher.start();
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
const list = await manager.listProcesses();
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].pid).toBe(4242);
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager receive-health wiring (#233)', () => {
|
||||
it('forwards stale and recovered receive health for the owning PID', async () => {
|
||||
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await ctx.manager.refreshProcess(4242);
|
||||
await flush();
|
||||
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
try {
|
||||
client.emit('packet', {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
vi.advanceTimersByTime(105_000);
|
||||
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
|
||||
|
||||
client.emit('packet', {
|
||||
seq: 2,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { EventEmitter } from 'events';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
|
||||
import type { QqPortLoginInfo } from '../src/qq-port-probe';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
@@ -42,6 +43,7 @@ function makeSession(opts: {
|
||||
pipeLive?: boolean;
|
||||
clientFailsConnect?: boolean;
|
||||
onPacket?: PacketSink;
|
||||
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
} = {}) {
|
||||
const pid = opts.pid ?? 1234;
|
||||
let pipeLive = opts.pipeLive ?? false;
|
||||
@@ -50,6 +52,9 @@ function makeSession(opts: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
// Default probe reports "not logged in" so the reconcile safety net is inert
|
||||
// unless a test opts into a logged-in probe (never hits the real port scan).
|
||||
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', loggedIn: false }));
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector,
|
||||
@@ -60,6 +65,7 @@ function makeSession(opts: {
|
||||
// Cast: FakeClient mirrors only the surface HookSession touches.
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
probeLogin,
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
onPacket: opts.onPacket,
|
||||
});
|
||||
@@ -347,6 +353,95 @@ describe('HookSession — process gone', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — refresh drift fix', () => {
|
||||
// refresh while the pipe is down on a connected-but-never-logged-in
|
||||
// session now reports 'connecting' (matching what onPipeDown gives for the
|
||||
// same state), not the old spurious 'disconnected'. Pre-refactor, refresh's
|
||||
// down branch ignored wasLoggedIn and always reported 'disconnected'.
|
||||
|
||||
it('refresh-while-down + never logged in → connecting (not disconnected), no disconnect emit', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
expect(ctx.session.status).toBe('loaded'); // connected, never logged in
|
||||
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
ctx.setPipeLive(false);
|
||||
|
||||
const info = await ctx.session.refresh();
|
||||
|
||||
expect(info.status).toBe('connecting'); // drift fix: was 'disconnected'
|
||||
expect(discSpy).not.toHaveBeenCalled(); // never logged in ⇒ nothing owed
|
||||
});
|
||||
|
||||
it('refresh-while-down after login still → disconnected + emits disconnected(true)', async () => {
|
||||
// The flip is scoped to the never-logged-in case; a real session that
|
||||
// had reached login must still settle to 'disconnected' and notify.
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
ctx.setPipeLive(false);
|
||||
|
||||
const info = await ctx.session.refresh();
|
||||
|
||||
expect(info.status).toBe('disconnected');
|
||||
expect(discSpy).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — pipe-down must not clobber a settled error', () => {
|
||||
// Regression net for the phase-2 reconcilePipeDown !connected short-circuit:
|
||||
// a pipe-down tick on a session that never reached a live connection must
|
||||
// not wipe a diagnostic error or emit a spurious status-changed.
|
||||
|
||||
it('onPipeDown after a failed connect keeps the error and does not re-emit', async () => {
|
||||
const ctx = makeSession({ pipeLive: true, clientFailsConnect: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
expect(ctx.session.error).toBe('connect failed');
|
||||
|
||||
const statusSpy = vi.fn();
|
||||
ctx.session.on('status-changed', statusSpy);
|
||||
ctx.session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
expect(ctx.session.error).toBe('connect failed'); // not wiped to ''
|
||||
expect(statusSpy).not.toHaveBeenCalled(); // no spurious emit
|
||||
});
|
||||
|
||||
it('onPipeDown after a failed load leaves the error status intact', async () => {
|
||||
const injector = {
|
||||
inject: vi.fn(() => { throw new Error('inject boom'); }),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
const session = new HookSession(1234, {
|
||||
injector,
|
||||
makeClient: () => new FakeClient() as unknown as QqHookClient,
|
||||
pipeWatcher: { isPipeLive: () => false },
|
||||
});
|
||||
await session.load();
|
||||
expect(session.status).toBe('error');
|
||||
expect(session.error).toBe('inject boom');
|
||||
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
expect(session.status).toBe('error'); // not flipped to 'available'
|
||||
expect(session.error).toBe('inject boom'); // not wiped
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — packet forwarding', () => {
|
||||
// These tests cover the field-rename + filter logic that used to live
|
||||
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
|
||||
@@ -444,3 +539,293 @@ describe('HookSession — packet forwarding', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
|
||||
it('reconciles login via the active probe when the pushed frame is missed', async () => {
|
||||
// Probe reports logged-in; the FakeClient never fires a loginState frame
|
||||
// (the missed-edge Docker case). The immediate reconcile probe must detect
|
||||
// it and emit "login".
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); // connect (not logged in via frame) → starts reconcile
|
||||
await flush(); // immediate probe resolves → handleLoginState
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
expect(ctx.session.uin).toBe('10001');
|
||||
});
|
||||
|
||||
it('does not log in when the probe reports not-logged-in', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 0, uin: '', loggedIn: false }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
});
|
||||
|
||||
it('ignores a probe with a non-real uin (0)', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => { throw new Error('port scan failed'); },
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
});
|
||||
|
||||
it('detects a login that lands on a LATER interval probe', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let loggedIn = false;
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
|
||||
loggedIn = true; // QQ finishes auto-login
|
||||
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.status).toBe('online');
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not double-emit when the pushed frame logs in first', async () => {
|
||||
// Pushed-frame login wins; a subsequent probe with the same uin must not
|
||||
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
|
||||
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true }));
|
||||
const ctx = makeSession({ pipeLive: true, probeLogin });
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001'); // pushed-frame login first
|
||||
await flush();
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.status).toBe('online');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — end-to-end receive health (#233)', () => {
|
||||
const HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat';
|
||||
const MESSAGE_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||
|
||||
async function startReceiveSession(onPacket?: PacketSink) {
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
const healthChanges: boolean[] = [];
|
||||
ctx.session.on('receive-health-changed', (healthy: boolean) => healthChanges.push(healthy));
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
return { ctx, healthChanges };
|
||||
}
|
||||
|
||||
function firePacket(
|
||||
ctx: ReturnType<typeof makeSession>,
|
||||
cmd: string,
|
||||
uin = '10001',
|
||||
seq = 1,
|
||||
): void {
|
||||
ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) });
|
||||
}
|
||||
|
||||
it('becomes unhealthy only after an observed QQ heartbeat stays silent, then recovers on the next packet', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
|
||||
vi.advanceTimersByTime(90_000);
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
|
||||
vi.advanceTimersByTime(15_000);
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
expect(healthChanges).toEqual([false]);
|
||||
|
||||
firePacket(ctx, MESSAGE_CMD, '10001', 2);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([false, true]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not arm the watchdog when this QQ session has never exposed its heartbeat', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, MESSAGE_CMD);
|
||||
|
||||
vi.advanceTimersByTime(10 * 60_000);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('uses the confirmation window to avoid a sleep-resume false alarm', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
|
||||
vi.advanceTimersByTime(90_000);
|
||||
vi.advanceTimersByTime(14_999);
|
||||
firePacket(ctx, HEARTBEAT_CMD, '10001', 2);
|
||||
vi.advanceTimersByTime(1);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not carry an armed watchdog across a direct account switch', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
|
||||
ctx.currentClient().fireLogin('20002');
|
||||
vi.advanceTimersByTime(10 * 60_000);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('requires the new account heartbeat after packet-driven PID migration', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
firePacket(ctx, MESSAGE_CMD, '20002', 2);
|
||||
vi.advanceTimersByTime(10 * 60_000);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([]);
|
||||
|
||||
firePacket(ctx, HEARTBEAT_CMD, '20002', 3);
|
||||
vi.advanceTimersByTime(105_000);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
expect(healthChanges).toEqual([false]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('counts an invalid-UIN frame as receive activity without routing it', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const onPacket = vi.fn();
|
||||
const { ctx, healthChanges } = await startReceiveSession(onPacket);
|
||||
|
||||
try {
|
||||
firePacket(ctx, HEARTBEAT_CMD);
|
||||
onPacket.mockClear();
|
||||
|
||||
vi.advanceTimersByTime(80_000);
|
||||
firePacket(ctx, 'trpc.status.invalid-uin-probe', '0', 2);
|
||||
vi.advanceTimersByTime(104_999);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
|
||||
firePacket(ctx, 'trpc.status.invalid-uin-probe', '0', 3);
|
||||
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([false, true]);
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile does not stack concurrent probes', () => {
|
||||
it('skips overlapping ticks while a slow probe is in flight', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
// A probe that never resolves — simulates a slow port scan spanning
|
||||
// multiple intervals. The in-flight guard must call it only once.
|
||||
const probeLogin = vi.fn(() => new Promise<never>(() => { /* pending */ }));
|
||||
const ctx = makeSession({ pipeLive: true, probeLogin });
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending)
|
||||
await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks
|
||||
|
||||
expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { statusFor, type HookFlags } from '../src/hook-status';
|
||||
import type { HookProcessStatus } from '../src/types';
|
||||
|
||||
const F = (o: Partial<HookFlags>): HookFlags => ({
|
||||
injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o,
|
||||
});
|
||||
|
||||
describe('statusFor — settled HookProcessStatus derivation', () => {
|
||||
it('not injected → available (regardless of other flags)', () => {
|
||||
expect(statusFor(F({ injected: false }))).toBe('available');
|
||||
// !injected dominates: stale connected/loggedIn bits must not leak through.
|
||||
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
|
||||
});
|
||||
|
||||
it('injected, connected, loggedIn → online', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
|
||||
});
|
||||
|
||||
it('injected, connected, not loggedIn → loaded', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
|
||||
});
|
||||
|
||||
it('injected, not connected, had logged in → disconnected', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('injected, not connected, never logged in → connecting', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
|
||||
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
|
||||
const base = { injected: true, connected: false, loggedIn: false };
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
|
||||
it('covers exactly the five settled states across the flag space', () => {
|
||||
const seen = new Set<HookProcessStatus>();
|
||||
for (const injected of [false, true]) {
|
||||
for (const connected of [false, true]) {
|
||||
for (const loggedIn of [false, true]) {
|
||||
for (const wasLoggedIn of [false, true]) {
|
||||
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect([...seen].sort()).toEqual(
|
||||
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
|
||||
);
|
||||
// The two out-of-band states are never produced by the pure derivation.
|
||||
expect(seen.has('loading')).toBe(false);
|
||||
expect(seen.has('error')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -192,4 +192,40 @@ describe('PipeWatcher', () => {
|
||||
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
|
||||
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
let live = new Set<number>([1234]);
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => result,
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
const events = captureEvents(watcher);
|
||||
|
||||
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
|
||||
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
|
||||
result = null;
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
// Enumeration recovers with the same set → still no churn.
|
||||
result = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
|
||||
// A REAL disappearance (empty list, not null) still fires the teardown.
|
||||
result = [];
|
||||
live = new Set();
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
watcher.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { createNativeProcessEnumerator } from '../src/process-enumerator';
|
||||
import type { HookProcessBaseInfo } from '../src/injector';
|
||||
|
||||
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
|
||||
|
||||
describe('createNativeProcessEnumerator', () => {
|
||||
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
|
||||
it('returns the sync lister result', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => [QQ(10), QQ(20)],
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
|
||||
en.dispose();
|
||||
});
|
||||
|
||||
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => { throw new Error('boom'); },
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toBeNull();
|
||||
en.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('worker isolation that cannot load the addon → permanent fallback', () => {
|
||||
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
|
||||
const fallback = vi.fn(() => [QQ(7)]);
|
||||
const en = createNativeProcessEnumerator({
|
||||
// A path that exists nowhere → process.dlopen throws in the worker →
|
||||
// the worker posts 'fatal' → isolation is abandoned for good.
|
||||
addonPath: '/nonexistent/snowluma-test.node',
|
||||
fallbackSync: fallback,
|
||||
processName: 'qq',
|
||||
timeoutMs: 200,
|
||||
});
|
||||
|
||||
// First call spawns the worker; the fatal message drains it to UNKNOWN.
|
||||
const first = await en.enumerate();
|
||||
expect(first).toBeNull();
|
||||
|
||||
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
|
||||
// already, then subsequent calls take the synchronous fallback.
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const second = await en.enumerate();
|
||||
expect(second).toEqual([QQ(7)]);
|
||||
expect(fallback).toHaveBeenCalled();
|
||||
en.dispose();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import net from 'net';
|
||||
import { mkdtemp, rm, writeFile } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { Duplex } from 'stream';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
|
||||
import { listLiveLinuxPipePids, QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
@@ -42,3 +44,72 @@ describe('listLiveLinuxPipePids', () => {
|
||||
expect(probe).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('QqHookClient — pipe close mid-send', () => {
|
||||
// Regression: when the control pipe closes while a send() is awaiting its
|
||||
// ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The
|
||||
// reply is only `await`ed after the ack, so if the ack rejects first the
|
||||
// reply promise is rejected with NO awaiter — an UNHANDLED rejection that
|
||||
// crashes the Node process (Docker: supervisor restarts it ~1s later; on
|
||||
// Windows it just dies → "connection pipe closed", bot down). The .catch()
|
||||
// guard on each deferred prevents it; without the guard this test trips the
|
||||
// unhandledRejection assertion below.
|
||||
it('does not raise an unhandled rejection', async () => {
|
||||
const PID = 778899;
|
||||
const helloFrame = (): Buffer => {
|
||||
const h = Buffer.alloc(40);
|
||||
h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC
|
||||
h.writeUInt16LE(1, 4); // PIPE_VERSION
|
||||
h.writeUInt16LE(1, 6); // PipeOp.hello
|
||||
h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid
|
||||
return h;
|
||||
};
|
||||
|
||||
let controlConn: net.Socket | null = null;
|
||||
let signalControlWrite!: () => void;
|
||||
const controlWriteStarted = new Promise<void>((resolve) => { signalControlWrite = resolve; });
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({
|
||||
read() { /* peer data is injected with emit('data') */ },
|
||||
write(_chunk, _encoding, callback) {
|
||||
signalControlWrite();
|
||||
callback();
|
||||
},
|
||||
}) as net.Socket;
|
||||
controlConn = socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => socket.emit('data', helloFrame()));
|
||||
});
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown): void => { unhandled.push(reason); };
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
|
||||
const client = new QqHookClient(PID);
|
||||
client.on('error', () => { /* socket reset on destroy — ignore */ });
|
||||
try {
|
||||
await client.connect();
|
||||
|
||||
// Start a reply-expecting send, let it reach the in-flight (awaiting-ack)
|
||||
// state, then have the "hook" drop the pipe before it answers.
|
||||
const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
|
||||
.then(() => 'resolved' as const, (e: unknown) => e);
|
||||
await controlWriteStarted;
|
||||
controlConn?.destroy();
|
||||
|
||||
const outcome = await sent;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
expect(outcome).toBeInstanceOf(Error);
|
||||
expect((outcome as Error).message).toBe('control pipe closed');
|
||||
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
client.close();
|
||||
createConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.2",
|
||||
"version": "1.12.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
@@ -15,6 +16,18 @@
|
||||
"types": "./src/logger.ts",
|
||||
"default": "./src/logger.ts"
|
||||
},
|
||||
"./coerce": {
|
||||
"types": "./src/coerce.ts",
|
||||
"default": "./src/coerce.ts"
|
||||
},
|
||||
"./single-flight-cache": {
|
||||
"types": "./src/single-flight-cache.ts",
|
||||
"default": "./src/single-flight-cache.ts"
|
||||
},
|
||||
"./concurrency": {
|
||||
"types": "./src/concurrency.ts",
|
||||
"default": "./src/concurrency.ts"
|
||||
},
|
||||
"./hex": {
|
||||
"types": "./src/hex.ts",
|
||||
"default": "./src/hex.ts"
|
||||
@@ -27,6 +40,10 @@
|
||||
"types": "./src/log-file-transport.ts",
|
||||
"default": "./src/log-file-transport.ts"
|
||||
},
|
||||
"./log-sanitize": {
|
||||
"types": "./src/log-sanitize.ts",
|
||||
"default": "./src/log-sanitize.ts"
|
||||
},
|
||||
"./log-summary": {
|
||||
"types": "./src/log-summary.ts",
|
||||
"default": "./src/log-summary.ts"
|
||||
@@ -42,13 +59,19 @@
|
||||
"./runtime": {
|
||||
"types": "./src/runtime.ts",
|
||||
"default": "./src/runtime.ts"
|
||||
},
|
||||
"./uin": {
|
||||
"types": "./src/uin.ts",
|
||||
"default": "./src/uin.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
"typescript": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Scalar coercion primitives for normalizing untrusted JSON config into
|
||||
// typed values with fallbacks. Zero dependencies — these were duplicated
|
||||
// verbatim across notifications/config and webui/ui-config; this is their
|
||||
// single home. Input tolerance is deliberate (numeric strings coerce), but
|
||||
// validity is strict (a wrong type yields the caller's fallback, never a
|
||||
// silent 0/'' — except where the primitive's contract says otherwise).
|
||||
|
||||
/** True only for a plain, non-null, non-array object. */
|
||||
export function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** The value when it is a real boolean, else the fallback. Strings/numbers
|
||||
* are NOT coerced — `'true'` and `1` both yield the fallback. */
|
||||
export function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
/** A finite number (numeric strings coerced) clamped to `[min, max]`, else
|
||||
* the fallback. Fractional precision is preserved — use `clampInt` to floor. */
|
||||
export function clampNum(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
/** `clampNum` truncated toward zero — clamp first, then drop the fraction. */
|
||||
export function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Map `items` through `fn` in sequential batches of at most `concurrency`
|
||||
* items, awaiting each batch (`Promise.all`) before starting the next.
|
||||
* Results come back in input order.
|
||||
*
|
||||
* Batched, not a rolling pool: every item in a batch must settle before the
|
||||
* next batch starts. This caps peak parallelism — used to keep rate-limited
|
||||
* fan-out (e.g. the per-uin OIDB profile fetches during forward-node
|
||||
* enrichment) from bursting past a safe width and tripping Tencent
|
||||
* risk-control. Pair it with a cap on `items` (slice) and per-item error
|
||||
* handling inside `fn` for a fully bounded, best-effort enrichment — the
|
||||
* shape that was previously hand-rolled at each such call site.
|
||||
*/
|
||||
export async function mapWithConcurrency<T, R>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
fn: (item: T, index: number) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const limit = Math.max(1, Math.trunc(concurrency));
|
||||
const results = new Array<R>(items.length);
|
||||
for (let i = 0; i < items.length; i += limit) {
|
||||
const batch = items.slice(i, i + limit);
|
||||
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
|
||||
for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
|
||||
const DEFAULT_DIR = 'logs';
|
||||
const DEFAULT_MAX_MB = 50;
|
||||
@@ -8,13 +9,6 @@ const FILE_PREFIX = 'snowluma-';
|
||||
const FILE_SUFFIX = '.log';
|
||||
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
|
||||
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
|
||||
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
|
||||
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
|
||||
|
||||
function parsePositiveInt(v: string | undefined, dflt: number): number {
|
||||
if (!v) return dflt;
|
||||
const n = Number.parseInt(v, 10);
|
||||
@@ -33,10 +27,6 @@ function dateOf(s: string): Date {
|
||||
return new Date(y!, m! - 1, d!);
|
||||
}
|
||||
|
||||
function stripAnsi(line: string): string {
|
||||
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
|
||||
}
|
||||
|
||||
interface OpenFile {
|
||||
stream: fs.WriteStream;
|
||||
bytes: number;
|
||||
@@ -234,7 +224,7 @@ export class FileTransport {
|
||||
|
||||
write(line: string, uin?: number): void {
|
||||
if (!this.shared) return;
|
||||
const data = stripAnsi(line) + '\n';
|
||||
const data = sanitizeLogLine(line) + '\n';
|
||||
const bytes = Buffer.byteLength(data, 'utf8');
|
||||
|
||||
this.shared.write(data, bytes);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
const ESC = 0x1b;
|
||||
const BEL = 0x07;
|
||||
const C1_CSI = 0x9b;
|
||||
const C1_ST = 0x9c;
|
||||
const C1_OSC = 0x9d;
|
||||
const C1_STRING_STARTERS = new Set([0x90, 0x98, 0x9e, 0x9f]);
|
||||
|
||||
function skipCsi(line: string, start: number): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code >= 0x40 && code <= 0x7e) return i + 1;
|
||||
}
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipControlString(line: string, start: number, allowBell: boolean): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (allowBell && code === BEL) return i + 1;
|
||||
if (code === C1_ST) return i + 1;
|
||||
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) return i + 2;
|
||||
}
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipEscSequence(line: string, start: number): number {
|
||||
if (start >= line.length) return line.length;
|
||||
|
||||
const first = line.charCodeAt(start);
|
||||
if (first === 0x5b) return skipCsi(line, start + 1);
|
||||
if (first === 0x5d) return skipControlString(line, start + 1, true);
|
||||
if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) {
|
||||
return skipControlString(line, start + 1, false);
|
||||
}
|
||||
|
||||
let i = start;
|
||||
while (i < line.length) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code < 0x20 || code > 0x2f) break;
|
||||
i += 1;
|
||||
}
|
||||
const final = line.charCodeAt(i);
|
||||
return final >= 0x30 && final <= 0x7e ? i + 1 : start;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove terminal presentation and control sequences from a log line.
|
||||
*
|
||||
* The parser handles both seven-bit ESC forms and eight-bit C1 forms,
|
||||
* including CSI styling, OSC hyperlinks, and DCS/SOS/PM/APC control strings.
|
||||
* TAB and LF remain available for formatted records such as stack traces.
|
||||
* Unterminated terminal strings consume the remainder instead of leaking their
|
||||
* invisible payload into persisted or downloaded logs.
|
||||
*/
|
||||
export function sanitizeLogLine(line: string): string {
|
||||
let plain = '';
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (code === ESC) {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
}
|
||||
return plain;
|
||||
}
|
||||
@@ -49,3 +49,70 @@ export function summarizeParams(params: unknown): string {
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
|
||||
const VERBOSE_STRING_MAX = 200;
|
||||
const VERBOSE_TOTAL_MAX = 1500;
|
||||
// Keys whose values must never be rendered — tokens, passwords, secrets.
|
||||
const REDACT_KEY = /^(.*[-_])?(token|password|passwd|secret|access[-_]?token)([-_].*)?$/i;
|
||||
|
||||
/**
|
||||
* Deep, debug-grade render of a params object for the `trace` level: shows the
|
||||
* full nested structure (message segments, nested objects) so a reproduction
|
||||
* is legible — unlike {@link summarizeParams}, which collapses nested values.
|
||||
*
|
||||
* Three guards keep it safe and bounded:
|
||||
* - per-string cap (long values like base64 image data become `"…<N B>"`),
|
||||
* - total output budget (so a giant payload can't flood the buffer),
|
||||
* - key-based redaction (token / password / secret → `"***"`).
|
||||
*/
|
||||
export function renderParamsVerbose(params: unknown): string {
|
||||
const seen = new WeakSet<object>();
|
||||
let budget = VERBOSE_TOTAL_MAX;
|
||||
|
||||
const walk = (value: unknown, key?: string): string => {
|
||||
if (budget <= 0) return '…';
|
||||
if (key !== undefined && REDACT_KEY.test(key)) return '"***"';
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string': {
|
||||
const truncated =
|
||||
value.length > VERBOSE_STRING_MAX
|
||||
? `${value.slice(0, VERBOSE_STRING_MAX)}…<${value.length}B>`
|
||||
: value;
|
||||
const out = JSON.stringify(truncated);
|
||||
budget -= out.length;
|
||||
return out;
|
||||
}
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint': {
|
||||
const out = String(value);
|
||||
budget -= out.length;
|
||||
return out;
|
||||
}
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) return '"[circular]"';
|
||||
seen.add(value as object);
|
||||
const parts: string[] = [];
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
if (budget <= 0) { parts.push('…'); break; }
|
||||
parts.push(walk(item));
|
||||
}
|
||||
return `[${parts.join(',')}]`;
|
||||
}
|
||||
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (budget <= 0) { parts.push('…'); break; }
|
||||
parts.push(`${k}:${walk(v, k)}`);
|
||||
}
|
||||
return `{${parts.join(',')}}`;
|
||||
}
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
|
||||
return walk(params);
|
||||
}
|
||||
+107
-19
@@ -1,7 +1,9 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
import { currentRequestId } from './request-context';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
@@ -10,6 +12,8 @@ export interface LogEntry {
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
@@ -26,6 +30,7 @@ interface LogOptions {
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
@@ -34,6 +39,7 @@ const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
@@ -42,6 +48,7 @@ const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
@@ -53,13 +60,55 @@ const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
const logEntries: LogEntry[] = [];
|
||||
|
||||
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
|
||||
function resolveTraceBufferMax(): number {
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
* Fixed-capacity circular buffer. O(1) push + eviction (no array `.shift()`),
|
||||
* so the high-throughput trace stream never pays an O(n) shift per overflow.
|
||||
*/
|
||||
class RingBuffer<T> {
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
if (this.count < this.cap) this.count += 1;
|
||||
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
|
||||
const traceRing = new RingBuffer<LogEntry>(TRACE_BUFFER_MAX);
|
||||
const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
@@ -75,7 +124,7 @@ function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
@@ -110,15 +159,16 @@ function currentTime(): string {
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: number): string {
|
||||
const message = format(...args);
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
@@ -126,31 +176,49 @@ function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
}
|
||||
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
// Console / subscriber level filter. File output is debug-and-up always;
|
||||
// see log-file-transport.ts.
|
||||
const passesConsole = shouldLog(level);
|
||||
const message = format(...args);
|
||||
const line = render(level, options, args);
|
||||
|
||||
// `trace` never touches disk and is the high-volume full-chain stream. When
|
||||
// it won't reach the console/memory buffer either (level not dialed to
|
||||
// trace), bail BEFORE format/render AND before evaluating any lazy producer
|
||||
// — this is what keeps full-chain tracing ~free at the default level even
|
||||
// with hundreds of groups.
|
||||
if (level === 'trace' && !passesConsole) return;
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const message = format(...realArgs);
|
||||
const line = render(level, options, realArgs, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
@@ -162,10 +230,11 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// File transport always sees every level (debug-and-up) for post-mortem
|
||||
// value; ANSI stripping happens inside the transport. UIN routes the
|
||||
// line to its per-account sub-file in addition to the shared one.
|
||||
getFileTransport().write(line, options.uin);
|
||||
// File transport sees debug-and-up for post-mortem value; `trace` is
|
||||
// memory / WebUI only (omitted here to avoid huge on-disk volume). ANSI
|
||||
// stripping happens inside the transport. UIN routes the line to its
|
||||
// per-account sub-file in addition to the shared one.
|
||||
if (level !== 'trace') getFileTransport().write(line, options.uin);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -179,8 +248,14 @@ export function closeLogger(): Promise<void> {
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
|
||||
return logEntries.slice(-n);
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
// Merge the normal + trace rings by id (ids are monotonic, so id order is
|
||||
// chronological). The trace ring is empty unless trace level is/was active,
|
||||
// so the common case is just the normal ring with no sort.
|
||||
const merged = traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
return merged.slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
@@ -191,6 +266,13 @@ export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
@@ -207,6 +289,7 @@ export interface Logger {
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
@@ -226,3 +309,8 @@ function makeLogger(opts: LogOptions): Logger {
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
|
||||
// Request-correlation helpers live alongside the logger since `[req#N]`
|
||||
// stamping is a logging concern. Re-exported here so callers import the
|
||||
// whole logging surface from one place.
|
||||
export { nextRequestId, runWithRequestId, currentRequestId } from './request-context';
|
||||
@@ -0,0 +1,35 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
interface RequestStore {
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore>();
|
||||
let counter = 0;
|
||||
|
||||
/**
|
||||
* Allocate the next per-process request id (monotonic). Wraps via uint32 so
|
||||
* it never overflows to a non-integer; `0` is skipped so "no id" stays
|
||||
* unambiguous.
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` with `id` bound as the ambient request id for the entire async
|
||||
* chain it spawns. Any logger call anywhere in that chain — across packages,
|
||||
* across awaits — picks it up via {@link currentRequestId} with no signature
|
||||
* threading. Used by the OneBot action handler to correlate a request's whole
|
||||
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
|
||||
*/
|
||||
export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
}
|
||||
+106
-48
@@ -7,71 +7,102 @@ export interface RuntimeConfig {
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
/** WebUI listener bind address. '0.0.0.0' = all interfaces (default),
|
||||
* '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */
|
||||
webuiHost?: string;
|
||||
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
|
||||
* only flips serving on/off. Listener-level: change needs a restart. */
|
||||
webuiTls?: { enabled?: boolean };
|
||||
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
|
||||
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
|
||||
trustProxy?: string;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
};
|
||||
const DEFAULT_WEBUI_PORT = 5099;
|
||||
const DEFAULT_WEBUI_HOST = '0.0.0.0';
|
||||
|
||||
/**
|
||||
* Pure on-disk-object → typed config normalization (defaults + validation,
|
||||
* no fs / no env). Exported for testing; `loadRuntimeConfig` wraps it.
|
||||
*/
|
||||
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure SNOWLUMA_* env → override patch (no fs). Env wins over runtime.json
|
||||
* (a trusted launcher like SnowLumaDesktop pins these per-launch without
|
||||
* rewriting the file). Absent vars produce no key.
|
||||
*/
|
||||
export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<RuntimeConfig> {
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
if (port !== undefined) out.webuiPort = port;
|
||||
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim();
|
||||
|
||||
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
|
||||
// from "absent" — so gate on key presence, not truthiness.
|
||||
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
|
||||
if (typeof tp === 'string') out.trustProxy = tp;
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const loaded = tryLoadRuntimeConfig();
|
||||
let normalized: RuntimeConfig;
|
||||
if (!loaded) {
|
||||
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||
normalized = { ...DEFAULT_RUNTIME_CONFIG };
|
||||
} else {
|
||||
normalized = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
|
||||
// Persist when the file is absent or when normalization changed/backfilled
|
||||
// anything (e.g. an older runtime.json lacking webuiHost/webuiTls).
|
||||
if (parsed === null || !sameRuntimeConfig(parsed, normalized)) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
|
||||
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
|
||||
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
|
||||
// pick a free port per-launch while CLI/Docker users continue to drive
|
||||
// it from runtime.json.
|
||||
const envPort = envPortOverride();
|
||||
if (envPort !== undefined) {
|
||||
normalized = { ...normalized, webuiPort: envPort };
|
||||
}
|
||||
|
||||
return normalized;
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
}
|
||||
|
||||
function envPortOverride(): number | undefined {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
if (!raw || typeof raw !== 'string') return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
/**
|
||||
* Read the persisted config (normalized, no env overrides, no write). For the
|
||||
* settings panel's GET — shows what's actually saved/editable on disk.
|
||||
*/
|
||||
export function readRuntimeConfig(): RuntimeConfig {
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
/**
|
||||
* Persist a partial update. Merges onto the ON-DISK config (not the env-merged
|
||||
* runtime view) so an env override (e.g. SNOWLUMA_WEBUI_PORT) is never baked
|
||||
* into runtime.json. Returns the new persisted config (without env overrides).
|
||||
*/
|
||||
export function updateRuntimeConfig(patch: Partial<RuntimeConfig>): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
const next = normalizeRuntimeConfig({ ...onDisk, ...patch });
|
||||
saveRuntimeConfig(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): Record<string, unknown> | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!isObject(parsed)) return null;
|
||||
|
||||
return {
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
|
||||
};
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -81,6 +112,33 @@ function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/** True when the raw on-disk object already matches the normalized config
|
||||
* on every known field (so we can skip a needless rewrite). */
|
||||
function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): boolean {
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort
|
||||
&& parsed.hookAutoLoad === n.hookAutoLoad
|
||||
&& parsed.webuiHost === n.webuiHost
|
||||
&& parsedTls === n.webuiTls?.enabled
|
||||
&& parsed.trustProxy === n.trustProxy
|
||||
);
|
||||
}
|
||||
|
||||
function parsePortString(raw: unknown): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeHost(value: unknown): string {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Single-flight + TTL memoization.
|
||||
*
|
||||
* Concentrates the "don't refetch what's fresh, and don't stampede the same
|
||||
* key with concurrent loads" pattern that was hand-rolled (slightly
|
||||
* differently each time) across the codebase — e.g. `ContactsApi`'s group
|
||||
* member-list cache and the WebUI update-check. Each copy re-implemented the
|
||||
* same fiddly trio: a TTL freshness check, an in-flight promise map to
|
||||
* de-dupe concurrent callers, and `finally`-cleanup of that map. Getting any
|
||||
* of the three subtly wrong (forgetting the `finally`, caching an error,
|
||||
* racing the timestamp) is a real hazard — so it lives in one place.
|
||||
*
|
||||
* The underlying concern is Tencent risk-control: a busy OneBot client can
|
||||
* fan out one uncached OIDB fetch per inbound message, and sustained bursts
|
||||
* trip a ban. TTL + single-flight collapse that fan-out.
|
||||
*/
|
||||
|
||||
export interface SingleFlightCacheOptions<K, V> {
|
||||
/** Freshness window in ms. A cached entry older than this is reloaded. */
|
||||
ttlMs: number;
|
||||
/** Load the value for a key. Rejections propagate and are never cached. */
|
||||
load: (key: K) => Promise<V>;
|
||||
/**
|
||||
* Decide whether a resolved value should be cached. Default: always.
|
||||
* Return `false` to leave an entry uncached (e.g. an error-shaped result the
|
||||
* next call should retry) while still de-duping concurrent in-flight callers.
|
||||
*/
|
||||
shouldCache?: (value: V) => boolean;
|
||||
/** Clock, injectable for tests. Defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export class SingleFlightCache<K, V> {
|
||||
private readonly ttlMs: number;
|
||||
private readonly load: (key: K) => Promise<V>;
|
||||
private readonly shouldCache: (value: V) => boolean;
|
||||
private readonly now: () => number;
|
||||
private readonly fresh = new Map<K, { at: number; value: V }>();
|
||||
private readonly inflight = new Map<K, Promise<V>>();
|
||||
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
this.load = opts.load;
|
||||
this.shouldCache = opts.shouldCache ?? (() => true);
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value for `key`.
|
||||
*
|
||||
* - Returns a fresh cached value when the last load was within `ttlMs`.
|
||||
* - Otherwise de-dupes concurrent callers onto a single `load()` and caches
|
||||
* the result (subject to `shouldCache`). A rejected `load` propagates to
|
||||
* every joined caller, clears the in-flight slot, and is not cached.
|
||||
* - `force` bypasses the freshness check but still joins an in-flight load
|
||||
* rather than starting a second one.
|
||||
*/
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value);
|
||||
}
|
||||
const existing = this.inflight.get(key);
|
||||
if (existing) return existing;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const value = await this.load(key);
|
||||
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
|
||||
return value;
|
||||
} finally {
|
||||
this.inflight.delete(key);
|
||||
}
|
||||
})();
|
||||
this.inflight.set(key, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
/** Drop a cached entry. Does not abort an in-flight load. */
|
||||
invalidate(key: K): void {
|
||||
this.fresh.delete(key);
|
||||
}
|
||||
|
||||
/** Drop all cached entries. Does not abort in-flight loads. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export function createSingleFlightCache<K, V>(
|
||||
opts: SingleFlightCacheOptions<K, V>,
|
||||
): SingleFlightCache<K, V> {
|
||||
return new SingleFlightCache(opts);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Shared QQ UIN validity check. A "real" UIN is a live QQ account number, not
|
||||
// a garbage value the native hook can emit during the probe→inject race — e.g.
|
||||
// a 13-digit millisecond timestamp read from not-yet-populated QQ memory
|
||||
// (issue #162). No real QQ UIN exceeds 10 digits (they fit in uint32, max
|
||||
// 4294967295), so a pure digit string of 5..10 chars is the accept window.
|
||||
//
|
||||
// Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit
|
||||
// string. Keep that contract if the pattern ever changes.
|
||||
export function isRealUin(uin: string): boolean {
|
||||
return /^\d{5,10}$/.test(uin);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { isObject, boolOr, clampNum, clampInt } from '../src/coerce';
|
||||
|
||||
describe('isObject', () => {
|
||||
it('is true only for plain non-null non-array objects', () => {
|
||||
expect(isObject({})).toBe(true);
|
||||
expect(isObject({ a: 1 })).toBe(true);
|
||||
expect(isObject(null)).toBe(false);
|
||||
expect(isObject([])).toBe(false);
|
||||
expect(isObject('x')).toBe(false);
|
||||
expect(isObject(42)).toBe(false);
|
||||
expect(isObject(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('boolOr', () => {
|
||||
it('returns the value only when it is a real boolean, else the fallback', () => {
|
||||
expect(boolOr(true, false)).toBe(true);
|
||||
expect(boolOr(false, true)).toBe(false);
|
||||
expect(boolOr('true', false)).toBe(false); // strings are NOT coerced
|
||||
expect(boolOr(1, false)).toBe(false);
|
||||
expect(boolOr(undefined, true)).toBe(true);
|
||||
expect(boolOr(null, true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampNum', () => {
|
||||
it('passes finite numbers through, clamped to [min,max]', () => {
|
||||
expect(clampNum(5, 0, 10, -1)).toBe(5);
|
||||
expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min
|
||||
expect(clampNum(99, 0, 10, -1)).toBe(10); // above max
|
||||
});
|
||||
|
||||
it('coerces numeric strings', () => {
|
||||
expect(clampNum('7', 0, 10, -1)).toBe(7);
|
||||
expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt)
|
||||
});
|
||||
|
||||
it('falls back on non-finite / non-numeric input', () => {
|
||||
expect(clampNum('abc', 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(NaN, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(Infinity, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(undefined, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(null, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum({}, 0, 10, 3)).toBe(3);
|
||||
});
|
||||
|
||||
it('preserves fractional precision within bounds', () => {
|
||||
expect(clampNum(0.42, 0, 1, 0)).toBe(0.42);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampInt', () => {
|
||||
it('is clampNum truncated toward zero', () => {
|
||||
expect(clampInt(7.9, 0, 10, -1)).toBe(7);
|
||||
expect(clampInt('7.9', 0, 10, -1)).toBe(7);
|
||||
expect(clampInt(5, 0, 10, -1)).toBe(5);
|
||||
});
|
||||
|
||||
it('clamps before truncating', () => {
|
||||
expect(clampInt(99.9, 0, 10, -1)).toBe(10);
|
||||
expect(clampInt(-3.5, 0, 10, -1)).toBe(0);
|
||||
});
|
||||
|
||||
it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => {
|
||||
// Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4
|
||||
// with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl
|
||||
// would floor to 2 then clamp up to 2.5. Pins the order for the shared
|
||||
// primitive (future callers may use fractional bounds).
|
||||
expect(clampInt(2.4, 2.5, 10, 0)).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back on non-finite input', () => {
|
||||
expect(clampInt('abc', 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(NaN, 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(undefined, 0, 10, 4)).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mapWithConcurrency } from '../src/concurrency';
|
||||
|
||||
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
|
||||
|
||||
describe('mapWithConcurrency', () => {
|
||||
it('returns results in input order', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
|
||||
expect(out).toEqual([10, 20, 30, 40, 50]);
|
||||
});
|
||||
|
||||
it('passes the absolute index (across batch boundaries)', async () => {
|
||||
const seen: Array<[number, number]> = [];
|
||||
await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => {
|
||||
seen.push([i, item.charCodeAt(0)]);
|
||||
return i;
|
||||
});
|
||||
expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const order: number[] = [];
|
||||
await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
order.push(n);
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(peak).toBeLessThanOrEqual(3);
|
||||
// batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts.
|
||||
expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]);
|
||||
expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]);
|
||||
expect(order[6]).toBe(6);
|
||||
});
|
||||
|
||||
it('handles a length not divisible by concurrency (short final batch)', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n);
|
||||
expect(out).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('runs everything in one batch when concurrency >= length', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
});
|
||||
expect(out).toEqual([1, 2, 3]);
|
||||
expect(peak).toBe(3);
|
||||
});
|
||||
|
||||
it('returns [] for an empty input without calling fn', async () => {
|
||||
let called = 0;
|
||||
const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; });
|
||||
expect(out).toEqual([]);
|
||||
expect(called).toBe(0);
|
||||
});
|
||||
|
||||
it('treats concurrency < 1 as 1 (fully serial)', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
});
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
|
||||
|
||||
describe('hex', () => {
|
||||
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
|
||||
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
|
||||
expect(toHex(b)).toBe('000fa0ff');
|
||||
expect(toHexUpper(b)).toBe('000FA0FF');
|
||||
expect(toHex(Uint8Array.of())).toBe('');
|
||||
});
|
||||
|
||||
it('hexPreview appends "..." only past maxBytes', () => {
|
||||
const b = Uint8Array.from([1, 2, 3, 4, 5]);
|
||||
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
|
||||
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
|
||||
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
|
||||
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
|
||||
});
|
||||
|
||||
it('fromHex round-trips toHex and rejects odd-length input', () => {
|
||||
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
|
||||
expect(fromHex(toHex(b)).equals(b)).toBe(true);
|
||||
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
|
||||
expect(() => fromHex('abc')).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeLogLine } from '../src/log-sanitize';
|
||||
|
||||
describe('sanitizeLogLine', () => {
|
||||
it('removes SGR styling in seven-bit and eight-bit forms', () => {
|
||||
expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green');
|
||||
});
|
||||
|
||||
it('removes OSC hyperlinks without removing their visible label', () => {
|
||||
expect(
|
||||
sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07'),
|
||||
).toBe('visible');
|
||||
});
|
||||
|
||||
it('removes terminal control-string payloads', () => {
|
||||
expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter');
|
||||
});
|
||||
|
||||
it('preserves tabs and newlines while removing other controls', () => {
|
||||
expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree');
|
||||
});
|
||||
|
||||
it('does not leak unterminated terminal strings', () => {
|
||||
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { renderParamsVerbose, summarizeParams } from '../src/log-summary';
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders null/undefined as {}', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
|
||||
it('renders a top-level non-object via String() WITHOUT quotes', () => {
|
||||
// The reported change-request: a top-level primitive is NOT JSON-quoted.
|
||||
expect(summarizeParams('hello')).toBe('hello');
|
||||
expect(summarizeParams(123)).toBe('123');
|
||||
});
|
||||
|
||||
it('collapses a top-level array to [len=N]', () => {
|
||||
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
|
||||
});
|
||||
|
||||
it('quotes string fields, collapses nested values, truncates long strings', () => {
|
||||
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
|
||||
.toBe('a=1 b="x" c={...} e=[len=2]');
|
||||
expect(summarizeParams({ s: 'x'.repeat(50) }))
|
||||
.toBe(`s="${'x'.repeat(40)}..."`);
|
||||
});
|
||||
|
||||
it('caps total output and appends "..." on overflow', () => {
|
||||
const big: Record<string, number> = {};
|
||||
for (let i = 0; i < 60; i++) big['key' + i] = i;
|
||||
const out = summarizeParams(big);
|
||||
expect(out.startsWith('key0=0')).toBe(true);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderParamsVerbose', () => {
|
||||
it('redacts token / password / secret keys at any depth', () => {
|
||||
const out = renderParamsVerbose({ token: 'abc', password: 'p', nested: { secret: 's' }, ok: 'v' });
|
||||
expect(out).toContain('token:"***"');
|
||||
expect(out).toContain('password:"***"');
|
||||
expect(out).toContain('secret:"***"');
|
||||
expect(out).toContain('ok:"v"');
|
||||
});
|
||||
|
||||
it('truncates long strings with a Unicode ellipsis + byte count (not ASCII dots)', () => {
|
||||
// The reported change-request: the marker is `…<N B>` (U+2026), not `...<N B>`.
|
||||
const out = renderParamsVerbose({ blob: 'a'.repeat(500) });
|
||||
expect(out).toContain('…<500B>');
|
||||
expect(out).not.toContain('...<500B>');
|
||||
});
|
||||
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// The file transport writes to disk; stub it so the test has no side effects.
|
||||
vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: () => {} }),
|
||||
}));
|
||||
|
||||
import { createLogger, subscribeLogs, type LogEntry } from '../src/logger';
|
||||
|
||||
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
|
||||
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
|
||||
// render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value
|
||||
// → uncaughtException. The padding must clamp at zero.
|
||||
describe('logger UIN slot padding', () => {
|
||||
let prevTTY: boolean | undefined;
|
||||
let prevNoColor: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
prevTTY = process.stdout.isTTY;
|
||||
prevNoColor = process.env.NO_COLOR;
|
||||
// Force the colored render path (the only one that used .repeat()).
|
||||
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
|
||||
delete process.env.NO_COLOR;
|
||||
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||
if (prevNoColor === undefined) delete process.env.NO_COLOR;
|
||||
else process.env.NO_COLOR = prevNoColor;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not throw when the UIN tag exceeds the slot width', () => {
|
||||
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
|
||||
expect(() => log.info('phantom account line')).not.toThrow();
|
||||
expect(() => log.error('phantom error line')).not.toThrow();
|
||||
});
|
||||
|
||||
it('still renders a normal-width UIN and a no-UIN logger', () => {
|
||||
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
|
||||
expect(() => createLogger('Test').info('no uin')).not.toThrow();
|
||||
});
|
||||
|
||||
it('keeps structured subscriber lines plain while terminal output stays colored', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => captured.push(entry));
|
||||
|
||||
createLogger('WebUI.Export').info('download me');
|
||||
unsubscribe();
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/);
|
||||
expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b['));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { currentRequestId, nextRequestId, runWithRequestId } from '../src/request-context';
|
||||
|
||||
describe('request-context', () => {
|
||||
it('nextRequestId increments monotonically and stays a positive integer', () => {
|
||||
const a = nextRequestId();
|
||||
const b = nextRequestId();
|
||||
expect(a).toBeGreaterThan(0);
|
||||
expect(b).toBe(a + 1);
|
||||
});
|
||||
|
||||
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
runWithRequestId(42, () => {
|
||||
expect(currentRequestId()).toBe(42);
|
||||
runWithRequestId(99, () => {
|
||||
expect(currentRequestId()).toBe(99);
|
||||
});
|
||||
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
|
||||
});
|
||||
|
||||
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
|
||||
|
||||
await runWithRequestId(7, async () => {
|
||||
await Promise.resolve();
|
||||
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the callback result', () => {
|
||||
expect(runWithRequestId(1, () => 'value')).toBe('value');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime';
|
||||
|
||||
describe('normalizeRuntimeConfig', () => {
|
||||
it('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '0.0.0.0',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('passes through valid values', () => {
|
||||
expect(normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
})).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back on invalid types', () => {
|
||||
const out = normalizeRuntimeConfig({
|
||||
webuiPort: 0, // out of range → default
|
||||
webuiHost: 123, // non-string → default
|
||||
webuiTls: 'yes', // non-object → default
|
||||
trustProxy: 5, // non-string → default
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('0.0.0.0');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
|
||||
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
|
||||
});
|
||||
|
||||
it('rejects a non-object input back to full defaults', () => {
|
||||
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRuntimeEnvOverrides', () => {
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateRuntimeConfig (fs)', () => {
|
||||
let prevCwd: string;
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs'); const os = await import('os'); const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
});
|
||||
afterEach(async () => {
|
||||
const fs = await import('fs');
|
||||
process.chdir(prevCwd);
|
||||
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiHost).toBe('127.0.0.1');
|
||||
expect(onDisk.webuiTls).toEqual({ enabled: true });
|
||||
});
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { createSingleFlightCache } from '../src/single-flight-cache';
|
||||
|
||||
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (v: T) => void;
|
||||
let reject!: (e: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
describe('SingleFlightCache', () => {
|
||||
it('caches within the TTL and reloads once expired', async () => {
|
||||
let clock = 1000;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 100, load, now: () => clock });
|
||||
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
clock = 1050; // still fresh (< 100)
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
clock = 1101; // 101ms since store → expired
|
||||
expect(await cache.get('a')).toBe('a@1101');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('de-dupes concurrent callers onto a single load (single-flight)', async () => {
|
||||
const d = deferred<string>();
|
||||
const load = vi.fn(() => d.promise);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
const p3 = cache.get('k');
|
||||
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
|
||||
|
||||
d.resolve('v');
|
||||
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keys independently — different keys load separately', async () => {
|
||||
const load = vi.fn(async (k: number) => k * 2);
|
||||
const cache = createSingleFlightCache<number, number>({ ttlMs: 1000, load });
|
||||
expect(await cache.get(1)).toBe(2);
|
||||
expect(await cache.get(2)).toBe(4);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('force bypasses the freshness check but still joins an in-flight load', async () => {
|
||||
let clock = 0;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load, now: () => clock });
|
||||
|
||||
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
|
||||
clock = 5; // still fresh
|
||||
expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// force still single-flights: two concurrent forced gets share one load.
|
||||
const d = deferred<string>();
|
||||
load.mockImplementationOnce(() => d.promise);
|
||||
const p1 = cache.get('a', { force: true });
|
||||
const p2 = cache.get('a', { force: true });
|
||||
expect(load).toHaveBeenCalledTimes(3); // not 4
|
||||
d.resolve('shared');
|
||||
expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']);
|
||||
});
|
||||
|
||||
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
|
||||
let n = 0;
|
||||
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error });
|
||||
|
||||
// concurrent callers still share one load...
|
||||
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
|
||||
expect(a).toEqual({ error: true, n: 1 });
|
||||
expect(b).toEqual({ error: true, n: 1 });
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// ...but nothing was cached, so the next call reloads.
|
||||
expect(await cache.get('k')).toEqual({ error: true, n: 2 });
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// a good result IS cached.
|
||||
load.mockImplementationOnce(async () => ({ error: false, n: ++n }));
|
||||
const good = await cache.get('k');
|
||||
expect(good).toEqual({ error: false, n: 3 });
|
||||
expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => {
|
||||
let attempt = 0;
|
||||
const load = vi.fn(async () => {
|
||||
attempt++;
|
||||
if (attempt === 1) throw new Error('boom');
|
||||
return 'ok';
|
||||
});
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
await expect(p1).rejects.toThrow('boom');
|
||||
await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// in-flight cleared + not cached → next call retries and succeeds.
|
||||
expect(await cache.get('k')).toBe('ok');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('invalidate drops a cached entry; clear drops all', async () => {
|
||||
const load = vi.fn(async (k: string) => k.toUpperCase());
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
cache.invalidate('a');
|
||||
await cache.get('a'); // reloads
|
||||
await cache.get('b'); // still cached
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
|
||||
cache.clear();
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isRealUin } from '../src/uin';
|
||||
|
||||
describe('isRealUin', () => {
|
||||
it('accepts real QQ UINs (5..10 digits)', () => {
|
||||
expect(isRealUin('10001')).toBe(true); // 5-digit floor
|
||||
expect(isRealUin('123456789')).toBe(true);
|
||||
expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits
|
||||
});
|
||||
|
||||
it('rejects the empty string and "0"', () => {
|
||||
expect(isRealUin('')).toBe(false);
|
||||
expect(isRealUin('0')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects too-short UINs (< 5 digits)', () => {
|
||||
expect(isRealUin('1')).toBe(false);
|
||||
expect(isRealUin('1234')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => {
|
||||
expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp
|
||||
expect(isRealUin('1614019567632')).toBe(false);
|
||||
expect(isRealUin('2014024115056')).toBe(false);
|
||||
expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width
|
||||
});
|
||||
|
||||
it('rejects non-digit strings (path traversal / injection guards)', () => {
|
||||
expect(isRealUin('12345a')).toBe(false);
|
||||
expect(isRealUin('12 345')).toBe(false);
|
||||
expect(isRealUin('../etc')).toBe(false);
|
||||
expect(isRealUin('123456\n')).toBe(false);
|
||||
});
|
||||
|
||||
it('guarantees a BigInt-safe pure-digit string on accept', () => {
|
||||
const uin = '123456789';
|
||||
expect(isRealUin(uin)).toBe(true);
|
||||
expect(() => BigInt(uin)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
// Vitest config for @snowluma/common. Pure-TS package (no proton), so a
|
||||
// plain node-environment runner over tests/ is enough.
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
# Per-instance runtime state written by the dev server / production daemon.
|
||||
# `runtime.json` is the only tracked file (the deploy-time overrides for
|
||||
# webuiPort, hookAutoLoad, etc); everything else here is operator-private:
|
||||
# * webui.json — admin password hash + rotation state
|
||||
# * consent.json — EULA/PRIVACY acceptance per agreement version
|
||||
# * notifications.json — per-account webhook destinations
|
||||
# * onebot_<uin>.json — per-uin OneBot transport binding (HTTP/WS ports etc)
|
||||
# * ui.json — WebUI panel layout per operator
|
||||
#
|
||||
# Without this ignore file, every `pnpm dev:mode` / `node dist/index.mjs`
|
||||
# leaves a 5-file untracked surface in `packages/core/config/` that pollutes
|
||||
# `git status` and would accidentally commit local creds if `git add -A` is used.
|
||||
|
||||
*
|
||||
!.gitignore
|
||||
!runtime.json
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.9.2",
|
||||
"version": "1.12.7",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -46,7 +47,6 @@
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -54,7 +54,7 @@
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "^24.12.2",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.18",
|
||||
"hono": "^4.12.25",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import {
|
||||
getCollectionList,
|
||||
type CollectionListResult,
|
||||
} from '@snowluma/protocol/web/collection';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
const COLLECTION_DOMAIN = 'weiyun.com';
|
||||
|
||||
/** Read-only access to the account's QQ collection list. */
|
||||
export class CollectionApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async list(category = 0, count = 50): Promise<CollectionListResult> {
|
||||
const { domainPskeyMap } = await GetPskey.invoke(this.ctx, {
|
||||
domainList: [COLLECTION_DOMAIN],
|
||||
});
|
||||
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
|
||||
if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
|
||||
|
||||
return getCollectionList({
|
||||
uin: this.ctx.identity.uin,
|
||||
pskey,
|
||||
category,
|
||||
count,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,18 @@
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
|
||||
import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail';
|
||||
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
|
||||
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
|
||||
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
|
||||
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
|
||||
import { toHex } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
import type {
|
||||
FriendCategoryInfo,
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
@@ -15,6 +22,8 @@ import type {
|
||||
import type { DownloadRKeyInfo } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
const log = createLogger('Bridge.Contacts');
|
||||
|
||||
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
|
||||
|
||||
type FriendPropertySource = {
|
||||
@@ -29,6 +38,23 @@ type FriendPropertySource = {
|
||||
}>;
|
||||
};
|
||||
|
||||
interface FriendRosterEntry {
|
||||
friend: FriendInfo;
|
||||
categoryId: number;
|
||||
}
|
||||
|
||||
interface FriendCategoryMeta {
|
||||
categoryId: number;
|
||||
categoryName: string;
|
||||
memberCount: number;
|
||||
sortId: number;
|
||||
}
|
||||
|
||||
interface FriendRoster {
|
||||
entries: FriendRosterEntry[];
|
||||
categories: FriendCategoryMeta[];
|
||||
}
|
||||
|
||||
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
|
||||
const props = new Map<number, string>();
|
||||
for (const additional of raw.additional ?? []) {
|
||||
@@ -52,39 +78,111 @@ const MEMBER_LIST_TTL_MS = 60_000;
|
||||
|
||||
export class ContactsApi {
|
||||
/**
|
||||
* Per-group inflight + last-fetch cache for `fetchGroupMemberList`.
|
||||
* Keyed by groupId, lives for the lifetime of the Bridge.
|
||||
* Per-group TTL + single-flight cache for `fetchGroupMemberList`, keyed by
|
||||
* groupId, living for the lifetime of the Bridge.
|
||||
*
|
||||
* Without this, a busy OneBot client (e.g. MaiBot calling
|
||||
* `get_group_member_info` once per inbound message) triggers one
|
||||
* OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips
|
||||
* Tencent risk-control and gets the account banned for 7 days.
|
||||
*/
|
||||
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
private readonly memberListCache: SingleFlightCache<number, GroupMemberInfo[]> =
|
||||
createSingleFlightCache({
|
||||
ttlMs: MEMBER_LIST_TTL_MS,
|
||||
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
|
||||
});
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const friends: FriendInfo[] = [];
|
||||
let nextUin: number | null = null;
|
||||
do {
|
||||
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
|
||||
/** Server-built ARK share card (JSON string) recommending a friend. */
|
||||
getBuddyRecommendArk(userId: number, phoneNumber = ''): Promise<string> {
|
||||
return GetBuddyRecommendArk.invoke(this.ctx, { userId, phoneNumber });
|
||||
}
|
||||
|
||||
/** Server-built ARK share card (JSON string) recommending a group. */
|
||||
getGroupRecommendArk(groupId: number): Promise<string> {
|
||||
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
private async fetchFriendRoster(): Promise<FriendRoster> {
|
||||
const entries: FriendRosterEntry[] = [];
|
||||
const categories = new Map<number, FriendCategoryMeta>();
|
||||
const seenCookies = new Set<string>();
|
||||
let cookie: Uint8Array | undefined;
|
||||
|
||||
for (;;) {
|
||||
const resp = await FetchFriendListPage.invoke(this.ctx, { cookie });
|
||||
for (const raw of resp.friends ?? []) {
|
||||
const props = buildFriendProperties(raw);
|
||||
friends.push({
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
entries.push({
|
||||
categoryId: raw.customGroup ?? 0,
|
||||
friend: {
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
},
|
||||
});
|
||||
}
|
||||
for (const raw of resp.categories ?? []) {
|
||||
const categoryId = raw.categoryId ?? 0;
|
||||
categories.set(categoryId, {
|
||||
categoryId,
|
||||
categoryName: raw.categoryName ?? '',
|
||||
memberCount: raw.memberCount ?? 0,
|
||||
sortId: raw.sortId ?? 0,
|
||||
});
|
||||
}
|
||||
nextUin = resp.next?.uin ?? null;
|
||||
if (nextUin === 0) nextUin = null;
|
||||
} while (nextUin !== null);
|
||||
|
||||
const next = resp.cookie;
|
||||
if (!next?.length) break;
|
||||
const key = toHex(next);
|
||||
if (seenCookies.has(key)) {
|
||||
throw new Error(`repeated friend-list cookie ${key}`);
|
||||
}
|
||||
seenCookies.add(key);
|
||||
cookie = next;
|
||||
}
|
||||
|
||||
const friends = entries.map(entry => entry.friend);
|
||||
this.ctx.identity.rememberFriends(friends);
|
||||
return friends;
|
||||
return { entries, categories: [...categories.values()] };
|
||||
}
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const roster = await this.fetchFriendRoster();
|
||||
return roster.entries.map(entry => entry.friend);
|
||||
}
|
||||
|
||||
async fetchFriendCategories(): Promise<FriendCategoryInfo[]> {
|
||||
const roster = await this.fetchFriendRoster();
|
||||
const buckets = new Map(
|
||||
roster.categories.map(category => [category.categoryId, [] as FriendInfo[]]),
|
||||
);
|
||||
|
||||
for (const entry of roster.entries) {
|
||||
const bucket = buckets.get(entry.categoryId);
|
||||
if (!bucket) {
|
||||
throw new Error(
|
||||
`friend roster references missing category ${entry.categoryId} `
|
||||
+ `(${roster.entries.length} friends total)`,
|
||||
);
|
||||
}
|
||||
bucket.push(entry.friend);
|
||||
}
|
||||
|
||||
return roster.categories.map(category => {
|
||||
const friends = buckets.get(category.categoryId)!;
|
||||
if (friends.length !== category.memberCount) {
|
||||
log.warn(
|
||||
'friend category member count mismatch category=%d server=%d assembled=%d',
|
||||
category.categoryId,
|
||||
category.memberCount,
|
||||
friends.length,
|
||||
);
|
||||
}
|
||||
return { ...category, friends };
|
||||
});
|
||||
}
|
||||
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> {
|
||||
@@ -98,34 +196,48 @@ export class ContactsApi {
|
||||
memberCount: raw.info?.memberCount ?? 0,
|
||||
memberMax: raw.info?.memberMax ?? 0,
|
||||
members: new Map(),
|
||||
// #197: the list already carries these — no extra fetch needed. `level`
|
||||
// is not in the list (0x88D_0 detail only), so it stays undefined here.
|
||||
createTime: raw.info?.createdTime ?? 0,
|
||||
memo: raw.info?.announcement || raw.info?.description || '',
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
}
|
||||
|
||||
async fetchGroupMemberList(
|
||||
/**
|
||||
* Fetch a single group's public detail by id via `0x88D_0` — works even for a
|
||||
* group the bot hasn't joined (used to resolve a group-invite's name). Returns
|
||||
* null when the server has no such group / denies the lookup. Deliberately
|
||||
* does NOT `rememberGroups` it — a non-member group must not pollute the
|
||||
* joined-groups roster / get_group_list.
|
||||
*/
|
||||
async fetchGroupDetail(groupId: number): Promise<QQGroupInfo | null> {
|
||||
if (!(groupId > 0)) return null;
|
||||
const resp = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const r = resp.groupInfo?.results;
|
||||
if (!r) return null;
|
||||
return {
|
||||
groupId,
|
||||
groupName: r.name ?? '',
|
||||
remark: '',
|
||||
memberCount: Number(r.memberCount ?? 0n),
|
||||
memberMax: Number(r.maxMemberCount ?? 0n),
|
||||
members: new Map(),
|
||||
// #197: the detail is the only source of `level`; it also carries
|
||||
// createTime + the notice preview (memo).
|
||||
createTime: Number(r.createTime ?? 0n),
|
||||
level: Number(r.level ?? 0n),
|
||||
memo: r.noticePreview ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
fetchGroupMemberList(
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> {
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch.get(groupId);
|
||||
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
|
||||
return last.data;
|
||||
}
|
||||
const inflight = this.memberListInflight.get(groupId);
|
||||
if (inflight) return inflight;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const data = await this.fetchGroupMemberListUncached(groupId);
|
||||
this.memberListLastFetch.set(groupId, { at: Date.now(), data });
|
||||
return data;
|
||||
} finally {
|
||||
this.memberListInflight.delete(groupId);
|
||||
}
|
||||
})();
|
||||
this.memberListInflight.set(groupId, task);
|
||||
return task;
|
||||
return this.memberListCache.get(groupId, { force: options.force });
|
||||
}
|
||||
|
||||
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
@@ -197,6 +309,19 @@ export class ContactsApi {
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** The approval msgseq captured from a private "qun.invite" card for this
|
||||
* group, or undefined if none was seen. `set_group_add_request` uses it to
|
||||
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
|
||||
getGroupInviteCardSequence(groupId: number): number | undefined {
|
||||
return this.ctx.identity.getGroupInviteCardSequence(groupId);
|
||||
}
|
||||
|
||||
/** Resolve the group for a private invite-card msgseq. Numeric OneBot flags
|
||||
* use this path because the card sequence is absent from 0x10C0. */
|
||||
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
|
||||
return this.ctx.identity.findGroupInviteCardGroupBySequence(sequence);
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
|
||||
@@ -5,9 +5,33 @@ import {
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
|
||||
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MediaIndexNode } from './shared';
|
||||
|
||||
/** Inputs for a voice-to-text request, gathered from the received `record`
|
||||
* element + its message meta. `uuid`/`md5Hex` come from the cached record;
|
||||
* the uins + scene from the message meta. */
|
||||
export interface PttTransInput {
|
||||
isGroup: boolean;
|
||||
msgId: number;
|
||||
senderUin: number;
|
||||
/** Receiver uin (c2c) or group uin (group). */
|
||||
peerUin: number;
|
||||
uuid: string;
|
||||
md5Hex: string;
|
||||
duration: number;
|
||||
size: number;
|
||||
format: number;
|
||||
/** Group ptt numeric file id (group only; optional). */
|
||||
fileId?: number;
|
||||
}
|
||||
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
|
||||
export type StrangerStatus = NamespaceStrangerStatus;
|
||||
@@ -26,7 +50,41 @@ export interface AiVoiceItem {
|
||||
voiceExampleUrl: string;
|
||||
}
|
||||
|
||||
export interface AiVoiceSendReceipt {
|
||||
sequence: number;
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge.Extras');
|
||||
const AI_VOICE_RECEIPT_TIMEOUT_MS = 5_000;
|
||||
const AI_VOICE_CANDIDATE_LIMIT = 64;
|
||||
const AI_VOICE_CLAIM_LIMIT = 256;
|
||||
|
||||
type GroupMessageEvent = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
|
||||
function normalizeMediaUuid(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
function matchesAiVoiceEvent(node: MediaIndexNode, event: GroupMessageEvent): boolean {
|
||||
const expectedUuid = normalizeMediaUuid(node.fileUuid);
|
||||
if (!expectedUuid) return false;
|
||||
for (const element of event.elements) {
|
||||
if (element.type !== 'record') continue;
|
||||
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
|
||||
if (actualUuid === expectedUuid) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function describeAiVoiceFingerprint(node: MediaIndexNode): string {
|
||||
const uuid = normalizeMediaUuid(node.fileUuid);
|
||||
if (uuid) return `uuid:${uuid.slice(-12)}`;
|
||||
return 'missing';
|
||||
}
|
||||
|
||||
export class ExtrasApi {
|
||||
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
@@ -69,9 +127,11 @@ export class ExtrasApi {
|
||||
* the render is in-flight; we retry until a node materialises or the
|
||||
* cap is hit. napcat uses the same 30-retry budget.
|
||||
*
|
||||
* The returned MediaIndexNode plugs directly into
|
||||
* The returned node plugs directly into
|
||||
* `apis.groupFile.getPttUrl`, which already handles every other
|
||||
* download-URL fetch in SnowLuma.
|
||||
* download-URL fetch in SnowLuma. The synthesis response does not contain a
|
||||
* reliable message sequence; callers that need one must use `sendAiVoice`,
|
||||
* which correlates the subsequent self-message receipt.
|
||||
*/
|
||||
async fetchAiVoice(
|
||||
groupId: number,
|
||||
@@ -84,8 +144,186 @@ export class ExtrasApi {
|
||||
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
|
||||
if (node) return node as MediaIndexNode;
|
||||
if (node) {
|
||||
log.debug(
|
||||
'AI voice synthesis completed group=%d media=%s polls=%d',
|
||||
groupId,
|
||||
describeAiVoiceFingerprint(node),
|
||||
i + 1,
|
||||
);
|
||||
return node as MediaIndexNode;
|
||||
}
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish an AI voice and wait for QQ's canonical self-message receipt.
|
||||
*
|
||||
* The 0x929B completion response carries the media node but, on live QQ,
|
||||
* omits the group message sequence. Subscribe before publishing so an echo
|
||||
* that wins the response race is buffered, then correlate by the exact media
|
||||
* UUID. Never guess from content hashes or "the next voice in the group":
|
||||
* concurrent requests can legitimately render byte-identical audio.
|
||||
*/
|
||||
async sendAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS,
|
||||
): Promise<AiVoiceSendReceipt> {
|
||||
const candidates: GroupMessageEvent[] = [];
|
||||
let candidatesOverflowed = false;
|
||||
let expectedNode: MediaIndexNode | null = null;
|
||||
let receiptSettled = false;
|
||||
let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null;
|
||||
const receiptPromise = new Promise<GroupMessageEvent>((resolve) => {
|
||||
resolveReceipt = resolve;
|
||||
});
|
||||
|
||||
const claim = (event: GroupMessageEvent): boolean => {
|
||||
if (receiptSettled) return false;
|
||||
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
|
||||
if (this.claimedAiVoiceReceiptKeys.has(key)) return false;
|
||||
this.claimedAiVoiceReceiptKeys.add(key);
|
||||
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
|
||||
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
|
||||
if (oldest !== undefined) this.claimedAiVoiceReceiptKeys.delete(oldest);
|
||||
}
|
||||
receiptSettled = true;
|
||||
return true;
|
||||
};
|
||||
|
||||
const accept = (event: GroupMessageEvent): void => {
|
||||
if (event.groupId !== groupId || event.senderUin !== event.selfUin) return;
|
||||
if (!event.elements.some(element => element.type === 'record')) return;
|
||||
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
|
||||
resolveReceipt?.(event);
|
||||
return;
|
||||
}
|
||||
candidates.push(event);
|
||||
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
|
||||
candidates.shift();
|
||||
candidatesOverflowed = true;
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribe = this.ctx.events.on('group_message', accept);
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
|
||||
expectedNode = node;
|
||||
const fingerprint = describeAiVoiceFingerprint(node);
|
||||
if (fingerprint === 'missing') {
|
||||
throw new Error('AI voice was published but QQ returned no exact media identifier for receipt correlation');
|
||||
}
|
||||
|
||||
const buffered = candidates.find(event => matchesAiVoiceEvent(node, event) && claim(event));
|
||||
if (!buffered && candidatesOverflowed) {
|
||||
throw new Error(
|
||||
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} `
|
||||
+ `unmatched self voice messages (group=${groupId} media=${fingerprint})`,
|
||||
);
|
||||
}
|
||||
const event = buffered ?? await Promise.race([
|
||||
receiptPromise,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
reject(new Error(
|
||||
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms `
|
||||
+ `(group=${groupId} media=${fingerprint})`,
|
||||
));
|
||||
}, receiptTimeoutMs);
|
||||
timeout.unref?.();
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
|
||||
throw new Error(`AI voice receipt carried invalid message sequence: ${event.msgSeq}`);
|
||||
}
|
||||
|
||||
log.debug(
|
||||
'AI voice receipt matched group=%d media=%s sequence=%d random=%d',
|
||||
groupId,
|
||||
fingerprint,
|
||||
event.msgSeq,
|
||||
event.msgId,
|
||||
);
|
||||
return {
|
||||
sequence: event.msgSeq,
|
||||
};
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
|
||||
|
||||
/**
|
||||
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
|
||||
* return the recognised text IF the response carries it inline (the
|
||||
* already-transcribed case). For a freshly-received voice the response is an
|
||||
* empty ack and the text is delivered later via the async Event 0x210
|
||||
* subType-61 push — callers should treat `''` as "pending" and wait for the
|
||||
* `ptt_trans_result` event (correlated by msgId).
|
||||
*/
|
||||
async translatePttToText(input: PttTransInput): Promise<string> {
|
||||
// QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16
|
||||
// bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5
|
||||
// field goes through a bytes→hex helper). Sending raw bytes → errCode -1079.
|
||||
const md5 = input.md5Hex.toLowerCase();
|
||||
const req: PttTransReq = input.isGroup
|
||||
? {
|
||||
type: 1,
|
||||
groupItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
|
||||
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
|
||||
format: input.format, uuid: input.uuid,
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: 2,
|
||||
c2cItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
|
||||
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
|
||||
},
|
||||
};
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'ptt translate request failed');
|
||||
}
|
||||
const resp = protobuf_decode<PttTransResp>(result.responseData);
|
||||
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
|
||||
if (item?.errCode) {
|
||||
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
|
||||
// sourced from cache, to tell a server-side ASR failure apart from our own
|
||||
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
|
||||
log.warn(
|
||||
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
item.errCode, input.isGroup,
|
||||
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
|
||||
input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size,
|
||||
);
|
||||
throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
}
|
||||
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
|
||||
}
|
||||
|
||||
/**
|
||||
* Transcode a voice record (`get_record out_format`, #165). `source` is a
|
||||
* URL / local path / `base64://…` (the record's download URL in practice);
|
||||
* it is loaded then transcoded to `format` via the bundled SILK-capable
|
||||
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
|
||||
* failed conversion.
|
||||
*/
|
||||
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
|
||||
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
|
||||
// default so a tampered/oversized source can't be pulled in.
|
||||
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
|
||||
return convertAudioBytes(bytes, format);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
// FlashTransferApi — 闪传(fileset)业务编排。
|
||||
// 复用 OIDB 基础设施(invokeOidb),协议层在 @snowluma/protocol/oidb-services/flash-transfer/。
|
||||
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { resolveSelfUid } from './shared';
|
||||
import type { FlashFileEntry } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
|
||||
import { GetFilesetDetail } from '@snowluma/protocol/oidb-services/flash-transfer/get-fileset-detail';
|
||||
import { ListFilesets } from '@snowluma/protocol/oidb-services/flash-transfer/list-filesets';
|
||||
import { GetDownloadUrl } from '@snowluma/protocol/oidb-services/flash-transfer/get-download-url';
|
||||
import { GetFlashDownload } from '@snowluma/protocol/oidb-services/flash-transfer/get-flash-download';
|
||||
import { DeleteFlashFile } from '@snowluma/protocol/oidb-services/flash-transfer/delete-file';
|
||||
import { RenameFlashFile } from '@snowluma/protocol/oidb-services/flash-transfer/rename-file';
|
||||
import { ApplyFileset } from '@snowluma/protocol/oidb-services/flash-transfer/apply-fileset';
|
||||
import { CommitFile } from '@snowluma/protocol/oidb-services/flash-transfer/commit-file';
|
||||
import { CompleteFileset } from '@snowluma/protocol/oidb-services/flash-transfer/complete-fileset';
|
||||
import { SetFilesetStatus } from '@snowluma/protocol/oidb-services/flash-transfer/set-status';
|
||||
import { ApplyUpload } from '@snowluma/protocol/oidb-services/flash-transfer/apply-upload';
|
||||
import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/prepare-upload';
|
||||
import { SendFlashMsg } from '@snowluma/protocol/oidb-services/flash-transfer/send-flash';
|
||||
import { loadBinarySource, computeHashes } from '@snowluma/protocol/highway/utils';
|
||||
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { FlashSliceUploadBody, FlashSliceUploadResp, FlashFileId } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
|
||||
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
||||
import { deflateSync } from 'node:zlib';
|
||||
|
||||
/** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */
|
||||
export interface FlashFileInfo {
|
||||
filesetUuid: string;
|
||||
fileName: string;
|
||||
origName: string;
|
||||
fileSize: number;
|
||||
/** 上传/分享链接 qfile.qq.com/q/<code>。 */
|
||||
shareUrl: string;
|
||||
fileId: string;
|
||||
/** 下载链接 multimedia.qfile.qq.com/download?...&rkey=... */
|
||||
downloadUrl: string;
|
||||
}
|
||||
|
||||
function entryToInfo(e: FlashFileEntry): FlashFileInfo {
|
||||
return {
|
||||
filesetUuid: e.filesetUuid ?? '',
|
||||
fileName: e.fileName ?? '',
|
||||
origName: e.origName ?? '',
|
||||
fileSize: Number(e.fileSize ?? 0),
|
||||
shareUrl: e.uploadUrlWrap?.uploadUrl ?? '',
|
||||
fileId: e.fileIdWrap?.fileId ?? '',
|
||||
downloadUrl: e.fileIdWrap?.download?.downloadUrl ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
// 手写 PNG 编码(zlib 压缩,避免引入图像库)。缩略图用随机纯色,每次 SHA1 不同,
|
||||
// 避免命中服务端秒传缓存。
|
||||
const CRC_TABLE: Uint32Array = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
|
||||
table[n] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(buf: Buffer): number {
|
||||
let c = 0xFFFFFFFF;
|
||||
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8);
|
||||
return (c ^ 0xFFFFFFFF) >>> 0;
|
||||
}
|
||||
|
||||
function pngChunk(type: string, data: Buffer): Buffer {
|
||||
const len = Buffer.alloc(4);
|
||||
len.writeUInt32BE(data.length, 0);
|
||||
const typeBuf = Buffer.from(type, 'ascii');
|
||||
const crc = crc32(Buffer.concat([typeBuf, data]));
|
||||
const crcBuf = Buffer.alloc(4);
|
||||
crcBuf.writeUInt32BE(crc, 0);
|
||||
return Buffer.concat([len, typeBuf, data, crcBuf]);
|
||||
}
|
||||
|
||||
/** 生成 width×height 随机纯色 PNG(8-bit RGB)。每次随机颜色,SHA1 不同以避免秒传。 */
|
||||
function generatePng(width: number, height: number): Buffer {
|
||||
const r = Math.floor(Math.random() * 256);
|
||||
const g = Math.floor(Math.random() * 256);
|
||||
const b = Math.floor(Math.random() * 256);
|
||||
const rowLen = 1 + width * 3;
|
||||
const raw = Buffer.alloc(rowLen * height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
const off = y * rowLen;
|
||||
raw[off] = 0; // filter none
|
||||
for (let x = 0; x < width; x++) {
|
||||
raw[off + 1 + x * 3] = r;
|
||||
raw[off + 1 + x * 3 + 1] = g;
|
||||
raw[off + 1 + x * 3 + 2] = b;
|
||||
}
|
||||
}
|
||||
const compressed = deflateSync(raw);
|
||||
const sig = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(width, 0);
|
||||
ihdr.writeUInt32BE(height, 4);
|
||||
ihdr[8] = 8; // bit depth
|
||||
ihdr[9] = 2; // color type RGB
|
||||
ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
|
||||
return Buffer.concat([sig, pngChunk('IHDR', ihdr), pngChunk('IDAT', compressed), pngChunk('IEND', Buffer.alloc(0))]);
|
||||
}
|
||||
|
||||
export class FlashTransferApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
/** 获取文件集信息(get_fileset_info)。 */
|
||||
async getFilesetInfo(filesetUuid: string): Promise<FlashFileInfo[]> {
|
||||
const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid });
|
||||
return entries.map(entryToInfo);
|
||||
}
|
||||
|
||||
/** 获取闪传文件列表(get_flash_file_list)。同 getFilesetInfo,返回文件数组。 */
|
||||
async getFlashFileList(filesetUuid: string): Promise<FlashFileInfo[]> {
|
||||
return this.getFilesetInfo(filesetUuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拿指定文件的下载直链 + 元信息。0x93d4 返回 fileset 内所有文件(f3 repeated,
|
||||
* 多文件时每条 f6=序号、f14=主文件 fileId),按 fileIndex 选中后走 0x12a9 sub=200
|
||||
* 拿主文件直链。0x93d3/0x93d4 的 downloadUrl 字段是缩略图(appid=14903/14902),
|
||||
* 主文件必须走 0x12a9 sub=200。
|
||||
*/
|
||||
private async getFileDownload(
|
||||
filesetUuid: string, fileIndex: number = 1,
|
||||
): Promise<{ url: string; fileName: string; fileSize: number } | null> {
|
||||
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
|
||||
const meta = metas.find((m) => m.fileIndex === fileIndex);
|
||||
if (!meta || !meta.fileId) return null;
|
||||
const url = await GetFlashDownload.invoke(this.ctx, {
|
||||
filesetUuid: meta.filesetUuid,
|
||||
fileUuid: meta.fileUuid,
|
||||
fileId: meta.fileId,
|
||||
fileName: meta.fileName,
|
||||
});
|
||||
if (!url) return null;
|
||||
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取闪传文件下载链接(get_flash_file_url)。主文件直链走 0x12a9 sub=200
|
||||
* (0x93d3 的 downloadUrl 是缩略图 appid=14903,非主文件)。多文件 fileset 用
|
||||
* fileIndex 指定第几个文件(默认 1)。找不到文件或拿不到直链时抛错。
|
||||
*/
|
||||
async getFlashFileUrl(filesetUuid: string, fileIndex: number = 1): Promise<string> {
|
||||
const dl = await this.getFileDownload(filesetUuid, fileIndex);
|
||||
if (!dl || !dl.url) throw new Error('get_flash_file_url: no download url available');
|
||||
return dl.url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析闪传文件下载直链(download_fileset)。返回指定文件的下载 URL + 文件名/大小,
|
||||
* 不下载文件内容(由调用方拉)。多文件 fileset 用 fileIndex 指定第几个文件(默认 1)。
|
||||
*/
|
||||
async downloadFileset(
|
||||
filesetUuid: string,
|
||||
opts?: { fileName?: string; fileIndex?: number },
|
||||
): Promise<{ url: string; fileName: string; fileSize: number }> {
|
||||
const dl = await this.getFileDownload(filesetUuid, opts?.fileIndex ?? 1);
|
||||
if (!dl || !dl.url) throw new Error('download_fileset: no download url available');
|
||||
return dl;
|
||||
}
|
||||
|
||||
/** 获取分享链接(get_share_link)= qfile.qq.com/q/<code>。 */
|
||||
async getShareLink(filesetUuid: string): Promise<string> {
|
||||
const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid });
|
||||
return entries.find((e) => e.uploadUrlWrap?.uploadUrl)?.uploadUrlWrap?.uploadUrl ?? '';
|
||||
}
|
||||
|
||||
/** 列出当前账号的所有 fileset(OneBot 标准未定义,QQ 面板有此入口)。 */
|
||||
async listFilesets(): Promise<FlashFileInfo[]> {
|
||||
const entries = await ListFilesets.invoke(this.ctx, {});
|
||||
return entries.map(entryToInfo);
|
||||
}
|
||||
|
||||
/** 删除闪传文件(delete_flash_file)。 */
|
||||
async deleteFlashFile(filesetUuid: string): Promise<void> {
|
||||
await DeleteFlashFile.invoke(this.ctx, { filesetUuid });
|
||||
}
|
||||
|
||||
/** 重命名闪传文件(rename_flash_file)。 */
|
||||
async renameFlashFile(filesetUuid: string, newName: string): Promise<void> {
|
||||
await RenameFlashFile.invoke(this.ctx, { filesetUuid, newName });
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送闪传文件(send_flash_msg,0x93d7)。私聊:user_id→uid;群聊:group_id 直接用。
|
||||
* 0x93d7 响应无 message_id(分享 fileset,非传统消息),OneBot 层 message_id 由 action 返回 0。
|
||||
*/
|
||||
async sendFlashMsg(filesetUuid: string, target: { userId?: number; groupId?: number }): Promise<void> {
|
||||
if (target.groupId) {
|
||||
await SendFlashMsg.invoke(this.ctx, { groupId: target.groupId, filesetUuid });
|
||||
return;
|
||||
}
|
||||
const userId = target.userId;
|
||||
if (!userId) throw new Error('send_flash_msg: user_id or group_id is required');
|
||||
const targetUid = await this.ctx.identity.resolveUid(userId);
|
||||
await SendFlashMsg.invoke(this.ctx, { targetUid, filesetUuid });
|
||||
}
|
||||
|
||||
/**
|
||||
* 从分享码/链接获取 fileset_id(get_fileset_id)。code→UUID 不走 OIDB,QQ 客户端
|
||||
* 走 trpc HTTP API;分享页 qfile.qq.com/q/<code> 的 HTML 内嵌了 fileset_id(trpc
|
||||
* 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。
|
||||
*/
|
||||
async getFilesetIdByCode(shareCode: string): Promise<string> {
|
||||
const url = /^https?:\/\//i.test(shareCode) ? shareCode : `https://qfile.qq.com/q/${shareCode}`;
|
||||
const resp = await fetch(url);
|
||||
if (!resp.ok) throw new Error(`get_fileset_id: HTTP ${resp.status}`);
|
||||
const html = await resp.text();
|
||||
// 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。
|
||||
const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html);
|
||||
if (!m) throw new Error('get_fileset_id: fileset_id not found in share page');
|
||||
return m[1];
|
||||
}
|
||||
|
||||
// ─────────────── 文件上传 ───────────────
|
||||
|
||||
/**
|
||||
* 文件扩展名 → 闪传类型码映射。typeCode 用于 0x93cf f3,formatCode 用于
|
||||
* 0x93d0 commit f7 与 0x12a9 filesetWrap.f7(两者同值)。mp4 → 2,rar/zip → 4。
|
||||
* 未知扩展名按媒体类处理(formatCode=2),服务端按文件名扩展名判定。
|
||||
*/
|
||||
private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } {
|
||||
const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? '';
|
||||
switch (ext) {
|
||||
case 'rar': return { typeCode: 2, formatCode: 4 };
|
||||
case 'zip': return { typeCode: 6, formatCode: 4 };
|
||||
case '7z': case 'gz': case 'tar': case 'bz2': return { typeCode: 2, formatCode: 4 };
|
||||
case 'png': case 'jpg': case 'jpeg': case 'bmp': case 'gif': case 'webp':
|
||||
case 'mp4': case 'mov': case 'avi': case 'mkv':
|
||||
return { typeCode: 7, formatCode: 2 };
|
||||
default: return { typeCode: 7, formatCode: 2 };
|
||||
}
|
||||
}
|
||||
|
||||
/** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。
|
||||
* f2=SHA1, f3=filesize, f4=appid, f5=微秒时间戳, f6="prod",
|
||||
* f10=TTL(1209600), f11=16B 会话ID, f15=3B, f16="gz"。
|
||||
* f11/f15 随机生成,服务端不校验。
|
||||
* appid 决定 fileId 落在哪个槽位:主文件用 14901(0x93d4 f14.f1),
|
||||
* png 缩略图用 14903、jpg 缩略图用 14902(f13.f1)。主文件必须用 14901,
|
||||
* 否则 fileId 不会被服务端采纳进 f14,对端无法拿到主文件下载入口。 */
|
||||
private static buildFileId(sha1: Uint8Array, fileSize: number, appid: number = 14901): string {
|
||||
const fileId: FlashFileId = {
|
||||
sha1: new Uint8Array(sha1),
|
||||
fileSize,
|
||||
appid,
|
||||
timestamp: BigInt(Date.now()) * 1000n, // 微秒时间戳
|
||||
env: 'prod',
|
||||
ttl: 1209600,
|
||||
sessionId: randomBytes(16),
|
||||
field15: randomBytes(3),
|
||||
region: 'gz',
|
||||
};
|
||||
return Buffer.from(protobuf_encode<FlashFileId>(fileId)).toString('base64url');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建闪传任务(create_flash_task)。所有文件统一走 sub=100/103+sliceupload,
|
||||
* 不走小文件 PUT——QQ 客户端即使几百 KB 的文件也走 sliceupload。只有 sliceupload
|
||||
* 路径会上报主文件 sha1/size,服务端据此把 fileset 标记为完成(对端可下载);
|
||||
* PUT 路径不上报 sha1,fileset 会卡在"上传中"无法被下载。
|
||||
*
|
||||
* 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件
|
||||
* 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete →
|
||||
* 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit
|
||||
* 的 f6 一致,否则文件不计入 fileset。多文件时 ApplyFileset 的 fileName 用
|
||||
* 「<首文件名>等N个文件」、fileSize 用总和——服务端据此判定 fileset 为多文件。
|
||||
*/
|
||||
async createFlashTask(files: string | string[], _name?: string, _thumbPath?: string): Promise<{ filesetId: string }> {
|
||||
const fileList = Array.isArray(files) ? files : [files];
|
||||
if (fileList.length === 0) throw new Error('create_flash_task: files is empty');
|
||||
const uploader = {
|
||||
uin: this.ctx.identity.uin,
|
||||
nickname: this.ctx.identity.nickname,
|
||||
// Resolve our own uid rather than ship an empty one — a blank uploader
|
||||
// uid drops the fileset if this runs before warmup populated selfUid.
|
||||
uid: await resolveSelfUid(this.ctx),
|
||||
};
|
||||
// 读取所有文件,每个分配 fileUuid + 序号 + formatCode
|
||||
const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = [];
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const { bytes, fileName } = await loadBinarySource(fileList[i], 'flash-transfer');
|
||||
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
|
||||
items.push({ bytes: new Uint8Array(bytes), fileName, fileUuid: randomUUID(), fileIndex: i + 1, formatCode });
|
||||
}
|
||||
// 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
|
||||
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
|
||||
const first = items[0];
|
||||
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
|
||||
const isMulti = items.length > 1;
|
||||
const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName;
|
||||
const totalSize = items.reduce((s, it) => s + it.bytes.length, 0);
|
||||
const apply = await ApplyFileset.invoke(this.ctx, {
|
||||
fileName: filesetName, origName: filesetName,
|
||||
fileSize: totalSize, typeCode, uploader,
|
||||
});
|
||||
const filesetUuid = apply.filesetUuid;
|
||||
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
|
||||
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
|
||||
const commitEntries = items.map((it) => ({
|
||||
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
|
||||
fileSize: it.bytes.length, formatCode: it.formatCode, fileIndex: it.fileIndex,
|
||||
}));
|
||||
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
|
||||
await CompleteFileset.invoke(this.ctx, { filesetUuid });
|
||||
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
|
||||
const prepared: { it: typeof items[0]; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
|
||||
for (const it of items) {
|
||||
const p = await this.prepareAndApply(filesetUuid, it.bytes, it.fileName, it.fileUuid, it.fileIndex, it.formatCode);
|
||||
if (p) prepared.push({ it, ...p });
|
||||
}
|
||||
for (const p of prepared) {
|
||||
await this.sliceuploadFile(p.it.bytes, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName);
|
||||
}
|
||||
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
|
||||
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
|
||||
return { filesetId: filesetUuid };
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段1:prepare(拿 rkey)+ apply(注册 fileId)。返回 sliceupload 所需的 rkey/sha1state。
|
||||
* 秒传(rkey=null)返回 null,调用方跳过 sliceupload。
|
||||
*/
|
||||
private async prepareAndApply(
|
||||
filesetUuid: string, bytes: Uint8Array, fileName: string, fileUuid: string, fileIndex: number, formatCode: number,
|
||||
): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> {
|
||||
const fileSize = bytes.length;
|
||||
const hashes = computeHashes(bytes);
|
||||
const SLICE_SIZE = 1024 * 1024;
|
||||
const sliceCount = Math.ceil(fileSize / SLICE_SIZE);
|
||||
const sha1StateV = computeSha1StateV(bytes, sliceCount, SLICE_SIZE);
|
||||
|
||||
const rkey = await PrepareUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, fileIndex, formatCode,
|
||||
});
|
||||
if (rkey === null) return null; // 秒传
|
||||
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize);
|
||||
await ApplyUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileId, fileName, fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode,
|
||||
});
|
||||
return { rkey, sha1StateV, sliceCount };
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段2:sliceupload 分片上传(所有文件 prepare+apply 完成后调用)。
|
||||
*/
|
||||
private async sliceuploadFile(
|
||||
bytes: Uint8Array, rkey: string, sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
|
||||
): Promise<void> {
|
||||
const fileSize = bytes.length;
|
||||
const SLICE_SIZE = 1024 * 1024;
|
||||
for (let i = 0; i < sliceCount; i++) {
|
||||
const start = i * SLICE_SIZE;
|
||||
const chunk = bytes.subarray(start, Math.min(start + SLICE_SIZE, fileSize));
|
||||
const chunkLen = chunk.length;
|
||||
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
|
||||
const body: FlashSliceUploadBody = {
|
||||
field1: 0,
|
||||
appid: 14901,
|
||||
field3: 2,
|
||||
payload: {
|
||||
field1: {},
|
||||
rkey,
|
||||
start,
|
||||
end: start + chunkLen - 1,
|
||||
sha1: chunkSha1,
|
||||
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
|
||||
chunk: new Uint8Array(chunk),
|
||||
},
|
||||
};
|
||||
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
|
||||
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST sliceupload 并校验响应。服务端即使 HTTP 200 也可能在业务体里返回错误,
|
||||
* 所以必须解析 f5(status),非 "success" 视为失败。label 用于错误信息定位切片来源。
|
||||
*/
|
||||
private async postSliceupload(bodyBytes: Uint8Array, label: string): Promise<void> {
|
||||
const resp = await fetch('https://multimedia.qfile.qq.com/sliceupload', {
|
||||
method: 'POST', body: bodyBytes,
|
||||
headers: {
|
||||
Accept: '*/*', Connection: 'Keep-Alive',
|
||||
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)',
|
||||
Pragma: 'no-cache', 'Cache-Control': 'no-cache',
|
||||
'Content-Length': String(bodyBytes.length),
|
||||
'X-Retried-Times': '1',
|
||||
},
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const errBody = await resp.text().catch(() => '');
|
||||
throw new Error(`${label} failed: HTTP ${resp.status} ${errBody.slice(0, 300)}`);
|
||||
}
|
||||
const respBuf = new Uint8Array(await resp.arrayBuffer());
|
||||
const sliceResp = protobuf_decode<FlashSliceUploadResp>(respBuf);
|
||||
if (sliceResp.status !== 'success') {
|
||||
throw new Error(`${label} failed: ${sliceResp.status || 'no status in response'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传占位缩略图(png+jpg)。主文件上传后调用——主文件下载入口(0x93d3 的下载
|
||||
* fileId)需要缩略图关联才会被服务端填充,不传缩略图时 bot 自身上传的 fileset
|
||||
* 无法被 download_fileset 解析。缩略图用随机纯色 PNG,无需 ffmpeg/sharp。
|
||||
* fileIndex 为缩略图在 fileset 内的序号(主文件之后递增),与 commit f6 对齐。
|
||||
*/
|
||||
private async uploadThumbnail(
|
||||
filesetUuid: string, mainFileUuid: string, thumbType: 'png' | 'jpg', fileIndex: number,
|
||||
): Promise<void> {
|
||||
// 526x360 是 QQ 客户端缩略图尺寸;1x1 会被服务端拒(HTTP 400,宽高太小)。
|
||||
const width = 526, height = 360;
|
||||
const thumbBytes = generatePng(width, height); // 随机纯色,SHA1 不同避免秒传
|
||||
const appid = thumbType === 'png' ? 14903 : 14902; // png=14903, jpg=14902
|
||||
const fileUuid = thumbType === 'png' ? randomUUID() : mainFileUuid; // png 独立,jpg 挂主文件
|
||||
const fileName = thumbType === 'png'
|
||||
? `${randomUUID().slice(0, 8)}_one.png`
|
||||
: `${createHash('md5').update(thumbBytes).digest('hex').slice(0, 32)}.jpg`;
|
||||
const hashes = computeHashes(new Uint8Array(thumbBytes));
|
||||
const fileSize = thumbBytes.length;
|
||||
const thumbFormatCode = thumbType === 'png' ? 26 : 2; // png缩略图=26, jpg缩略图=2
|
||||
const rkey = await PrepareUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex,
|
||||
fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
|
||||
});
|
||||
if (rkey === null) return; // 秒传
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid);
|
||||
await ApplyUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileId, fileName, fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
|
||||
});
|
||||
// sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1])
|
||||
const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize);
|
||||
const body: FlashSliceUploadBody = {
|
||||
field1: 0, appid, field3: 2,
|
||||
payload: {
|
||||
field1: {}, rkey,
|
||||
start: 0, end: fileSize - 1,
|
||||
sha1: new Uint8Array(hashes.sha1),
|
||||
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
|
||||
chunk: new Uint8Array(thumbBytes),
|
||||
},
|
||||
};
|
||||
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
|
||||
await this.postSliceupload(bodyBytes, 'thumbnail sliceupload');
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
LongMsgResult,
|
||||
RecvLongMsgReq,
|
||||
@@ -8,13 +10,14 @@ import type {
|
||||
} from '@snowluma/proto-defs/longmsg';
|
||||
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
|
||||
import type { ForwardNodePayload, MessageElement, MessageElementOf } from '@snowluma/protocol/events';
|
||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
import { parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { gunzipSync, gzipSync } from 'zlib';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
@@ -24,6 +27,25 @@ function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge;
|
||||
// resolve a forward immediately after receiving the parent message.
|
||||
const forwardResCache = new Map<string, ForwardNodePayload[]>();
|
||||
|
||||
const log = createLogger('Bridge.Forward');
|
||||
|
||||
// Forward bodies are gzip-compressed by QQ. Bound decompression while zlib is
|
||||
// producing output so a small server response cannot expand until the process
|
||||
// exhausts its heap. 32 MiB leaves ample room for legitimate merged forwards
|
||||
// while making the maximum per-fetch allocation explicit.
|
||||
const FORWARD_LONG_MSG_MAX_OUTPUT_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
/** QQ's placeholder when it doesn't hand back a real sender name — treated as
|
||||
* "missing" so #174's enrichment resolves the real nickname. */
|
||||
const FORWARD_NAME_PLACEHOLDER = 'QQ用户';
|
||||
|
||||
/** Bounds on the L4 (per-uin profile) fallback when enriching forward senders.
|
||||
* Profile lookups are un-cached single-point OIDB calls Tencent rate-limits
|
||||
* aggressively, so cap how many distinct uins one forward resolves and how
|
||||
* many run at once — the rest keep the placeholder. */
|
||||
const FORWARD_PROFILE_MAX = 20;
|
||||
const FORWARD_PROFILE_CONCURRENCY = 4;
|
||||
|
||||
// Per-layer piggyback entry. Each level of a nested forward attaches
|
||||
// its own msgBody under a uuid `actionCommand`, so when the receiver
|
||||
// fetches the outermost res_id it gets every layer in one shot
|
||||
@@ -139,7 +161,9 @@ async function buildForwardPushBody(
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin,
|
||||
toUid: bridge.identity.selfUid ?? '',
|
||||
// Resolve our own uid rather than ship an empty one — a blank toUid is a
|
||||
// broken packet if this runs before warmup populated selfUid.
|
||||
toUid: await resolveSelfUid(bridge),
|
||||
forward: {
|
||||
friendName: nickname,
|
||||
},
|
||||
@@ -149,8 +173,10 @@ async function buildForwardPushBody(
|
||||
subType: 4,
|
||||
msgId: random,
|
||||
sequence: seq,
|
||||
timestamp: now,
|
||||
divSeq: 0,
|
||||
// Honour a custom per-node display time (#209); default to now. `now`
|
||||
// still drives the c2c-file expireTime above, which must stay real.
|
||||
timestamp: node.time && node.time > 0 ? node.time : now,
|
||||
c2cCmd: 0,
|
||||
},
|
||||
body: {
|
||||
richText: {
|
||||
@@ -202,14 +228,167 @@ function previewFromElements(elements: MessageElement[]): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
|
||||
return {
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements,
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
innerForward: node.innerForward,
|
||||
};
|
||||
}
|
||||
|
||||
function stripFileSource(element: MessageElementOf<'file'>): MessageElementOf<'file'> {
|
||||
const next: MessageElementOf<'file'> = { ...element };
|
||||
delete next.url;
|
||||
return next;
|
||||
}
|
||||
|
||||
function isCachedFileUsableInTarget(
|
||||
cached: UploadedFileMeta | undefined,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): boolean {
|
||||
if (!cached) return true;
|
||||
if (groupId !== undefined) {
|
||||
return cached.scope === 'group' && cached.groupId === groupId;
|
||||
}
|
||||
if (userId !== undefined) {
|
||||
return cached.scope === 'private' && cached.userId === userId;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta): string {
|
||||
return (element.fileName ?? cached?.fileName ?? '').trim();
|
||||
}
|
||||
|
||||
function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
|
||||
for (const node of nodes) {
|
||||
const fileCount = node.elements.filter((element) => element.type === 'file').length;
|
||||
if (fileCount > 1) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'a private forward node can contain at most one file element',
|
||||
'file',
|
||||
);
|
||||
}
|
||||
if (node.innerForward) assertPrivateForwardFileCapacity(node.innerForward);
|
||||
}
|
||||
}
|
||||
|
||||
export class ForwardApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
|
||||
// A c2c RichText owns exactly one msgContent/FileExtra payload. Validate
|
||||
// the entire recursive tree before any file/media/long-message upload so a
|
||||
// second file cannot be uploaded and then silently discarded.
|
||||
if (groupId === undefined) assertPrivateForwardFileCapacity(nodes);
|
||||
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
|
||||
return resId;
|
||||
}
|
||||
|
||||
private async downloadSourceFromCachedFile(cached: UploadedFileMeta): Promise<string> {
|
||||
if (cached.scope === 'group' && cached.groupId !== undefined) {
|
||||
return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId);
|
||||
}
|
||||
if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) {
|
||||
return this.ctx.apis.groupFile.getPrivateUrl(cached.userId, cached.fileId, cached.fileHash);
|
||||
}
|
||||
throw new Error('forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it');
|
||||
}
|
||||
|
||||
private async uploadForwardFileSource(
|
||||
source: string,
|
||||
name: string,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<MessageElementOf<'file'>> {
|
||||
if (groupId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false);
|
||||
if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id');
|
||||
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
|
||||
const element: MessageElement = {
|
||||
type: 'file',
|
||||
fileId: uploaded.fileId,
|
||||
};
|
||||
const fileName = cached?.fileName || name;
|
||||
if (fileName) element.fileName = fileName;
|
||||
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
|
||||
return element;
|
||||
}
|
||||
if (userId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.uploadPrivate(userId, source, name, true, false);
|
||||
if (!uploaded.fileId) throw new Error('forward private file upload returned no file_id');
|
||||
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
|
||||
const element: MessageElement = {
|
||||
type: 'file',
|
||||
fileId: uploaded.fileId,
|
||||
};
|
||||
const fileName = cached?.fileName || name;
|
||||
const fileHash = uploaded.fileHash ?? cached?.fileHash ?? '';
|
||||
if (fileName) element.fileName = fileName;
|
||||
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
|
||||
if (fileHash) element.fileHash = fileHash;
|
||||
return element;
|
||||
}
|
||||
throw new Error('forward file source requires group_id or user_id');
|
||||
}
|
||||
|
||||
private async prepareForwardFileElement(
|
||||
element: MessageElement,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<MessageElement> {
|
||||
if (element.type !== 'file') return element;
|
||||
|
||||
const source = (element.url ?? '').trim();
|
||||
if (source && !element.fileId) {
|
||||
const uploaded = await this.uploadForwardFileSource(source, fileNameForUpload(element), groupId, userId);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
...uploaded,
|
||||
};
|
||||
}
|
||||
|
||||
if (element.fileId) {
|
||||
const cached = this.ctx.recallUploadedFile(element.fileId);
|
||||
if (isCachedFileUsableInTarget(cached, groupId, userId)) return element;
|
||||
const sourceFromCache = await this.downloadSourceFromCachedFile(cached!);
|
||||
const uploaded = await this.uploadForwardFileSource(
|
||||
sourceFromCache,
|
||||
fileNameForUpload(element, cached),
|
||||
groupId,
|
||||
userId,
|
||||
);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
...uploaded,
|
||||
};
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
private async prepareForwardFiles(
|
||||
nodes: ForwardNodePayload[],
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<ForwardNodePayload[]> {
|
||||
return Promise.all(nodes.map(async (node) => {
|
||||
const elements = await Promise.all(node.elements.map(
|
||||
element => this.prepareForwardFileElement(element, groupId, userId),
|
||||
));
|
||||
return cloneNodeWithElements(node, elements);
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive upload with NapCat-style piggyback. Each invocation:
|
||||
* 1. Walks `nodes`. For any node whose `innerForward` is set,
|
||||
@@ -304,8 +483,10 @@ export class ForwardApi {
|
||||
}
|
||||
}
|
||||
|
||||
const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId);
|
||||
|
||||
// Encode this level's msgBody.
|
||||
const msgBody = await Promise.all(processedNodes.map(
|
||||
const msgBody = await Promise.all(uploadReadyNodes.map(
|
||||
node => buildForwardPushBody(bridge, node, groupId, userUid),
|
||||
));
|
||||
|
||||
@@ -349,7 +530,7 @@ export class ForwardApi {
|
||||
throw new Error('upload forward message response missing res_id');
|
||||
}
|
||||
|
||||
forwardResCache.set(resId, processedNodes.map(node => ({
|
||||
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
@@ -381,7 +562,7 @@ export class ForwardApi {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cached = forwardResCache.get(resId);
|
||||
if (cached) {
|
||||
return cached.map(node => ({
|
||||
const nodes = cached.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
@@ -392,6 +573,10 @@ export class ForwardApi {
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
|
||||
// on read (a no-op once names are present) and persist so later hits skip.
|
||||
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
|
||||
return nodes;
|
||||
}
|
||||
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
@@ -420,7 +605,27 @@ export class ForwardApi {
|
||||
throw new Error('download forward message payload is empty');
|
||||
}
|
||||
|
||||
const inflate = gunzipSync(Buffer.from(payload));
|
||||
let inflate: Buffer;
|
||||
try {
|
||||
inflate = gunzipSync(Buffer.from(payload), {
|
||||
maxOutputLength: FORWARD_LONG_MSG_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
} catch (cause) {
|
||||
const reason = cause instanceof Error ? cause.message : String(cause);
|
||||
log.warn(
|
||||
'forward long-msg decompression failed: res_id=%s compressed_bytes=%d max_output_bytes=%d error=%s',
|
||||
resId,
|
||||
payload.byteLength,
|
||||
FORWARD_LONG_MSG_MAX_OUTPUT_BYTES,
|
||||
reason,
|
||||
);
|
||||
throw new Error(
|
||||
`download forward message decompression failed ` +
|
||||
`(res_id=${resId}, compressed_bytes=${payload.byteLength}, ` +
|
||||
`max_output_bytes=${FORWARD_LONG_MSG_MAX_OUTPUT_BYTES}): ${reason}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
const longMsg = protobuf_decode<LongMsgResult>(inflate);
|
||||
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
|
||||
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
|
||||
@@ -451,12 +656,94 @@ export class ForwardApi {
|
||||
this.consumePiggybacks(nodes, piggybackByUuid);
|
||||
}
|
||||
|
||||
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
|
||||
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
|
||||
// isn't always populated, and the sync decode only consults the L1 cache.
|
||||
await this.enrichSenders(nodes);
|
||||
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/** A node whose display name the server didn't give us (empty or the QQ
|
||||
* placeholder) and that we can resolve (has a uin). */
|
||||
private needsName(n: ForwardNodePayload): boolean {
|
||||
return !!n.userUin && (!n.nickname || n.nickname === FORWARD_NAME_PLACEHOLDER);
|
||||
}
|
||||
|
||||
/** Backfill sender nickname/card on forward nodes the long-msg payload left
|
||||
* nameless. Resolves group senders via one member-list fetch per group (L3,
|
||||
* inflight+TTL cached in ContactsApi), then any residue + private nodes via
|
||||
* the user-profile lookup (L4). Best-effort: a failed lookup keeps the
|
||||
* placeholder rather than failing the whole forward. Returns true if any
|
||||
* node was changed (so callers can persist the enriched cache). */
|
||||
private async enrichSenders(nodes: ForwardNodePayload[]): Promise<boolean> {
|
||||
const pending = nodes.filter(n => this.needsName(n));
|
||||
if (pending.length === 0) return false;
|
||||
let changed = false;
|
||||
|
||||
// L3 — group member lists (one fetch resolves every sender from that group).
|
||||
const byGroup = new Map<number, ForwardNodePayload[]>();
|
||||
const residue: ForwardNodePayload[] = [];
|
||||
for (const n of pending) {
|
||||
if (n.messageType === 'group' && n.groupId) {
|
||||
const arr = byGroup.get(n.groupId) ?? [];
|
||||
arr.push(n);
|
||||
byGroup.set(n.groupId, arr);
|
||||
} else {
|
||||
residue.push(n);
|
||||
}
|
||||
}
|
||||
for (const [groupId, groupNodes] of byGroup) {
|
||||
let byUin: Map<number, { nickname: string; card: string }>;
|
||||
try {
|
||||
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
|
||||
byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }]));
|
||||
} catch {
|
||||
// Member list (one cheap, cached call) failed — keep the placeholder
|
||||
// rather than fanning the whole group out to per-uin profile lookups.
|
||||
// That error path is exactly what would amplify into a rate-limit ban.
|
||||
continue;
|
||||
}
|
||||
for (const n of groupNodes) {
|
||||
const m = byUin.get(n.userUin);
|
||||
const name = m?.card || m?.nickname;
|
||||
if (name) {
|
||||
n.senderCard = m!.card || n.senderCard || '';
|
||||
n.nickname = name;
|
||||
changed = true;
|
||||
} else {
|
||||
residue.push(n); // in-group sender that left the group → profile fallback
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// L4 — user profile for the residue (members who left the group, private
|
||||
// nodes). fetchUserProfile is an un-cached single-point OIDB 0xFE1_2, and
|
||||
// Tencent rate-limits these hard (see ContactsApi's member-list note), so:
|
||||
// dedupe by uin, CAP the count (drop the rest to placeholder), and resolve
|
||||
// in small concurrency-limited batches. Best-effort.
|
||||
const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))]
|
||||
.slice(0, FORWARD_PROFILE_MAX);
|
||||
if (uins.length > 0) {
|
||||
const byUin = new Map<number, string>();
|
||||
const results = await mapWithConcurrency(uins, FORWARD_PROFILE_CONCURRENCY,
|
||||
async (uin): Promise<readonly [number, string]> => {
|
||||
try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; }
|
||||
catch { return [uin, ''] as const; }
|
||||
});
|
||||
for (const [uin, nick] of results) byUin.set(uin, nick);
|
||||
for (const n of residue) {
|
||||
if (!this.needsName(n)) continue;
|
||||
const nick = byUin.get(n.userUin);
|
||||
if (nick) { n.nickname = nick; changed = true; }
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** Walk a list of PushMsgBody, run each through the regular msg-push
|
||||
* pipeline, and shape the result into ForwardNodePayloads. Extracted
|
||||
* so both the outer + piggyback decode paths share one implementation. */
|
||||
@@ -479,6 +766,9 @@ export class ForwardApi {
|
||||
if (!event) continue;
|
||||
|
||||
if (event.kind === 'group_message') {
|
||||
// [#201] The merged-forward sender name now comes through the group
|
||||
// decoder (event.senderNick), which reads grp.memberCard (field 4) when
|
||||
// there's no member cache — exactly the forward-node case.
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderCard || event.senderNick,
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
|
||||
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
||||
import { GetDoubtBuddyReq, type DoubtBuddyRequest } from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
|
||||
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
|
||||
import { RejectDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/reject-doubt-buddy-req';
|
||||
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export type { DoubtBuddyRequest };
|
||||
|
||||
export class FriendApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -26,4 +31,19 @@ export class FriendApi {
|
||||
setRemark(userId: number, remark: string): Promise<void> {
|
||||
return SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
|
||||
/** List doubtful friend-add requests (可能认识的人). */
|
||||
getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
return GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
}
|
||||
|
||||
/** Approve a doubtful friend-add request by its uid (the list item's flag). */
|
||||
approveDoubtRequest(uid: string): Promise<void> {
|
||||
return ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
}
|
||||
|
||||
/** Reject (delete/decline) a doubtful friend-add request by its uid. */
|
||||
rejectDoubtRequest(uid: string): Promise<void> {
|
||||
return RejectDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
}
|
||||
}
|
||||
@@ -12,11 +12,17 @@ import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set
|
||||
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
|
||||
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
|
||||
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
|
||||
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
/** Set the group's robot-add option (switch / examine) via group ext-info. */
|
||||
setRobotAddOption(groupId: number, robotMemberSwitch?: number, robotMemberExamine?: number): Promise<void> {
|
||||
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
|
||||
}
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
@@ -29,8 +35,8 @@ export class GroupAdminApi {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType });
|
||||
}
|
||||
|
||||
setSearch(groupId: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId });
|
||||
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
@@ -48,8 +54,26 @@ export class GroupAdminApi {
|
||||
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
|
||||
}
|
||||
|
||||
leave(groupId: number): Promise<void> {
|
||||
return LeaveGroup.invoke(this.ctx, { groupId });
|
||||
async leave(groupId: number): Promise<void> {
|
||||
await LeaveGroup.invoke(this.ctx, { groupId });
|
||||
// The server doesn't push a member-decrease back to the member who left of
|
||||
// its own accord, so synthesize the self group_member_leave here — otherwise
|
||||
// downstream never sees notice.group_decrease and keeps a "zombie" group in
|
||||
// its cache (#133). Also drop the group from our own roster.
|
||||
const selfUin = Number(this.ctx.identity.uin) || 0;
|
||||
const selfUid = this.ctx.identity.selfUid ?? '';
|
||||
await this.ctx.events.emit({
|
||||
kind: 'group_member_leave',
|
||||
time: Math.floor(Date.now() / 1000),
|
||||
selfUin,
|
||||
groupId,
|
||||
userUin: selfUin,
|
||||
operatorUin: selfUin,
|
||||
userUid: selfUid,
|
||||
operatorUid: selfUid,
|
||||
leaveType: 'leave',
|
||||
});
|
||||
this.ctx.identity.forgetGroup(groupId);
|
||||
}
|
||||
|
||||
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
|
||||
|
||||
@@ -1,19 +1,101 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
AlbumCreator,
|
||||
DeleteMediasRequest,
|
||||
DeleteMediasResponse,
|
||||
DoQunCommentRequest,
|
||||
DoQunCommentResponse,
|
||||
DoQunLikeRequest,
|
||||
DoQunLikeResponse,
|
||||
GetAlbumListRequest,
|
||||
GetAlbumListResponse,
|
||||
GroupAlbumInfo as GroupAlbumInfoWire,
|
||||
GetMediaListRequest,
|
||||
GetMediaListResponse,
|
||||
MediaInfo,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
|
||||
import { uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
const log = createLogger('Bridge.GroupAlbum');
|
||||
const GET_ALBUM_LIST_CMD = 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetAlbumList';
|
||||
const GET_ALBUM_LIST_SEQ = 3331;
|
||||
|
||||
function uint64ToString(value: bigint | undefined): string {
|
||||
return (value ?? 0n).toString();
|
||||
}
|
||||
|
||||
function uint64ToSafeNumber(value: bigint | undefined, fieldName: string): number {
|
||||
const normalized = value ?? 0n;
|
||||
if (normalized > BigInt(Number.MAX_SAFE_INTEGER)) {
|
||||
throw new Error(`group album ${fieldName} exceeds Number.MAX_SAFE_INTEGER: ${normalized}`);
|
||||
}
|
||||
return Number(normalized);
|
||||
}
|
||||
|
||||
function normalizeAlbumCreator(creator: AlbumCreator | undefined): QunAlbumCreator | undefined {
|
||||
if (!creator) return undefined;
|
||||
return {
|
||||
uid: creator.uid ?? '',
|
||||
nick: creator.nick ?? '',
|
||||
is_sweet: creator.isSweet ?? false,
|
||||
is_special: creator.isSpecial ?? false,
|
||||
is_super_like: creator.isSuperLike ?? false,
|
||||
custom_id: creator.customId ?? '',
|
||||
poly_id: creator.polyId ?? '',
|
||||
portrait: creator.portrait ?? '',
|
||||
can_follow: creator.canFollow ?? 0,
|
||||
isfollowed: creator.isFollowed ?? 0,
|
||||
uin: creator.uin ?? '',
|
||||
ditto_uin: creator.dittoUin ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQunAlbum(album: GroupAlbumInfoWire): QunAlbumInfo {
|
||||
const normalized: QunAlbumInfo = {
|
||||
album_id: album.albumId ?? '',
|
||||
owner: album.owner ?? '',
|
||||
name: album.name ?? '',
|
||||
desc: album.description ?? '',
|
||||
create_time: uint64ToString(album.createTime),
|
||||
modify_time: uint64ToString(album.modifyTime),
|
||||
last_upload_time: uint64ToString(album.lastUploadTime),
|
||||
upload_number: uint64ToString(album.uploadNumber),
|
||||
top_flag: uint64ToString(album.topFlag),
|
||||
busi_type: album.busiType ?? 0,
|
||||
status: album.status ?? 0,
|
||||
allow_share: album.allowShare ?? false,
|
||||
is_subscribe: album.isSubscribe ?? false,
|
||||
bitmap: album.bitmap ?? '',
|
||||
is_share_album: album.isShareAlbum ?? false,
|
||||
qz_album_type: album.qzAlbumType ?? 0,
|
||||
cover_type: album.coverType ?? 0,
|
||||
default_desc: album.defaultDesc ?? '',
|
||||
sort_type: album.sortType ?? 0,
|
||||
};
|
||||
const creator = normalizeAlbumCreator(album.creator);
|
||||
if (creator) normalized.creator = creator;
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function toLegacyAlbum(album: GroupAlbumInfoWire): GroupAlbumInfo {
|
||||
const creator = normalizeAlbumCreator(album.creator);
|
||||
return {
|
||||
id: album.albumId ?? '',
|
||||
name: album.name ?? '',
|
||||
picNum: uint64ToSafeNumber(album.uploadNumber, 'upload_number'),
|
||||
createTime: uint64ToSafeNumber(album.createTime, 'create_time'),
|
||||
desc: album.description ?? '',
|
||||
owner: album.owner ?? '',
|
||||
createuin: creator?.uin || album.owner || creator?.uid || '',
|
||||
// QQ NT's AlbumService returns this as a normal UTF-8 protobuf string.
|
||||
// Unlike the legacy Qzone HTTP endpoint, it does not rewrite Unicode
|
||||
// emoji into ambiguous [em]...[/em] tags.
|
||||
createnickname: creator?.nick ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
function convertBigIntToString(obj: unknown): JsonValue {
|
||||
if (obj === null || obj === undefined) return null;
|
||||
@@ -33,13 +115,73 @@ function convertBigIntToString(obj: unknown): JsonValue {
|
||||
export class GroupAlbumApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
|
||||
private async fetchAlbumList(groupId: number, attachInfo: string): Promise<GroupAlbumWireResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
const body = protobuf_encode<GetAlbumListRequest>({
|
||||
seq: GET_ALBUM_LIST_SEQ,
|
||||
field2: new Uint8Array(0),
|
||||
field3: new Uint8Array(0),
|
||||
data: {
|
||||
groupId: groupId.toString(),
|
||||
attachInfo,
|
||||
},
|
||||
traceId,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
log.debug(
|
||||
'get album list request: group=%d cursorChars=%d requestBytes=%d',
|
||||
groupId,
|
||||
attachInfo.length,
|
||||
body.length,
|
||||
);
|
||||
|
||||
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(
|
||||
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
|
||||
);
|
||||
}
|
||||
|
||||
const response = protobuf_decode<GetAlbumListResponse>(result.responseData);
|
||||
const resultCode = response.result ?? 0;
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(
|
||||
`get group album list failed: result=${resultCode}, error=${response.errorText || 'unknown'}`,
|
||||
);
|
||||
}
|
||||
|
||||
const normalized: GroupAlbumWireResult = {
|
||||
albumList: response.data?.albumList ?? [],
|
||||
attachInfo: response.data?.attachInfo ?? '',
|
||||
hasMore: response.data?.hasMore ?? false,
|
||||
};
|
||||
|
||||
log.debug(
|
||||
'get album list response: group=%d albums=%d hasMore=%s cursorChars=%d responseBytes=%d',
|
||||
groupId,
|
||||
normalized.albumList.length,
|
||||
String(normalized.hasMore),
|
||||
normalized.attachInfo.length,
|
||||
result.responseData.length,
|
||||
);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/** QQ NT AlbumService-backed list, including its pagination cursor. */
|
||||
async listQun(groupId: number, attachInfo = ''): Promise<QunAlbumListResult> {
|
||||
const result = await this.fetchAlbumList(groupId, attachInfo);
|
||||
return {
|
||||
albumList: result.albumList.map(normalizeQunAlbum),
|
||||
attachInfo: result.attachInfo,
|
||||
hasMore: result.hasMore,
|
||||
};
|
||||
}
|
||||
|
||||
// OneBot compatibility shape used by get_group_album_list.
|
||||
async list(groupId: number): Promise<GroupAlbumList> {
|
||||
const groupCode = groupId.toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
|
||||
return albumData?.album || [];
|
||||
const result = await this.fetchAlbumList(groupId, '');
|
||||
return result.albumList.map(toLegacyAlbum);
|
||||
}
|
||||
|
||||
// 上传图片到现有相册(HTTP 分片上传)。
|
||||
@@ -61,8 +203,8 @@ export class GroupAlbumApi {
|
||||
groupId: groupId.toString(),
|
||||
albumId,
|
||||
field3: 0,
|
||||
attachInfo,
|
||||
field5: '',
|
||||
field4: '',
|
||||
pageInfo: attachInfo,
|
||||
},
|
||||
traceId,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
@@ -80,8 +222,9 @@ export class GroupAlbumApi {
|
||||
|
||||
const resp = protobuf_decode<GetMediaListResponse>(result.responseData);
|
||||
|
||||
if (resp.field1 !== 0) {
|
||||
throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`);
|
||||
const retCode = resp.field1 ?? 0;
|
||||
if (retCode !== 0) {
|
||||
throw new Error(`fetch album media list error: retCode ${retCode}`);
|
||||
}
|
||||
|
||||
const data = resp.data ?? {};
|
||||
@@ -268,7 +411,69 @@ export interface GroupAlbumMediaResult {
|
||||
nextAttachInfo: string;
|
||||
}
|
||||
|
||||
export type GroupAlbumList = NonNullable<Awaited<ReturnType<typeof getGroupAlbumList>>>['album'];
|
||||
interface GroupAlbumWireResult {
|
||||
albumList: GroupAlbumInfoWire[];
|
||||
attachInfo: string;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
export interface GroupAlbumInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
picNum: number;
|
||||
createTime: number;
|
||||
desc: string;
|
||||
owner: string;
|
||||
createuin: string;
|
||||
createnickname: string;
|
||||
[key: string]: JsonValue;
|
||||
}
|
||||
|
||||
export type GroupAlbumList = GroupAlbumInfo[];
|
||||
|
||||
export interface QunAlbumCreator {
|
||||
uid: string;
|
||||
nick: string;
|
||||
is_sweet: boolean;
|
||||
is_special: boolean;
|
||||
is_super_like: boolean;
|
||||
custom_id: string;
|
||||
poly_id: string;
|
||||
portrait: string;
|
||||
can_follow: number;
|
||||
isfollowed: number;
|
||||
uin: string;
|
||||
ditto_uin: string;
|
||||
}
|
||||
|
||||
export interface QunAlbumInfo {
|
||||
album_id: string;
|
||||
owner: string;
|
||||
name: string;
|
||||
desc: string;
|
||||
create_time: string;
|
||||
modify_time: string;
|
||||
last_upload_time: string;
|
||||
upload_number: string;
|
||||
creator?: QunAlbumCreator;
|
||||
top_flag: string;
|
||||
busi_type: number;
|
||||
status: number;
|
||||
allow_share: boolean;
|
||||
is_subscribe: boolean;
|
||||
bitmap: string;
|
||||
is_share_album: boolean;
|
||||
qz_album_type: number;
|
||||
cover_type: number;
|
||||
default_desc: string;
|
||||
sort_type: number;
|
||||
}
|
||||
|
||||
export interface QunAlbumListResult {
|
||||
albumList: QunAlbumInfo[];
|
||||
attachInfo: string;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
export interface GroupAlbumCommentResult {
|
||||
id: string;
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { toHexUpper } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { FILE_UPLOAD_MAX_BYTES } from '@snowluma/protocol/highway/utils';
|
||||
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
|
||||
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { promises as fsp } from 'fs';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
|
||||
@@ -12,6 +15,7 @@ import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/c
|
||||
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
|
||||
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
|
||||
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
|
||||
import { GetGroupFileSpace } from '@snowluma/protocol/oidb-services/group-file/get-group-file-space';
|
||||
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
|
||||
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
|
||||
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
|
||||
@@ -21,7 +25,9 @@ import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/
|
||||
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
|
||||
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
|
||||
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
|
||||
import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file';
|
||||
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
|
||||
import { TransGroupFile, type TransGroupFileResult } from '@snowluma/protocol/oidb-services/group-file/trans-group-file';
|
||||
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
|
||||
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
|
||||
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
|
||||
@@ -52,6 +58,9 @@ export interface GroupFolderInfo {
|
||||
creator: number;
|
||||
creatorName: string;
|
||||
totalFileCount: number;
|
||||
lastUploadTime: number;
|
||||
lastUploader: number;
|
||||
lastUploaderName: string;
|
||||
}
|
||||
|
||||
export interface GroupFilesResult {
|
||||
@@ -99,9 +108,20 @@ function normalizeUploadFileName(name: string, fallback: string): string {
|
||||
return safeFallback || 'file.bin';
|
||||
}
|
||||
|
||||
function md5First10MB(bytes: Uint8Array): Uint8Array {
|
||||
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
|
||||
return computeMd5(bytes.subarray(0, limit));
|
||||
// QQ's "first 10 MB" checksum uses the magic limit 0x98A000 (10002432) —
|
||||
// NOT 10*1024*1024 and not 10^7. Using the wrong limit makes the server's
|
||||
// first-block verification fail for files larger than 0x98A000, so the
|
||||
// offline file uploads but never finalises as downloadable (#157).
|
||||
const MD5_HEAD_LIMIT = 10002432;
|
||||
|
||||
/** Fail cleanly if the staged file changed since the streaming hash pass (a
|
||||
* local source mutated mid-send). The server's per-chunk md5 during the PUT is
|
||||
* the backstop; this is the cheap early check. */
|
||||
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
|
||||
const now = await fsp.stat(filePath);
|
||||
if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) {
|
||||
throw new Error('file source changed during send (mutated between hashing and upload)');
|
||||
}
|
||||
}
|
||||
|
||||
function buildGroupFileUploadExt(
|
||||
@@ -176,7 +196,12 @@ function buildPrivateFileUploadExt(
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
// #157: NapCat/Lagrange (and the QQ client, confirmed by packet
|
||||
// capture) emit a busiBuff with ONLY senderUin — no busId. A stale
|
||||
// busId:102 here made the offline-file server accept the highway
|
||||
// upload but never finalise it as downloadable once the file got
|
||||
// big (>5 MiB): the receiver saw the file but every download failed.
|
||||
// (The other half of that bug was the wrong md5-head limit above.)
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: 0n,
|
||||
groupCode: 0n,
|
||||
@@ -226,12 +251,21 @@ export class GroupFileApi {
|
||||
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
|
||||
if (!fileId) throw new Error('trans requires fileId');
|
||||
return TransGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
// ─────────────── count ───────────────
|
||||
|
||||
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
|
||||
return GetGroupFileCount.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
getSpace(groupId: number): Promise<{ usedSpace: number; totalSpace: number }> {
|
||||
return GetGroupFileSpace.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
|
||||
|
||||
async upload(
|
||||
@@ -240,99 +274,113 @@ export class GroupFileApi {
|
||||
name = '',
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
publishFile = uploadFile,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('group file is empty');
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
|
||||
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
|
||||
// local disk path and stream-hash it — the (up to 4 GiB) file is never
|
||||
// buffered in RAM.
|
||||
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
|
||||
try {
|
||||
if (staged.fileSize === 0) throw new Error('group file is empty');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const fileName = normalizeUploadFileName(name, staged.fileName);
|
||||
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
|
||||
const hashes = await hashFileStreaming(staged.filePath);
|
||||
|
||||
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileName,
|
||||
folderId: normalizeDirectory(folderId),
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
|
||||
|
||||
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
// to thread fileName/size/md5 separately. For groups the wire
|
||||
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
|
||||
// mainly for log-line correctness; the c2c counterpart in
|
||||
// `uploadPrivate` is where the cache is actually load-bearing.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'group',
|
||||
groupId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
||||
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|
||||
|| '';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('group file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
hashes.md5,
|
||||
folderId: normalizeDirectory(folderId),
|
||||
fileSize: staged.fileSize,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
|
||||
|
||||
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
// to thread fileName/size/md5 separately. For groups the wire
|
||||
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
|
||||
// mainly for log-line correctness; the c2c counterpart in
|
||||
// `uploadPrivate` is where the cache is actually load-bearing.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
|
||||
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
scope: 'group',
|
||||
groupId,
|
||||
fileName,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
|
||||
}
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
||||
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
//
|
||||
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||
// the chat shows nothing. The publish step goes via a dedicated OIDB
|
||||
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
|
||||
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
|
||||
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
|
||||
// caller opts out via `uploadFile=false` (treat that as "I only
|
||||
// wanted the slot allocated, hold the chat post"). Routes through
|
||||
// `this.publish` so tests can mock at the same Api boundary.
|
||||
if (uploadFile) {
|
||||
try {
|
||||
await this.publish(groupId, fileId);
|
||||
} catch (err) {
|
||||
// The bytes are already on the server and the fileId is valid —
|
||||
// fail loud but don't lose the upload result the action handler
|
||||
// committed to returning. Callers can still resolve the file by
|
||||
// id; they'll just have to re-publish it themselves.
|
||||
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|
||||
|| '';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('group file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
groupId,
|
||||
fileName,
|
||||
staged.fileSize,
|
||||
hashes.md5,
|
||||
fileId,
|
||||
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
|
||||
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
// Fail cleanly if the source changed since hashing, then stream the PUT
|
||||
// from disk. Fetch the session BEFORE opening the handle so
|
||||
// uploadHighwayHttp (the handle's owner) is the next call and always
|
||||
// closes it.
|
||||
await assertUnchanged(staged.filePath, guardStat);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
|
||||
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
//
|
||||
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||
// the chat shows nothing. The publish step goes via a dedicated OIDB
|
||||
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
|
||||
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
|
||||
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when a
|
||||
// caller only needs a valid file_id embedded elsewhere, e.g. a
|
||||
// forward-message long-msg payload. Routes through `this.publish` so
|
||||
// tests can mock at the same Api boundary.
|
||||
if (publishFile) {
|
||||
try {
|
||||
await this.publish(groupId, fileId);
|
||||
} catch (err) {
|
||||
// The bytes are already on the server and the fileId is valid —
|
||||
// fail loud but don't lose the upload result the action handler
|
||||
// committed to returning. Callers can still resolve the file by
|
||||
// id; they'll just have to re-publish it themselves.
|
||||
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
} finally {
|
||||
await staged.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async uploadPrivate(
|
||||
@@ -340,35 +388,34 @@ export class GroupFileApi {
|
||||
source: string,
|
||||
name = '',
|
||||
uploadFile = true,
|
||||
publishFile = uploadFile,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('private file is empty');
|
||||
// Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is
|
||||
// never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file
|
||||
// md510MCheckSum in the same single pass.
|
||||
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
|
||||
try {
|
||||
if (staged.fileSize === 0) throw new Error('private file is empty');
|
||||
|
||||
const targetUid = await this.ctx.resolveUserUid(userId);
|
||||
let selfUid = this.ctx.identity.selfUid;
|
||||
if (!selfUid) {
|
||||
const selfUin = toInt(this.ctx.identity.uin);
|
||||
if (selfUin > 0) {
|
||||
selfUid = await this.ctx.resolveUserUid(selfUin);
|
||||
}
|
||||
}
|
||||
if (!selfUid) throw new Error('self uid is unavailable');
|
||||
const selfUid = await resolveSelfUid(this.ctx);
|
||||
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const fileName = normalizeUploadFileName(name, staged.fileName);
|
||||
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
|
||||
const hashes = await hashFileStreaming(staged.filePath, { headLimit: MD5_HEAD_LIMIT });
|
||||
|
||||
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
|
||||
senderUid: selfUid,
|
||||
receiverUid: targetUid,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSize: staged.fileSize,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
md510MCheckSum: md5First10MB(loaded.bytes),
|
||||
md510MCheckSum: hashes.headMd5!,
|
||||
});
|
||||
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
|
||||
|
||||
@@ -386,7 +433,7 @@ export class GroupFileApi {
|
||||
scope: 'private',
|
||||
userId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
fileHash: fileHash ?? '',
|
||||
@@ -460,7 +507,7 @@ export class GroupFileApi {
|
||||
const ext = buildPrivateFileUploadExt(
|
||||
senderUin,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
staged.fileSize,
|
||||
hashes.md5,
|
||||
hashes.sha1,
|
||||
fileId,
|
||||
@@ -471,8 +518,13 @@ export class GroupFileApi {
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
// Fail cleanly if the source changed since hashing, then stream the PUT
|
||||
// from disk. Session BEFORE opening the handle so uploadHighwayHttp (the
|
||||
// handle's owner) is the next call and always closes it.
|
||||
await assertUnchanged(staged.filePath, guardStat);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
|
||||
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
|
||||
await uploadHighwayHttp(bridge, session, 95, chunkSource, hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Stage 3: publish the file as a c2c chat message. C2C files use
|
||||
@@ -481,12 +533,12 @@ export class GroupFileApi {
|
||||
// which only knows about elems[]. NapCat does the same atomic
|
||||
// upload+send dance — without it the file sits on the server and
|
||||
// the recipient sees nothing.
|
||||
if (uploadFile) {
|
||||
if (publishFile) {
|
||||
try {
|
||||
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
|
||||
fileId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileHash: fileHash ?? '',
|
||||
});
|
||||
@@ -497,6 +549,9 @@ export class GroupFileApi {
|
||||
}
|
||||
|
||||
return { fileId, fileHash };
|
||||
} finally {
|
||||
await staged.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── list (paginated loop) ───────────────
|
||||
@@ -540,6 +595,8 @@ export class GroupFileApi {
|
||||
const folder = item.folderInfo;
|
||||
const creator = toInt(folder.creatorUin);
|
||||
const cached = this.ctx.identity.findGroupMember(groupId, creator);
|
||||
const lastUploader = toInt(folder.modifierUin);
|
||||
const lastUploaderCached = this.ctx.identity.findGroupMember(groupId, lastUploader);
|
||||
folders.push({
|
||||
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
|
||||
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
|
||||
@@ -550,6 +607,12 @@ export class GroupFileApi {
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
totalFileCount: toInt(folder.totalFileCount),
|
||||
lastUploadTime: toInt(folder.modifiedTime),
|
||||
lastUploader,
|
||||
lastUploaderName: (typeof folder.modifierName === 'string' && folder.modifierName)
|
||||
|| lastUploaderCached?.card
|
||||
|| lastUploaderCached?.nickname
|
||||
|| '',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -604,9 +667,13 @@ export class GroupFileApi {
|
||||
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
|
||||
}
|
||||
|
||||
rename(groupId: number, fileId: string, parentDirectory: string, newFileName: string): Promise<void> {
|
||||
return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName });
|
||||
}
|
||||
|
||||
// ─────────────── folders ───────────────
|
||||
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<CreateGroupFolder.Result> {
|
||||
return CreateGroupFolder.invoke(this.ctx, {
|
||||
groupId, parentId: normalizeDirectory(parentId), folderName: name,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { CollectionApi } from './collection';
|
||||
import { ContactsApi } from './contacts';
|
||||
import { ExtrasApi } from './extras';
|
||||
import { FlashTransferApi } from './flash-transfer';
|
||||
import { ForwardApi } from './forward';
|
||||
import { FriendApi } from './friend';
|
||||
import { GroupAdminApi } from './group-admin';
|
||||
@@ -10,9 +12,12 @@ import { InteractionApi } from './interaction';
|
||||
import { MessageApi } from './message';
|
||||
import { MiscApi } from './misc';
|
||||
import { ProfileApi } from './profile';
|
||||
import { QzoneApi } from './qzone';
|
||||
import { WebApi } from './web';
|
||||
|
||||
export interface ApiHub {
|
||||
/** Personal QQ collections: authenticated list retrieval and pagination. */
|
||||
readonly collection: CollectionApi;
|
||||
/** Send/recall/markRead operations across c2c + group + c2c-file. */
|
||||
readonly message: MessageApi;
|
||||
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
|
||||
@@ -23,12 +28,16 @@ export interface ApiHub {
|
||||
readonly groupFile: GroupFileApi;
|
||||
/** Group photo album: list/upload/comment/like/delete + media listing. */
|
||||
readonly groupAlbum: GroupAlbumApi;
|
||||
/** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */
|
||||
readonly qzone: QzoneApi;
|
||||
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
|
||||
readonly interaction: InteractionApi;
|
||||
/** Friend roster mutations: handleRequest / delete / setRemark. */
|
||||
readonly friend: FriendApi;
|
||||
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
|
||||
readonly profile: ProfileApi;
|
||||
/** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */
|
||||
readonly flashTransfer: FlashTransferApi;
|
||||
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
|
||||
readonly forward: ForwardApi;
|
||||
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
|
||||
@@ -49,14 +58,17 @@ export interface ApiHub {
|
||||
*/
|
||||
export function buildApiHub(ctx: BridgeContext): ApiHub {
|
||||
return {
|
||||
collection: new CollectionApi(ctx),
|
||||
message: new MessageApi(ctx),
|
||||
contacts: new ContactsApi(ctx),
|
||||
groupAdmin: new GroupAdminApi(ctx),
|
||||
groupFile: new GroupFileApi(ctx),
|
||||
groupAlbum: new GroupAlbumApi(ctx),
|
||||
qzone: new QzoneApi(ctx),
|
||||
interaction: new InteractionApi(ctx),
|
||||
friend: new FriendApi(ctx),
|
||||
profile: new ProfileApi(ctx),
|
||||
flashTransfer: new FlashTransferApi(ctx),
|
||||
forward: new ForwardApi(ctx),
|
||||
misc: new MiscApi(ctx),
|
||||
extras: new ExtrasApi(ctx),
|
||||
@@ -68,6 +80,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
|
||||
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
|
||||
// signature use. Concrete instances always come from `bridge.apis.*`.
|
||||
export { ContactsApi } from './contacts';
|
||||
export { CollectionApi } from './collection';
|
||||
export { ExtrasApi } from './extras';
|
||||
export { ForwardApi } from './forward';
|
||||
export { FriendApi } from './friend';
|
||||
@@ -78,5 +91,6 @@ export { InteractionApi } from './interaction';
|
||||
export { MessageApi } from './message';
|
||||
export { MiscApi } from './misc';
|
||||
export { ProfileApi } from './profile';
|
||||
export { QzoneApi } from './qzone';
|
||||
export { FlashTransferApi, type FlashFileInfo } from './flash-transfer';
|
||||
export { WebApi } from './web';
|
||||
|
||||
@@ -4,14 +4,22 @@ import type {
|
||||
} from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import type {
|
||||
C2CReadedReportResponseItem,
|
||||
C2CRecallRequest,
|
||||
GroupReadedReportResponseItem,
|
||||
GroupRecallRequest,
|
||||
SsoReadedReportReq,
|
||||
SsoReadedReportResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { resolveSelfUid } from './shared';
|
||||
// `Bridge` is imported as a type only so we can narrow `ctx` back to
|
||||
// the concrete Bridge instance when passing it to `buildSendElems`
|
||||
// (which still takes `Bridge` because the highway upload helpers it
|
||||
@@ -23,6 +31,219 @@ import type { BridgeContext } from '../bridge-context';
|
||||
import type { Bridge, SendMessageReceipt } from '../bridge';
|
||||
|
||||
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
const READ_REPORT_CMD = 'trpc.msg.msg_svc.MsgService.SsoReadedReport';
|
||||
const READ_REPORT_BATCH_SIZE = 100;
|
||||
|
||||
const log = createLogger('Bridge.Message');
|
||||
|
||||
function decodeReadReportResponse(result: SendPacketResult, label: string): SsoReadedReportResp {
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || `${label} transport failed`);
|
||||
}
|
||||
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
|
||||
throw new Error(`${label} response is empty`);
|
||||
}
|
||||
|
||||
let response: SsoReadedReportResp;
|
||||
try {
|
||||
response = protobuf_decode<SsoReadedReportResp>(result.responseData);
|
||||
} catch (error) {
|
||||
throw new Error(`${label} response decode failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
const resultCode = response.resultCode ?? 0;
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(response.errorMessage || `${label} failed with result code ${resultCode}`);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
interface C2CReadTarget {
|
||||
userId: number;
|
||||
uid: string;
|
||||
}
|
||||
|
||||
interface ReadResponseItem {
|
||||
resultCode?: number;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
function uniqueSessionIds(ids: readonly number[], label: string): number[] {
|
||||
const result: number[] = [];
|
||||
const seen = new Set<number>();
|
||||
for (const id of ids) {
|
||||
if (!Number.isSafeInteger(id) || id <= 0) {
|
||||
throw new Error(`invalid ${label} read target ${String(id)}`);
|
||||
}
|
||||
if (!seen.has(id)) {
|
||||
seen.add(id);
|
||||
result.push(id);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function requireReadResponseItem<T extends ReadResponseItem>(
|
||||
items: readonly T[] | undefined,
|
||||
index: number,
|
||||
matches: (item: T) => boolean,
|
||||
label: string,
|
||||
): T {
|
||||
const item = items?.find(matches) ?? items?.[index];
|
||||
if (!item) throw new Error(`${label} response item is missing`);
|
||||
|
||||
const resultCode = item.resultCode ?? 0;
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(item.errorMessage || `${label} failed with result code ${resultCode}`);
|
||||
}
|
||||
if (!matches(item)) throw new Error(`${label} response identity does not match the request`);
|
||||
return item;
|
||||
}
|
||||
|
||||
function readUnsignedSequence(value: bigint | null | undefined, label: string): bigint {
|
||||
// Proton represents an omitted protobuf scalar as null; protobuf semantics
|
||||
// define that as the numeric default (zero), not a decode failure.
|
||||
if (value == null) return 0n;
|
||||
if (typeof value !== 'bigint' || value < 0n) throw new Error(`${label} is invalid`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function requirePositiveSequence(value: bigint | null | undefined, label: string): bigint {
|
||||
const sequence = readUnsignedSequence(value, label);
|
||||
if (sequence === 0n) throw new Error(`${label} is missing`);
|
||||
return sequence;
|
||||
}
|
||||
|
||||
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
|
||||
|
||||
// ── Group-history fetch guards (the server frequency-limits / kicks abusive
|
||||
// pulls, so keep each request small, bound the loop, and space the sends). ──
|
||||
const HISTORY_MAX_COUNT = 200; // hard cap on messages returned per call
|
||||
const HISTORY_CHUNK_SEQ = 30; // sequence span per server request (small packet)
|
||||
const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop
|
||||
const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends
|
||||
const HISTORY_MAX_SEQUENCE = 0xffff_ffff; // sequence fields are protobuf uint32
|
||||
|
||||
// Serialized throttle gate: chains so concurrent callers queue, and enforces
|
||||
// at least HISTORY_MIN_GAP_MS between actual sends (the first send isn't
|
||||
// penalized). Process-wide — shared across all groups AND accounts in this
|
||||
// process — so no client can make us flood the server regardless of fan-out.
|
||||
let historyLastSendAt = 0;
|
||||
let historyGate: Promise<void> = Promise.resolve();
|
||||
function throttleHistory(): Promise<void> {
|
||||
const run = historyGate.then(async () => {
|
||||
const wait = historyLastSendAt + HISTORY_MIN_GAP_MS - Date.now();
|
||||
if (wait > 0) await new Promise<void>((resolve) => setTimeout(resolve, wait));
|
||||
historyLastSendAt = Date.now();
|
||||
});
|
||||
historyGate = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared walk-back loop for group + c2c history: pull HISTORY_CHUNK_SEQ-wide
|
||||
* windows ending at `endSeq`, throttled, walking strictly backward (handling a
|
||||
* server-side short cap via the oldest sequence actually returned), dedup by
|
||||
* sequence, until `count` (capped) is gathered or the floor is reached. Returns
|
||||
* the newest `want` items oldest→newest.
|
||||
*/
|
||||
async function walkBackHistory<T extends { msgSeq: number }>(
|
||||
endSeq: number,
|
||||
count: number,
|
||||
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
|
||||
): Promise<T[]> {
|
||||
if (!(endSeq > 0)) return [];
|
||||
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
|
||||
|
||||
const collected = new Map<number, T>(); // dedup by sequence
|
||||
let curEnd = endSeq;
|
||||
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) {
|
||||
const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1);
|
||||
await throttleHistory();
|
||||
const batch = await fetchWindow(start, curEnd);
|
||||
if (batch.length > 0) {
|
||||
let minSeq = curEnd;
|
||||
for (const ev of batch) {
|
||||
collected.set(ev.msgSeq, ev);
|
||||
if (ev.msgSeq < minSeq) minSeq = ev.msgSeq;
|
||||
}
|
||||
curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps)
|
||||
} else {
|
||||
curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it
|
||||
}
|
||||
}
|
||||
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
|
||||
return all.slice(-want); // newest `want`, oldest→newest
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull sequence windows starting at `startSeq`, retaining the oldest `want`
|
||||
* messages at or after the anchor. The returned list is chronological, matching
|
||||
* the existing backward-history API shape.
|
||||
*/
|
||||
async function walkForwardHistory<T extends { msgSeq: number }>(
|
||||
startSeq: number,
|
||||
count: number,
|
||||
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
|
||||
): Promise<T[]> {
|
||||
if (!(startSeq > 0) || startSeq > HISTORY_MAX_SEQUENCE) return [];
|
||||
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
|
||||
|
||||
const collected = new Map<number, T>();
|
||||
const budget = { remaining: HISTORY_MAX_REQUESTS };
|
||||
let curStart = startSeq;
|
||||
while (budget.remaining > 0 && collected.size < want && curStart <= HISTORY_MAX_SEQUENCE) {
|
||||
const end = Math.min(HISTORY_MAX_SEQUENCE, curStart + HISTORY_CHUNK_SEQ - 1);
|
||||
const window = await fetchForwardWindow(curStart, end, budget, fetchWindow);
|
||||
for (const event of window.messages) collected.set(event.msgSeq, event);
|
||||
if (!window.complete || end === HISTORY_MAX_SEQUENCE) break;
|
||||
curStart = end + 1;
|
||||
}
|
||||
|
||||
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
|
||||
return all.slice(0, want);
|
||||
}
|
||||
|
||||
interface ForwardWindowResult<T> {
|
||||
messages: T[];
|
||||
complete: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one forward window from its lower boundary. The history service may
|
||||
* short-cap a range to its newest suffix; recursively fetch the omitted prefix
|
||||
* before exposing that suffix so callers never skip messages nearest the
|
||||
* anchor. An exhausted request budget marks the window incomplete, preventing
|
||||
* later messages from being returned ahead of an unresolved prefix.
|
||||
*/
|
||||
async function fetchForwardWindow<T extends { msgSeq: number }>(
|
||||
startSeq: number,
|
||||
endSeq: number,
|
||||
budget: { remaining: number },
|
||||
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
|
||||
): Promise<ForwardWindowResult<T>> {
|
||||
if (budget.remaining <= 0) return { messages: [], complete: false };
|
||||
|
||||
budget.remaining--;
|
||||
await throttleHistory();
|
||||
const batch = await fetchWindow(startSeq, endSeq);
|
||||
if (batch.length === 0) return { messages: [], complete: true };
|
||||
|
||||
const messages = [...new Map(batch.map((event) => [event.msgSeq, event])).values()]
|
||||
.sort((a, b) => a.msgSeq - b.msgSeq);
|
||||
for (const message of messages) {
|
||||
if (!Number.isInteger(message.msgSeq) || message.msgSeq < startSeq || message.msgSeq > endSeq) {
|
||||
throw new Error(`history response sequence is outside requested range ${startSeq}-${endSeq}`);
|
||||
}
|
||||
}
|
||||
const firstSequence = messages[0]!.msgSeq;
|
||||
if (firstSequence === startSeq) return { messages, complete: true };
|
||||
|
||||
const prefix = await fetchForwardWindow(startSeq, firstSequence - 1, budget, fetchWindow);
|
||||
if (!prefix.complete) return prefix;
|
||||
return { messages: [...prefix.messages, ...messages], complete: true };
|
||||
}
|
||||
|
||||
export class MessageApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
@@ -146,6 +367,54 @@ export class MessageApi {
|
||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reply into an existing group temp session (临时会话). Wire primitive only —
|
||||
* it does NOT gate; the caller verifies the session before calling. Routes
|
||||
* through `grpTmp` (RoutingHead field 3) with { groupUin, toUid } and a normal
|
||||
* c2c content head.
|
||||
*/
|
||||
async sendGroupTempMessage(
|
||||
userUin: number,
|
||||
groupUin: number,
|
||||
elements: MessageElement[],
|
||||
): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
const userUid = await this.ctx.resolveUserUid(userUin);
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
grpTmp: { groupUin: BigInt(groupUin), toUid: userUid },
|
||||
},
|
||||
contentHead: { type: 1, subType: 0, c2cCmd: 11 },
|
||||
messageBody: { richText: { elems: protoElems } },
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
via: 0,
|
||||
dataStatist: 0,
|
||||
ctrl: { msgFlag: Math.floor(Date.now() / 1000) },
|
||||
multiSendSeq: 0,
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(`send temp message failed: ${result.errorMessage || 'no response'}`);
|
||||
}
|
||||
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
||||
if (!response) throw new Error('failed to decode SendMessageResponse');
|
||||
if (response.result != null && response.result !== 0) {
|
||||
throw new Error(`send temp message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||
}
|
||||
const seq = response.privateSequence ?? 0;
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a c2c file as a chat message.
|
||||
*
|
||||
@@ -170,6 +439,12 @@ export class MessageApi {
|
||||
* - `subcmd: 1` — c2c file send command code
|
||||
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
|
||||
* - `expireTime` — 7 days from now (Lagrange convention)
|
||||
*
|
||||
* `FileExtra.file` alone makes the file downloadable (verified on a live
|
||||
* account). We ALSO attach `FileExtra.field6` — extra server-issued download
|
||||
* routing from a best-effort 0xE37_800 finalize that mirrors NapCat and may
|
||||
* help some receiver clients. The finalize is non-fatal: if it fails we send
|
||||
* without field6 rather than failing the send (issue #157).
|
||||
*/
|
||||
async sendC2cFile(
|
||||
userUin: number,
|
||||
@@ -179,9 +454,35 @@ export class MessageApi {
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
// Resolve our own uid — needed both for the 0xE37_800 finalize and the
|
||||
// `field6` download-routing the receiver reads.
|
||||
const selfUid = await resolveSelfUid(this.ctx);
|
||||
|
||||
// The file is already downloadable from the `NotOnlineFile` reference
|
||||
// alone — verified on a live account: a plain c2c file send (no field6)
|
||||
// downloads fine. `field6` is EXTRA server-issued download routing (from
|
||||
// the 0xE37_800 finalize) that mirrors NapCat and may help some receiver
|
||||
// clients. So fetch it BEST-EFFORT: if the finalize fails, send without
|
||||
// field6 rather than failing the whole send. (issue #157 — the finalize
|
||||
// was originally fatal, which could regress a send that would otherwise
|
||||
// succeed.)
|
||||
const fileHash = info.fileHash ?? '';
|
||||
let meta: Awaited<ReturnType<typeof FinalizeOfflineFile.invoke>> | null = null;
|
||||
try {
|
||||
meta = await FinalizeOfflineFile.invoke(this.ctx, {
|
||||
senderUid: selfUid,
|
||||
receiverUid: userUid,
|
||||
fileUuid: info.fileId,
|
||||
fileHash,
|
||||
});
|
||||
} catch (err) {
|
||||
log.warn('c2c file finalize (0xE37_800) failed, sending without field6: %s',
|
||||
err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const sevenDaysSec = 7 * 24 * 60 * 60;
|
||||
const fileExtraBytes = protobuf_encode<FileExtra>({
|
||||
const fileExtra: FileExtra = {
|
||||
file: {
|
||||
fileType: 0,
|
||||
fileUuid: info.fileId,
|
||||
@@ -191,9 +492,26 @@ export class MessageApi {
|
||||
subcmd: 1,
|
||||
dangerEvel: 0,
|
||||
expireTime: nowSec + sevenDaysSec,
|
||||
fileHash: info.fileHash ?? '',
|
||||
fileHash,
|
||||
},
|
||||
});
|
||||
};
|
||||
if (meta) {
|
||||
fileExtra.field6 = {
|
||||
field2: {
|
||||
field1: meta.field110,
|
||||
fileUuid: info.fileId,
|
||||
fileName: info.fileName,
|
||||
field6: meta.field3,
|
||||
field7: meta.field101,
|
||||
field8: meta.field100,
|
||||
timestamp1: meta.timestamp1,
|
||||
fileHash,
|
||||
selfUid,
|
||||
destUid: userUid,
|
||||
},
|
||||
};
|
||||
}
|
||||
const fileExtraBytes = protobuf_encode<FileExtra>(fileExtra);
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
@@ -284,49 +602,264 @@ export class MessageApi {
|
||||
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
|
||||
}
|
||||
|
||||
/** Mark the entire group conversation read, matching QQ NT's setMsgRead(peer). */
|
||||
async markGroupRead(groupId: number): Promise<void> {
|
||||
await this.markAllRead([groupId], []);
|
||||
}
|
||||
|
||||
/** Mark the entire private conversation read, matching QQ NT's setMsgRead(peer). */
|
||||
async markPrivateRead(userId: number): Promise<void> {
|
||||
await this.markAllRead([], [userId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`)
|
||||
* advancing the bot's last-read marker to `sequence`. Mirrors the QQ
|
||||
* NT client's own "scrolled to bottom" behaviour so subsequent
|
||||
* sync packets don't replay messages we've already processed.
|
||||
* Mark every supplied conversation read through SsoReadedReport.
|
||||
*
|
||||
* Message-head sequences are not valid C2C read sequences. The first packet
|
||||
* therefore reports zero for every conversation and reads the server's
|
||||
* current read/latest pair from the response without moving the marker
|
||||
* backwards. A second packet advances only conversations that are behind.
|
||||
* QQ NT caps each packet at 100 C2C plus 100 group entries and waits for the
|
||||
* response before sending the next page; mirror that strictly here.
|
||||
*/
|
||||
async markGroupRead(groupId: number, sequence: number): Promise<void> {
|
||||
const request = protobuf_encode<SsoReadedReportReq>({
|
||||
groupList: [
|
||||
{
|
||||
groupUin: BigInt(groupId),
|
||||
lastReadSeq: BigInt(sequence),
|
||||
},
|
||||
],
|
||||
});
|
||||
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark group message read failed');
|
||||
async markAllRead(groupIds: readonly number[], privateUserIds: readonly number[]): Promise<void> {
|
||||
const groups = uniqueSessionIds(groupIds, 'group');
|
||||
const privateUsers = uniqueSessionIds(privateUserIds, 'private');
|
||||
const c2cTargets: C2CReadTarget[] = [];
|
||||
|
||||
// Keep UID resolution sequential. A cache miss may itself use the network,
|
||||
// so Promise.all here would reintroduce the burst this method is designed
|
||||
// to avoid.
|
||||
for (const userId of privateUsers) {
|
||||
const uid = await this.ctx.resolveUserUid(userId);
|
||||
if (!uid) throw new Error(`failed to resolve uid for private read target ${userId}`);
|
||||
c2cTargets.push({ userId, uid });
|
||||
}
|
||||
|
||||
const totalBatches = Math.max(
|
||||
Math.ceil(groups.length / READ_REPORT_BATCH_SIZE),
|
||||
Math.ceil(c2cTargets.length / READ_REPORT_BATCH_SIZE),
|
||||
);
|
||||
if (totalBatches === 0) return;
|
||||
|
||||
log.debug(
|
||||
'mark-read start: groups=%d c2c=%d batches=%d',
|
||||
groups.length,
|
||||
c2cTargets.length,
|
||||
totalBatches,
|
||||
);
|
||||
|
||||
for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) {
|
||||
const start = batchIndex * READ_REPORT_BATCH_SIZE;
|
||||
await this.markReadBatch(
|
||||
groups.slice(start, start + READ_REPORT_BATCH_SIZE),
|
||||
c2cTargets.slice(start, start + READ_REPORT_BATCH_SIZE),
|
||||
batchIndex + 1,
|
||||
totalBatches,
|
||||
);
|
||||
}
|
||||
|
||||
log.debug('mark-read complete: groups=%d c2c=%d', groups.length, c2cTargets.length);
|
||||
}
|
||||
|
||||
private async sendReadReport(request: SsoReadedReportReq, label: string): Promise<SsoReadedReportResp> {
|
||||
log.debug(
|
||||
'%s send: groups=%d c2c=%d',
|
||||
label,
|
||||
request.groupList?.length ?? 0,
|
||||
request.c2cList?.length ?? 0,
|
||||
);
|
||||
const payload = protobuf_encode<SsoReadedReportReq>(request);
|
||||
const result = await this.ctx.sendRawPacket(READ_REPORT_CMD, payload);
|
||||
const response = decodeReadReportResponse(result, label);
|
||||
log.debug(
|
||||
'%s response: groups=%d c2c=%d',
|
||||
label,
|
||||
response.groupList?.length ?? 0,
|
||||
response.c2cList?.length ?? 0,
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
private groupReadResponse(
|
||||
response: SsoReadedReportResp,
|
||||
groupId: number,
|
||||
index: number,
|
||||
label: string,
|
||||
): GroupReadedReportResponseItem {
|
||||
const groupUin = BigInt(groupId);
|
||||
return requireReadResponseItem(
|
||||
response.groupList,
|
||||
index,
|
||||
item => item.groupUin === groupUin,
|
||||
`${label} group ${groupId}`,
|
||||
);
|
||||
}
|
||||
|
||||
private c2cReadResponse(
|
||||
response: SsoReadedReportResp,
|
||||
target: C2CReadTarget,
|
||||
index: number,
|
||||
label: string,
|
||||
): C2CReadedReportResponseItem {
|
||||
return requireReadResponseItem(
|
||||
response.c2cList,
|
||||
index,
|
||||
item => item.uid === target.uid,
|
||||
`${label} private user ${target.userId}`,
|
||||
);
|
||||
}
|
||||
|
||||
private async markReadBatch(
|
||||
groupIds: readonly number[],
|
||||
c2cTargets: readonly C2CReadTarget[],
|
||||
batchIndex: number,
|
||||
totalBatches: number,
|
||||
): Promise<void> {
|
||||
const batchLabel = `mark-read batch ${batchIndex}/${totalBatches}`;
|
||||
const probe = await this.sendReadReport({
|
||||
groupList: groupIds.map(groupId => ({ groupUin: BigInt(groupId), lastReadSeq: 0n })),
|
||||
c2cList: c2cTargets.map(target => ({ uid: target.uid, lastReadTime: 0n, lastReadSeq: 0n })),
|
||||
}, `${batchLabel} probe`);
|
||||
|
||||
const groupList: NonNullable<SsoReadedReportReq['groupList']> = [];
|
||||
for (let i = 0; i < groupIds.length; i++) {
|
||||
const groupId = groupIds[i]!;
|
||||
const item = this.groupReadResponse(probe, groupId, i, `${batchLabel} probe`);
|
||||
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} group ${groupId} read sequence`);
|
||||
const latestSeq = readUnsignedSequence(item.latestSeq, `${batchLabel} group ${groupId} latest sequence`);
|
||||
if (latestSeq < readSeq) {
|
||||
throw new Error(`${batchLabel} group ${groupId} latest sequence ${latestSeq} is before read sequence ${readSeq}`);
|
||||
}
|
||||
if (latestSeq > readSeq) groupList.push({ groupUin: BigInt(groupId), lastReadSeq: latestSeq });
|
||||
}
|
||||
|
||||
const c2cList: NonNullable<SsoReadedReportReq['c2cList']> = [];
|
||||
const c2cConfirmTargets: C2CReadTarget[] = [];
|
||||
for (let i = 0; i < c2cTargets.length; i++) {
|
||||
const target = c2cTargets[i]!;
|
||||
const item = this.c2cReadResponse(probe, target, i, `${batchLabel} probe`);
|
||||
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} private user ${target.userId} read sequence`);
|
||||
const latestSeq = readUnsignedSequence(item.latestSeq, `${batchLabel} private user ${target.userId} latest sequence`);
|
||||
if (latestSeq < readSeq) {
|
||||
throw new Error(
|
||||
`${batchLabel} private user ${target.userId} latest sequence ${latestSeq} is before read sequence ${readSeq}`,
|
||||
);
|
||||
}
|
||||
if (latestSeq > readSeq) {
|
||||
const lastMsgTime = requirePositiveSequence(
|
||||
item.lastMsgTime,
|
||||
`${batchLabel} private user ${target.userId} last message time`,
|
||||
);
|
||||
c2cList.push({ uid: target.uid, lastReadTime: lastMsgTime, lastReadSeq: latestSeq });
|
||||
c2cConfirmTargets.push(target);
|
||||
}
|
||||
}
|
||||
|
||||
if (groupList.length === 0 && c2cList.length === 0) {
|
||||
log.debug('%s already current', batchLabel);
|
||||
return;
|
||||
}
|
||||
|
||||
const confirm = await this.sendReadReport({ groupList, c2cList }, `${batchLabel} confirm`);
|
||||
for (let i = 0; i < groupList.length; i++) {
|
||||
const requested = groupList[i]!;
|
||||
const groupId = Number(requested.groupUin);
|
||||
const item = this.groupReadResponse(confirm, groupId, i, `${batchLabel} confirm`);
|
||||
const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} group ${groupId} confirmed read sequence`);
|
||||
if (readSeq < (requested.lastReadSeq ?? 0n)) {
|
||||
throw new Error(
|
||||
`${batchLabel} group ${groupId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < c2cList.length; i++) {
|
||||
const requested = c2cList[i]!;
|
||||
const target = c2cConfirmTargets[i]!;
|
||||
const item = this.c2cReadResponse(confirm, target, i, `${batchLabel} confirm`);
|
||||
const readSeq = readUnsignedSequence(
|
||||
item.readSeq,
|
||||
`${batchLabel} private user ${target.userId} confirmed read sequence`,
|
||||
);
|
||||
if (readSeq < (requested.lastReadSeq ?? 0n)) {
|
||||
throw new Error(
|
||||
`${batchLabel} private user ${target.userId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a c2c read-report. Same wire-cmd as the group variant but
|
||||
* keyed by friend uid (resolved from uin via IdentityService).
|
||||
* `lastReadTime` defaults to "now" — matches the QQ NT client
|
||||
* which also uses wall-clock seconds rather than the read-message
|
||||
* timestamp.
|
||||
* Fetch real group history from the server (`SsoGetGroupMsg`), including the
|
||||
* anchor and walking backward or forward in small windows. Rate-limited and
|
||||
* capped so a hammering client cannot flood the server. Returns decoded
|
||||
* `group_message` events oldest→newest regardless of query direction.
|
||||
*/
|
||||
async markPrivateRead(userId: number, sequence: number): Promise<void> {
|
||||
const uid = await this.ctx.resolveUserUid(userId);
|
||||
const request = protobuf_encode<SsoReadedReportReq>({
|
||||
c2cList: [
|
||||
{
|
||||
uid,
|
||||
lastReadTime: BigInt(Math.floor(Date.now() / 1000)),
|
||||
lastReadSeq: BigInt(sequence),
|
||||
},
|
||||
],
|
||||
});
|
||||
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark private message read failed');
|
||||
async getGroupHistory(
|
||||
groupUin: number,
|
||||
anchorSeq: number,
|
||||
count: number,
|
||||
selfUin = 0,
|
||||
reverseOrder = true,
|
||||
): Promise<GroupMessage[]> {
|
||||
if (!(groupUin > 0)) return [];
|
||||
const fetchWindow = (start: number, end: number) =>
|
||||
fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end);
|
||||
return reverseOrder
|
||||
? walkBackHistory(anchorSeq, count, fetchWindow)
|
||||
: walkForwardHistory(anchorSeq, count, fetchWindow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch real private history from the server (`SsoGetC2cMsg`), including the
|
||||
* anchor in the requested direction. It shares the group variant's throttle
|
||||
* and data-volume guards. Returns decoded events oldest→newest.
|
||||
*/
|
||||
async getC2cHistory(
|
||||
friendUid: string,
|
||||
anchorSeq: number,
|
||||
count: number,
|
||||
selfUin = 0,
|
||||
reverseOrder = true,
|
||||
): Promise<FriendMessage[]> {
|
||||
if (!friendUid) return [];
|
||||
const fetchWindow = (start: number, end: number) =>
|
||||
fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end);
|
||||
return reverseOrder
|
||||
? walkBackHistory(anchorSeq, count, fetchWindow)
|
||||
: walkForwardHistory(anchorSeq, count, fetchWindow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single group message by its exact sequence — `SsoGetGroupMsg` over a
|
||||
* 1-wide `[seq, seq]` range, through the shared history throttle gate. Used to
|
||||
* back-fill a replied-to message the local store never saw. Returns the
|
||||
* matching `group_message`, or null if absent / on error.
|
||||
*/
|
||||
async getGroupMessageBySeq(groupUin: number, seq: number, selfUin = 0): Promise<GroupMessage | null> {
|
||||
if (!(groupUin > 0) || !(seq > 0)) return null;
|
||||
await throttleHistory();
|
||||
try {
|
||||
const batch = await fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, seq, seq);
|
||||
return batch.find((m) => m.msgSeq === seq) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single c2c message by its exact sequence — `SsoGetC2cMsg` over a
|
||||
* 1-wide `[seq, seq]` range, through the same throttle gate. `friendUid` is the
|
||||
* conversation peer. Returns the matching `friend_message`, or null.
|
||||
*/
|
||||
async getC2cMessageBySeq(friendUid: string, seq: number, selfUin = 0): Promise<FriendMessage | null> {
|
||||
if (!friendUid || !(seq > 0)) return null;
|
||||
await throttleHistory();
|
||||
try {
|
||||
const batch = await fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, seq, seq);
|
||||
return batch.find((m) => m.msgSeq === seq) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import type { BridgeContext } from '../bridge-context';
|
||||
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
|
||||
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
|
||||
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
|
||||
import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key';
|
||||
import { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
@@ -17,6 +19,10 @@ export class MiscApi {
|
||||
return TranslateEnToZh.invoke(this.ctx, { words });
|
||||
}
|
||||
|
||||
ocrImage(imageUrl: string): Promise<OcrResult> {
|
||||
return ImageOcr.invoke(this.ctx, { imageUrl });
|
||||
}
|
||||
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
@@ -75,4 +81,15 @@ export class MiscApi {
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
return SendGroupSign.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
async getDecryptKey(dbSalt: string): Promise<string> {
|
||||
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
|
||||
}
|
||||
if (!result.dbKey) {
|
||||
throw new Error('Decrypt key is empty');
|
||||
}
|
||||
return result.dbKey;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,12 @@ import type {
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
|
||||
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
|
||||
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
|
||||
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
|
||||
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
|
||||
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
|
||||
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
@@ -88,7 +93,7 @@ export class ProfileApi {
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
|
||||
await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -115,7 +120,7 @@ export class ProfileApi {
|
||||
field5: 3,
|
||||
field6: 1,
|
||||
});
|
||||
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
|
||||
await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra);
|
||||
}
|
||||
|
||||
// ─────────────── queries on me / my contacts ───────────────
|
||||
@@ -147,4 +152,73 @@ export class ProfileApi {
|
||||
const faceIds = resp.item?.faceIds || [];
|
||||
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
|
||||
}
|
||||
|
||||
/** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */
|
||||
deleteCustomFace(emojiId: string): Promise<void> {
|
||||
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加收藏表情(custom face)。imageSource 支持 file:///、base64://、http(s)://
|
||||
* (复用 highway utils 的 loadBinarySource)。返回新 emoji_id。
|
||||
*/
|
||||
async addCustomFace(imageSource: string): Promise<string> {
|
||||
const { bytes } = await loadBinarySource(imageSource, 'custom-face');
|
||||
return AddCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, imageBytes: bytes });
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的
|
||||
* URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串
|
||||
* 则清空备注。
|
||||
*/
|
||||
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
|
||||
return ModifyCustomFace.invoke(this.ctx, {
|
||||
emojiId,
|
||||
md5: md5FromEmojiId(emojiId),
|
||||
desc,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 收藏表情(custom face)移到最前。QQ 客户端只有"移动到最前",协议层
|
||||
* (0x902f 的 f3=1)也只支持最前,不支持移到其他位置。两步流程:先 0x902f
|
||||
* 移动指令,再 0x902e opType=2 上传新顺序(fetch 当前列表把目标挪到第一)。
|
||||
* 两步都发才生效。
|
||||
*/
|
||||
async moveCustomFaceToFront(emojiId: string): Promise<void> {
|
||||
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
|
||||
const urls = await this.fetchCustomFace(1000);
|
||||
const ids = urls.map((url) => {
|
||||
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
|
||||
return m ? m[1] : '';
|
||||
}).filter(Boolean);
|
||||
const idx = ids.indexOf(emojiId);
|
||||
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
|
||||
// 新顺序:目标挪到第一,其余按原顺序
|
||||
const reordered = ids.slice();
|
||||
reordered.splice(idx, 1);
|
||||
reordered.unshift(emojiId);
|
||||
// 2. 0x902f 移动指令(f3=1 = 移到最前)
|
||||
await OrderCustomFace.invoke(this.ctx, { emojiId, position: 1 });
|
||||
// 3. 0x902e opType=2 上传新顺序
|
||||
await MoveCustomFace.invoke(this.ctx, {
|
||||
emojis: reordered.map((id) => ({ emojiId: id, md5: md5FromEmojiId(id) })),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 emoji_id `<uin>_0_0_0_<MD5>_0_0` 提取中段 32 位大写 hex MD5。
|
||||
* 格式固定(fetch/delete/move 共用),取第 5 段。解析失败抛错——比静默
|
||||
* 传空串让服务端拒绝更早定位问题。
|
||||
*/
|
||||
function md5FromEmojiId(emojiId: string): string {
|
||||
const parts = emojiId.split('_');
|
||||
// 期望形如 `<uin>_0_0_0_<md5>_0_0`,共 7 段,md5 在 index 4。
|
||||
const md5 = parts[4];
|
||||
if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) {
|
||||
throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`);
|
||||
}
|
||||
return md5.toUpperCase();
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import {
|
||||
commentQzoneMsg,
|
||||
deleteQzoneMsg,
|
||||
getQzoneFeeds,
|
||||
getQzoneMsgList,
|
||||
publishQzoneMsg,
|
||||
setQzoneBlack,
|
||||
setQzoneLike,
|
||||
updateQzoneMsgRight,
|
||||
uploadQzoneImageFromSource,
|
||||
type QzoneCommentResult,
|
||||
type QzoneFeedsResult,
|
||||
type QzoneMsgListResult,
|
||||
type QzonePublishResult,
|
||||
type QzoneUpdateRightResult,
|
||||
type QzoneUploadImageResult,
|
||||
} from '@snowluma/protocol/web/qzone';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
/**
|
||||
* Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes,
|
||||
* comments, image upload — all over the cookie-backed qzone.qq.com CGIs,
|
||||
* reusing the same `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi.
|
||||
* Distinct from the group-album surface, which lives on GroupAlbumApi.
|
||||
*/
|
||||
export class QzoneApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
/**
|
||||
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
|
||||
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
|
||||
*/
|
||||
async getMsgList(targetUin?: number, pos = 0, num = 20): Promise<QzoneMsgListResult> {
|
||||
const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneMsgList(cookieObject, uin, pos, num);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
|
||||
* 始终以机器人自己的身份拉取好友动态。
|
||||
*/
|
||||
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从来源上传图片到 QQ 空间。
|
||||
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
|
||||
*/
|
||||
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
|
||||
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
|
||||
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
|
||||
* `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。
|
||||
*/
|
||||
async publish(
|
||||
content: string,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
ugcRight = 1,
|
||||
targetUins?: string,
|
||||
): Promise<QzonePublishResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins);
|
||||
}
|
||||
|
||||
/** 删除机器人自己空间的一条说说(按 tid)。 */
|
||||
async delete(tid: string): Promise<void> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
|
||||
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
|
||||
*/
|
||||
async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise<QzoneUpdateRightResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
|
||||
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
|
||||
*/
|
||||
async like(tid: string, targetUin: number | undefined, like: boolean, abstime = 0): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneLike(cookieObject, selfUin, owner, tid, like, abstime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
|
||||
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
|
||||
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
|
||||
* (从 uploadImageFromSource 的 url 字段获取)。
|
||||
*/
|
||||
async comment(
|
||||
tid: string,
|
||||
content: string,
|
||||
targetUin: number | undefined,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
): Promise<QzoneCommentResult> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。
|
||||
* `ban=true` 拉黑,`ban=false` 解除拉黑。
|
||||
*/
|
||||
async setBlack(targetUin: number, ban: boolean): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { Bridge } from '../bridge';
|
||||
|
||||
export function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'bigint') {
|
||||
@@ -26,22 +24,10 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
|
||||
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the bot's own UID. Cached on Identity once warmup populates
|
||||
* `selfProfile`; forward/profile actions need this fast path before
|
||||
* warmup completes.
|
||||
*/
|
||||
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
|
||||
let selfUid = bridge.identity.selfUid;
|
||||
if (selfUid) return selfUid;
|
||||
|
||||
const selfUin = toInt(bridge.identity.uin);
|
||||
if (selfUin <= 0) {
|
||||
throw new Error('self uid is unavailable');
|
||||
}
|
||||
selfUid = await bridge.resolveUserUid(selfUin);
|
||||
return selfUid;
|
||||
}
|
||||
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
|
||||
// (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing
|
||||
// `resolveSelfUid(bridge)` call sites in this package keep importing from shared.
|
||||
export { resolveSelfUid } from '@snowluma/protocol/self-uid';
|
||||
|
||||
/**
|
||||
* Index describing a server-side rich-media object (image / video /
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
|
||||
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
|
||||
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
|
||||
import {
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
GROUP_NOTICE_TYPE_NORMAL,
|
||||
getGroupNoticeWebAPI,
|
||||
setGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
type SetNoticeRetSuccess,
|
||||
type WebApiGroupNoticeCollection,
|
||||
type WebApiGroupNoticeFeed,
|
||||
type WebApiGroupNoticeRet,
|
||||
} from '@snowluma/protocol/web/group-notice';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
import type { Bridge } from '../bridge';
|
||||
@@ -40,6 +47,113 @@ export interface WebNoticeInfo {
|
||||
};
|
||||
settings: import('@snowluma/common/json').JsonValue;
|
||||
read_num: number;
|
||||
/** Server response type. Regular notices are commonly returned as 6. */
|
||||
type: number;
|
||||
pinned: number;
|
||||
send_to_new_members: boolean;
|
||||
}
|
||||
|
||||
export interface SendNoticeOptions {
|
||||
image?: string;
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
sendToNewMembers?: boolean;
|
||||
isShowEditCard?: number;
|
||||
tipWindowType?: number;
|
||||
confirmRequired?: number;
|
||||
}
|
||||
|
||||
function finiteNumber(value: unknown, field: string): number {
|
||||
const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN;
|
||||
if (!Number.isFinite(parsed)) {
|
||||
throw new Error(`invalid group notice response: ${field} must be a finite number`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function collectionValues(
|
||||
collection: WebApiGroupNoticeCollection | undefined,
|
||||
field: 'feeds' | 'inst',
|
||||
): WebApiGroupNoticeFeed[] {
|
||||
if (collection === undefined) return [];
|
||||
if (Array.isArray(collection)) return collection;
|
||||
if (collection === null || typeof collection !== 'object') {
|
||||
throw new Error(`invalid group notice response: ${field} must be an array or object`);
|
||||
}
|
||||
return Object.values(collection);
|
||||
}
|
||||
|
||||
function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boolean): WebNoticeInfo {
|
||||
if (!feed || typeof feed !== 'object') {
|
||||
throw new Error('invalid group notice response: feed must be an object');
|
||||
}
|
||||
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
|
||||
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
|
||||
}
|
||||
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
|
||||
}
|
||||
if (feed.settings === undefined) {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
|
||||
}
|
||||
|
||||
const image = (feed.msg.pics ?? []).map((pic, index) => {
|
||||
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} image ${index} is malformed`);
|
||||
}
|
||||
return {
|
||||
id: pic.id,
|
||||
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
|
||||
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
|
||||
};
|
||||
});
|
||||
const responseType = feed.type === undefined
|
||||
? sendToNewMembers ? GROUP_NOTICE_TYPE_NEW_MEMBERS : GROUP_NOTICE_TYPE_NORMAL
|
||||
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
|
||||
|
||||
return {
|
||||
notice_id: feed.fid,
|
||||
sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`),
|
||||
publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`),
|
||||
message: {
|
||||
text: feed.msg.text,
|
||||
image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
|
||||
type: responseType,
|
||||
pinned: feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
|
||||
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
};
|
||||
}
|
||||
|
||||
/** Merge QQ's regular (`feeds`) and new-member (`inst`) announcement lists. */
|
||||
export function mapGroupNoticeResponse(ret: WebApiGroupNoticeRet): WebNoticeInfo[] {
|
||||
if (ret.ec !== 0) {
|
||||
throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`);
|
||||
}
|
||||
|
||||
const notices: WebNoticeInfo[] = [];
|
||||
const indexByNoticeId = new Map<string, number>();
|
||||
const append = (collection: WebApiGroupNoticeCollection | undefined, sendToNewMembers: boolean, field: 'feeds' | 'inst') => {
|
||||
for (const feed of collectionValues(collection, field)) {
|
||||
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
|
||||
const existingIndex = indexByNoticeId.get(mapped.notice_id);
|
||||
if (existingIndex === undefined) {
|
||||
indexByNoticeId.set(mapped.notice_id, notices.length);
|
||||
notices.push(mapped);
|
||||
} else if (sendToNewMembers) {
|
||||
// If QQ returns the same item in both collections, `inst` is the
|
||||
// authoritative signal that it targets new members.
|
||||
notices[existingIndex] = mapped;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
append(ret.feeds, false, 'feeds');
|
||||
append(ret.inst, true, 'inst');
|
||||
return notices;
|
||||
}
|
||||
|
||||
// ─────────────── private helpers (cookie acquisition) ───────────────
|
||||
@@ -226,17 +340,22 @@ export class WebApi {
|
||||
return honorInfo;
|
||||
}
|
||||
|
||||
// ─────────────── group sign-in (打卡) ───────────────
|
||||
|
||||
/** Today's group sign-in list via qun.qq.com. [] when the group has no
|
||||
* sign-ins; THROWS on transport / auth failure (caller maps to failed). */
|
||||
async getSignedList(groupId: number): Promise<SignedListMember[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return getDaySignedListWebAPI(cookieObject, groupId.toString(), bridge.identity.uin.toString());
|
||||
}
|
||||
|
||||
// ─────────────── group notice ───────────────
|
||||
|
||||
async sendNotice(
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: {
|
||||
image?: string; // local path, http URL, or undefined (text-only)
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
confirm_required?: number;
|
||||
},
|
||||
options?: SendNoticeOptions,
|
||||
): Promise<SetNoticeRetSuccess> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
@@ -247,41 +366,37 @@ export class WebApi {
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
let imageBuffer: Buffer;
|
||||
|
||||
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
|
||||
const response = await fetch(options.image);
|
||||
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
|
||||
imageBuffer = Buffer.from(await response.arrayBuffer());
|
||||
} else {
|
||||
const { readFileSync } = await import('fs');
|
||||
imageBuffer = readFileSync(options.image);
|
||||
}
|
||||
// Route through loadBinarySource so the group-notice image download
|
||||
// gets the same browser-UA + Referer-retry hardening as every other
|
||||
// media fetch — and http/file/base64 source handling for free.
|
||||
const loaded = await loadBinarySource(options.image, 'group-notice image');
|
||||
const imageBuffer = Buffer.from(loaded.bytes);
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
if (picInfo) {
|
||||
picId = picInfo.id;
|
||||
imgWidth = picInfo.width;
|
||||
imgHeight = picInfo.height;
|
||||
}
|
||||
picId = picInfo.id;
|
||||
imgWidth = picInfo.width;
|
||||
imgHeight = picInfo.height;
|
||||
}
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(
|
||||
cookieObject,
|
||||
groupCode,
|
||||
content,
|
||||
options?.pinned ?? 0,
|
||||
options?.type ?? 1,
|
||||
1,
|
||||
1,
|
||||
options?.confirm_required ?? 1,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
{
|
||||
pinned: options?.pinned,
|
||||
type: options?.type,
|
||||
sendToNewMembers: options?.sendToNewMembers,
|
||||
isShowEditCard: options?.isShowEditCard,
|
||||
tipWindowType: options?.tipWindowType,
|
||||
confirmRequired: options?.confirmRequired,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
},
|
||||
);
|
||||
|
||||
if (!ret || ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
|
||||
if (ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
|
||||
}
|
||||
|
||||
return ret;
|
||||
@@ -293,39 +408,7 @@ export class WebApi {
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
||||
if (!ret) {
|
||||
throw new Error('获取公告失败');
|
||||
}
|
||||
|
||||
const retNotices: WebNoticeInfo[] = [];
|
||||
|
||||
if (ret.feeds) {
|
||||
for (const key in ret.feeds) {
|
||||
const feed = ret.feeds[key];
|
||||
if (!feed) continue;
|
||||
|
||||
const image = feed.msg?.pics?.map((pic) => ({
|
||||
id: pic.id,
|
||||
height: pic.h,
|
||||
width: pic.w,
|
||||
})) || [];
|
||||
|
||||
retNotices.push({
|
||||
notice_id: feed.fid,
|
||||
sender_id: feed.u,
|
||||
publish_time: feed.pubt,
|
||||
message: {
|
||||
text: feed.msg?.text || '',
|
||||
image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: feed.read_num,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return retNotices;
|
||||
return mapGroupNoticeResponse(ret);
|
||||
}
|
||||
|
||||
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
|
||||
export interface BridgeInterface extends BridgeContext {
|
||||
readonly activePid: number | null;
|
||||
/** False only when every attached QQ process is confirmed stale.
|
||||
* An unarmed watchdog remains true for compatibility. */
|
||||
readonly receiveHealthy: boolean;
|
||||
/** Latest device snapshot observed on this Bridge lifecycle. `null` means
|
||||
* QQ has not emitted its cache notification since SnowLuma attached. */
|
||||
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { MSG_PUSH_CMD, parseMsgPush, SysMsgDedup } from '@snowluma/protocol/msg-push';
|
||||
import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
|
||||
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import {
|
||||
AiVoiceChatType,
|
||||
@@ -12,18 +15,28 @@ import {
|
||||
} from './apis/extras';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
private pids_ = new Set<number>();
|
||||
private readonly receiveHealthByPid_ = new Map<number, boolean>();
|
||||
/** Packet senders keyed by their owning QQ process. Keeping the sender and
|
||||
* PID together is what makes disconnect fallback deterministic: a sender
|
||||
* can never outlive the PID that supplied it. */
|
||||
private readonly packetClientsByPid_ = new Map<number, PacketSender>();
|
||||
readonly events = new BridgeEventBus();
|
||||
readonly apis: ApiHub;
|
||||
private readonly pipeline: IncomingPacketPipeline;
|
||||
private packetClient_: PacketSender | null = null;
|
||||
private packetClientPid_: number | null = null;
|
||||
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
||||
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
|
||||
private readonly sysMsgDedup_ = new SysMsgDedup();
|
||||
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
|
||||
|
||||
constructor(identity: IdentityService) {
|
||||
this.identity = identity;
|
||||
@@ -47,29 +60,76 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
},
|
||||
resolveGroupJoinRequest: async (groupId, uid, subType) => {
|
||||
try {
|
||||
const requests = await this.apis.contacts.fetchGroupRequests();
|
||||
const match = requests.find(r => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
|
||||
});
|
||||
if (!match) return null;
|
||||
return { comment: match.comment, sequence: match.sequence };
|
||||
} catch {
|
||||
return null;
|
||||
const [main, filtered] = await Promise.allSettled([
|
||||
this.apis.contacts.fetchGroupRequests(false),
|
||||
this.apis.contacts.fetchGroupRequests(true),
|
||||
]);
|
||||
if (main.status === 'rejected') {
|
||||
log.warn('group-request enrichment main inbox failed: group=%d uid=%s err=%s',
|
||||
groupId, uid, main.reason instanceof Error ? main.reason.message : String(main.reason));
|
||||
}
|
||||
if (filtered.status === 'rejected') {
|
||||
log.warn('group-request enrichment filtered inbox failed: group=%d uid=%s err=%s',
|
||||
groupId, uid, filtered.reason instanceof Error ? filtered.reason.message : String(filtered.reason));
|
||||
}
|
||||
if (main.status === 'rejected' && filtered.status === 'rejected') {
|
||||
throw new Error('failed to fetch group requests from both inboxes');
|
||||
}
|
||||
const requests = [
|
||||
...(main.status === 'fulfilled' ? main.value : []),
|
||||
...(filtered.status === 'fulfilled' ? filtered.value : []),
|
||||
];
|
||||
return requests.find(r => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
|
||||
}) ?? null;
|
||||
},
|
||||
resolveGroupInviteCardSequence: async (groupId) => {
|
||||
const deadline = Date.now() + 1_000;
|
||||
do {
|
||||
const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId);
|
||||
if (sequence) return sequence;
|
||||
await new Promise(resolve => setTimeout(resolve, 25));
|
||||
} while (Date.now() < deadline);
|
||||
return null;
|
||||
},
|
||||
});
|
||||
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_));
|
||||
this.pipeline.registerCmd(KICK_NT_CMD, parseKickNT);
|
||||
this.events.on('online_devices_changed', (event) => {
|
||||
const snapshot = event.devices.map((device) => Object.freeze({ ...device }));
|
||||
this.onlineClients_ = Object.freeze(snapshot);
|
||||
log.debug('online-device snapshot updated: uin=%s clients=%d types=%s',
|
||||
this.identity.uin, snapshot.length,
|
||||
snapshot.map((device) => device.clientType).join(','));
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.identity.close();
|
||||
this.events.clear();
|
||||
this.pids_.clear();
|
||||
this.receiveHealthByPid_.clear();
|
||||
this.packetClientsByPid_.clear();
|
||||
this.packetClient_ = null;
|
||||
this.packetClientPid_ = null;
|
||||
this.onlineClients_ = null;
|
||||
try {
|
||||
this.identity.close();
|
||||
} finally {
|
||||
// A close failure must remain visible to the caller, but must not leave
|
||||
// event subscribers attached to a Bridge that Manager already removed.
|
||||
this.events.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Legacy two-step setter retained for external compatibility. It assigns
|
||||
* the sender to the most recently attached PID when one exists. New
|
||||
* BridgeManager code uses bindPid() for an atomic transition. */
|
||||
setPacketClient(client: PacketSender): void {
|
||||
this.packetClient_ = client;
|
||||
const pids = [...this.pids_];
|
||||
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
|
||||
this.packetClientPid_ = pid;
|
||||
if (pid !== null) this.packetClientsByPid_.set(pid, client);
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
@@ -80,17 +140,80 @@ export class Bridge implements BridgeInterface {
|
||||
return this.pipeline.handlesCmd(cmd);
|
||||
}
|
||||
|
||||
/** Attach a process without a sender. Retained for compatibility; the
|
||||
* manager uses bindPid() for the atomic PID+sender transition. Re-attaching
|
||||
* deliberately refreshes recency. */
|
||||
attachPid(pid: number): void {
|
||||
this.pids_.delete(pid);
|
||||
this.pids_.add(pid);
|
||||
// A fresh/rebound login starts UNKNOWN-but-compatible. The receive
|
||||
// watchdog only flips this false after observing QQ's own heartbeat and
|
||||
// then missing the full stale + confirmation window.
|
||||
this.receiveHealthByPid_.set(pid, true);
|
||||
}
|
||||
|
||||
/** Atomically attach a process and make its sender the active sender.
|
||||
* Set insertion order is the recency order used for fallback. */
|
||||
bindPid(pid: number, client: PacketSender): void {
|
||||
this.attachPid(pid);
|
||||
this.packetClientsByPid_.set(pid, client);
|
||||
this.packetClient_ = client;
|
||||
this.packetClientPid_ = pid;
|
||||
}
|
||||
|
||||
/** @internal BridgeManager lookup used when an incoming packet is the first
|
||||
* observation that a live PID changed UIN. */
|
||||
packetClientForPid(pid: number): PacketSender | null {
|
||||
return this.packetClientsByPid_.get(pid) ?? null;
|
||||
}
|
||||
|
||||
detachPid(pid: number): void {
|
||||
this.pids_.delete(pid);
|
||||
this.receiveHealthByPid_.delete(pid);
|
||||
this.packetClientsByPid_.delete(pid);
|
||||
|
||||
if (this.packetClientPid_ !== pid) {
|
||||
// An unscoped legacy sender cannot be associated with a particular PID.
|
||||
// It is safe to retain while another PID exists, but never after the
|
||||
// Bridge becomes empty.
|
||||
if (this.pids_.size === 0) {
|
||||
this.packetClient_ = null;
|
||||
this.packetClientPid_ = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.selectFallbackPacketClient(pid);
|
||||
}
|
||||
hasPid(pid: number): boolean { return this.pids_.has(pid); }
|
||||
get empty(): boolean { return this.pids_.size === 0; }
|
||||
get activePid(): number | null {
|
||||
for (const pid of this.pids_) return pid;
|
||||
return null;
|
||||
if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) {
|
||||
return this.packetClientPid_;
|
||||
}
|
||||
const pids = [...this.pids_];
|
||||
return pids.length > 0 ? pids[pids.length - 1]! : null;
|
||||
}
|
||||
get receiveHealthy(): boolean {
|
||||
for (const pid of this.pids_) {
|
||||
const healthy = this.receiveHealthByPid_.get(pid);
|
||||
if (healthy === undefined) {
|
||||
const message = `Bridge receive-health invariant violated: PID=${pid} has no health state`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
if (healthy) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
setPidReceiveHealthy(pid: number, healthy: boolean): void {
|
||||
if (!this.pids_.has(pid)) {
|
||||
throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`);
|
||||
}
|
||||
this.receiveHealthByPid_.set(pid, healthy);
|
||||
}
|
||||
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
|
||||
return this.onlineClients_;
|
||||
}
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
this.pipeline.process(pkt);
|
||||
@@ -129,12 +252,59 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
|
||||
return {
|
||||
success: false, gotResponse: false, errorCode: -1,
|
||||
errorMessage: 'no packet sender attached', responseData: null,
|
||||
};
|
||||
}
|
||||
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const startedAt = Date.now();
|
||||
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const respLen = result.responseData ? result.responseData.length : 0;
|
||||
if (!result.success || result.errorCode !== 0) {
|
||||
// QQ-side rejection or transport failure — the usual root cause when an
|
||||
// action misbehaves. Warn (persisted) with cmd + code so a user's log
|
||||
// shows exactly where the chain broke.
|
||||
log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
|
||||
serviceCmd, result.errorCode, result.gotResponse,
|
||||
result.errorMessage ?? '', this.identity.uin, body.length, elapsed);
|
||||
} else {
|
||||
// Happy path — memory-only trace so the full chain shows under the
|
||||
// request's [req#N] when debugging, without flooding disk.
|
||||
log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private selectFallbackPacketClient(detachedPid: number): void {
|
||||
const pids = [...this.pids_];
|
||||
for (let index = pids.length - 1; index >= 0; index -= 1) {
|
||||
const fallbackPid = pids[index]!;
|
||||
const fallback = this.packetClientsByPid_.get(fallbackPid);
|
||||
if (!fallback) continue;
|
||||
|
||||
this.packetClient_ = fallback;
|
||||
this.packetClientPid_ = fallbackPid;
|
||||
log.debug(
|
||||
'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d',
|
||||
this.identity.uin,
|
||||
detachedPid,
|
||||
fallbackPid,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.packetClient_ = null;
|
||||
this.packetClientPid_ = null;
|
||||
if (this.pids_.size > 0) {
|
||||
log.warn(
|
||||
'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d',
|
||||
this.identity.uin,
|
||||
detachedPid,
|
||||
this.pids_.size,
|
||||
);
|
||||
}
|
||||
}
|
||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
@@ -180,4 +350,3 @@ export interface ClientKeyInfo {
|
||||
}
|
||||
export { AiVoiceChatType };
|
||||
export type { AiVoiceCategory, StrangerStatus };
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { Bridge } from './bridge';
|
||||
|
||||
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string) => void;
|
||||
export type SessionClosedCallback = (uin: string, bridge: Bridge) => void;
|
||||
|
||||
interface QQSession {
|
||||
bridge: Bridge;
|
||||
@@ -16,83 +17,184 @@ const log = createLogger('Bridge');
|
||||
export class BridgeManager {
|
||||
private sessions_ = new Map<string, QQSession>();
|
||||
private pidToUin_ = new Map<number, string>();
|
||||
private pidPacketClients_ = new Map<number, PacketSender>();
|
||||
|
||||
private onSessionStarted_: SessionStartedCallback | null = null;
|
||||
private onSessionClosed_: SessionClosedCallback | null = null;
|
||||
private sessionStartedListeners_: SessionStartedCallback[] = [];
|
||||
private sessionClosedListeners_: SessionClosedCallback[] = [];
|
||||
|
||||
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
|
||||
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
|
||||
/** Additive subscription: every observer (OneBotManager, NotificationManager,
|
||||
* …) receives every session edge. (Was a single `set*Callback` setter —
|
||||
* converted to N listeners so a second observer can't clobber the first.)
|
||||
* The close edge now carries the bridge too, since callers read the last
|
||||
* nickname before it is disposed. */
|
||||
addSessionStartedListener(cb: SessionStartedCallback): void {
|
||||
this.sessionStartedListeners_.push(cb);
|
||||
}
|
||||
addSessionClosedListener(cb: SessionClosedCallback): void {
|
||||
this.sessionClosedListeners_.push(cb);
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
this.pidPacketClients_.delete(pid);
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return;
|
||||
|
||||
this.pidToUin_.delete(pid);
|
||||
const session = this.sessions_.get(uin);
|
||||
if (!session) return;
|
||||
|
||||
session.bridge.detachPid(pid);
|
||||
if (session.bridge.empty) {
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
if (this.onSessionClosed_) this.onSessionClosed_(uin);
|
||||
session.bridge.dispose();
|
||||
private fireSessionStarted(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionStartedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-started listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
private fireSessionClosed(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionClosedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-closed listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return;
|
||||
|
||||
this.detachPidFromSession(pid, uin);
|
||||
}
|
||||
|
||||
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) {
|
||||
const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
if (!session || !session.bridge.hasPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
session.bridge.setPidReceiveHealthy(pid, healthy);
|
||||
}
|
||||
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (!BridgeManager.isRealUin(uin)) return;
|
||||
if (!isRealUin(uin)) return;
|
||||
|
||||
this.pidPacketClients_.set(pid, packetClient);
|
||||
|
||||
const { session, created } = this.ensureSession(uin);
|
||||
session.bridge.attachPid(pid);
|
||||
session.bridge.setPacketClient(packetClient);
|
||||
this.pidToUin_.set(pid, uin);
|
||||
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
|
||||
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
|
||||
if (!pkt.uin || !isRealUin(pkt.uin)) return;
|
||||
const uin = pkt.uin;
|
||||
|
||||
// Ensure session exists
|
||||
const { session, created } = this.ensureSession(uin);
|
||||
|
||||
// Attach PID if known
|
||||
if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) {
|
||||
session.bridge.attachPid(pkt.pid);
|
||||
this.pidToUin_.set(pkt.pid, uin);
|
||||
|
||||
const client = this.pidPacketClients_.get(pkt.pid);
|
||||
if (client) session.bridge.setPacketClient(client);
|
||||
}
|
||||
// A packet may be the first trustworthy observation that a live PID moved
|
||||
// to another UIN. Apply the exact same ownership transition as login so a
|
||||
// PID can never remain attached to two Bridges.
|
||||
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
|
||||
const { session, created } = client
|
||||
? this.bindPid(pkt.pid, uin, client, 'packet')
|
||||
: this.ensureSession(uin);
|
||||
|
||||
// Notify session started on first real packet
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
|
||||
// Dispatch packet to bridge
|
||||
session.bridge.onPacket(pkt);
|
||||
}
|
||||
|
||||
/** Bind PID + sender as one state transition. If the PID changed accounts,
|
||||
* the old Bridge is fully detached (and, when empty, closed) before the new
|
||||
* Bridge is created. */
|
||||
private bindPid(
|
||||
pid: number,
|
||||
uin: string,
|
||||
packetClient: PacketSender,
|
||||
source: 'login' | 'packet',
|
||||
): { session: QQSession; created: boolean } {
|
||||
const previousUin = this.pidToUin_.get(pid);
|
||||
if (previousUin && previousUin !== uin) {
|
||||
log.warn(
|
||||
'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s',
|
||||
pid,
|
||||
previousUin,
|
||||
uin,
|
||||
source,
|
||||
);
|
||||
this.detachPidFromSession(pid, previousUin);
|
||||
}
|
||||
|
||||
const result = this.ensureSession(uin);
|
||||
result.session.bridge.bindPid(pid, packetClient);
|
||||
this.pidToUin_.set(pid, uin);
|
||||
return result;
|
||||
}
|
||||
|
||||
private packetClientForPid(pid: number): PacketSender | null {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return null;
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
if (!session) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const packetClient = session.bridge.packetClientForPid(pid);
|
||||
if (packetClient) return packetClient;
|
||||
|
||||
const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
private detachPidFromSession(pid: number, uin: string): void {
|
||||
const mappedUin = this.pidToUin_.get(pid);
|
||||
if (mappedUin !== uin) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
if (!session) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
if (!session.bridge.hasPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
if (!session.bridge.packetClientForPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
// Validation is complete. Mutate both sides only after the ownership
|
||||
// invariant is known to hold, so a fail-fast error preserves the evidence.
|
||||
this.pidToUin_.delete(pid);
|
||||
session.bridge.detachPid(pid);
|
||||
if (!session.bridge.empty) return;
|
||||
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
// Fire before dispose() so listeners can still read bridge.identity.
|
||||
this.fireSessionClosed(uin, session.bridge);
|
||||
session.bridge.dispose();
|
||||
}
|
||||
|
||||
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
||||
let session = this.sessions_.get(uin);
|
||||
if (session) return { session, created: false };
|
||||
|
||||
@@ -2,23 +2,66 @@ import { HookManager } from '@snowluma/bridge';
|
||||
import { closeLogger, createLogger } from '@snowluma/common/logger';
|
||||
import { loadRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
|
||||
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { createNotificationManager } from './notifications/manager';
|
||||
import { createStateWiring } from './webui/state-wiring';
|
||||
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
const log = createLogger('App');
|
||||
|
||||
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
|
||||
// can drop at any moment, and a stray rejection on a detached callback (or a
|
||||
// throw that escapes one) must NOT take the whole process down — otherwise
|
||||
// Docker restarts it (dropping every session) and a bare Windows run just dies
|
||||
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
|
||||
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
|
||||
// known paths (e.g. the hook-client send deferreds) — these only catch what
|
||||
// slips through, and surface its stack so the real source can be fixed.
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
log.error('unhandledRejection (kept alive): %s',
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
|
||||
});
|
||||
process.on('uncaughtException', (error) => {
|
||||
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
|
||||
});
|
||||
|
||||
async function main() {
|
||||
log.info('SnowLuma starting');
|
||||
|
||||
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
|
||||
// any session (and thus any per-UIN config rewrite) can drop it.
|
||||
migrateGlobalSettings();
|
||||
|
||||
// One-shot: purge any persisted phantom accounts (onebot_<garbage>.json) the
|
||||
// native hook may have created with a timestamp-shaped UIN (issue #162).
|
||||
cleanupInvalidPerUinConfigs();
|
||||
|
||||
const bridgeManager = new BridgeManager();
|
||||
const oneBotManager = new OneBotManager();
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
|
||||
|
||||
// WebUI state-push wiring: HookManager + BridgeManager edges publish
|
||||
// `processes` / `qq-list` / `connections` invalidations into a bus the
|
||||
// /api/state/stream SSE handler subscribes to (no REST polling required).
|
||||
const stateWiring = createStateWiring();
|
||||
const hookManager = new HookManager({
|
||||
bridgeManager,
|
||||
autoLoadOnDiscovery,
|
||||
onSessionsChanged: stateWiring.onSessionsChanged,
|
||||
});
|
||||
if (autoLoadOnDiscovery) {
|
||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||
}
|
||||
|
||||
oneBotManager.bind(bridgeManager);
|
||||
stateWiring.bindBridgeManager(bridgeManager);
|
||||
|
||||
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
||||
// OneBotManager so the nickname fallback is already populated when it observes.
|
||||
const notificationManager = createNotificationManager();
|
||||
notificationManager.bind(bridgeManager);
|
||||
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
@@ -26,7 +69,12 @@ async function main() {
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
|
||||
host: runtimeConfig.webuiHost,
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
stateBus: stateWiring.bus,
|
||||
});
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
}
|
||||
@@ -34,12 +82,32 @@ async function main() {
|
||||
|
||||
// Graceful shutdown: dispose managers, await log flush, then exit.
|
||||
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
|
||||
let shutdownStarted = false;
|
||||
const shutdown = (signal: string) => async () => {
|
||||
if (shutdownStarted) return;
|
||||
shutdownStarted = true;
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
oneBotManager.dispose();
|
||||
hookManager.dispose();
|
||||
let exitCode = 0;
|
||||
try {
|
||||
await oneBotManager.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('OneBot shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
try { notificationManager.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
try { hookManager.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
try { stateWiring.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
await closeLogger();
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
};
|
||||
process.on('SIGINT', shutdown('SIGINT'));
|
||||
process.on('SIGTERM', shutdown('SIGTERM'));
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
// Global notification-channel store + the pure template renderer.
|
||||
//
|
||||
// Mirrors the conventions of `webui/ui-config.ts` (the plan calls for this
|
||||
// explicitly): every `normalize*` is TOTAL — any unknown / corrupt input
|
||||
// collapses to a safe default, numbers clamp, unknown keys are dropped — and
|
||||
// persistence is an atomic write (tmp → rename) behind a module-level cache.
|
||||
//
|
||||
// Channels are GLOBAL (defined once here); each UIN opts into a subset via
|
||||
// `OneBotConfig.notifications.channelIds` (see packages/onebot/src/config.ts).
|
||||
import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const log = createLogger('Notifications.Config');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const NOTIFICATIONS_CONFIG_PATH = path.join(CONFIG_DIR, 'notifications.json');
|
||||
|
||||
export const NOTIFICATIONS_CONFIG_VERSION = 1 as const;
|
||||
|
||||
export const DEBOUNCE_SECONDS_MIN = 0;
|
||||
export const DEBOUNCE_SECONDS_MAX = 3600;
|
||||
export const DEFAULT_DEBOUNCE_SECONDS = 30;
|
||||
|
||||
/** A channel id is a slug: it is referenced by per-UIN `channelIds`, so it must
|
||||
* be safe to use as a stable key. Kept in sync with `normalizeChannelIds` in
|
||||
* packages/onebot/src/config.ts (cross-package; can't share without a circular
|
||||
* dep — core depends on onebot, not the reverse). */
|
||||
export const CHANNEL_ID_RE = /^[\w.-]+$/;
|
||||
const CHANNEL_ID_MAX = 64;
|
||||
const CHANNEL_NAME_MAX = 128;
|
||||
const BODY_TEMPLATE_MAX = 8192;
|
||||
|
||||
/** event ∈ {offline, online}; rendered verbatim into `{event}`. */
|
||||
export type NotificationEvent = 'offline' | 'online';
|
||||
|
||||
export interface NotificationChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
bodyTemplate: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface NotificationsConfig {
|
||||
version: typeof NOTIFICATIONS_CONFIG_VERSION;
|
||||
debounceSeconds: number;
|
||||
channels: NotificationChannel[];
|
||||
}
|
||||
|
||||
/** Default body template — Server酱-style JSON ({title}/{desp}). The WebUI
|
||||
* ships additional per-vendor presets (钉钉/Discord/…) as frontend constants
|
||||
* the operator can drop in. */
|
||||
export const DEFAULT_BODY_TEMPLATE = `{
|
||||
"title": "账号状态通知:{event}",
|
||||
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
|
||||
}`;
|
||||
|
||||
export function defaultNotificationsConfig(): NotificationsConfig {
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds: DEFAULT_DEBOUNCE_SECONDS,
|
||||
channels: [],
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Template renderer ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Mechanical `{key}` substitution — no logic, no conditionals, no escaping.
|
||||
* A key present in `vars` is replaced by its value; an unknown `{key}` is left
|
||||
* untouched (原样) so a typo'd placeholder is visible rather than silently
|
||||
* blanked. Pure + total (a non-string template yields '').
|
||||
*
|
||||
* **JSON safety**: When the template is valid JSON (parseable by JSON.parse),
|
||||
* values are escaped to prevent breaking the JSON structure — backslashes
|
||||
* become `\\` and double-quotes become `\"`.
|
||||
*/
|
||||
export function renderTemplate(template: string, vars: Record<string, string>): string {
|
||||
if (typeof template !== 'string') return '';
|
||||
let isJson = false;
|
||||
try {
|
||||
JSON.parse(template);
|
||||
isJson = true;
|
||||
} catch {
|
||||
// not JSON — plain text mode
|
||||
}
|
||||
return template.replace(/\{(\w+)\}/g, (match, key: string) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(vars, key)) return match;
|
||||
const val = vars[key];
|
||||
return isJson ? val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : val;
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Normalization helpers ──────────────────────────────────────────────────
|
||||
// isObject / boolOr / clampInt come from @snowluma/common/coerce. strOr is
|
||||
// notifications-only (string truncation to maxLen), so it stays here.
|
||||
|
||||
function strOr(value: unknown, fallback: string, maxLen: number): string {
|
||||
return typeof value === 'string' ? value.slice(0, maxLen) : fallback;
|
||||
}
|
||||
|
||||
function normalizeChannelId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim();
|
||||
if (v.length === 0 || v.length > CHANNEL_ID_MAX) return null;
|
||||
if (!CHANNEL_ID_RE.test(v)) return null;
|
||||
return v;
|
||||
}
|
||||
|
||||
function isHttpUrl(value: string): boolean {
|
||||
try {
|
||||
const u = new URL(value);
|
||||
return u.protocol === 'http:' || u.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** A channel is usable only with a valid id AND an http(s) target — anything
|
||||
* else is unusable, so the whole entry is dropped (total normalize). */
|
||||
function normalizeChannel(raw: unknown): NotificationChannel | null {
|
||||
if (!isObject(raw)) return null;
|
||||
const id = normalizeChannelId(raw.id);
|
||||
if (!id) return null;
|
||||
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
|
||||
if (!isHttpUrl(url)) return null;
|
||||
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
url,
|
||||
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
|
||||
enabled: boolOr(raw.enabled, true),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeChannels(value: unknown): NotificationChannel[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const seen = new Set<string>();
|
||||
const out: NotificationChannel[] = [];
|
||||
for (const raw of value) {
|
||||
const ch = normalizeChannel(raw);
|
||||
if (!ch) continue;
|
||||
if (seen.has(ch.id)) continue; // dedupe by id — first occurrence wins
|
||||
seen.add(ch.id);
|
||||
out.push(ch);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeNotificationsConfig(value: unknown): NotificationsConfig {
|
||||
const v = isObject(value) ? value : {};
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds: clampInt(
|
||||
v.debounceSeconds,
|
||||
DEBOUNCE_SECONDS_MIN,
|
||||
DEBOUNCE_SECONDS_MAX,
|
||||
DEFAULT_DEBOUNCE_SECONDS,
|
||||
),
|
||||
channels: normalizeChannels(v.channels),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Persistence (atomic write + module-level cache) ────────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function atomicWrite(config: NotificationsConfig): void {
|
||||
ensureConfigDir();
|
||||
const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH);
|
||||
}
|
||||
|
||||
let cached: NotificationsConfig | null = null;
|
||||
|
||||
/** Load + normalize the channel store, creating it from defaults if absent. */
|
||||
export function loadNotificationsConfig(): NotificationsConfig {
|
||||
if (cached) return cached;
|
||||
ensureConfigDir();
|
||||
|
||||
if (!fs.existsSync(NOTIFICATIONS_CONFIG_PATH)) {
|
||||
const fresh = defaultNotificationsConfig();
|
||||
try {
|
||||
atomicWrite(fresh);
|
||||
} catch (err) {
|
||||
log.warn('failed to write initial notifications.json: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const normalized = normalizeNotificationsConfig(parsed);
|
||||
// Self-heal on disk only if normalization changed something (corrupt/old).
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
|
||||
try {
|
||||
atomicWrite(normalized);
|
||||
} catch {
|
||||
/* best-effort self-heal */
|
||||
}
|
||||
}
|
||||
cached = normalized;
|
||||
return normalized;
|
||||
} catch (err) {
|
||||
log.warn('notifications.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err));
|
||||
const fresh = defaultNotificationsConfig();
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a (possibly partial) client-supplied config. A missing `channels` or
|
||||
* `debounceSeconds` keeps the current on-disk value — section-level merge, same
|
||||
* as `saveUiConfig`. Returns the stored, normalized config.
|
||||
*/
|
||||
export function saveNotificationsConfig(incoming: unknown): NotificationsConfig {
|
||||
const current = loadNotificationsConfig();
|
||||
const v = isObject(incoming) ? incoming : {};
|
||||
const next: NotificationsConfig = {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds:
|
||||
v.debounceSeconds !== undefined
|
||||
? clampInt(v.debounceSeconds, DEBOUNCE_SECONDS_MIN, DEBOUNCE_SECONDS_MAX, DEFAULT_DEBOUNCE_SECONDS)
|
||||
: current.debounceSeconds,
|
||||
channels: Array.isArray(v.channels) ? normalizeChannels(v.channels) : current.channels,
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Per-UIN debounce state machine for online↔offline notifications.
|
||||
//
|
||||
// Uptime-Kuma semantics (grill-locked in the plan): an offline that SURVIVES
|
||||
// `debounceSeconds` fires an "offline" notification; its later recovery fires
|
||||
// the paired "online". An offline that self-heals within the window fires
|
||||
// NOTHING (the blip is suppressed). A cold online — one with no prior fired
|
||||
// offline — fires nothing (it is not a recovery).
|
||||
//
|
||||
// This module is PURE: no timers, no I/O, no clock. It only decides; the
|
||||
// manager owns the timer + the side effects. That keeps the debounce logic
|
||||
// fully unit-testable by driving a sequence of events.
|
||||
import type { NotificationEvent } from './config';
|
||||
|
||||
export type DebounceDecision =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'schedule'; delayMs: number }
|
||||
| { kind: 'cancel' }
|
||||
| { kind: 'emit'; event: NotificationEvent };
|
||||
|
||||
interface UinState {
|
||||
/** An offline debounce timer is armed but has not yet fired. */
|
||||
pending: boolean;
|
||||
/** An "offline" notification has fired and is awaiting its recovery. */
|
||||
firedOffline: boolean;
|
||||
}
|
||||
|
||||
export class DebounceMachine {
|
||||
private readonly states = new Map<string, UinState>();
|
||||
|
||||
private state(uin: string): UinState {
|
||||
let s = this.states.get(uin);
|
||||
if (!s) {
|
||||
s = { pending: false, firedOffline: false };
|
||||
this.states.set(uin, s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Account went offline. `debounceSeconds` is read fresh from config so a
|
||||
* reload takes effect on the next transition. */
|
||||
onOffline(uin: string, debounceSeconds: number): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.firedOffline || s.pending) return { kind: 'none' }; // already down / already counting
|
||||
// Non-finite / non-positive → no debounce, fire immediately. Stays total:
|
||||
// never schedule a setTimeout(NaN|Infinity). Production config always
|
||||
// clamps to a finite [0,3600]; this only hardens direct callers.
|
||||
if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) {
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
s.pending = true;
|
||||
return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
|
||||
}
|
||||
|
||||
/** Account came online. */
|
||||
onOnline(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.pending) {
|
||||
s.pending = false;
|
||||
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
|
||||
}
|
||||
if (s.firedOffline) {
|
||||
s.firedOffline = false;
|
||||
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
|
||||
}
|
||||
return { kind: 'none' }; // cold online / already up
|
||||
}
|
||||
|
||||
/** The offline debounce window elapsed (the armed timer fired). */
|
||||
onTimerElapsed(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (!s.pending) return { kind: 'none' }; // cancelled before firing
|
||||
s.pending = false;
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
|
||||
/** Drop a UIN's state (e.g. on dispose). */
|
||||
forget(uin: string): void {
|
||||
this.states.delete(uin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// The global notification subsystem: one singleton watching ALL accounts.
|
||||
//
|
||||
// Subscribes to BridgeManager session online/offline edges, runs a per-UIN
|
||||
// debounce state machine (see debounce.ts), and on a fired transition renders
|
||||
// each opted-in + enabled channel's body template and POSTs it — recording the
|
||||
// outcome in a bounded in-memory history (lost on restart, by design).
|
||||
//
|
||||
// Side-effecting collaborators (config load, per-UIN channel ids, the outbound
|
||||
// POST, the clock) are injected so the class is fully unit-testable; the real
|
||||
// wiring lives in `createNotificationManager()` at the bottom.
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import {
|
||||
loadNotificationsConfig,
|
||||
renderTemplate,
|
||||
type NotificationChannel,
|
||||
type NotificationEvent,
|
||||
type NotificationsConfig,
|
||||
} from './config';
|
||||
import { DebounceMachine, type DebounceDecision } from './debounce';
|
||||
|
||||
const log = createLogger('Notifications');
|
||||
|
||||
const DEFAULT_HISTORY_LIMIT = 100;
|
||||
const DEFAULT_POST_TIMEOUT_MS = 10_000;
|
||||
const FALLBACK_DEBOUNCE_SECONDS = 30;
|
||||
|
||||
/** One delivery attempt; kept only in memory (the plan forbids persistence). */
|
||||
export interface DeliveryRecord {
|
||||
time: number;
|
||||
uin: string;
|
||||
event: NotificationEvent;
|
||||
channelId: string;
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface PostResult {
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface NotificationManagerDeps {
|
||||
/** Global channel store (channels + debounceSeconds). */
|
||||
loadConfig: () => NotificationsConfig;
|
||||
/** The channel ids a UIN has opted into. */
|
||||
loadChannelIds: (uin: string) => string[];
|
||||
/** Outbound delivery — never throws; failures come back as `{ ok: false }`. */
|
||||
post: (url: string, body: string) => Promise<PostResult>;
|
||||
now: () => number;
|
||||
historyLimit?: number;
|
||||
}
|
||||
|
||||
function errMsg(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure: the channels a UIN should be notified through — globally enabled AND
|
||||
* opted into by the UIN — preserving config order. Exported for unit tests.
|
||||
*/
|
||||
export function selectChannels(channels: NotificationChannel[], enabledIds: string[]): NotificationChannel[] {
|
||||
const wanted = new Set(enabledIds);
|
||||
return channels.filter((c) => c.enabled && wanted.has(c.id));
|
||||
}
|
||||
|
||||
export class NotificationManager {
|
||||
private readonly deps: NotificationManagerDeps;
|
||||
private readonly machine = new DebounceMachine();
|
||||
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
private readonly nicknames = new Map<string, string>();
|
||||
private readonly history: DeliveryRecord[] = [];
|
||||
private readonly historyLimit: number;
|
||||
|
||||
constructor(deps: NotificationManagerDeps) {
|
||||
this.deps = deps;
|
||||
this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY_LIMIT;
|
||||
}
|
||||
|
||||
/** Subscribe to the global session online/offline edges. Register AFTER
|
||||
* OneBotManager so the nickname fallback is already populated. */
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => this.handleOnline(uin, bridge.identity.nickname));
|
||||
bridgeManager.addSessionClosedListener((uin, bridge) => this.handleOffline(uin, bridge.identity.nickname));
|
||||
}
|
||||
|
||||
handleOnline(uin: string, nickname?: string): void {
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOnline(uin));
|
||||
}
|
||||
|
||||
handleOffline(uin: string, nickname?: string): void {
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
|
||||
}
|
||||
|
||||
private debounceSeconds(): number {
|
||||
try {
|
||||
return this.deps.loadConfig().debounceSeconds;
|
||||
} catch {
|
||||
return FALLBACK_DEBOUNCE_SECONDS;
|
||||
}
|
||||
}
|
||||
|
||||
private apply(uin: string, decision: DebounceDecision): void {
|
||||
switch (decision.kind) {
|
||||
case 'schedule': {
|
||||
const existing = this.timers.get(uin);
|
||||
if (existing) clearTimeout(existing);
|
||||
const timer = setTimeout(() => {
|
||||
this.timers.delete(uin);
|
||||
this.apply(uin, this.machine.onTimerElapsed(uin));
|
||||
}, decision.delayMs);
|
||||
// Don't let a pending notification timer keep the process alive.
|
||||
if (typeof (timer as { unref?: () => void }).unref === 'function') {
|
||||
(timer as { unref: () => void }).unref();
|
||||
}
|
||||
this.timers.set(uin, timer);
|
||||
break;
|
||||
}
|
||||
case 'cancel': {
|
||||
const timer = this.timers.get(uin);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.timers.delete(uin);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'emit':
|
||||
void this.notify(uin, decision.event);
|
||||
break;
|
||||
case 'none':
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/** Render + POST a transition to every opted-in, enabled channel and record
|
||||
* the outcome. Never throws (a bad channel can't break the others). */
|
||||
async notify(uin: string, event: NotificationEvent): Promise<void> {
|
||||
let channels: NotificationChannel[];
|
||||
try {
|
||||
const cfg = this.deps.loadConfig();
|
||||
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
|
||||
} catch (err) {
|
||||
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
|
||||
return;
|
||||
}
|
||||
if (channels.length === 0) return;
|
||||
|
||||
const nickname = this.nicknames.get(uin) || uin;
|
||||
const vars: Record<string, string> = {
|
||||
uin,
|
||||
nickname,
|
||||
event,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
};
|
||||
|
||||
for (const ch of channels) {
|
||||
const body = renderTemplate(ch.bodyTemplate, vars);
|
||||
let result: PostResult;
|
||||
try {
|
||||
result = await this.deps.post(ch.url, body);
|
||||
} catch (err) {
|
||||
// The injected post is contracted not to throw, but guard anyway.
|
||||
result = { ok: false, error: errMsg(err) };
|
||||
}
|
||||
this.record({
|
||||
time: this.deps.now(),
|
||||
uin,
|
||||
event,
|
||||
channelId: ch.id,
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
error: result.ok ? undefined : (result.error ?? (result.status ? `HTTP ${result.status}` : 'delivery failed')),
|
||||
});
|
||||
if (!result.ok) {
|
||||
log.warn('notify %s→%s channel=%s failed: %s', uin, event, ch.id, result.error ?? `HTTP ${result.status ?? '?'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Send a one-off test to a single channel by id — ignores `enabled` and the
|
||||
* per-UIN opt-in (you test a channel before wiring it up), with sample
|
||||
* variables. Reuses the real render+POST path; NOT recorded to history.
|
||||
* `found:false` means the channel id is unknown. */
|
||||
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
|
||||
let channel: NotificationChannel | undefined;
|
||||
try {
|
||||
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
|
||||
} catch (err) {
|
||||
return { ok: false, found: false, error: errMsg(err) };
|
||||
}
|
||||
if (!channel) return { ok: false, found: false };
|
||||
const body = renderTemplate(channel.bodyTemplate, {
|
||||
uin: '10000',
|
||||
nickname: '测试账号',
|
||||
event: 'offline',
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
});
|
||||
try {
|
||||
return { ...(await this.deps.post(channel.url, body)), found: true };
|
||||
} catch (err) {
|
||||
return { ok: false, found: true, error: errMsg(err) };
|
||||
}
|
||||
}
|
||||
|
||||
private record(rec: DeliveryRecord): void {
|
||||
this.history.push(rec);
|
||||
if (this.history.length > this.historyLimit) {
|
||||
this.history.splice(0, this.history.length - this.historyLimit);
|
||||
}
|
||||
}
|
||||
|
||||
/** Most-recent-first delivery history (capped at the buffer size). */
|
||||
getRecent(limit = this.historyLimit): DeliveryRecord[] {
|
||||
const n = Math.max(0, Math.min(Math.trunc(limit) || 0, this.history.length));
|
||||
return this.history.slice(this.history.length - n).reverse();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const timer of this.timers.values()) clearTimeout(timer);
|
||||
this.timers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Default outbound POST: a single attempt with a timeout, JSON content-type
|
||||
* (the common case for 钉钉/Discord/飞书). Never throws. */
|
||||
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
|
||||
return async (url, body) => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
return { ok: res.ok, status: res.status, error: res.ok ? undefined : `HTTP ${res.status}` };
|
||||
} catch (err) {
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The real, fully-wired singleton. */
|
||||
export function createNotificationManager(): NotificationManager {
|
||||
return new NotificationManager({
|
||||
loadConfig: loadNotificationsConfig,
|
||||
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
|
||||
post: createDefaultPost(),
|
||||
now: () => Date.now(),
|
||||
});
|
||||
}
|
||||
@@ -64,16 +64,52 @@ function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function isValidState(value: unknown): value is WebuiAuthState {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
/**
|
||||
* Validate credential state before it crosses a persistence boundary.
|
||||
*
|
||||
* The hash/salt lengths are part of the on-disk contract: accepting any hex
|
||||
* string here only postpones failure until password verification, where the
|
||||
* operator would be locked out after a restore.
|
||||
*/
|
||||
export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('credential state must be an object');
|
||||
}
|
||||
const v = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof v.passwordHash === 'string' &&
|
||||
typeof v.passwordSalt === 'string' &&
|
||||
typeof v.mustChangePassword === 'boolean' &&
|
||||
/^[0-9a-f]+$/i.test(v.passwordHash) &&
|
||||
/^[0-9a-f]+$/i.test(v.passwordSalt)
|
||||
);
|
||||
if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) {
|
||||
throw new Error('passwordHash must be exactly 128 hexadecimal characters');
|
||||
}
|
||||
if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) {
|
||||
throw new Error('passwordSalt must be exactly 32 hexadecimal characters');
|
||||
}
|
||||
if (typeof v.mustChangePassword !== 'boolean') {
|
||||
throw new Error('mustChangePassword must be a boolean');
|
||||
}
|
||||
if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) {
|
||||
throw new Error('generatedAt must be a valid timestamp');
|
||||
}
|
||||
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
|
||||
throw new Error('updatedAt must be a valid timestamp');
|
||||
}
|
||||
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt']);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
if (unknown) throw new Error(`unknown field $.${unknown}`);
|
||||
return {
|
||||
passwordHash: v.passwordHash,
|
||||
passwordSalt: v.passwordSalt,
|
||||
mustChangePassword: v.mustChangePassword,
|
||||
generatedAt: v.generatedAt,
|
||||
updatedAt: v.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function isValidState(value: unknown): value is WebuiAuthState {
|
||||
try {
|
||||
prepareWebuiAuthStateForRestore(value);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function generateInitialState(initialPassword: string): WebuiAuthState {
|
||||
|
||||
@@ -0,0 +1,545 @@
|
||||
// WebUI config backup/restore (Wave A2). Format: a zero-dep JSON bundle
|
||||
// { version, app, createdAt, files: { "<name>": { encoding, data } } }
|
||||
// over an explicit allowlist (never a whole-dir sweep) so a stray/unknown file
|
||||
// can't leak and an import can't path-traverse.
|
||||
//
|
||||
// Credentials are gated by a toggle on both export and import. The credential
|
||||
// set is: webui.json (password hash), key.pem (TLS private key), AND every
|
||||
// OneBot config (onebot.json + per-account onebot_<uin>.json) — those carry the
|
||||
// OneBot access token, so a no-credentials backup must NOT include them.
|
||||
// cert.pem is public so it always travels.
|
||||
//
|
||||
// Pure functions here own bundle validation and semantic preflight. Filesystem
|
||||
// transaction choreography lives in restore.ts. A non-empty restore remains
|
||||
// restart-to-apply, like A1.
|
||||
|
||||
import { normalizeRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { normalizeGlobalSettings } from '@snowluma/onebot/global-config';
|
||||
import { prepareOneBotConfigForRestore } from '@snowluma/onebot/config';
|
||||
import { isIP } from 'node:net';
|
||||
import { normalizeNotificationsConfig } from '../notifications/config';
|
||||
import { prepareWebuiAuthStateForRestore } from './auth';
|
||||
import { MAX_BACKGROUND_BYTES, normalizeStoredUiConfig, sniffImageMime } from './ui-config';
|
||||
import { validateTlsPair } from './tls';
|
||||
|
||||
export const BACKUP_VERSION = 1;
|
||||
export const BACKUP_APP = 'snowluma';
|
||||
export const MAX_BACKUP_DECODED_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
export interface BackupFileSpec {
|
||||
/** Path relative to the config dir; also the bundle key. */
|
||||
name: string;
|
||||
binary: boolean;
|
||||
/** Sensitive (private key / password hash / access token) — credential-gated. */
|
||||
credential: boolean;
|
||||
}
|
||||
|
||||
/** Static allowlist. Per-account `onebot_<uin>.json` are matched by pattern. */
|
||||
export const BACKUP_FILES: readonly BackupFileSpec[] = [
|
||||
{ name: 'runtime.json', binary: false, credential: false },
|
||||
{ name: 'ui.json', binary: false, credential: false },
|
||||
{ name: 'notifications.json', binary: false, credential: false },
|
||||
// Global all-accounts SnowLuma settings (rkey fallback servers, …). Same
|
||||
// class as notifications.json: global, opt-in, non-credential.
|
||||
{ name: 'snowluma.json', binary: false, credential: false },
|
||||
{ name: 'cert.pem', binary: false, credential: false },
|
||||
{ name: 'ui-assets/background', binary: true, credential: false },
|
||||
{ name: 'webui.json', binary: false, credential: true },
|
||||
{ name: 'key.pem', binary: false, credential: true },
|
||||
// OneBot config carries the access token → credential.
|
||||
{ name: 'onebot.json', binary: false, credential: true },
|
||||
];
|
||||
|
||||
const SPEC_BY_NAME = new Map(BACKUP_FILES.map((f) => [f.name, f]));
|
||||
const PER_UIN_ONEBOT = /^onebot_(\d+)\.json$/;
|
||||
|
||||
function isPerUinOneBotName(name: string): boolean {
|
||||
const match = PER_UIN_ONEBOT.exec(name);
|
||||
return match !== null && isRealUin(match[1]);
|
||||
}
|
||||
|
||||
/** Resolve a file name (static or per-uin onebot pattern) to its spec, or null. */
|
||||
export function specFor(name: string): BackupFileSpec | null {
|
||||
const s = SPEC_BY_NAME.get(name);
|
||||
if (s) return s;
|
||||
if (isPerUinOneBotName(name)) return { name, binary: false, credential: true };
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface BackupEntry { encoding: 'utf8' | 'base64'; data: string }
|
||||
export interface Backup {
|
||||
version: number;
|
||||
app: string;
|
||||
createdAt?: string;
|
||||
files: Record<string, BackupEntry>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble a bundle from the allowlist plus any per-account onebot files.
|
||||
* `readFile` returns null for missing.
|
||||
*/
|
||||
export function buildBackup(
|
||||
readFile: (name: string) => Buffer | null,
|
||||
perUinOnebotNames: readonly string[],
|
||||
opts: { includeCredentials: boolean },
|
||||
createdAt: string,
|
||||
): Backup {
|
||||
const files: Record<string, BackupEntry> = {};
|
||||
const all: BackupFileSpec[] = [
|
||||
...BACKUP_FILES,
|
||||
...perUinOnebotNames.filter(isPerUinOneBotName).map((n) => ({ name: n, binary: false, credential: true })),
|
||||
];
|
||||
for (const spec of all) {
|
||||
if (spec.credential && !opts.includeCredentials) continue;
|
||||
const buf = readFile(spec.name);
|
||||
if (!buf) continue;
|
||||
files[spec.name] = spec.binary
|
||||
? { encoding: 'base64', data: buf.toString('base64') }
|
||||
: { encoding: 'utf8', data: buf.toString('utf8') };
|
||||
}
|
||||
return { version: BACKUP_VERSION, app: BACKUP_APP, createdAt, files };
|
||||
}
|
||||
|
||||
function validateBackupEntries(
|
||||
parsed: unknown,
|
||||
skipEntryValidation: (spec: BackupFileSpec) => boolean,
|
||||
): { ok: true; backup: Backup } | { ok: false; error: string } {
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
||||
return { ok: false, error: 'backup must be an object' };
|
||||
}
|
||||
const b = parsed as Record<string, unknown>;
|
||||
if (b.app !== BACKUP_APP) return { ok: false, error: 'not a SnowLuma backup' };
|
||||
if (b.version !== BACKUP_VERSION) return { ok: false, error: `unsupported backup version ${String(b.version)}` };
|
||||
if (typeof b.files !== 'object' || b.files === null || Array.isArray(b.files)) {
|
||||
return { ok: false, error: 'backup.files must be an object' };
|
||||
}
|
||||
const files = b.files as Record<string, unknown>;
|
||||
for (const [name, entry] of Object.entries(files)) {
|
||||
const spec = specFor(name);
|
||||
if (!spec) return { ok: false, error: `unknown file in backup: ${name}` };
|
||||
if (skipEntryValidation(spec)) continue;
|
||||
if (typeof entry !== 'object' || entry === null) return { ok: false, error: `malformed entry: ${name}` };
|
||||
const e = entry as Record<string, unknown>;
|
||||
if (e.encoding !== 'utf8' && e.encoding !== 'base64') return { ok: false, error: `bad encoding for ${name}` };
|
||||
if (typeof e.data !== 'string') return { ok: false, error: `bad data for ${name}` };
|
||||
}
|
||||
return { ok: true, backup: { version: BACKUP_VERSION, app: BACKUP_APP, createdAt: typeof b.createdAt === 'string' ? b.createdAt : undefined, files: files as Record<string, BackupEntry> } };
|
||||
}
|
||||
|
||||
export interface PreparedRestoreFile {
|
||||
name: string;
|
||||
data: Buffer;
|
||||
mode: 0o600 | 0o644;
|
||||
}
|
||||
|
||||
export interface RestoreMigration {
|
||||
name: string;
|
||||
fields: string[];
|
||||
}
|
||||
|
||||
export interface PreparedRestorePlan {
|
||||
restore: PreparedRestoreFile[];
|
||||
skipped: string[];
|
||||
migrated: RestoreMigration[];
|
||||
}
|
||||
|
||||
export interface PrepareRestoreOptions {
|
||||
restoreCredentials: boolean;
|
||||
/** Read an existing live file for overlay-wide validation (TLS/UI). */
|
||||
readCurrent: (name: string) => Buffer | null;
|
||||
/** Current per-account configs affected when onebot.json is replaced. */
|
||||
listCurrentOneBotNames?: () => string[];
|
||||
}
|
||||
|
||||
export class RestorePreflightError extends Error {
|
||||
readonly file: string;
|
||||
|
||||
constructor(file: string, message: string, options?: { cause?: unknown }) {
|
||||
super(`${file}: ${message}`, options);
|
||||
this.name = 'RestorePreflightError';
|
||||
this.file = file;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate every selected file semantically and materialize canonical bytes
|
||||
* before the transaction is allowed to touch live configuration.
|
||||
*/
|
||||
export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions): PreparedRestorePlan {
|
||||
const checked = validateBackupEntries(parsed, (spec) => spec.credential && !opts.restoreCredentials);
|
||||
if (!checked.ok) throw new RestorePreflightError('<backup>', checked.error);
|
||||
|
||||
const restore: PreparedRestoreFile[] = [];
|
||||
const skipped: string[] = [];
|
||||
const migrated: RestoreMigration[] = [];
|
||||
const selected: Array<{ name: string; data: Buffer; spec: BackupFileSpec }> = [];
|
||||
let decodedBytes = 0;
|
||||
|
||||
for (const [name, entry] of Object.entries(checked.backup.files)) {
|
||||
const spec = specFor(name);
|
||||
if (!spec) throw new RestorePreflightError(name, 'file is not in the restore allowlist');
|
||||
if (spec.credential && !opts.restoreCredentials) {
|
||||
skipped.push(name);
|
||||
continue;
|
||||
}
|
||||
if (entry.encoding !== (spec.binary ? 'base64' : 'utf8')) {
|
||||
throw new RestorePreflightError(name, `encoding must be ${spec.binary ? 'base64' : 'utf8'}`);
|
||||
}
|
||||
|
||||
const decoded = decodeEntryStrict(name, entry);
|
||||
decodedBytes += decoded.length;
|
||||
if (decodedBytes > MAX_BACKUP_DECODED_BYTES) {
|
||||
throw new RestorePreflightError(name, `selected files exceed ${String(MAX_BACKUP_DECODED_BYTES)} decoded bytes`);
|
||||
}
|
||||
|
||||
selected.push({ name, data: decoded, spec });
|
||||
}
|
||||
|
||||
const selectedGlobal = selected.find((file) => file.name === 'onebot.json');
|
||||
const selectedPerUin = selected.filter((file) => isPerUinOneBotName(file.name));
|
||||
const selectedPerUinRaw = new Map(selectedPerUin.map((file) => [file.name, parseJson(file.name, file.data)]));
|
||||
const perUinNeedsGlobal = [...selectedPerUinRaw.values()].some((raw) => !isPlainObject(raw) || raw.mode !== 'snapshot');
|
||||
let effectiveGlobalOneBot: unknown;
|
||||
let preparedGlobalOneBot: ReturnType<typeof prepareOneBotConfigForRestore> | null = null;
|
||||
if (selectedGlobal) {
|
||||
if (!opts.listCurrentOneBotNames) {
|
||||
throw new RestorePreflightError('onebot.json', 'current per-account config listing is required to validate the effective overlay');
|
||||
}
|
||||
const raw = parseJson(selectedGlobal.name, selectedGlobal.data);
|
||||
preparedGlobalOneBot = prepareOneBotOrThrow(selectedGlobal.name, raw, 'global');
|
||||
effectiveGlobalOneBot = preparedGlobalOneBot.value;
|
||||
} else if (perUinNeedsGlobal) {
|
||||
const current = readCurrentForPreflight(opts, 'onebot.json');
|
||||
if (current) {
|
||||
const raw = parseJson('onebot.json', current);
|
||||
effectiveGlobalOneBot = prepareOneBotOrThrow('onebot.json', raw, 'global').value;
|
||||
}
|
||||
}
|
||||
|
||||
for (const { name, data, spec } of selected) {
|
||||
let prepared: { data: Buffer; migratedFields: string[] };
|
||||
if (name === 'onebot.json') {
|
||||
const global = preparedGlobalOneBot!;
|
||||
prepared = { data: serializeJson(global.value), migratedFields: global.migratedFields };
|
||||
} else if (isPerUinOneBotName(name)) {
|
||||
const raw = selectedPerUinRaw.get(name);
|
||||
const onebot = prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot);
|
||||
prepared = { data: serializeJson(onebot.value), migratedFields: onebot.migratedFields };
|
||||
} else {
|
||||
prepared = prepareFile(name, data);
|
||||
}
|
||||
restore.push({ name, data: prepared.data, mode: spec.credential ? 0o600 : 0o644 });
|
||||
if (prepared.migratedFields.length > 0) {
|
||||
migrated.push({ name, fields: [...prepared.migratedFields].sort() });
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedGlobal) {
|
||||
const selectedNames = new Set(selected.map((file) => file.name));
|
||||
let currentNames: string[];
|
||||
try {
|
||||
currentNames = opts.listCurrentOneBotNames!();
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError('onebot.json', `failed to list current per-account configs: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
}
|
||||
for (const name of currentNames) {
|
||||
if (!isPerUinOneBotName(name) || selectedNames.has(name)) continue;
|
||||
const current = readCurrentForPreflight(opts, name);
|
||||
if (!current) continue;
|
||||
const raw = parseJson(name, current);
|
||||
prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot);
|
||||
}
|
||||
}
|
||||
|
||||
validateEffectiveTls(restore, opts);
|
||||
validateEffectiveUi(restore, opts);
|
||||
return { restore, skipped, migrated };
|
||||
}
|
||||
|
||||
function decodeEntryStrict(name: string, entry: BackupEntry): Buffer {
|
||||
if (entry.encoding === 'utf8') return Buffer.from(entry.data, 'utf8');
|
||||
if (!isCanonicalBase64(entry.data)) {
|
||||
throw new RestorePreflightError(name, 'data is not canonical base64');
|
||||
}
|
||||
return Buffer.from(entry.data, 'base64');
|
||||
}
|
||||
|
||||
function isCanonicalBase64(value: string): boolean {
|
||||
if (value.length === 0) return true;
|
||||
if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
|
||||
return false;
|
||||
}
|
||||
return Buffer.from(value, 'base64').toString('base64') === value;
|
||||
}
|
||||
|
||||
function prepareFile(name: string, data: Buffer): { data: Buffer; migratedFields: string[] } {
|
||||
try {
|
||||
switch (name) {
|
||||
case 'runtime.json':
|
||||
return prepareRuntimeJson(name, data);
|
||||
case 'ui.json':
|
||||
return prepareNormalizedJson(name, data, normalizeStoredUiConfig);
|
||||
case 'notifications.json':
|
||||
return prepareNormalizedJson(name, data, normalizeNotificationsConfig);
|
||||
case 'snowluma.json':
|
||||
return prepareGlobalSettingsJson(name, data);
|
||||
case 'webui.json': {
|
||||
const value = parseJson(name, data);
|
||||
const canonical = prepareWebuiAuthStateForRestore(value);
|
||||
return { data: serializeJson(canonical), migratedFields: [] };
|
||||
}
|
||||
case 'ui-assets/background':
|
||||
if (data.length > MAX_BACKGROUND_BYTES) {
|
||||
throw new Error(`image exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`);
|
||||
}
|
||||
if (!sniffImageMime(data)) throw new Error('image must be PNG, JPEG, or WebP');
|
||||
return { data, migratedFields: [] };
|
||||
case 'cert.pem':
|
||||
case 'key.pem':
|
||||
if (!data.toString('utf8').trim()) throw new Error('PEM file must not be empty');
|
||||
return { data, migratedFields: [] };
|
||||
default:
|
||||
throw new Error('file is not in the restore allowlist');
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RestorePreflightError) throw error;
|
||||
throw new RestorePreflightError(name, error instanceof Error ? error.message : String(error), { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function prepareOneBotOrThrow(
|
||||
name: string,
|
||||
value: unknown,
|
||||
scope: 'global' | 'per-uin',
|
||||
inheritedGlobal?: unknown,
|
||||
): ReturnType<typeof prepareOneBotConfigForRestore> {
|
||||
try {
|
||||
return prepareOneBotConfigForRestore(value, scope, inheritedGlobal);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError(name, error instanceof Error ? error.message : String(error), { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function readCurrentForPreflight(opts: PrepareRestoreOptions, name: string): Buffer | null {
|
||||
try {
|
||||
return opts.readCurrent(name);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function parseJson(name: string, data: Buffer): unknown {
|
||||
try {
|
||||
return JSON.parse(data.toString('utf8')) as unknown;
|
||||
} catch (error) {
|
||||
// V8 may quote the offending input in SyntaxError.message. Some restored
|
||||
// JSON files contain credentials, so expose only a fixed diagnostic while
|
||||
// retaining the original exception as the in-process cause.
|
||||
throw new RestorePreflightError(name, 'invalid JSON', { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function prepareNormalizedJson<T>(name: string, data: Buffer, normalize: (value: unknown) => T): {
|
||||
data: Buffer;
|
||||
migratedFields: string[];
|
||||
} {
|
||||
const raw = parseJson(name, data);
|
||||
const canonical = normalize(raw);
|
||||
const migratedFields: string[] = [];
|
||||
assertNoLossyNormalization(name, raw, canonical, '$', migratedFields);
|
||||
return { data: serializeJson(canonical), migratedFields };
|
||||
}
|
||||
|
||||
function prepareRuntimeJson(name: string, data: Buffer): {
|
||||
data: Buffer;
|
||||
migratedFields: string[];
|
||||
} {
|
||||
const prepared = prepareNormalizedJson(name, data, normalizeRuntimeConfig);
|
||||
const runtime = JSON.parse(prepared.data.toString('utf8')) as ReturnType<typeof normalizeRuntimeConfig>;
|
||||
if (!runtime.webuiHost || !isValidBindHost(runtime.webuiHost)) {
|
||||
throw new RestorePreflightError(name, '$.webuiHost is not a valid TCP bind host');
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
|
||||
function prepareGlobalSettingsJson(name: string, data: Buffer): {
|
||||
data: Buffer;
|
||||
migratedFields: string[];
|
||||
} {
|
||||
const raw = parseJson(name, data);
|
||||
const normalized = normalizeGlobalSettings(raw);
|
||||
const canonical: Record<string, unknown> = { rkey: normalized.rkey };
|
||||
// Missing is the existing one-shot migration sentinel: startup scans legacy
|
||||
// onebot*.json only until snowluma.json first carries this key.
|
||||
if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'musicSignUrl')) {
|
||||
canonical.musicSignUrl = normalized.musicSignUrl;
|
||||
}
|
||||
const migratedFields: string[] = [];
|
||||
assertNoLossyNormalization(name, raw, canonical, '$', migratedFields);
|
||||
return { data: serializeJson(canonical), migratedFields };
|
||||
}
|
||||
|
||||
function assertNoLossyNormalization(
|
||||
name: string,
|
||||
raw: unknown,
|
||||
canonical: unknown,
|
||||
at: string,
|
||||
additions: string[],
|
||||
): void {
|
||||
if (isPlainObject(raw)) {
|
||||
if (!isPlainObject(canonical)) throw new RestorePreflightError(name, `${at} has an invalid type`);
|
||||
for (const [key, rawValue] of Object.entries(raw)) {
|
||||
const child = `${at}.${key}`;
|
||||
if (!Object.prototype.hasOwnProperty.call(canonical, key)) {
|
||||
throw new RestorePreflightError(name, `${child} is unsupported or would be discarded`);
|
||||
}
|
||||
assertNoLossyNormalization(name, rawValue, canonical[key], child, additions);
|
||||
}
|
||||
for (const key of Object.keys(canonical)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(raw, key)) additions.push(`${at}.${key}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(raw)) {
|
||||
if (!Array.isArray(canonical) || raw.length !== canonical.length) {
|
||||
throw new RestorePreflightError(name, `${at} contains an invalid, duplicate, or discarded item`);
|
||||
}
|
||||
raw.forEach((value, index) => {
|
||||
assertNoLossyNormalization(name, value, canonical[index], `${at}[${String(index)}]`, additions);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!Object.is(raw, canonical)) {
|
||||
if (isKnownLosslessScalarCoercion(name, at, raw, canonical)) {
|
||||
additions.push(at);
|
||||
return;
|
||||
}
|
||||
throw new RestorePreflightError(name, `${at} is invalid or would be changed`);
|
||||
}
|
||||
}
|
||||
|
||||
function isKnownLosslessScalarCoercion(name: string, at: string, raw: unknown, canonical: unknown): boolean {
|
||||
if (typeof raw === 'string' && typeof canonical === 'string' && raw.trim() === canonical) {
|
||||
return true;
|
||||
}
|
||||
if (typeof raw === 'string' && typeof canonical === 'number') {
|
||||
const parsed = Number(raw.trim());
|
||||
return raw.trim().length > 0 && Number.isFinite(parsed) && Object.is(parsed, canonical);
|
||||
}
|
||||
if (
|
||||
name === 'runtime.json' &&
|
||||
(at === '$.hookAutoLoad' || at === '$.webuiTls.enabled') &&
|
||||
typeof canonical === 'boolean'
|
||||
) {
|
||||
if (raw === 1 || raw === 0) return canonical === (raw === 1);
|
||||
if (typeof raw !== 'string') return false;
|
||||
const token = raw.trim().toLowerCase();
|
||||
const truthy = new Set(['true', '1', 'yes', 'on']);
|
||||
const falsy = new Set(['false', '0', 'no', 'off', '']);
|
||||
return (canonical && truthy.has(token)) || (!canonical && falsy.has(token));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function serializeJson(value: unknown): Buffer {
|
||||
return Buffer.from(JSON.stringify(value, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function isValidBindHost(value: string): boolean {
|
||||
const host = value.trim();
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
|
||||
if (host.includes(':')) return isIP(host) === 6;
|
||||
if (/^[\d.]+$/.test(host)) {
|
||||
return isIP(host) === 4;
|
||||
}
|
||||
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
|
||||
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
|
||||
}
|
||||
|
||||
function validateEffectiveTls(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void {
|
||||
const byName = new Map(restore.map((file) => [file.name, file.data]));
|
||||
const pairTouched = byName.has('cert.pem') || byName.has('key.pem');
|
||||
const tlsRelated = pairTouched || byName.has('runtime.json');
|
||||
if (!tlsRelated) return;
|
||||
|
||||
const readEffective = (name: string): Buffer | null => {
|
||||
const prepared = byName.get(name);
|
||||
if (prepared) return prepared;
|
||||
try {
|
||||
return opts.readCurrent(name);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
}
|
||||
};
|
||||
const runtime = readEffective('runtime.json');
|
||||
let tlsEnabled = false;
|
||||
if (runtime) {
|
||||
try {
|
||||
tlsEnabled = normalizeRuntimeConfig(JSON.parse(runtime.toString('utf8')) as unknown).webuiTls?.enabled === true;
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError('runtime.json', 'effective runtime config is invalid JSON', { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
if (!tlsEnabled && !pairTouched) return;
|
||||
const cert = readEffective('cert.pem');
|
||||
const key = readEffective('key.pem');
|
||||
|
||||
if (cert && key) {
|
||||
const valid = validateTlsPair(cert, key);
|
||||
if (!valid.ok) throw new RestorePreflightError('cert.pem + key.pem', valid.reason ?? 'TLS pair is invalid');
|
||||
return;
|
||||
}
|
||||
if (tlsEnabled) {
|
||||
throw new RestorePreflightError('cert.pem + key.pem', 'TLS is enabled but the effective certificate/private-key pair is incomplete');
|
||||
}
|
||||
}
|
||||
|
||||
function validateEffectiveUi(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void {
|
||||
const byName = new Map(restore.map((file) => [file.name, file.data]));
|
||||
if (!byName.has('ui.json') && !byName.has('ui-assets/background')) return;
|
||||
|
||||
const readEffective = (name: string): Buffer | null => {
|
||||
const prepared = byName.get(name);
|
||||
if (prepared) return prepared;
|
||||
try {
|
||||
return opts.readCurrent(name);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
}
|
||||
};
|
||||
const uiBytes = readEffective('ui.json');
|
||||
if (!uiBytes) return;
|
||||
|
||||
let ui;
|
||||
try {
|
||||
ui = normalizeStoredUiConfig(JSON.parse(uiBytes.toString('utf8')) as unknown);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError('ui.json', 'effective UI config is invalid JSON', { cause: error });
|
||||
}
|
||||
const background = ui.appearance.background;
|
||||
if (!background.hasImage) return;
|
||||
|
||||
const image = readEffective('ui-assets/background');
|
||||
if (!image) {
|
||||
throw new RestorePreflightError('ui.json + ui-assets/background', 'background metadata says an image exists, but the effective image is missing');
|
||||
}
|
||||
if (image.length > MAX_BACKGROUND_BYTES) {
|
||||
throw new RestorePreflightError('ui.json + ui-assets/background', `effective background exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`);
|
||||
}
|
||||
const mime = sniffImageMime(image);
|
||||
if (!mime) {
|
||||
throw new RestorePreflightError('ui.json + ui-assets/background', 'effective background is not PNG, JPEG, or WebP');
|
||||
}
|
||||
if (mime !== background.imageMime) {
|
||||
throw new RestorePreflightError(
|
||||
'ui.json + ui-assets/background',
|
||||
`background metadata MIME ${background.imageMime} does not match image bytes ${mime}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Connection-status diff loop. OneBot adapters don't have an internal
|
||||
* event-emitter for connection state (listening / connected / client-count
|
||||
* changes), so this loop polls `getConnectionStatuses()` and publishes
|
||||
* `connections` to the StateBus when the JSON-serialised snapshot changes
|
||||
* vs the previous tick.
|
||||
*
|
||||
* Cheap (500ms default cadence, 1-3 accounts, ~hundreds of bytes), only
|
||||
* fires the StateBus when state actually moves — so the SSE handler only
|
||||
* pushes a fresh `connections` frame when the user would actually see
|
||||
* something update.
|
||||
*/
|
||||
|
||||
import type { StateBus } from './state-bus';
|
||||
|
||||
export interface ConnectionDiffLoopOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current adapter-status snapshot for every live UIN. */
|
||||
getSnapshot: () => unknown;
|
||||
/** Optional projector — return the "comparable" subset of the snapshot.
|
||||
* The full snapshot is what the SSE handler ships to the WebUI; this
|
||||
* projection is what the diff loop compares between ticks. Use it to
|
||||
* strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter
|
||||
* `detail` strings) that would otherwise produce a publish every tick
|
||||
* under any active webhook — defeating the loop's whole purpose.
|
||||
* Default: identity. */
|
||||
pickComparable?: (snapshot: unknown) => unknown;
|
||||
/** Poll cadence in milliseconds; default 500. */
|
||||
intervalMs?: number;
|
||||
}
|
||||
|
||||
export interface ConnectionDiffLoopHandle {
|
||||
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
|
||||
const intervalMs = opts.intervalMs ?? 500;
|
||||
let lastSerialized = '';
|
||||
let haveBaseline = false;
|
||||
let disposed = false;
|
||||
// One-shot diagnostic latch: a projector that starts throwing only after
|
||||
// a shape regression would otherwise wedge the baseline silently — no
|
||||
// publishes, no log, no symptom besides "the dashboard's connections
|
||||
// card stops updating". Surface it ONCE so the failure is visible.
|
||||
let warnedProjectorThrew = false;
|
||||
|
||||
const tick = (): void => {
|
||||
if (disposed) return;
|
||||
let snap: unknown;
|
||||
try {
|
||||
snap = opts.getSnapshot();
|
||||
} catch {
|
||||
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
|
||||
// next one will retry. Don't reset the baseline so we don't
|
||||
// spuriously republish when the snapshot starts working again.
|
||||
return;
|
||||
}
|
||||
let comparable: unknown;
|
||||
try {
|
||||
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
|
||||
} catch (err) {
|
||||
// A buggy projector must not crash the diff loop or wedge baseline.
|
||||
// But silent wedge is its own bug class — log the FIRST occurrence
|
||||
// so an operator can find it without re-running the loop locally.
|
||||
if (!warnedProjectorThrew) {
|
||||
warnedProjectorThrew = true;
|
||||
// Static logger import avoided to keep the loop self-contained;
|
||||
// stderr is good enough for a once-per-process latch.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('[connection-diff-loop] pickComparable threw — connections SSE diff will wedge until restart:', err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const serialized = JSON.stringify(comparable);
|
||||
if (!haveBaseline) {
|
||||
// First successful observation. The SSE handler's sendAllInitial
|
||||
// already shipped a `connections` frame to every connected client
|
||||
// on connect, so the baseline is what they already have — emitting
|
||||
// it again would be a duplicate. Just store it.
|
||||
lastSerialized = serialized;
|
||||
haveBaseline = true;
|
||||
return;
|
||||
}
|
||||
if (serialized === lastSerialized) return;
|
||||
lastSerialized = serialized;
|
||||
opts.bus.publish('connections');
|
||||
};
|
||||
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
// Don't pin the Node event loop: the loop is permanent for the server
|
||||
// lifetime by design, but tests / a future hot-reload scenario must be
|
||||
// able to exit cleanly without an outstanding interval ref. Mirrors the
|
||||
// tokenJanitor pattern in server.ts.
|
||||
timer.unref?.();
|
||||
|
||||
return {
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const log = createLogger('WebUI.Consent');
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const CONSENT_CONFIG_PATH = path.join(CONFIG_DIR, 'consent.json');
|
||||
|
||||
// The two legal documents shown at the consent gate. Source of truth is the
|
||||
// repo-root markdown; the build copies them next to the bundle (dist/) so the
|
||||
// same lookup works in a packaged deploy. See vite.config.ts cp targets.
|
||||
const AGREEMENT_FILES = [
|
||||
{ id: 'eula' as const, file: 'EULA.md' },
|
||||
{ id: 'privacy' as const, file: 'PRIVACY.md' },
|
||||
];
|
||||
|
||||
export const EULA_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_EULA';
|
||||
export const PRIVACY_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_PRIVACY';
|
||||
|
||||
type ConsentEnvironment = Readonly<Record<string, string | undefined>>;
|
||||
|
||||
export interface EnvironmentConsent {
|
||||
eulaAccepted: boolean;
|
||||
privacyAccepted: boolean;
|
||||
/** Both documents must be accepted; a partial opt-in never unlocks the gate. */
|
||||
accepted: boolean;
|
||||
}
|
||||
|
||||
export interface AgreementDoc {
|
||||
id: 'eula' | 'privacy';
|
||||
/** First markdown `# ` heading, for the tab/section title. */
|
||||
title: string;
|
||||
/** Declared "Version: x" from the doc — display only, NOT the consent key. */
|
||||
declaredVersion: string;
|
||||
/** Declared effective date (YYYY-MM-DD) — display only. */
|
||||
effectiveDate: string;
|
||||
/** Full markdown body the frontend renders. */
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ConsentRecord {
|
||||
/** The content-hash agreements version that was accepted. */
|
||||
version: string;
|
||||
/** ISO timestamp of acceptance. */
|
||||
acceptedAt: string;
|
||||
}
|
||||
|
||||
export interface AgreementsPayload {
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/**
|
||||
* True when the operator must (re-)accept: the agreements carry real text,
|
||||
* environment consent is incomplete, AND the stored consent version differs
|
||||
* from the current one. A missing or unreadable agreement set fails OPEN (no
|
||||
* gate) so a broken bundle can never lock the admin out of their own panel.
|
||||
*/
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
}
|
||||
|
||||
function parseEnvironmentAcceptance(name: string, raw: string | undefined): boolean {
|
||||
if (raw === undefined || raw.trim() === '') return false;
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === '1' || normalized === 'true') return true;
|
||||
if (normalized === '0' || normalized === 'false') return false;
|
||||
|
||||
throw new Error(
|
||||
`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve declarative consent for unattended deployments. Environment consent
|
||||
* is intentionally ephemeral: removing either variable restores the normal
|
||||
* versioned consent gate instead of silently writing a permanent record.
|
||||
*/
|
||||
export function resolveEnvironmentConsent(
|
||||
env: ConsentEnvironment = process.env,
|
||||
): EnvironmentConsent {
|
||||
const eulaAccepted = parseEnvironmentAcceptance(EULA_ACCEPT_ENV, env[EULA_ACCEPT_ENV]);
|
||||
const privacyAccepted = parseEnvironmentAcceptance(PRIVACY_ACCEPT_ENV, env[PRIVACY_ACCEPT_ENV]);
|
||||
return {
|
||||
eulaAccepted,
|
||||
privacyAccepted,
|
||||
accepted: eulaAccepted && privacyAccepted,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Agreement loading (pure-ish; file read + parse, cached) ─────────────────
|
||||
|
||||
/**
|
||||
* Resolve an agreement file across the dev and packaged layouts. In dev the
|
||||
* server runs from source (`__dirname` = packages/core/src/webui); in a build
|
||||
* it is the single bundled dist/index.mjs (`__dirname` = dist/) with the docs
|
||||
* copied alongside. cwd is not reliable (dev cwd = packages/core, prod = repo
|
||||
* root or dist/), so we probe a handful of candidates and take the first hit.
|
||||
*/
|
||||
function resolveAgreementFile(file: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, file), // packaged: dist/<file>
|
||||
path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/<file>
|
||||
path.resolve(process.cwd(), file), // started from repo root
|
||||
path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
} catch {
|
||||
/* unreadable candidate, try next */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Extract title / declared version / effective date from a doc body. */
|
||||
export function parseAgreementMeta(text: string): {
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
} {
|
||||
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? '';
|
||||
// Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines.
|
||||
const declaredVersion =
|
||||
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.-]*)/)?.[1]?.trim() ?? '';
|
||||
const effectiveDate =
|
||||
text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? '';
|
||||
return { title, declaredVersion, effectiveDate };
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical agreements version = short sha256 over each doc's id + body.
|
||||
* Deliberately content-derived, NOT app-version-derived: it stays stable when
|
||||
* only the app is upgraded (so a one-time consent survives across versions),
|
||||
* and changes the moment any agreement's TEXT changes (forcing re-consent).
|
||||
*/
|
||||
export function computeAgreementsVersion(docs: { id: string; text: string }[]): string {
|
||||
const hash = createHash('sha256');
|
||||
for (const doc of docs) {
|
||||
hash.update(doc.id);
|
||||
hash.update('\0');
|
||||
hash.update(doc.text);
|
||||
hash.update('\0');
|
||||
}
|
||||
return hash.digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
let cache: { docs: AgreementDoc[]; version: string } | null = null;
|
||||
|
||||
/** Load + parse both agreements and compute the version. Cached per process. */
|
||||
export function loadAgreements(): { docs: AgreementDoc[]; version: string } {
|
||||
if (cache) return cache;
|
||||
const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => {
|
||||
const resolved = resolveAgreementFile(file);
|
||||
let text = '';
|
||||
if (resolved) {
|
||||
try {
|
||||
text = fs.readFileSync(resolved, 'utf8');
|
||||
} catch (err) {
|
||||
log.warn('failed to read %s: %s', file, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else {
|
||||
log.warn('agreement file not found (looked for %s near the bundle and repo root)', file);
|
||||
}
|
||||
const meta = parseAgreementMeta(text);
|
||||
return { id, title: meta.title, declaredVersion: meta.declaredVersion, effectiveDate: meta.effectiveDate, text };
|
||||
});
|
||||
cache = { docs, version: computeAgreementsVersion(docs) };
|
||||
return cache;
|
||||
}
|
||||
|
||||
// ── Consent persistence (config/consent.json, atomic) ───────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function isConsentRecord(value: unknown): value is ConsentRecord {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string';
|
||||
}
|
||||
|
||||
export function loadConsentRecord(): ConsentRecord | null {
|
||||
try {
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) return null;
|
||||
const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isConsentRecord(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn('consent.json unreadable, treating as no consent: %s', err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(record: ConsentRecord): void {
|
||||
ensureConfigDir();
|
||||
const tmp = CONSENT_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' });
|
||||
fs.renameSync(tmp, CONSENT_CONFIG_PATH);
|
||||
}
|
||||
|
||||
/** Persist that the operator accepted `version`. Returns the stored record. */
|
||||
export function recordConsent(version: string): ConsentRecord {
|
||||
const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() };
|
||||
atomicWrite(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
/** True when neither environment nor stored consent covers the current agreements. */
|
||||
export function isConsentRequired(env: ConsentEnvironment = process.env): boolean {
|
||||
if (resolveEnvironmentConsent(env).accepted) return false;
|
||||
|
||||
const { docs, version } = loadAgreements();
|
||||
const hasContent = docs.some((d) => d.text.trim().length > 0);
|
||||
if (!hasContent) return false; // fail open: never brick the panel on a broken bundle
|
||||
return loadConsentRecord()?.version !== version;
|
||||
}
|
||||
|
||||
/** Public payload for GET /api/agreements (texts + version + consentRequired). */
|
||||
export function getAgreementsPayload(): AgreementsPayload {
|
||||
const { docs, version } = loadAgreements();
|
||||
return { version, consentRequired: isConsentRequired(), documents: docs };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// SSE frame pusher for the debug stream (Wave A3). Drops frames under
|
||||
// backpressure (consumer slow → desiredSize <= 0) instead of buffering
|
||||
// unbounded into memory, and coalesces the drop count into a {kind:'dropped'}
|
||||
// marker emitted just before the next delivered frame. Extracted from the route
|
||||
// handler so this (easy-to-get-wrong) logic is unit-tested.
|
||||
|
||||
export interface FramePusherOptions {
|
||||
/** The stream controller's current desiredSize (null = no backpressure info). */
|
||||
desiredSize: () => number | null;
|
||||
/** Deliver an encoded SSE chunk (the caller maps this to the controller). */
|
||||
enqueue: (chunk: Uint8Array) => void;
|
||||
encode?: (s: string) => Uint8Array;
|
||||
}
|
||||
|
||||
/** Returns a `push(payload)` that frames + delivers with backpressure dropping. */
|
||||
export function createFramePusher(opts: FramePusherOptions): (payload: unknown) => void {
|
||||
const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s));
|
||||
let dropped = 0;
|
||||
return (payload: unknown): void => {
|
||||
const d = opts.desiredSize();
|
||||
if (d !== null && d <= 0) { dropped += 1; return; }
|
||||
if (dropped > 0) {
|
||||
opts.enqueue(encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`));
|
||||
dropped = 0;
|
||||
}
|
||||
opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// debug-tools — backend for the debug console's two heavier endpoints
|
||||
// (Phase 2 of the debug-console expansion):
|
||||
//
|
||||
// • POST /api/debug/invoke-stream — drive a Stream API action and relay every
|
||||
// frame to the browser over an SSE body. Unlike the live-activity stream
|
||||
// (debug-stream.ts), this MUST NOT drop frames: a file transfer that loses a
|
||||
// chunk is corrupt. So backpressure is handled by *waiting* for the consumer
|
||||
// to drain, never by dropping.
|
||||
// • POST /api/debug/upload — stream a browser-selected file to a temp path on
|
||||
// the SERVER (the bot runs on the server, not the user's machine), so the
|
||||
// returned path can be fed to a send action. Streamed straight to disk with a
|
||||
// byte cap — never buffered whole, so large videos don't blow up memory.
|
||||
//
|
||||
// The pure pieces live here (path sanitisation, the size-capped disk sink, the
|
||||
// stream-invoke Response builder) so they are unit-testable away from Hono.
|
||||
|
||||
import { createWriteStream } from 'fs';
|
||||
import { mkdir, readdir, rm, stat } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
|
||||
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
|
||||
* kept distinct so the two cleanup stories don't entangle. */
|
||||
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload');
|
||||
|
||||
/** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */
|
||||
export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
|
||||
/** Uploads older than this are swept on the next upload (best-effort). */
|
||||
const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Reduce a client-supplied filename to a safe basename (extension preserved),
|
||||
* with no path separators or traversal. The client path is NEVER trusted for
|
||||
* placement — this is only used to keep the stored name human-readable. */
|
||||
export function safeUploadName(raw: string | undefined): string {
|
||||
// Treat both separators as path delimiters, then take the basename so any
|
||||
// `../` / absolute prefix is discarded regardless of host platform.
|
||||
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
|
||||
const cleaned = base
|
||||
.replace(/[^\w.\-]+/g, '_') // collapse anything exotic to underscore
|
||||
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
|
||||
.slice(0, 120);
|
||||
return cleaned || 'file';
|
||||
}
|
||||
|
||||
/** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name.
|
||||
* Throws if the composed path would escape the dir (defence in depth — it
|
||||
* can't, given the random id + basename, but we assert anyway). */
|
||||
export function uploadDestPath(safeName: string): string {
|
||||
const id = randomBytes(12).toString('hex');
|
||||
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
|
||||
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
|
||||
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||
throw new Error('invalid upload path');
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
/** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing
|
||||
* a byte cap. Returns the final server path + byte size. On overflow or any
|
||||
* error the partial file is removed and the call rejects. Never buffers the
|
||||
* whole body. */
|
||||
export async function streamUploadToDisk(
|
||||
body: ReadableStream<Uint8Array> | null,
|
||||
filename: string | undefined,
|
||||
opts: { maxBytes?: number } = {},
|
||||
): Promise<{ path: string; size: number }> {
|
||||
if (!body) throw new Error('empty body');
|
||||
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
|
||||
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
|
||||
void sweepOldUploads(); // fire-and-forget TTL cleanup
|
||||
|
||||
const dest = uploadDestPath(safeUploadName(filename));
|
||||
const out = createWriteStream(dest, { mode: 0o600 });
|
||||
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
|
||||
// background flush — typically while we're parked at reader.read() or waiting
|
||||
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
|
||||
// backpressured error would leave 'drain' to never fire (a forever-hung await
|
||||
// + leaked fd). So turn it into a rejection and race it into every await; the
|
||||
// catch below then destroys + unlinks the partial.
|
||||
const errored = new Promise<never>((_, rej) => out.once('error', rej));
|
||||
errored.catch(() => { /* swallow a late error after success (still raced below) */ });
|
||||
let size = 0;
|
||||
try {
|
||||
const reader = body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await Promise.race([errored, reader.read()]);
|
||||
if (done) break;
|
||||
if (!value || value.byteLength === 0) continue;
|
||||
size += value.byteLength;
|
||||
if (size > maxBytes) throw new Error('上传超出大小上限');
|
||||
// Respect the write stream's backpressure (but never hang on an error).
|
||||
if (!out.write(value)) {
|
||||
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
|
||||
}
|
||||
}
|
||||
await Promise.race([errored, new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]);
|
||||
if (size === 0) throw new Error('empty body');
|
||||
return { path: dest, size };
|
||||
} catch (err) {
|
||||
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
|
||||
// opens the fd asynchronously, so a fast failure can reach `rm` before the
|
||||
// file even exists on disk — then the late open would re-create it and leak
|
||||
// the partial. 'close' guarantees the fd is settled and no more writes land.
|
||||
out.destroy();
|
||||
if (!out.closed) await new Promise<void>((res) => out.once('close', () => res()));
|
||||
await rm(dest, { force: true }).catch(() => { /* best-effort */ });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove upload temp files older than the TTL. Best-effort; never throws. */
|
||||
export async function sweepOldUploads(now: number = Date.now()): Promise<number> {
|
||||
let removed = 0;
|
||||
try {
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR);
|
||||
await Promise.all(
|
||||
names.map(async (n) => {
|
||||
const p = path.join(DEBUG_UPLOAD_DIR, n);
|
||||
try {
|
||||
const s = await stat(p);
|
||||
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
|
||||
await rm(p, { force: true, recursive: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch { /* racing cleanup / vanished file */ }
|
||||
}),
|
||||
);
|
||||
} catch { /* dir absent yet */ }
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** Drives a stream-capable action and relays its frames. The driver is the
|
||||
* instance's `invokeStream` (which itself handles non-stream actions by emitting
|
||||
* a single frame). */
|
||||
export type StreamInvokeDriver = (
|
||||
rawRequest: string,
|
||||
emit: (json: string) => Promise<void>,
|
||||
isAlive: () => boolean,
|
||||
) => Promise<void>;
|
||||
|
||||
/** How long emit() will wait for a backed-up consumer to drain before it gives
|
||||
* up waiting and enqueues anyway (the request abort / action idle-watchdog are
|
||||
* the real stall guards). */
|
||||
const DRAIN_WAIT_MS = 20;
|
||||
const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s
|
||||
|
||||
/** Build the SSE `Response` for `/api/debug/invoke-stream`: each relayed frame
|
||||
* is one `data: <json>\n\n` event; no frame is ever dropped. A driver error
|
||||
* becomes a terminal `failed` frame. Closing the request (signal abort) stops
|
||||
* delivery. `delay` is injectable for tests. */
|
||||
export function buildStreamInvokeResponse(
|
||||
driver: StreamInvokeDriver,
|
||||
rawRequest: string,
|
||||
signal: AbortSignal,
|
||||
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
||||
): Response {
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
let closed = false;
|
||||
const onAbort = () => { closed = true; };
|
||||
signal.addEventListener('abort', onAbort);
|
||||
const isAlive = () => !closed && !signal.aborted;
|
||||
|
||||
const emit = async (json: string): Promise<void> => {
|
||||
if (!isAlive()) throw new Error('stream transport closed');
|
||||
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
|
||||
let spins = 0;
|
||||
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
|
||||
await delay(DRAIN_WAIT_MS);
|
||||
spins += 1;
|
||||
}
|
||||
if (!isAlive()) throw new Error('stream transport closed');
|
||||
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
|
||||
try {
|
||||
await driver(rawRequest, emit, isAlive);
|
||||
} catch (err) {
|
||||
if (isAlive()) {
|
||||
const msg = err instanceof Error ? err.message : 'stream error';
|
||||
try {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`));
|
||||
} catch { /* controller already torn down */ }
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
try { controller.close(); } catch { /* already closed */ }
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
prepareRestorePlan,
|
||||
RestorePreflightError,
|
||||
type RestoreMigration,
|
||||
} from './backup';
|
||||
|
||||
const log = createLogger('WebUI.Restore');
|
||||
|
||||
export type RestorePhase = 'preflight' | 'snapshot' | 'stage' | 'commit' | 'rollback' | 'cleanup';
|
||||
|
||||
export interface RestoreOperation {
|
||||
phase: Exclude<RestorePhase, 'preflight'>;
|
||||
operation:
|
||||
| 'copy-current'
|
||||
| 'write-staged'
|
||||
| 'chmod-staged'
|
||||
| 'rename-staged'
|
||||
| 'restore-current'
|
||||
| 'remove-created'
|
||||
| 'remove-transaction';
|
||||
file?: string;
|
||||
}
|
||||
|
||||
export interface RestoreBackupOptions {
|
||||
configDir: string;
|
||||
restoreCredentials: boolean;
|
||||
/** Deterministic id for tests/diagnostics; production normally omits it. */
|
||||
transactionId?: string;
|
||||
/** Filesystem-boundary fault hook used by the transaction fault matrix. */
|
||||
beforeOperation?: (operation: RestoreOperation) => void;
|
||||
}
|
||||
|
||||
export interface RestoreBackupResult {
|
||||
transactionId: string;
|
||||
restored: string[];
|
||||
skipped: string[];
|
||||
migrated: RestoreMigration[];
|
||||
restartRequiredToApply: boolean;
|
||||
}
|
||||
|
||||
export class RestoreTransactionError extends Error {
|
||||
readonly phase: RestorePhase;
|
||||
readonly transactionId: string;
|
||||
readonly rollbackSucceeded?: boolean;
|
||||
readonly snapshotDir?: string;
|
||||
readonly committed: boolean;
|
||||
readonly failedFiles: string[];
|
||||
|
||||
constructor(options: {
|
||||
phase: RestorePhase;
|
||||
transactionId: string;
|
||||
message: string;
|
||||
cause: unknown;
|
||||
rollbackSucceeded?: boolean;
|
||||
snapshotDir?: string;
|
||||
committed?: boolean;
|
||||
failedFiles?: string[];
|
||||
}) {
|
||||
super(options.message, { cause: options.cause });
|
||||
this.name = 'RestoreTransactionError';
|
||||
this.phase = options.phase;
|
||||
this.transactionId = options.transactionId;
|
||||
this.rollbackSucceeded = options.rollbackSucceeded;
|
||||
this.snapshotDir = options.snapshotDir;
|
||||
this.committed = options.committed ?? false;
|
||||
this.failedFiles = options.failedFiles ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
interface CommittedFile {
|
||||
name: string;
|
||||
existed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore one validated overlay as a process-level transaction.
|
||||
*
|
||||
* This deliberately does not promise recovery from power loss or SIGKILL.
|
||||
* Within the running process, every failure before commit leaves live files
|
||||
* untouched. A partial commit is rolled back when possible; incomplete
|
||||
* rollback retains the transaction directory and reports its recovery path.
|
||||
*/
|
||||
export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): RestoreBackupResult {
|
||||
const transactionId = options.transactionId ?? randomUUID();
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(transactionId)) {
|
||||
throw new Error('restore transactionId must contain only letters, numbers, _ or -');
|
||||
}
|
||||
const configDir = path.resolve(options.configDir);
|
||||
const readCurrent = (name: string): Buffer | null => {
|
||||
const file = path.join(configDir, name);
|
||||
try {
|
||||
return fs.readFileSync(file);
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
const listCurrentOneBotNames = (): string[] => {
|
||||
try {
|
||||
return fs.readdirSync(configDir);
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) return [];
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
log.info('restore transaction=%s phase=preflight', transactionId);
|
||||
let prepared: ReturnType<typeof prepareRestorePlan>;
|
||||
try {
|
||||
prepared = prepareRestorePlan(parsed, {
|
||||
restoreCredentials: options.restoreCredentials,
|
||||
readCurrent,
|
||||
listCurrentOneBotNames,
|
||||
});
|
||||
} catch (error) {
|
||||
const file = error instanceof RestorePreflightError ? error.file : undefined;
|
||||
log.warn(
|
||||
'restore transaction=%s phase=preflight file=%s failed error=%s',
|
||||
transactionId,
|
||||
file ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'preflight',
|
||||
transactionId,
|
||||
message: `restore preflight failed: ${errorMessage(error)}`,
|
||||
cause: error,
|
||||
failedFiles: file ? [file] : [],
|
||||
});
|
||||
}
|
||||
const names = prepared.restore.map((file) => file.name);
|
||||
log.info('restore transaction=%s phase=preflight-complete files=%s', transactionId, names.join(','));
|
||||
|
||||
if (prepared.restore.length === 0) {
|
||||
return {
|
||||
transactionId,
|
||||
restored: [],
|
||||
skipped: prepared.skipped,
|
||||
migrated: prepared.migrated,
|
||||
restartRequiredToApply: false,
|
||||
};
|
||||
}
|
||||
|
||||
const transactionDir = path.join(configDir, `.restore-transaction-${transactionId}`);
|
||||
const snapshotRoot = path.join(transactionDir, 'snapshot');
|
||||
const stagedRoot = path.join(transactionDir, 'staged');
|
||||
const rollbackRoot = path.join(transactionDir, 'rollback');
|
||||
const existed = new Map<string, boolean>();
|
||||
const committed: CommittedFile[] = [];
|
||||
let phase: 'snapshot' | 'stage' | 'commit' = 'snapshot';
|
||||
let activeFile: string | undefined;
|
||||
let transactionCreated = false;
|
||||
|
||||
try {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.mkdirSync(transactionDir, { mode: 0o700 });
|
||||
transactionCreated = true;
|
||||
fs.chmodSync(transactionDir, 0o700);
|
||||
|
||||
log.info('restore transaction=%s phase=snapshot files=%s', transactionId, names.join(','));
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const live = path.join(configDir, file.name);
|
||||
let wasPresent: boolean;
|
||||
try {
|
||||
fs.lstatSync(live);
|
||||
wasPresent = true;
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) throw error;
|
||||
wasPresent = false;
|
||||
}
|
||||
existed.set(file.name, wasPresent);
|
||||
if (!wasPresent) continue;
|
||||
const snapshot = path.join(snapshotRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(snapshot), { recursive: true });
|
||||
invoke(options, { phase: 'snapshot', operation: 'copy-current', file: file.name });
|
||||
fs.copyFileSync(live, snapshot);
|
||||
}
|
||||
|
||||
phase = 'stage';
|
||||
log.info('restore transaction=%s phase=stage files=%s', transactionId, names.join(','));
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const staged = path.join(stagedRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(staged), { recursive: true });
|
||||
invoke(options, { phase: 'stage', operation: 'write-staged', file: file.name });
|
||||
fs.writeFileSync(staged, file.data, { flag: 'wx', mode: file.mode });
|
||||
invoke(options, { phase: 'stage', operation: 'chmod-staged', file: file.name });
|
||||
fs.chmodSync(staged, file.mode);
|
||||
}
|
||||
|
||||
phase = 'commit';
|
||||
log.info('restore transaction=%s phase=commit files=%s', transactionId, names.join(','));
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const staged = path.join(stagedRoot, file.name);
|
||||
const live = path.join(configDir, file.name);
|
||||
fs.mkdirSync(path.dirname(live), { recursive: true });
|
||||
invoke(options, { phase: 'commit', operation: 'rename-staged', file: file.name });
|
||||
fs.renameSync(staged, live);
|
||||
committed.push({ name: file.name, existed: existed.get(file.name) === true });
|
||||
}
|
||||
activeFile = undefined;
|
||||
} catch (error) {
|
||||
if (phase !== 'commit') {
|
||||
const cleanupError = transactionCreated ? removeTransaction(options, transactionDir) : null;
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=%s file=%s original-error=%s cleanup-error=%s',
|
||||
transactionId,
|
||||
phase,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
errorMessage(cleanupError),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: `restore ${phase} failed and transaction cleanup also failed`,
|
||||
cause: new AggregateError([error, cleanupError], `restore ${phase} and cleanup both failed`),
|
||||
snapshotDir: transactionDir,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
log.warn(
|
||||
'restore transaction=%s phase=%s file=%s failed error=%s',
|
||||
transactionId,
|
||||
phase,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase,
|
||||
transactionId,
|
||||
message: `restore ${phase} failed before live commit`,
|
||||
cause: error,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
const rollbackErrors = rollbackCommitted(options, configDir, snapshotRoot, rollbackRoot, committed);
|
||||
if (rollbackErrors.length > 0) {
|
||||
const failedFiles = rollbackErrors.map((entry) => entry.name);
|
||||
const rollbackDetails = rollbackErrors
|
||||
.map((entry) => `${entry.name}:${errorMessage(entry.error)}`)
|
||||
.join(';');
|
||||
log.error(
|
||||
'restore transaction=%s phase=rollback commit-file=%s commit-error=%s failed=%s snapshot=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
rollbackDetails,
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'rollback',
|
||||
transactionId,
|
||||
message: 'restore commit failed and rollback was incomplete',
|
||||
cause: new AggregateError(
|
||||
[error, ...rollbackErrors.map((entry) => entry.error)],
|
||||
'restore commit and rollback both failed',
|
||||
),
|
||||
rollbackSucceeded: false,
|
||||
snapshotDir: transactionDir,
|
||||
committed: committed.length > 0,
|
||||
failedFiles,
|
||||
});
|
||||
}
|
||||
|
||||
const cleanupError = removeTransaction(options, transactionDir);
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=rollback commit-file=%s commit-error=%s cleanup-error=%s snapshot=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
errorMessage(cleanupError),
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: 'restore commit failed, rollback succeeded, but transaction cleanup failed',
|
||||
cause: new AggregateError([error, cleanupError], 'restore commit and post-rollback cleanup both failed'),
|
||||
rollbackSucceeded: true,
|
||||
snapshotDir: transactionDir,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
log.warn(
|
||||
'restore transaction=%s phase=commit file=%s failed rollback=complete error=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'commit',
|
||||
transactionId,
|
||||
message: 'restore commit failed; every committed file was rolled back',
|
||||
cause: error,
|
||||
rollbackSucceeded: true,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
const cleanupError = removeTransaction(options, transactionDir);
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=commit cleanup-error=%s snapshot=%s',
|
||||
transactionId,
|
||||
errorMessage(cleanupError),
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: 'restore committed successfully, but transaction cleanup failed',
|
||||
cause: cleanupError,
|
||||
snapshotDir: transactionDir,
|
||||
committed: true,
|
||||
});
|
||||
}
|
||||
|
||||
log.info('restore transaction=%s phase=complete files=%s', transactionId, names.join(','));
|
||||
return {
|
||||
transactionId,
|
||||
restored: names,
|
||||
skipped: prepared.skipped,
|
||||
migrated: prepared.migrated,
|
||||
restartRequiredToApply: true,
|
||||
};
|
||||
}
|
||||
|
||||
function rollbackCommitted(
|
||||
options: RestoreBackupOptions,
|
||||
configDir: string,
|
||||
snapshotRoot: string,
|
||||
rollbackRoot: string,
|
||||
committed: readonly CommittedFile[],
|
||||
): Array<{ name: string; error: unknown }> {
|
||||
const errors: Array<{ name: string; error: unknown }> = [];
|
||||
for (const file of [...committed].reverse()) {
|
||||
const live = path.join(configDir, file.name);
|
||||
try {
|
||||
if (!file.existed) {
|
||||
invoke(options, { phase: 'rollback', operation: 'remove-created', file: file.name });
|
||||
fs.rmSync(live, { force: true });
|
||||
continue;
|
||||
}
|
||||
const snapshot = path.join(snapshotRoot, file.name);
|
||||
const rollback = path.join(rollbackRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(rollback), { recursive: true });
|
||||
invoke(options, { phase: 'rollback', operation: 'restore-current', file: file.name });
|
||||
fs.copyFileSync(snapshot, rollback);
|
||||
fs.chmodSync(rollback, fs.statSync(snapshot).mode & 0o777);
|
||||
fs.renameSync(rollback, live);
|
||||
} catch (error) {
|
||||
errors.push({ name: file.name, error });
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
function removeTransaction(options: RestoreBackupOptions, transactionDir: string): unknown | null {
|
||||
try {
|
||||
invoke(options, { phase: 'cleanup', operation: 'remove-transaction' });
|
||||
fs.rmSync(transactionDir, { recursive: true, force: true });
|
||||
return null;
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
function invoke(options: RestoreBackupOptions, operation: RestoreOperation): void {
|
||||
options.beforeOperation?.(operation);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function isMissingPathError(error: unknown): boolean {
|
||||
return typeof error === 'object'
|
||||
&& error !== null
|
||||
&& 'code' in error
|
||||
&& error.code === 'ENOENT';
|
||||
}
|
||||
+1034
-76
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,69 @@
|
||||
import { type Context } from 'hono';
|
||||
|
||||
/**
|
||||
* The per-connection channel handed to an SSE endpoint's `start` callback.
|
||||
* Everything the endpoint needs to talk to the client, without owning the
|
||||
* transport lifecycle (heartbeat / teardown / abort / headers).
|
||||
*/
|
||||
export interface SseChannel {
|
||||
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
|
||||
raw(chunk: Uint8Array): void;
|
||||
/** Encode a string to bytes (shared TextEncoder). */
|
||||
encode(s: string): Uint8Array;
|
||||
/** Convenience: enqueue one `data: <json>\n\n` frame. */
|
||||
send(payload: unknown): void;
|
||||
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
|
||||
onClose(fn: () => void): void;
|
||||
/** True after teardown — guard sends from late subscription callbacks. */
|
||||
isClosed(): boolean;
|
||||
/** Underlying controller backpressure signal, for `createFramePusher`. */
|
||||
desiredSize(): number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The SSE HTTP transport shell shared by the WebUI's live endpoints. Owns the
|
||||
* TextEncoder, a `closed` guard, a 15s `: heartbeat` keep-alive, teardown
|
||||
* (clear heartbeat → run registered cleanups → close the controller), safe
|
||||
* enqueue (a throw means the peer dropped → teardown), the abort listener, and
|
||||
* the `text/event-stream` headers. `start` wires up the endpoint-specific
|
||||
* subscription + initial sends via the channel.
|
||||
*
|
||||
* Each of `/api/debug/stream`, `/api/state/stream`, `/api/logs/stream`
|
||||
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
|
||||
* teardown-order / header change had to be kept in sync across all three.
|
||||
*/
|
||||
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
||||
const cleanups: Array<() => void> = [];
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
const ch: SseChannel = {
|
||||
raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
|
||||
onClose: (fn) => { cleanups.push(fn); },
|
||||
isClosed: () => closed,
|
||||
desiredSize: () => controller.desiredSize,
|
||||
};
|
||||
start(ch);
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* StateBus — pure pub/sub for WebUI state-resource invalidations.
|
||||
*
|
||||
* Three resources are tracked: `processes`, `qq-list`, `connections`. A
|
||||
* publisher (HookSession status change, BridgeManager session start/close,
|
||||
* the connection-status diff loop) calls `publish(resource)` to signal "the
|
||||
* snapshot for THIS resource is stale; whoever cares should re-read". The
|
||||
* `/api/state/stream` SSE handler subscribes, debounces, and pushes fresh
|
||||
* snapshots to connected WebUI clients.
|
||||
*
|
||||
* Intentionally pure pub/sub (no debounce, no snapshot caching): debounce
|
||||
* and snapshot reads live with the subscriber so different consumers can
|
||||
* coalesce on different cadences. Snapshot semantics on fan-out: the
|
||||
* subscriber set is FROZEN at the start of each publish, so a listener
|
||||
* that subscribes during the fan-out only sees the FOLLOWING publish, and
|
||||
* a listener that unsubscribes mid-fan-out does not prevent its peers
|
||||
* from completing.
|
||||
*/
|
||||
|
||||
export type StateResource = 'processes' | 'qq-list' | 'connections';
|
||||
|
||||
export type StateListener = (resource: StateResource) => void;
|
||||
|
||||
export class StateBus {
|
||||
private readonly listeners = new Set<StateListener>();
|
||||
private disposed = false;
|
||||
|
||||
/** Subscribe to every publish; returns an unsubscribe handle. Calling
|
||||
* the handle more than once is a no-op. */
|
||||
subscribe(listener: StateListener): () => void {
|
||||
if (this.disposed) return () => undefined;
|
||||
this.listeners.add(listener);
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** Notify every CURRENTLY-subscribed listener that `resource` is stale.
|
||||
* Iterates a frozen snapshot of the subscriber set so add/remove during
|
||||
* the emit don't change which listeners see THIS publish; subscriber
|
||||
* exceptions are isolated and do not abort the fan-out. */
|
||||
publish(resource: StateResource): void {
|
||||
if (this.disposed) return;
|
||||
// Snapshot the current subscribers — any subscribe()/unsubscribe()
|
||||
// called by a listener during the fan-out takes effect only for the
|
||||
// NEXT publish, not this one.
|
||||
const snapshot = [...this.listeners];
|
||||
for (const fn of snapshot) {
|
||||
try {
|
||||
fn(resource);
|
||||
} catch {
|
||||
// Subscriber-internal failure is its own problem. The bus's job
|
||||
// is to keep delivery moving — surfacing an error here would
|
||||
// partially abort the fan-out and create skip-the-listener bugs.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every subscriber and refuse future subscribes / publishes. */
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.listeners.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Bind a StateBus to an SSE-friendly `send` callback: every publish becomes
|
||||
* a debounced fresh-snapshot frame, and `sendAllInitial()` primes a new
|
||||
* connection with one frame per resource.
|
||||
*
|
||||
* Decoupled from the HTTP layer so the route handler in server.ts can drop
|
||||
* its responsibility down to "open a ReadableStream, hand its enqueue to
|
||||
* bindStateStream, abort tears it down". Pure logic = unit-testable with
|
||||
* fake timers; no Response/controller mocking needed.
|
||||
*
|
||||
* Per-resource debounce, not global: an 'qq-list' churn during a slow
|
||||
* 'processes' burst must not delay the qq-list frame, and a 'connections'
|
||||
* diff loop running at 500ms must not coalesce 10 unrelated processes
|
||||
* events into one. Each resource is its own timer.
|
||||
*/
|
||||
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
|
||||
export interface StateStreamFrame {
|
||||
resource: StateResource;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export interface BindStateStreamOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current snapshot for one resource. May be sync or async. */
|
||||
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
|
||||
/** Receive a fresh frame; called once per debounced publish.
|
||||
* Exceptions are caught — a dead controller must not abort the bus
|
||||
* subscription or break sibling resources. */
|
||||
send: (frame: StateStreamFrame) => void;
|
||||
/** Coalesce window in milliseconds; default 50. */
|
||||
debounceMs?: number;
|
||||
}
|
||||
|
||||
export interface StateStreamHandle {
|
||||
/** Emit one frame per resource using the current snapshot. Use on connect. */
|
||||
sendAllInitial(): Promise<void>;
|
||||
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
|
||||
* produce nothing through this binding. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connections'];
|
||||
|
||||
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
|
||||
const debounceMs = opts.debounceMs ?? 50;
|
||||
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
|
||||
// Single-flight per resource: at most one in-flight flush per resource so
|
||||
// an uneven snapshot latency cannot interleave sends out of order (a slow
|
||||
// earlier snapshot landing AFTER a later one, leaving the client's last
|
||||
// observed frame stale). Publishes arriving while a flush is in flight
|
||||
// mark `pending` and rearm the debounce timer once the flush completes.
|
||||
const inFlight = new Set<StateResource>();
|
||||
const pending = new Set<StateResource>();
|
||||
let disposed = false;
|
||||
|
||||
const flush = async (resource: StateResource): Promise<void> => {
|
||||
if (disposed) return;
|
||||
inFlight.add(resource);
|
||||
try {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = await opts.snapshot(resource);
|
||||
} catch {
|
||||
// Per-resource snapshot failure (e.g. listProcesses threw): skip
|
||||
// this frame so siblings keep flowing. The next publish for the
|
||||
// same resource gets a fresh attempt.
|
||||
return;
|
||||
}
|
||||
if (disposed) return;
|
||||
try {
|
||||
opts.send({ resource, data });
|
||||
} catch {
|
||||
// Downstream consumer (e.g. closed SSE controller) — same isolation
|
||||
// contract as snapshot failures.
|
||||
}
|
||||
} finally {
|
||||
inFlight.delete(resource);
|
||||
// If a publish arrived during the in-flight window, schedule one
|
||||
// follow-up flush. Re-uses the debounce so a sustained publish
|
||||
// stream produces at most one frame per (debounceMs + flushLatency),
|
||||
// not back-to-back frames.
|
||||
if (!disposed && pending.has(resource)) {
|
||||
pending.delete(resource);
|
||||
schedule(resource);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const schedule = (resource: StateResource): void => {
|
||||
if (disposed) return;
|
||||
if (inFlight.has(resource)) {
|
||||
// Defer to the post-flush re-arm; no new timer until the in-flight
|
||||
// send completes. This is the load-bearing invariant for ordering.
|
||||
pending.add(resource);
|
||||
return;
|
||||
}
|
||||
const existing = timers.get(resource);
|
||||
if (existing) clearTimeout(existing);
|
||||
const t = setTimeout(() => {
|
||||
timers.delete(resource);
|
||||
void flush(resource);
|
||||
}, debounceMs);
|
||||
timers.set(resource, t);
|
||||
};
|
||||
|
||||
const unsubscribe = opts.bus.subscribe(schedule);
|
||||
|
||||
return {
|
||||
async sendAllInitial(): Promise<void> {
|
||||
if (disposed) return;
|
||||
// Fire all three in parallel. Each resource's snapshot is independent
|
||||
// so a slow listProcesses() doesn't gate qq-list/connections. Each
|
||||
// call goes through the single-flight gate so a concurrent bus
|
||||
// publish during this initial fan-out coalesces correctly.
|
||||
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
for (const t of timers.values()) clearTimeout(t);
|
||||
timers.clear();
|
||||
pending.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* State-wiring — couples the publisher edges (HookManager session events,
|
||||
* BridgeManager session-started / session-closed) to a fresh StateBus so the
|
||||
* `/api/state/stream` SSE handler can push snapshot invalidations to the
|
||||
* WebUI without REST polling.
|
||||
*
|
||||
* Decoupling rationale:
|
||||
* - HookManager owns the per-process state-machine; it knows when a
|
||||
* session's `listProcesses()` view changes. We feed it `onSessionsChanged`
|
||||
* (callable from outside the bridge package) so this file is the ONLY
|
||||
* place that imports both the bus and HookManager's dep shape.
|
||||
* - BridgeManager fires `session-started` / `session-closed` listeners on
|
||||
* account edges (the OneBot instance list mutates around these). We add
|
||||
* listeners directly so `qq-list` + `connections` invalidate at the right
|
||||
* moment without modifying BridgeManager.
|
||||
*
|
||||
* `dispose()` unwires everything so a test (or a future hot-reload) can
|
||||
* recreate the wiring without leaking listeners.
|
||||
*/
|
||||
|
||||
import { StateBus } from './state-bus';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
|
||||
export interface StateWiring {
|
||||
/** The bus the SSE handler subscribes to. */
|
||||
readonly bus: StateBus;
|
||||
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
|
||||
onSessionsChanged: () => void;
|
||||
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
|
||||
* 'connections'. Can be called at most once per wiring (subsequent calls
|
||||
* add duplicate listeners). */
|
||||
bindBridgeManager(bm: BridgeManager): void;
|
||||
/** Drop every listener + neuter the bus so further publishes do nothing. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function createStateWiring(): StateWiring {
|
||||
const bus = new StateBus();
|
||||
let disposed = false;
|
||||
|
||||
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
|
||||
if (disposed) return;
|
||||
bus.publish(resource);
|
||||
};
|
||||
|
||||
return {
|
||||
bus,
|
||||
onSessionsChanged: () => publish('processes'),
|
||||
bindBridgeManager(bm: BridgeManager): void {
|
||||
// Account appeared: the qq-list response gains an entry and the
|
||||
// connections response gains the new account's adapter row. Two
|
||||
// distinct resource invalidations, in source-of-truth order
|
||||
// (account exists → only then can adapters be enumerated for it).
|
||||
bm.addSessionStartedListener(() => {
|
||||
publish('qq-list');
|
||||
publish('connections');
|
||||
});
|
||||
// Account disappeared: same two resources shrink, same order so a
|
||||
// racy WebUI receiving both events independently sees the qq-list
|
||||
// shrink before it tries to render connections for a uin that's
|
||||
// about to vanish.
|
||||
bm.addSessionClosedListener(() => {
|
||||
publish('qq-list');
|
||||
publish('connections');
|
||||
});
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
bus.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Pure validator for the POST /api/system/settings body. Rejects clearly-bad
|
||||
// input with a message (→ 400) rather than silently normalizing it, then hands
|
||||
// a clean patch to updateRuntimeConfig. Wire field `tlsEnabled` maps to the
|
||||
// nested `webuiTls.enabled`.
|
||||
|
||||
import type { RuntimeConfig } from '@snowluma/common/runtime';
|
||||
|
||||
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
|
||||
|
||||
export type CoerceResult =
|
||||
| { ok: true; patch: SettingsPatch }
|
||||
| { ok: false; error: string };
|
||||
|
||||
function isObject(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
export function coerceSettingsPatch(body: unknown): CoerceResult {
|
||||
if (!isObject(body)) return { ok: false, error: 'body must be an object' };
|
||||
const patch: SettingsPatch = {};
|
||||
|
||||
if ('webuiPort' in body) {
|
||||
const p = body.webuiPort;
|
||||
if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) {
|
||||
return { ok: false, error: 'webuiPort must be an integer in 1..65535' };
|
||||
}
|
||||
patch.webuiPort = p;
|
||||
}
|
||||
|
||||
if ('webuiHost' in body) {
|
||||
if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) {
|
||||
return { ok: false, error: 'webuiHost must be a non-empty string' };
|
||||
}
|
||||
patch.webuiHost = body.webuiHost.trim();
|
||||
}
|
||||
|
||||
if ('tlsEnabled' in body) {
|
||||
if (typeof body.tlsEnabled !== 'boolean') {
|
||||
return { ok: false, error: 'tlsEnabled must be a boolean' };
|
||||
}
|
||||
patch.webuiTls = { enabled: body.tlsEnabled };
|
||||
}
|
||||
|
||||
if ('trustProxy' in body) {
|
||||
if (typeof body.trustProxy !== 'string') {
|
||||
return { ok: false, error: 'trustProxy must be a string' };
|
||||
}
|
||||
patch.trustProxy = body.trustProxy;
|
||||
}
|
||||
|
||||
return { ok: true, patch };
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem
|
||||
// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish
|
||||
// helpers: validate a pasted pair (save path) and resolve the on-disk pair
|
||||
// (boot path). Validation is `tls.createSecureContext` — it parses the PEM
|
||||
// and checks the key matches the cert; expiry is NOT checked here.
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import tls from 'tls';
|
||||
|
||||
export interface TlsValidation {
|
||||
ok: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface TlsResolution {
|
||||
ok: boolean;
|
||||
cert?: Buffer;
|
||||
key?: Buffer;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
function errMsg(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */
|
||||
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
|
||||
if (!cert || !cert.toString().trim()) return { ok: false, reason: 'certificate is empty' };
|
||||
if (!key || !key.toString().trim()) return { ok: false, reason: 'private key is empty' };
|
||||
try {
|
||||
tls.createSecureContext({ cert, key });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
/** Load + validate config/cert.pem + config/key.pem from `configDir`. */
|
||||
export function resolveTlsContext(configDir: string): TlsResolution {
|
||||
const certPath = path.join(configDir, 'cert.pem');
|
||||
const keyPath = path.join(configDir, 'key.pem');
|
||||
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
|
||||
return { ok: false, reason: 'cert.pem or key.pem missing in config dir' };
|
||||
}
|
||||
let cert: Buffer;
|
||||
let key: Buffer;
|
||||
try {
|
||||
cert = fs.readFileSync(certPath);
|
||||
key = fs.readFileSync(keyPath);
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
const valid = validateTlsPair(cert, key);
|
||||
if (!valid.ok) return { ok: false, reason: valid.reason };
|
||||
return { ok: true, cert, key };
|
||||
}
|
||||
@@ -0,0 +1,776 @@
|
||||
import { boolOr, clampInt, clampNum, isObject } from '@snowluma/common/coerce';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Server-side store for the WebUI customization config (`config/ui.json`).
|
||||
//
|
||||
// This is the single source of truth for appearance (A) + layout (C). The
|
||||
// browser caches it in localStorage only to avoid a first-paint flash; the
|
||||
// canonical copy lives here so a deployer's look + curated layout follow them
|
||||
// across devices/browsers.
|
||||
//
|
||||
// Trust boundaries that this module enforces:
|
||||
// * `normalizeAppearance` is total — any unknown/corrupt input collapses to
|
||||
// safe defaults. This matters because the cosmetic subset is served to an
|
||||
// UNAUTHENTICATED client (the login page) via `GET /api/ui/public`, so it
|
||||
// must never echo attacker-controlled garbage.
|
||||
// * The background-IMAGE lifecycle fields (`hasImage` / `imageMime` /
|
||||
// `imageVersion`) are server-managed: a plain `POST /api/ui` cannot set
|
||||
// them. Only the dedicated upload/delete endpoints mutate them. A client
|
||||
// save preserves whatever is currently on disk.
|
||||
|
||||
const log = createLogger('WebUI.UiConfig');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const UI_CONFIG_PATH = path.join(CONFIG_DIR, 'ui.json');
|
||||
|
||||
/** Directory for operator-uploaded UI assets (currently just the background). */
|
||||
export const UI_ASSETS_DIR = path.join(CONFIG_DIR, 'ui-assets');
|
||||
/** Fixed path of the single background image (overwrite-on-upload). */
|
||||
export const BACKGROUND_IMAGE_PATH = path.join(UI_ASSETS_DIR, 'background');
|
||||
/** Reject uploads larger than this (bytes). */
|
||||
export const MAX_BACKGROUND_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
export const UI_CONFIG_VERSION = 1 as const;
|
||||
|
||||
// ─── Schema ──────────────────────────────────────────────────────────────
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system';
|
||||
export type AccentMode = 'preset' | 'custom';
|
||||
export type AccentScope = 'sidebar' | 'global';
|
||||
export type DarkIntensity = 'soft' | 'black';
|
||||
export type SidebarStyle = 'follow' | 'panel' | 'accent';
|
||||
export type BackgroundType = 'none' | 'solid' | 'gradient' | 'image';
|
||||
export type Density = 'cozy' | 'compact';
|
||||
export type TimeFormat = '12h' | '24h';
|
||||
/** Full color scheme. 'default' keeps the sky theme (driven by `mode`); the
|
||||
* Catppuccin flavors are complete palettes that also fix light/dark. */
|
||||
export type Palette =
|
||||
| 'default'
|
||||
| 'catppuccin-latte' | 'catppuccin-frappe' | 'catppuccin-macchiato' | 'catppuccin-mocha'
|
||||
| 'rose-pine' | 'rose-pine-moon' | 'rose-pine-dawn'
|
||||
| 'nord'
|
||||
| 'everforest-dark' | 'everforest-light';
|
||||
|
||||
export interface UiBackground {
|
||||
type: BackgroundType;
|
||||
/** Solid-fill colour (hex). Used when type === 'solid'. */
|
||||
color: string;
|
||||
/** Gradient preset id (frontend owns the catalogue). Used when type === 'gradient'. */
|
||||
gradient: string;
|
||||
/** Image readability overlay: 0 (image fully visible) … 1 (fully masked). */
|
||||
imageOpacity: number;
|
||||
/** Image blur in px (0…40). */
|
||||
imageBlur: number;
|
||||
// ── server-managed (upload/delete endpoints only) ──
|
||||
hasImage: boolean;
|
||||
imageMime: string;
|
||||
/** Bumped on each successful upload so the browser can cache-bust. */
|
||||
imageVersion: number;
|
||||
}
|
||||
|
||||
export interface UiAppearance {
|
||||
mode: ThemeMode;
|
||||
accentMode: AccentMode;
|
||||
/** Preset accent id (frontend catalogue: sky/blue/violet/…). */
|
||||
accentPreset: string;
|
||||
/** Custom accent colour (hex). Used when accentMode === 'custom'. */
|
||||
accentCustom: string;
|
||||
accentScope: AccentScope;
|
||||
darkIntensity: DarkIntensity;
|
||||
/** Full color scheme; 'default' = the built-in sky theme. */
|
||||
palette: Palette;
|
||||
sidebarStyle: SidebarStyle;
|
||||
background: UiBackground;
|
||||
/** Sans font preset id (frontend catalogue); 'custom' uses `fontSansCustom`. */
|
||||
fontSans: string;
|
||||
/** Free-form sans font-family stack, used when `fontSans === 'custom'`. */
|
||||
fontSansCustom: string;
|
||||
/** Mono font preset id (frontend catalogue); 'custom' uses `fontMonoCustom`. */
|
||||
fontMono: string;
|
||||
/** Free-form mono font-family stack, used when `fontMono === 'custom'`. */
|
||||
fontMonoCustom: string;
|
||||
/** Global UI scale, 0.9…1.2. */
|
||||
uiScale: number;
|
||||
/** Corner radius in rem, 0…2. */
|
||||
radius: number;
|
||||
density: Density;
|
||||
/** Soften animations (transforms off, shorter durations). */
|
||||
reduceMotion: boolean;
|
||||
/** Hard-disable all UI animations (stronger than reduceMotion). */
|
||||
disableMotion: boolean;
|
||||
/** Use SnowLuma's adaptive cursor and custom context menu. */
|
||||
customPointerSystem: boolean;
|
||||
highContrast: boolean;
|
||||
sidebarPinned: boolean;
|
||||
timeFormat: TimeFormat;
|
||||
/** Dashboard poll interval (ms); 0 = paused. */
|
||||
pollInterval: number;
|
||||
/**
|
||||
* Operator custom CSS, applied AFTER auth only (never on the login page —
|
||||
* `publicAppearance` strips it). Capped at 50 KB. The client injects it as
|
||||
* the last <style> and skips it under `?safe-mode=1` so a broken rule can't
|
||||
* lock the operator out.
|
||||
*/
|
||||
customCss: string;
|
||||
/**
|
||||
* Theme-token overrides from the variable panel. Keys are restricted to a
|
||||
* fixed whitelist of `--token` names and values to colours / lengths, so
|
||||
* (unlike `customCss`) this is safe to serve to the unauthenticated login
|
||||
* page — `normalizeAppearance` drops unknown keys and invalid values.
|
||||
*/
|
||||
cssVars: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface UiLayoutItem {
|
||||
id: string;
|
||||
visible: boolean;
|
||||
/**
|
||||
* Grid position/size (overview blocks only; nav items omit them). The
|
||||
* client owns the widget catalogue, per-widget min sizes, and the
|
||||
* `stats`→tiles migration — the server just preserves + clamps these to
|
||||
* sane integer bounds so a corrupt file can't store absurd coords.
|
||||
*/
|
||||
x?: number;
|
||||
y?: number;
|
||||
w?: number;
|
||||
h?: number;
|
||||
/**
|
||||
* Per-widget settings (overview blocks only) — an opaque object the client
|
||||
* interprets by widget type (e.g. alerts: count + levels). The server only
|
||||
* checks it's a plain object within a size bound; it never reads the keys.
|
||||
*/
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface UiLayout {
|
||||
/** Ordered overview blocks (desktop 2D grid). Frontend reconciles vs its set. */
|
||||
overviewBlocks: UiLayoutItem[];
|
||||
/** Ordered single-column mobile overview (id+visible only; the 2D grid is
|
||||
* desktop-only). Kept separate so phone ordering never pollutes the grid. */
|
||||
overviewMobile: UiLayoutItem[];
|
||||
/** Ordered sidebar nav items, keyed by route path. */
|
||||
navItems: UiLayoutItem[];
|
||||
/** Top-bar element show/hide list (id+visible), mirroring navItems' shape. */
|
||||
topbarItems: UiLayoutItem[];
|
||||
}
|
||||
|
||||
export interface UiHighlightRule {
|
||||
keyword: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export type LogsPreset = 'dev' | 'ops' | 'minimal' | 'custom';
|
||||
|
||||
export interface UiLogsPrefs {
|
||||
/** Log levels shown by default (client display filter). */
|
||||
visibleLevels: string[];
|
||||
/** Ring-buffer cap for the live view (100…5000). */
|
||||
maxLines: number;
|
||||
autoScroll: boolean;
|
||||
wrap: boolean;
|
||||
/** Keyword → colour row highlights. */
|
||||
highlightRules: UiHighlightRule[];
|
||||
/** Active view preset id; 'custom' = the operator hand-tuned the prefs. The
|
||||
* client owns the preset → prefs bundles; the server just stores the id. */
|
||||
preset: LogsPreset;
|
||||
}
|
||||
|
||||
export interface UiPages {
|
||||
/** Route the operator lands on after login (a nav path; '/' if unset). */
|
||||
defaultRoute: string;
|
||||
logs: UiLogsPrefs;
|
||||
/** Default sort key for the processes page. */
|
||||
processesSort: string;
|
||||
/** Default tab id for the node-config page ('' = first). */
|
||||
configTab: string;
|
||||
}
|
||||
|
||||
export interface UiConfig {
|
||||
version: typeof UI_CONFIG_VERSION;
|
||||
appearance: UiAppearance;
|
||||
layout: UiLayout;
|
||||
pages: UiPages;
|
||||
}
|
||||
|
||||
// ─── Defaults ────────────────────────────────────────────────────────────
|
||||
// Mirror the pre-existing ThemeContext defaults so an upgrade is a no-op
|
||||
// visually until the operator changes something.
|
||||
|
||||
const DEFAULT_BACKGROUND: UiBackground = {
|
||||
type: 'none',
|
||||
color: '#0ea5e9',
|
||||
gradient: 'none',
|
||||
imageOpacity: 0.15,
|
||||
imageBlur: 0,
|
||||
hasImage: false,
|
||||
imageMime: '',
|
||||
imageVersion: 0,
|
||||
};
|
||||
|
||||
const DEFAULT_APPEARANCE: UiAppearance = {
|
||||
mode: 'system',
|
||||
accentMode: 'preset',
|
||||
accentPreset: 'sky',
|
||||
accentCustom: '#38bdf8',
|
||||
accentScope: 'global',
|
||||
darkIntensity: 'soft',
|
||||
palette: 'default',
|
||||
sidebarStyle: 'follow',
|
||||
background: DEFAULT_BACKGROUND,
|
||||
fontSans: 'default',
|
||||
fontSansCustom: '',
|
||||
fontMono: 'default',
|
||||
fontMonoCustom: '',
|
||||
uiScale: 1,
|
||||
radius: 0.75,
|
||||
density: 'cozy',
|
||||
reduceMotion: false,
|
||||
disableMotion: false,
|
||||
customPointerSystem: false,
|
||||
highContrast: false,
|
||||
sidebarPinned: false,
|
||||
timeFormat: '24h',
|
||||
pollInterval: 3000,
|
||||
customCss: '',
|
||||
cssVars: {},
|
||||
};
|
||||
|
||||
const DEFAULT_OVERVIEW_BLOCKS: UiLayoutItem[] = [
|
||||
{ id: 'stats', visible: true },
|
||||
{ id: 'connections', visible: true },
|
||||
{ id: 'alerts', visible: true },
|
||||
{ id: 'host', visible: true },
|
||||
{ id: 'sessions', visible: true },
|
||||
];
|
||||
|
||||
// Single-column mobile order = the desktop grid catalogue's widgets, flattened
|
||||
// (stat tiles, then the cards). The client reconciles against its real
|
||||
// catalogue, so this just seeds first run; unknown ids are dropped on load.
|
||||
const DEFAULT_OVERVIEW_MOBILE: UiLayoutItem[] = [
|
||||
{ id: 'stat:status', visible: true },
|
||||
{ id: 'stat:accounts', visible: true },
|
||||
{ id: 'stat:processes', visible: true },
|
||||
{ id: 'stat:host', visible: true },
|
||||
{ id: 'stat:uptime', visible: true },
|
||||
{ id: 'connections', visible: true },
|
||||
{ id: 'alerts', visible: true },
|
||||
{ id: 'host', visible: true },
|
||||
{ id: 'sessions', visible: true },
|
||||
];
|
||||
|
||||
const DEFAULT_NAV_ITEMS: UiLayoutItem[] = [
|
||||
{ id: '/', visible: true },
|
||||
{ id: '/processes', visible: true },
|
||||
{ id: '/config', visible: true },
|
||||
{ id: '/logs', visible: true },
|
||||
{ id: '/settings', visible: true },
|
||||
];
|
||||
|
||||
// Toggleable top-bar elements (essential ones — menu, page title, logout — are
|
||||
// pinned in the client and never appear here). The client reconciles, so a new
|
||||
// element (e.g. the kiosk button) just appears as visible.
|
||||
const DEFAULT_TOPBAR_ITEMS: UiLayoutItem[] = [
|
||||
{ id: 'status', visible: true },
|
||||
{ id: 'theme', visible: true },
|
||||
{ id: 'kiosk', visible: true },
|
||||
];
|
||||
|
||||
const LOG_LEVELS = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
const DEFAULT_PAGES: UiPages = {
|
||||
defaultRoute: '/',
|
||||
logs: {
|
||||
visibleLevels: [...LOG_LEVELS],
|
||||
maxLines: 1000,
|
||||
autoScroll: true,
|
||||
wrap: true,
|
||||
highlightRules: [],
|
||||
preset: 'custom',
|
||||
},
|
||||
processesSort: 'pid',
|
||||
configTab: '',
|
||||
};
|
||||
|
||||
export function defaultUiConfig(): UiConfig {
|
||||
return {
|
||||
version: UI_CONFIG_VERSION,
|
||||
appearance: { ...DEFAULT_APPEARANCE, background: { ...DEFAULT_BACKGROUND }, cssVars: {} },
|
||||
layout: {
|
||||
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((b) => ({ ...b })),
|
||||
overviewMobile: DEFAULT_OVERVIEW_MOBILE.map((b) => ({ ...b })),
|
||||
navItems: DEFAULT_NAV_ITEMS.map((b) => ({ ...b })),
|
||||
topbarItems: DEFAULT_TOPBAR_ITEMS.map((b) => ({ ...b })),
|
||||
},
|
||||
pages: defaultPages(),
|
||||
};
|
||||
}
|
||||
|
||||
function defaultPages(): UiPages {
|
||||
return { ...DEFAULT_PAGES, logs: { ...DEFAULT_PAGES.logs, visibleLevels: [...LOG_LEVELS], highlightRules: [] } };
|
||||
}
|
||||
|
||||
// ─── Normalization helpers ─────────────────────────────────────────────────
|
||||
// isObject / boolOr / clampNum / clampInt come from @snowluma/common/coerce.
|
||||
// oneOf (enum), isFiniteNum, and hexOr (CSS color) are ui-specific and stay.
|
||||
|
||||
function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
|
||||
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
|
||||
? (value as T)
|
||||
: fallback;
|
||||
}
|
||||
|
||||
function isFiniteNum(value: unknown): boolean {
|
||||
if (typeof value === 'number') return Number.isFinite(value);
|
||||
return typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value));
|
||||
}
|
||||
|
||||
const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
||||
function hexOr(value: unknown, fallback: string): string {
|
||||
return typeof value === 'string' && HEX_RE.test(value.trim()) ? value.trim() : fallback;
|
||||
}
|
||||
|
||||
/** Bounded free-form id (frontend owns the actual catalogue). */
|
||||
function idOr(value: unknown, fallback: string, maxLen = 64): string {
|
||||
if (typeof value !== 'string') return fallback;
|
||||
const v = value.trim();
|
||||
if (v.length === 0 || v.length > maxLen) return fallback;
|
||||
// Ids are slugs / route paths — refuse control chars and anything exotic.
|
||||
if (!/^[\w./:-]+$/.test(v)) return fallback;
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* A free-form font-family value (a single family or a comma-separated stack),
|
||||
* safe to interpolate into `--font-sans: <value>;`. Allows letters (incl. CJK),
|
||||
* digits, spaces and the punctuation real font names use, but refuses anything
|
||||
* that could break out of the declaration (`;`, `{`, `}`, control chars, etc.).
|
||||
* Empty / over-long / invalid → fallback ('' = "no custom family set").
|
||||
*/
|
||||
const FONT_FAMILY_RE = /^[\p{L}\p{N}\s,'"._-]+$/u;
|
||||
function fontFamilyOr(value: unknown, fallback: string, maxLen = 200): string {
|
||||
if (typeof value !== 'string') return fallback;
|
||||
const v = value.trim();
|
||||
if (v.length === 0) return ''; // explicitly cleared
|
||||
if (v.length > maxLen || !FONT_FAMILY_RE.test(v)) return fallback;
|
||||
return v;
|
||||
}
|
||||
|
||||
// ─── cssVars (theme-token override panel) ──────────────────────────────────
|
||||
// Both the keys (which `--token` may be set) and the values (colour / length)
|
||||
// are whitelisted so the result is safe to serve to the UNAUTHENTICATED login
|
||||
// page — it shares the trust level of palette/accent, not of `customCss`.
|
||||
|
||||
/** The `--token` names the variable panel is allowed to override. Kept in sync
|
||||
* with the surface/accent tokens `ThemeContext` actually injects. */
|
||||
const CSS_VAR_WHITELIST = new Set<string>([
|
||||
'--background', '--foreground',
|
||||
'--card', '--card-foreground',
|
||||
'--popover', '--popover-foreground',
|
||||
'--primary', '--primary-foreground',
|
||||
'--secondary', '--secondary-foreground',
|
||||
'--muted', '--muted-foreground',
|
||||
'--accent', '--accent-foreground',
|
||||
'--destructive', '--destructive-foreground',
|
||||
'--success', '--warning',
|
||||
'--border', '--input', '--ring',
|
||||
'--sidebar', '--sidebar-foreground',
|
||||
'--sidebar-primary', '--sidebar-primary-foreground',
|
||||
'--sidebar-accent', '--sidebar-accent-foreground',
|
||||
'--sidebar-border', '--sidebar-ring',
|
||||
]);
|
||||
|
||||
// A CSS colour value, restricted to forms that cannot break out of a `--token:
|
||||
// <value>;` declaration. Hex, a named colour, or a single balanced functional
|
||||
// notation (rgb/hsl/oklch/… and color-mix) over a safe char set — crucially no
|
||||
// `;`, `{`, `}`, `:` or angle brackets are permitted anywhere.
|
||||
const CSS_HEX_RE = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
||||
const CSS_NAMED_RE = /^[a-zA-Z]{1,24}$/;
|
||||
const CSS_FUNC_RE = /^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix)\([a-zA-Z0-9.,%/\s#-]{1,120}\)$/;
|
||||
function cssColorOrNull(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim();
|
||||
if (v.length === 0 || v.length > 128) return null;
|
||||
if (CSS_HEX_RE.test(v) || CSS_NAMED_RE.test(v) || CSS_FUNC_RE.test(v)) return v;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Keep only whitelisted token keys with valid colour values; drop the rest. */
|
||||
function normalizeCssVars(value: unknown): Record<string, string> {
|
||||
if (!isObject(value)) return {};
|
||||
const out: Record<string, string> = {};
|
||||
for (const key of Object.keys(value)) {
|
||||
if (!CSS_VAR_WHITELIST.has(key)) continue;
|
||||
const color = cssColorOrNull(value[key]);
|
||||
if (color) out[key] = color;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function normalizeLayoutItems(value: unknown, fallback: UiLayoutItem[]): UiLayoutItem[] {
|
||||
if (!Array.isArray(value)) return fallback.map((i) => ({ ...i }));
|
||||
const seen = new Set<string>();
|
||||
const out: UiLayoutItem[] = [];
|
||||
for (const raw of value) {
|
||||
if (!isObject(raw)) continue;
|
||||
const id = idOr(raw.id, '');
|
||||
if (!id || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
const item: UiLayoutItem = { id, visible: boolOr(raw.visible, true) };
|
||||
// Grid coords are optional (overview blocks carry them; nav items don't).
|
||||
// Preserve + clamp when any are present; missing ones get safe defaults
|
||||
// and the client re-applies per-widget min sizes on load.
|
||||
if (isFiniteNum(raw.x) || isFiniteNum(raw.y) || isFiniteNum(raw.w) || isFiniteNum(raw.h)) {
|
||||
item.x = clampInt(raw.x, 0, 50, 0);
|
||||
item.y = clampInt(raw.y, 0, 1000, 0);
|
||||
item.w = clampInt(raw.w, 1, 12, 1);
|
||||
item.h = clampInt(raw.h, 1, 100, 1);
|
||||
}
|
||||
// Opaque per-widget config: keep only a plain object within a size bound;
|
||||
// the server never interprets the keys (the client does, per widget type).
|
||||
if (isObject(raw.config)) {
|
||||
try {
|
||||
if (JSON.stringify(raw.config).length <= 4096) item.config = raw.config;
|
||||
} catch { /* unserializable (cycles) → drop */ }
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
// An array that parsed to nothing usable is indistinguishable from corrupt;
|
||||
// fall back so the frontend always has a baseline to reconcile against.
|
||||
return out.length > 0 ? out : fallback.map((i) => ({ ...i }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The background-image fields are server-managed (only the upload/delete
|
||||
* endpoints mutate them). Normalization NEVER derives them from the value
|
||||
* being normalized — the caller supplies the trusted source:
|
||||
* * LOAD path → the parsed-from-disk file IS the truth (`imageStateFromParsed`).
|
||||
* * SAVE path → the current on-disk config is the truth (a client payload
|
||||
* cannot forge `hasImage`).
|
||||
*/
|
||||
export interface ServerImageState {
|
||||
hasImage: boolean;
|
||||
imageMime: string;
|
||||
imageVersion: number;
|
||||
}
|
||||
|
||||
const DEFAULT_IMAGE_STATE: ServerImageState = { hasImage: false, imageMime: '', imageVersion: 0 };
|
||||
|
||||
const KNOWN_IMAGE_MIMES = ['image/png', 'image/jpeg', 'image/webp'];
|
||||
|
||||
/** Coerce a raw background-ish object into a coherent, trusted image state. */
|
||||
function sanitizeImageState(value: unknown): ServerImageState {
|
||||
const v = isObject(value) ? value : {};
|
||||
const version = Math.trunc(clampNum(v.imageVersion, 0, Number.MAX_SAFE_INTEGER, 0));
|
||||
if (!boolOr(v.hasImage, false)) return { hasImage: false, imageMime: '', imageVersion: version };
|
||||
const mime = typeof v.imageMime === 'string' && KNOWN_IMAGE_MIMES.includes(v.imageMime) ? v.imageMime : '';
|
||||
// "Has image" with no recognizable mime is incoherent on-disk state; treat
|
||||
// it as no image so the serve path and the UI stay consistent.
|
||||
if (!mime) return { hasImage: false, imageMime: '', imageVersion: version };
|
||||
return { hasImage: true, imageMime: mime, imageVersion: version };
|
||||
}
|
||||
|
||||
/** Trusted image state read FROM a parsed-from-disk config blob. */
|
||||
function imageStateFromParsed(parsed: unknown): ServerImageState {
|
||||
if (!isObject(parsed) || !isObject(parsed.appearance)) return DEFAULT_IMAGE_STATE;
|
||||
return sanitizeImageState(parsed.appearance.background);
|
||||
}
|
||||
|
||||
/** Normalize a complete ui.json read from disk or a backup bundle. */
|
||||
export function normalizeStoredUiConfig(value: unknown): UiConfig {
|
||||
return normalizeUiConfig(value, imageStateFromParsed(value));
|
||||
}
|
||||
|
||||
function normalizeBackground(value: unknown, imageState: ServerImageState): UiBackground {
|
||||
const v = isObject(value) ? value : {};
|
||||
let type = oneOf<BackgroundType>(v.type, ['none', 'solid', 'gradient', 'image'], DEFAULT_BACKGROUND.type);
|
||||
// An image background is only valid when an image is actually stored —
|
||||
// otherwise the serve route 404s and the UI shows a broken wallpaper.
|
||||
if (type === 'image' && !imageState.hasImage) type = 'none';
|
||||
return {
|
||||
type,
|
||||
color: hexOr(v.color, DEFAULT_BACKGROUND.color),
|
||||
gradient: idOr(v.gradient, DEFAULT_BACKGROUND.gradient),
|
||||
imageOpacity: clampNum(v.imageOpacity, 0, 1, DEFAULT_BACKGROUND.imageOpacity),
|
||||
imageBlur: clampNum(v.imageBlur, 0, 40, DEFAULT_BACKGROUND.imageBlur),
|
||||
// Server-managed — taken from the caller-supplied trusted source, never
|
||||
// from the value being normalized.
|
||||
hasImage: imageState.hasImage,
|
||||
imageMime: imageState.imageMime,
|
||||
imageVersion: imageState.imageVersion,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeAppearance(value: unknown, imageState: ServerImageState = DEFAULT_IMAGE_STATE): UiAppearance {
|
||||
const v = isObject(value) ? value : {};
|
||||
return {
|
||||
mode: oneOf<ThemeMode>(v.mode, ['light', 'dark', 'system'], DEFAULT_APPEARANCE.mode),
|
||||
accentMode: oneOf<AccentMode>(v.accentMode, ['preset', 'custom'], DEFAULT_APPEARANCE.accentMode),
|
||||
accentPreset: idOr(v.accentPreset, DEFAULT_APPEARANCE.accentPreset, 32),
|
||||
accentCustom: hexOr(v.accentCustom, DEFAULT_APPEARANCE.accentCustom),
|
||||
accentScope: oneOf<AccentScope>(v.accentScope, ['sidebar', 'global'], DEFAULT_APPEARANCE.accentScope),
|
||||
darkIntensity: oneOf<DarkIntensity>(v.darkIntensity, ['soft', 'black'], DEFAULT_APPEARANCE.darkIntensity),
|
||||
palette: oneOf<Palette>(v.palette, ['default', 'catppuccin-latte', 'catppuccin-frappe', 'catppuccin-macchiato', 'catppuccin-mocha', 'rose-pine', 'rose-pine-moon', 'rose-pine-dawn', 'nord', 'everforest-dark', 'everforest-light'], DEFAULT_APPEARANCE.palette),
|
||||
sidebarStyle: oneOf<SidebarStyle>(v.sidebarStyle, ['follow', 'panel', 'accent'], DEFAULT_APPEARANCE.sidebarStyle),
|
||||
background: normalizeBackground(v.background, imageState),
|
||||
fontSans: idOr(v.fontSans, DEFAULT_APPEARANCE.fontSans),
|
||||
fontSansCustom: fontFamilyOr(v.fontSansCustom, DEFAULT_APPEARANCE.fontSansCustom),
|
||||
fontMono: idOr(v.fontMono, DEFAULT_APPEARANCE.fontMono),
|
||||
fontMonoCustom: fontFamilyOr(v.fontMonoCustom, DEFAULT_APPEARANCE.fontMonoCustom),
|
||||
uiScale: clampNum(v.uiScale, 0.9, 1.2, DEFAULT_APPEARANCE.uiScale),
|
||||
radius: clampNum(v.radius, 0, 2, DEFAULT_APPEARANCE.radius),
|
||||
density: oneOf<Density>(v.density, ['cozy', 'compact'], DEFAULT_APPEARANCE.density),
|
||||
reduceMotion: boolOr(v.reduceMotion, DEFAULT_APPEARANCE.reduceMotion),
|
||||
disableMotion: boolOr(v.disableMotion, DEFAULT_APPEARANCE.disableMotion),
|
||||
customPointerSystem: boolOr(v.customPointerSystem, DEFAULT_APPEARANCE.customPointerSystem),
|
||||
highContrast: boolOr(v.highContrast, DEFAULT_APPEARANCE.highContrast),
|
||||
sidebarPinned: boolOr(v.sidebarPinned, DEFAULT_APPEARANCE.sidebarPinned),
|
||||
timeFormat: oneOf<TimeFormat>(v.timeFormat, ['12h', '24h'], DEFAULT_APPEARANCE.timeFormat),
|
||||
pollInterval: clampNum(v.pollInterval, 0, 60_000, DEFAULT_APPEARANCE.pollInterval),
|
||||
customCss: typeof v.customCss === 'string' ? v.customCss.slice(0, 50_000) : DEFAULT_APPEARANCE.customCss,
|
||||
cssVars: normalizeCssVars(v.cssVars),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeLayout(value: unknown): UiLayout {
|
||||
const layout = isObject(value) ? value : {};
|
||||
return {
|
||||
overviewBlocks: normalizeLayoutItems(layout.overviewBlocks, DEFAULT_OVERVIEW_BLOCKS),
|
||||
overviewMobile: normalizeLayoutItems(layout.overviewMobile, DEFAULT_OVERVIEW_MOBILE),
|
||||
navItems: normalizeLayoutItems(layout.navItems, DEFAULT_NAV_ITEMS),
|
||||
topbarItems: normalizeLayoutItems(layout.topbarItems, DEFAULT_TOPBAR_ITEMS),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeHighlightRules(value: unknown): UiHighlightRule[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const out: UiHighlightRule[] = [];
|
||||
for (const raw of value) {
|
||||
if (!isObject(raw) || typeof raw.keyword !== 'string') continue;
|
||||
const keyword = raw.keyword.trim().slice(0, 50);
|
||||
if (!keyword) continue; // drop empty / whitespace-only (would match every row)
|
||||
const color = typeof raw.color === 'string' ? raw.color.slice(0, 32) : '';
|
||||
out.push({ keyword, color });
|
||||
if (out.length >= 20) break; // cap the rule count
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizePages(value: unknown): UiPages {
|
||||
const v = isObject(value) ? value : {};
|
||||
const logs = isObject(v.logs) ? v.logs : {};
|
||||
const levels = Array.isArray(logs.visibleLevels)
|
||||
? LOG_LEVELS.filter((l) => (logs.visibleLevels as unknown[]).includes(l))
|
||||
: DEFAULT_PAGES.logs.visibleLevels;
|
||||
return {
|
||||
defaultRoute: idOr(v.defaultRoute, DEFAULT_PAGES.defaultRoute),
|
||||
logs: {
|
||||
visibleLevels: levels.length > 0 ? levels : [...LOG_LEVELS],
|
||||
maxLines: clampInt(logs.maxLines, 100, 5000, DEFAULT_PAGES.logs.maxLines),
|
||||
autoScroll: boolOr(logs.autoScroll, DEFAULT_PAGES.logs.autoScroll),
|
||||
wrap: boolOr(logs.wrap, DEFAULT_PAGES.logs.wrap),
|
||||
highlightRules: normalizeHighlightRules(logs.highlightRules),
|
||||
preset: oneOf<LogsPreset>(logs.preset, ['dev', 'ops', 'minimal', 'custom'], 'custom'),
|
||||
},
|
||||
processesSort: idOr(v.processesSort, DEFAULT_PAGES.processesSort),
|
||||
configTab: typeof v.configTab === 'string' ? v.configTab.slice(0, 64) : DEFAULT_PAGES.configTab,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUiConfig(value: unknown, imageState: ServerImageState = DEFAULT_IMAGE_STATE): UiConfig {
|
||||
const v = isObject(value) ? value : {};
|
||||
return {
|
||||
version: UI_CONFIG_VERSION,
|
||||
appearance: normalizeAppearance(v.appearance, imageState),
|
||||
layout: normalizeLayout(v.layout),
|
||||
pages: normalizePages(v.pages),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Persistence ────────────────────────────────────────────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function atomicWrite(config: UiConfig): void {
|
||||
ensureConfigDir();
|
||||
const tmp = UI_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(tmp, UI_CONFIG_PATH);
|
||||
}
|
||||
|
||||
let cached: UiConfig | null = null;
|
||||
|
||||
/** Load + normalize the UI config, creating it from defaults if absent. */
|
||||
export function loadUiConfig(): UiConfig {
|
||||
if (cached) return cached;
|
||||
ensureConfigDir();
|
||||
|
||||
if (!fs.existsSync(UI_CONFIG_PATH)) {
|
||||
const fresh = defaultUiConfig();
|
||||
try {
|
||||
atomicWrite(fresh);
|
||||
} catch (err) {
|
||||
log.warn('failed to write initial ui.json: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(UI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
// On load, the file itself is the source of truth for the server-managed
|
||||
// image fields — so they survive restarts (don't reset to defaults).
|
||||
const normalized = normalizeStoredUiConfig(parsed);
|
||||
// Re-persist only if normalization changed something (corrupt/old file),
|
||||
// so we self-heal on disk without rewriting on every boot.
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
|
||||
try {
|
||||
atomicWrite(normalized);
|
||||
} catch {
|
||||
/* best-effort self-heal */
|
||||
}
|
||||
}
|
||||
cached = normalized;
|
||||
return normalized;
|
||||
} catch (err) {
|
||||
log.warn('ui.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err));
|
||||
const fresh = defaultUiConfig();
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a client-supplied config. The incoming appearance is normalized and
|
||||
* its server-managed background-image fields are forced to the current on-disk
|
||||
* truth (the client cannot fake `hasImage`). Returns the stored config.
|
||||
*/
|
||||
export function saveUiConfig(incoming: unknown): UiConfig {
|
||||
const current = loadUiConfig();
|
||||
const v = isObject(incoming) ? incoming : {};
|
||||
// Section-level merge: a payload may carry just `appearance` (the theme
|
||||
// editor) or just `layout` (the layout editor) without clobbering the
|
||||
// other. A missing/non-object section keeps the current on-disk value.
|
||||
// The current on-disk state is the truth for the server-managed image
|
||||
// fields — a client payload cannot forge `hasImage` etc.
|
||||
const next: UiConfig = {
|
||||
version: UI_CONFIG_VERSION,
|
||||
appearance: isObject(v.appearance)
|
||||
? normalizeAppearance(v.appearance, current.appearance.background)
|
||||
: current.appearance,
|
||||
layout: isObject(v.layout) ? normalizeLayout(v.layout) : current.layout,
|
||||
pages: isObject(v.pages) ? normalizePages(v.pages) : (current.pages ?? defaultPages()),
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** The appearance subset served unauthenticated to the login page. Strips
|
||||
* `customCss` so a broken/hostile rule can never reach the pre-auth page
|
||||
* (and so the operator can always log in to fix it). */
|
||||
export function publicAppearance(): UiAppearance {
|
||||
return { ...loadUiConfig().appearance, customCss: '' };
|
||||
}
|
||||
|
||||
// ─── Background image lifecycle ─────────────────────────────────────────────
|
||||
|
||||
const IMAGE_MIME: Record<string, string> = {
|
||||
png: 'image/png',
|
||||
jpeg: 'image/jpeg',
|
||||
webp: 'image/webp',
|
||||
};
|
||||
|
||||
/**
|
||||
* Identify an image by its magic bytes (never by a client-supplied filename or
|
||||
* Content-Type). Returns the canonical MIME, or null if it isn't a supported
|
||||
* image. Supported: PNG, JPEG, WebP.
|
||||
*/
|
||||
export function sniffImageMime(bytes: Uint8Array): string | null {
|
||||
if (bytes.length >= 8 &&
|
||||
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 &&
|
||||
bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) {
|
||||
return IMAGE_MIME.png;
|
||||
}
|
||||
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
|
||||
return IMAGE_MIME.jpeg;
|
||||
}
|
||||
if (bytes.length >= 12 &&
|
||||
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
||||
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
|
||||
return IMAGE_MIME.webp;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Write the uploaded image to disk and record its metadata. Returns the config. */
|
||||
export function writeBackgroundImage(bytes: Uint8Array, mime: string): UiConfig {
|
||||
fs.mkdirSync(UI_ASSETS_DIR, { recursive: true });
|
||||
const tmp = BACKGROUND_IMAGE_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, bytes);
|
||||
fs.renameSync(tmp, BACKGROUND_IMAGE_PATH);
|
||||
|
||||
const current = loadUiConfig();
|
||||
const next: UiConfig = {
|
||||
...current,
|
||||
appearance: {
|
||||
...current.appearance,
|
||||
background: {
|
||||
...current.appearance.background,
|
||||
// Default to showing the freshly-uploaded image unless the operator
|
||||
// explicitly had a non-image background selected and we respect it;
|
||||
// switching to 'image' here matches the natural "I just set a wallpaper"
|
||||
// expectation.
|
||||
type: 'image',
|
||||
hasImage: true,
|
||||
imageMime: mime,
|
||||
imageVersion: current.appearance.background.imageVersion + 1,
|
||||
},
|
||||
},
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Remove the background image (if any) and clear its metadata. Returns the config. */
|
||||
export function clearBackgroundImage(): UiConfig {
|
||||
try {
|
||||
if (fs.existsSync(BACKGROUND_IMAGE_PATH)) fs.unlinkSync(BACKGROUND_IMAGE_PATH);
|
||||
} catch (err) {
|
||||
log.warn('failed to remove background image: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
const current = loadUiConfig();
|
||||
const next: UiConfig = {
|
||||
...current,
|
||||
appearance: {
|
||||
...current.appearance,
|
||||
background: {
|
||||
...current.appearance.background,
|
||||
// Fall back to 'none' if the image was the active background.
|
||||
type: current.appearance.background.type === 'image' ? 'none' : current.appearance.background.type,
|
||||
hasImage: false,
|
||||
imageMime: '',
|
||||
},
|
||||
},
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Read the background image bytes + MIME, or null if none is stored. */
|
||||
export function readBackgroundImage(): { bytes: Buffer; mime: string } | null {
|
||||
const { background } = loadUiConfig().appearance;
|
||||
if (!background.hasImage) return null;
|
||||
try {
|
||||
const bytes = fs.readFileSync(BACKGROUND_IMAGE_PATH);
|
||||
return { bytes, mime: background.imageMime || 'application/octet-stream' };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// Advisory update check against the public GitHub Releases API.
|
||||
//
|
||||
// Strictly read-only (T0): SnowLuma never downloads or applies anything
|
||||
// itself — cross-platform self-update is a minefield (Windows locks loaded
|
||||
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
|
||||
// have no supervisor). We only tell the WebUI that a newer *stable* release
|
||||
// exists and link the user to it; they download and apply manually.
|
||||
//
|
||||
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
|
||||
// rate limit, and every failure degrades silently (the UI just shows
|
||||
// "无法检查更新" rather than nagging).
|
||||
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
|
||||
const log = createLogger('Update');
|
||||
|
||||
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
|
||||
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
|
||||
const FETCH_TIMEOUT_MS = 8_000;
|
||||
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
|
||||
|
||||
export interface UpdateCheckResult {
|
||||
/** The running build's version (no `v` prefix). */
|
||||
current: string;
|
||||
/** Latest stable release version, or null when the check did not complete. */
|
||||
latest: string | null;
|
||||
/** True only when `latest` is strictly newer than `current`. */
|
||||
hasUpdate: boolean;
|
||||
/** GitHub release page URL for the latest release. */
|
||||
htmlUrl: string | null;
|
||||
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
|
||||
notes: string | null;
|
||||
/** ISO timestamp the latest release was published. */
|
||||
publishedAt: string | null;
|
||||
/** When this result was produced (epoch ms). */
|
||||
checkedAt: number;
|
||||
/** Set when the check was skipped or failed; the UI degrades silently. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface GithubRelease {
|
||||
tag_name?: string;
|
||||
html_url?: string;
|
||||
body?: string;
|
||||
published_at?: string;
|
||||
}
|
||||
|
||||
function currentVersion(): string {
|
||||
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
|
||||
}
|
||||
|
||||
function isEnabled(): boolean {
|
||||
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
||||
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two dotted versions. Returns >0 if `a` is newer than `b`, <0 if
|
||||
* older, 0 if equal. The numeric core (major.minor.patch) compares
|
||||
* numerically; a prerelease (`-rc.1`) ranks below its release. Good enough
|
||||
* for "is the latest stable strictly newer than what we run" — and avoids
|
||||
* pulling in a `semver` runtime dependency (the dist bundle ships none).
|
||||
*/
|
||||
export function compareVersions(a: string, b: string): number {
|
||||
const parse = (v: string) => {
|
||||
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
|
||||
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
|
||||
while (nums.length < 3) nums.push(0);
|
||||
return { nums, pre };
|
||||
};
|
||||
const pa = parse(a);
|
||||
const pb = parse(b);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (pa.nums[i] !== pb.nums[i]) return pa.nums[i] - pb.nums[i];
|
||||
}
|
||||
if (pa.pre === pb.pre) return 0;
|
||||
if (!pa.pre) return 1; // release > prerelease
|
||||
if (!pb.pre) return -1;
|
||||
return pa.pre < pb.pre ? -1 : 1;
|
||||
}
|
||||
|
||||
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
|
||||
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
|
||||
// are intentionally not cached (shouldCache) so the next check retries.
|
||||
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
shouldCache: (r) => !r.error,
|
||||
load: async (current) => {
|
||||
const result = await fetchLatest(current);
|
||||
if (result.error) {
|
||||
log.debug('update check failed: %s', result.error);
|
||||
} else if (result.hasUpdate) {
|
||||
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
|
||||
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
const base: UpdateCheckResult = {
|
||||
current,
|
||||
latest: null,
|
||||
hasUpdate: false,
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
try {
|
||||
// `/releases/latest` already excludes drafts and prereleases, so this is
|
||||
// stable-channel by construction.
|
||||
const res = await fetch(LATEST_RELEASE_URL, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': `SnowLuma/${current}`,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!res.ok) return { ...base, error: `github ${res.status}` };
|
||||
const rel = (await res.json()) as GithubRelease;
|
||||
const tag = (rel.tag_name ?? '').trim();
|
||||
if (!tag) return { ...base, error: 'no tag' };
|
||||
const latest = tag.replace(/^v/, '');
|
||||
return {
|
||||
current,
|
||||
latest,
|
||||
hasUpdate: compareVersions(latest, current) > 0,
|
||||
htmlUrl: rel.html_url ?? null,
|
||||
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
|
||||
publishedAt: rel.published_at ?? null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
} catch (e) {
|
||||
return { ...base, error: e instanceof Error ? e.message : 'network error' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the update-availability result. Cached for {@link CACHE_TTL_MS}; pass
|
||||
* `force` to bypass the cache (the WebUI's "立即检查" button). Never throws —
|
||||
* failures come back as a result with `error` set and `hasUpdate: false`, and
|
||||
* are not cached so the next check retries.
|
||||
*/
|
||||
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
|
||||
const current = currentVersion();
|
||||
if (!isEnabled()) {
|
||||
return { ...emptyResult(current), error: 'disabled' };
|
||||
}
|
||||
return updateCache.get(current, { force });
|
||||
}
|
||||
|
||||
function emptyResult(current: string): UpdateCheckResult {
|
||||
return {
|
||||
current,
|
||||
latest: null,
|
||||
hasUpdate: false,
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
@@ -27,6 +27,7 @@ export interface MockMessageApi {
|
||||
recallPrivate: ReturnType<typeof vi.fn>;
|
||||
markGroupRead: ReturnType<typeof vi.fn>;
|
||||
markPrivateRead: ReturnType<typeof vi.fn>;
|
||||
markAllRead: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
export function mockMessageApi(): MockMessageApi {
|
||||
@@ -38,6 +39,7 @@ export function mockMessageApi(): MockMessageApi {
|
||||
recallPrivate: vi.fn(async () => undefined),
|
||||
markGroupRead: vi.fn(async () => undefined),
|
||||
markPrivateRead: vi.fn(async () => undefined),
|
||||
markAllRead: vi.fn(async () => undefined),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,6 +67,7 @@ export interface MockGroupFileApi {
|
||||
upload: ReturnType<typeof vi.fn>;
|
||||
uploadPrivate: ReturnType<typeof vi.fn>;
|
||||
publish: ReturnType<typeof vi.fn>;
|
||||
trans: ReturnType<typeof vi.fn>;
|
||||
getCount: ReturnType<typeof vi.fn>;
|
||||
list: ReturnType<typeof vi.fn>;
|
||||
getUrl: ReturnType<typeof vi.fn>;
|
||||
@@ -85,6 +88,7 @@ export function mockGroupFileApi(): MockGroupFileApi {
|
||||
upload: vi.fn(async () => ({ fileId: 'stub-fid' })),
|
||||
uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })),
|
||||
publish: vi.fn(async () => undefined),
|
||||
trans: vi.fn(async () => ({ saveBusId: 102, saveFilePath: '/stub-path' })),
|
||||
getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })),
|
||||
list: vi.fn(async () => ({ files: [], folders: [] })),
|
||||
getUrl: vi.fn(async () => 'stub://url'),
|
||||
@@ -124,7 +128,9 @@ export interface MockBridge {
|
||||
findUidByUin: ReturnType<typeof vi.fn>;
|
||||
findUinByUid: ReturnType<typeof vi.fn>;
|
||||
findGroupMember: ReturnType<typeof vi.fn>;
|
||||
forgetGroup: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
events: { emit: ReturnType<typeof vi.fn> };
|
||||
apis: MockApiHub;
|
||||
sendRawPacket: ReturnType<typeof vi.fn>;
|
||||
fetchFriendList: ReturnType<typeof vi.fn>;
|
||||
@@ -154,8 +160,10 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
|
||||
findUidByUin: vi.fn(() => 'cached-uid'),
|
||||
findUinByUid: vi.fn(() => 0),
|
||||
findGroupMember: vi.fn(() => null),
|
||||
forgetGroup: vi.fn(),
|
||||
...(overrides.identity ?? {}),
|
||||
} as MockBridge['identity'],
|
||||
events: overrides.events ?? { emit: vi.fn(async () => undefined) },
|
||||
apis: overrides.apis ?? mockApiHub(),
|
||||
sendRawPacket: vi.fn(async () => defaultResp),
|
||||
fetchFriendList: vi.fn(async () => []),
|
||||
|
||||
Loaded 100 of 571 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user