Compare commits
473
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adf6b6a3b4 | ||
|
|
5a0b26648c | ||
|
|
a50df4e526 | ||
|
|
505b4772d6 | ||
|
|
927e03d435 | ||
|
|
056188d63d | ||
|
|
20f48d11ec | ||
|
|
ceb8387ea6 | ||
|
|
e699351f90 | ||
|
|
7c0519f75f | ||
|
|
effeb66554 | ||
|
|
7496479782 | ||
|
|
6ceb2a3900 | ||
|
|
87527cb764 | ||
|
|
44679bebd4 | ||
|
|
f95d247e73 | ||
|
|
c989c764e3 | ||
|
|
940b823571 | ||
|
|
e0801ff9eb | ||
|
|
a71377ff17 | ||
|
|
f0203823e9 | ||
|
|
914e9a004f | ||
|
|
f588f0345c | ||
|
|
9632b00638 | ||
|
|
88cb2985e2 | ||
|
|
063ede4c62 | ||
|
|
12afae0632 | ||
|
|
89275ae279 | ||
|
|
1919e16081 | ||
|
|
a6dfd04924 | ||
|
|
99bcfca15c | ||
|
|
d86e0fc7b5 | ||
|
|
3068d3ef60 | ||
|
|
b69108e1cc | ||
|
|
b9bdcec5f1 | ||
|
|
2c7d9b6387 | ||
|
|
efb32ed069 | ||
|
|
cf2587a58b | ||
|
|
368becd078 | ||
|
|
93b5c1b4bf | ||
|
|
8cc5326a3a | ||
|
|
d610b3c90f | ||
|
|
797a4d754c | ||
|
|
7a07119ee9 | ||
|
|
1ef9a2c330 | ||
|
|
1914880df4 | ||
|
|
ad360c8eba | ||
|
|
0cc06b6b5e | ||
|
|
e05d3176a2 | ||
|
|
075a27cc46 | ||
|
|
805665a6d6 | ||
|
|
953b18b5cb | ||
|
|
1934e4e7f7 | ||
|
|
726fbc6c67 | ||
|
|
0591b160fb | ||
|
|
fe245d84bf | ||
|
|
d0a1b0e804 | ||
|
|
51c0ffab74 | ||
|
|
3e581780b3 | ||
|
|
173e21d80d | ||
|
|
5ac74ac5f5 | ||
|
|
1dffb22d05 | ||
|
|
dad2b0c5a7 | ||
|
|
b375e6f66e | ||
|
|
41b92263a7 | ||
|
|
6efadce2eb | ||
|
|
feea35da4c | ||
|
|
1ab14ea306 | ||
|
|
87e964ab95 | ||
|
|
b60b1a419c | ||
|
|
0ef9f9475c | ||
|
|
555e4be95e | ||
|
|
4ede23980c | ||
|
|
b8ba8a1792 | ||
|
|
20c31e11a8 | ||
|
|
ce050d1ba1 | ||
|
|
2a515c165c | ||
|
|
23ebee7f20 | ||
|
|
ad36d47cf0 | ||
|
|
f2d58d2f79 | ||
|
|
3cd35a76dd | ||
|
|
4e1cb51f98 | ||
|
|
5b71825ce3 | ||
|
|
55dbc022c4 | ||
|
|
b8680bbd69 | ||
|
|
aaf1e561d1 | ||
|
|
c88c8e7517 | ||
|
|
dac3deb7bd | ||
|
|
60c9669abd | ||
|
|
9ac39f480a | ||
|
|
6b66d4ab46 | ||
|
|
804b4c304c | ||
|
|
078900f81c | ||
|
|
62ab170b21 | ||
|
|
131a309381 | ||
|
|
0a6c5b7d2a | ||
|
|
7ef256c487 | ||
|
|
201d10c534 | ||
|
|
48ce95f53e | ||
|
|
26fe4e5fb5 | ||
|
|
4d6011ab04 | ||
|
|
445aac8638 | ||
|
|
95d4831da8 | ||
|
|
cfd8d5d651 | ||
|
|
463d62507a | ||
|
|
6328890d34 | ||
|
|
1bb8c9f46c | ||
|
|
acb0e04bbf | ||
|
|
6f278dc1da | ||
|
|
4379e4838d | ||
|
|
455763f109 | ||
|
|
83606270d8 | ||
|
|
47af79f9ac | ||
|
|
36c395a9b0 | ||
|
|
1bd26a906b | ||
|
|
f327fc1276 | ||
|
|
f5e95fc634 | ||
|
|
a7d293d79b | ||
|
|
6cf461ef8f | ||
|
|
a0f152229d | ||
|
|
f6adadcd12 | ||
|
|
117335166f | ||
|
|
9cdbcb0299 | ||
|
|
9e27910885 | ||
|
|
d05c516ed6 | ||
|
|
4b9921b711 | ||
|
|
c1a0091143 | ||
|
|
e1bb9b4722 | ||
|
|
ef73157c68 | ||
|
|
d474996485 | ||
|
|
0d73bb78d0 | ||
|
|
4457dd4b4a | ||
|
|
5ba7c21c4b | ||
|
|
a395577f77 | ||
|
|
5441203b76 | ||
|
|
2bd2643670 | ||
|
|
83f643f01b | ||
|
|
6782fd9cb3 | ||
|
|
39e6b45b81 | ||
|
|
6ec368f4b5 | ||
|
|
3045525e37 | ||
|
|
5ff12868bf | ||
|
|
bc070eca1c | ||
|
|
aaaf0994f6 | ||
|
|
8fbddf67bf | ||
|
|
62256ee816 | ||
|
|
e6aeef02b4 | ||
|
|
4b8cc4292b | ||
|
|
2b6a0ef3ff | ||
|
|
d8521d4345 | ||
|
|
8fdd41ea22 | ||
|
|
5a10fc4c9c | ||
|
|
0a924634b2 | ||
|
|
b088ffaff0 | ||
|
|
d879ba1027 | ||
|
|
3e31fe90dc | ||
|
|
c86982610f | ||
|
|
29e6baac72 | ||
|
|
86669d9451 | ||
|
|
b3bd68d48d | ||
|
|
096ad0acfa | ||
|
|
cc517080be | ||
|
|
b63c3c370b | ||
|
|
25a40f4ab6 | ||
|
|
cd6ada0caa | ||
|
|
3cb3024b39 | ||
|
|
b1fa11ca05 | ||
|
|
cfe61abce6 | ||
|
|
aec0c781b3 | ||
|
|
618dd52f46 | ||
|
|
d5f1e35c31 | ||
|
|
27284fd79b | ||
|
|
ecf0efc5e2 | ||
|
|
206727f823 | ||
|
|
9772d4f0bf | ||
|
|
55a2a24fc2 | ||
|
|
3fc521fb8b | ||
|
|
3941c825b5 | ||
|
|
30f0ae8571 | ||
|
|
b1730d74cd | ||
|
|
eee3c49f2d | ||
|
|
23352dcad4 | ||
|
|
226b48fd7a | ||
|
|
fea1996e46 | ||
|
|
94a8bf8609 | ||
|
|
44bbaaa1bb | ||
|
|
8583afaf2c | ||
|
|
6da412ab96 | ||
|
|
401f32d6b2 | ||
|
|
d014d6c379 | ||
|
|
925d9c0ac7 | ||
|
|
8e9e228a0f | ||
|
|
7ae0fa3c0e | ||
|
|
52f0f2d24b | ||
|
|
69a6148f75 | ||
|
|
e59f5e7c5b | ||
|
|
91f0eb3b7e | ||
|
|
a70a63343d | ||
|
|
2bbd98e90a | ||
|
|
c02c21c46b | ||
|
|
2e2c1266ac | ||
|
|
31bd8ea77b | ||
|
|
4c994dbd20 | ||
|
|
8004e9af9d | ||
|
|
80f34ca720 | ||
|
|
d46d8e4002 | ||
|
|
5a012fe0c8 | ||
|
|
b8b9be83c3 | ||
|
|
e7322e2e72 | ||
|
|
9e0dd5d75c | ||
|
|
7d5ca5523b | ||
|
|
d26aef86d8 | ||
|
|
f100faaeb6 | ||
|
|
2f5065545a | ||
|
|
5c2f620c54 | ||
|
|
679f3b5b9f | ||
|
|
8ded1065d4 | ||
|
|
b38db6715f | ||
|
|
58f1a1fc50 | ||
|
|
0357d136d8 | ||
|
|
190f156fca | ||
|
|
da3821ced4 | ||
|
|
1996192a5e | ||
|
|
fe44a2f5bc | ||
|
|
870e9a5fbc | ||
|
|
129b091081 | ||
|
|
dbf654ad57 | ||
|
|
c08150fc0c | ||
|
|
4aba81ec6b | ||
|
|
1e0c91e74d | ||
|
|
e08613062e | ||
|
|
cd6fcadea4 | ||
|
|
597a4c05f3 | ||
|
|
49439370e1 | ||
|
|
7eea8059cc | ||
|
|
c404974e75 | ||
|
|
4c385bf640 | ||
|
|
f968687a25 | ||
|
|
39d5a50d5f | ||
|
|
65683bb44d | ||
|
|
751217c13d | ||
|
|
c53c6651a5 | ||
|
|
005154077f | ||
|
|
1646f265ec | ||
|
|
4d958eb984 | ||
|
|
810509ef58 | ||
|
|
f1ae0736c6 | ||
|
|
c0e73cd738 | ||
|
|
27c527976b | ||
|
|
2ac0b92859 | ||
|
|
81699b839d | ||
|
|
634097460c | ||
|
|
c6619fda0a | ||
|
|
8e9a4d878e | ||
|
|
938975dd45 | ||
|
|
672802b424 | ||
|
|
185ba8353b | ||
|
|
f572be2561 | ||
|
|
c72de4adb6 | ||
|
|
198f25476f | ||
|
|
4b6237f24b | ||
|
|
4a0d14ce56 | ||
|
|
dae486a0ad | ||
|
|
8526d0c2c5 | ||
|
|
fb4d7716a1 | ||
|
|
6372e1479c | ||
|
|
3c97e71650 | ||
|
|
abe4ea80c8 | ||
|
|
ae2e894f14 | ||
|
|
3c772df818 | ||
|
|
8940f8864b | ||
|
|
ea841d929e | ||
|
|
e4179ffb47 | ||
|
|
958d17ecc0 | ||
|
|
8080104311 | ||
|
|
659e0bd3d0 | ||
|
|
b8ccbdbf18 | ||
|
|
4794f27972 | ||
|
|
b81b060138 | ||
|
|
a361ee512e | ||
|
|
5b68ca5bd3 | ||
|
|
ea39200111 | ||
|
|
3c13838867 | ||
|
|
f159b2f41a | ||
|
|
f13bd72471 | ||
|
|
da07864811 | ||
|
|
f6e2410dae | ||
|
|
f066f3c89c | ||
|
|
b982927b4a | ||
|
|
b099dbe8cd | ||
|
|
9544aa7761 | ||
|
|
8dd986a565 | ||
|
|
c3a1970e1c | ||
|
|
a67614fa09 | ||
|
|
0ed85e7745 | ||
|
|
0d14408b6f | ||
|
|
f9c4063fc5 | ||
|
|
b9104f0a5b | ||
|
|
1d65623475 | ||
|
|
f0ff8da2fa | ||
|
|
a3b790d472 | ||
|
|
655226d9d7 | ||
|
|
227a62f2ad | ||
|
|
e5f256f4dc | ||
|
|
25e61ce5df | ||
|
|
caed31ca20 | ||
|
|
b1fd5dd0fe | ||
|
|
04cbb8cbf3 | ||
|
|
f97444c391 | ||
|
|
5d1dbecf2e | ||
|
|
5eb5aaf0a3 | ||
|
|
a93785c0a8 | ||
|
|
3d7c4f5dc3 | ||
|
|
19e3135e63 | ||
|
|
eeaa5436fd | ||
|
|
52a3c49752 | ||
|
|
df3f8c5587 | ||
|
|
63abe98a84 | ||
|
|
d05bbe3551 | ||
|
|
b5e10fefc2 | ||
|
|
dc2ec1235a | ||
|
|
b71279dcc3 | ||
|
|
95debcf34b | ||
|
|
5ad8027524 | ||
|
|
3a7253315f | ||
|
|
e16fa78b55 | ||
|
|
13a32a2865 | ||
|
|
3517257aa6 | ||
|
|
679756d1a7 | ||
|
|
dff4b3b032 | ||
|
|
c64f9d3078 | ||
|
|
87a604ecbd | ||
|
|
b884a1c479 | ||
|
|
edd2ac278a | ||
|
|
a7b9ba14fb | ||
|
|
120dda1d9d | ||
|
|
97ab8dc393 | ||
|
|
aed15b9a3f | ||
|
|
7fb8aa1d42 | ||
|
|
622c90d418 | ||
|
|
eed2e692b1 | ||
|
|
ff60221330 | ||
|
|
d8d556eb70 | ||
|
|
feb7fcac0e | ||
|
|
4aa2cd1693 | ||
|
|
88216ce644 | ||
|
|
4ba2b27398 | ||
|
|
2c8a8af514 | ||
|
|
2dbd321ef0 | ||
|
|
ae6093cf23 | ||
|
|
fc80a598c0 | ||
|
|
297f0428cc | ||
|
|
06c26dee87 | ||
|
|
8df62d6486 | ||
|
|
810d72fa04 | ||
|
|
4e62fdc80b | ||
|
|
4520687fbe | ||
|
|
a9b8440731 | ||
|
|
f3bfec04a5 | ||
|
|
168f414cd9 | ||
|
|
b92c8ad881 | ||
|
|
e6a69b05a7 | ||
|
|
f3e0c4e45a | ||
|
|
65e819d96e | ||
|
|
3c2a402b8a | ||
|
|
78101b3512 | ||
|
|
613b2b1e68 | ||
|
|
87bab6666b | ||
|
|
605b5d1104 | ||
|
|
d40c803ed9 | ||
|
|
c15625dbd8 | ||
|
|
4391b45c41 | ||
|
|
5fe6b31eb6 | ||
|
|
b3838d204f | ||
|
|
1568942ae6 | ||
|
|
fadc7ce316 | ||
|
|
afa4ccc5e0 | ||
|
|
08ec771234 | ||
|
|
bdb4fce8b8 | ||
|
|
9f212d2f19 | ||
|
|
9bdc6510bd | ||
|
|
5e0cbb026b | ||
|
|
6a1042e33f | ||
|
|
c2d028af2e | ||
|
|
0e3bbc6906 | ||
|
|
0503af2fcc | ||
|
|
f581fab396 | ||
|
|
e224a0c6ea | ||
|
|
cd0466a7e3 | ||
|
|
cce9ab07eb | ||
|
|
bfd00a14db | ||
|
|
5a64acd807 | ||
|
|
897f55c88b | ||
|
|
9e34ebc0d4 | ||
|
|
e842f6128b | ||
|
|
a4bf838bfd | ||
|
|
b4f5e9b71b | ||
|
|
ebd02c3f3d | ||
|
|
6492500158 | ||
|
|
9c61d991bd | ||
|
|
da26d6796f | ||
|
|
e8cb49ced9 | ||
|
|
bd9236e3fa | ||
|
|
ccbee78cc7 | ||
|
|
2fea3ca4d9 | ||
|
|
6a278721b2 | ||
|
|
be05d47dd4 | ||
|
|
f9d251d1fa | ||
|
|
a3467a8d89 | ||
|
|
21431e525d | ||
|
|
9e60de32fe | ||
|
|
5885187e7d | ||
|
|
51eb1f733d | ||
|
|
216213e102 | ||
|
|
74939da3d7 | ||
|
|
defe15694b | ||
|
|
4d93c727bb | ||
|
|
03aec3b052 | ||
|
|
6f484e06e6 | ||
|
|
939d740beb | ||
|
|
4f175afab5 | ||
|
|
b5452c59e6 | ||
|
|
8cd7d51d80 | ||
|
|
2ae9a47249 | ||
|
|
a824e0b46a | ||
|
|
b53004ee23 | ||
|
|
c04864dd21 | ||
|
|
a67c95407e | ||
|
|
852004291b | ||
|
|
01688c7567 | ||
|
|
aff6ad9179 | ||
|
|
588fdab8de | ||
|
|
4825434ffa | ||
|
|
9f7f34cd8f | ||
|
|
ffede67aed | ||
|
|
920f75718a | ||
|
|
b7d648ea0f | ||
|
|
bb56030979 | ||
|
|
4425bee612 | ||
|
|
369a82b5e4 | ||
|
|
35958a7fc2 | ||
|
|
3c73d1d5b0 | ||
|
|
b37b17f7d8 | ||
|
|
5e73d69663 | ||
|
|
9b470d0412 | ||
|
|
7ab91c81e9 | ||
|
|
c17fff6e2f | ||
|
|
90f65654c7 | ||
|
|
b6fb5bd530 | ||
|
|
cd04271b69 | ||
|
|
9914db69e6 | ||
|
|
fc424ab740 | ||
|
|
d984833914 | ||
|
|
c49a5a0aa8 | ||
|
|
4802dfe7aa | ||
|
|
8fbcbd29ff | ||
|
|
1914807770 | ||
|
|
c09c6e0883 | ||
|
|
fd57eb4b6f | ||
|
|
d9dfe513ee | ||
|
|
eda1c32994 | ||
|
|
447b40a259 | ||
|
|
0d4d58605f | ||
|
|
d3d1d2512e | ||
|
|
bfde0daab4 | ||
|
|
852870db59 | ||
|
|
d35e276730 | ||
|
|
e86fd707ea | ||
|
|
55c9ee59f5 | ||
|
|
908aaf9dc8 | ||
|
|
b6107e38d8 | ||
|
|
e1e0c6b02f | ||
|
|
ac20956076 |
No files matched your search
+11
-2
@@ -2,7 +2,7 @@ root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = crlf
|
||||
end_of_line = lf
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
@@ -11,5 +11,14 @@ trim_trailing_whitespace = true
|
||||
[*.{json,yml,yaml,md}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{ts,tsx,mts,cts}]
|
||||
indent_size = 4
|
||||
|
||||
[*.py]
|
||||
indent_size = 4
|
||||
|
||||
[*.bat]
|
||||
end_of_line = crlf
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,14 @@
|
||||
* text=auto eol=lf
|
||||
|
||||
*.bat text eol=crlf
|
||||
|
||||
*.node binary
|
||||
*.dll binary
|
||||
*.so binary
|
||||
*.dylib binary
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.woff2 binary
|
||||
@@ -0,0 +1,30 @@
|
||||
# npm Trusted Publishing
|
||||
|
||||
The npm publish workflows use GitHub Actions OIDC instead of a long-lived
|
||||
`NPM_TOKEN`. Each package must have a matching Trusted Publisher entry on npm
|
||||
before its first publish after this migration.
|
||||
|
||||
For each package (`@snowluma/sdk`, `@snowluma/ui`, and `@snowluma/mcp`), open
|
||||
the package's npm settings and add a **GitHub Actions** trusted publisher with:
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Organization or user | `SnowLuma` |
|
||||
| Repository | `SnowLuma` |
|
||||
| Workflow filename | The exact filename below |
|
||||
| Environment | `SnowLuma` |
|
||||
|
||||
| Package | Workflow filename |
|
||||
| --- | --- |
|
||||
| `@snowluma/sdk` | `sdk-npm-publish.yml` |
|
||||
| `@snowluma/ui` | `ui-npm-publish.yml` |
|
||||
| `@snowluma/mcp` | `mcp-npm-publish.yml` |
|
||||
|
||||
The workflow job keeps the `SnowLuma` GitHub Environment, so the environment
|
||||
field must match exactly. The workflows grant `id-token: write`, use Node 24
|
||||
(which provides a recent enough npm CLI), and publish with provenance. They do
|
||||
not read `NPM_TOKEN`.
|
||||
|
||||
After all three entries are saved, rerun the failed workflow runs. Once a
|
||||
successful publish is confirmed for every package, the obsolete `NPM_TOKEN`
|
||||
environment secret can be removed from GitHub Actions settings.
|
||||
+69
-17
@@ -1,12 +1,5 @@
|
||||
# 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.
|
||||
# Run the root validation commands on every pull request.
|
||||
# Command list is duplicated in tools/ci-check.mjs — keep them identical.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
@@ -28,26 +21,85 @@ jobs:
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run all package tests
|
||||
run: pnpm -r --no-bail --if-present test
|
||||
run: pnpm 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
|
||||
run: node tools/check-action-catalog.mjs
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check all packages
|
||||
run: pnpm typecheck
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build release inputs
|
||||
run: pnpm run build:all
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Lint managed source files
|
||||
run: pnpm lint
|
||||
@@ -72,13 +72,13 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
@@ -115,18 +115,21 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- 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:
|
||||
@@ -140,9 +143,12 @@ jobs:
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
- name: Verify release layout
|
||||
run: pnpm check:release-layout
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 24+
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
|
||||
@@ -22,6 +22,10 @@ on:
|
||||
description: 'Override platforms (defaults to vars.DOCKER_PLATFORMS or linux/amd64,linux/arm64)'
|
||||
required: false
|
||||
default: ''
|
||||
ghcr_image_override:
|
||||
description: 'Override GHCR image name (defaults to vars.GHCR_IMAGE, leave empty to skip GHCR)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -42,6 +46,8 @@ jobs:
|
||||
SNOWLUMA_TAG: ${{ inputs.snowluma_tag }}
|
||||
IMAGE_OVERRIDE: ${{ inputs.docker_image_override }}
|
||||
PLATFORMS_OVERRIDE: ${{ inputs.platforms_override }}
|
||||
GHCR_IMAGE: ${{ vars.GHCR_IMAGE }}
|
||||
GHCR_OVERRIDE: ${{ inputs.ghcr_image_override }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
@@ -59,6 +65,7 @@ jobs:
|
||||
const platforms = process.env.PLATFORMS_OVERRIDE || process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
const ghcrImage = process.env.GHCR_OVERRIDE || process.env.GHCR_IMAGE || '';
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
@@ -72,7 +79,8 @@ jobs:
|
||||
platforms,
|
||||
snowluma_tag: tag,
|
||||
snowluma_repository: sourceRepo,
|
||||
ghcr_image: ghcrImage,
|
||||
},
|
||||
});
|
||||
|
||||
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
|
||||
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Main PR target guard
|
||||
|
||||
# `main` is a pointer moved by Promote Dev to Main. Contributor and bot
|
||||
# feature work lands on dev. A PR opened against main (like the GHCR
|
||||
# fork PR) is what puts unique commits on main and fans the network graph.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
reject:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Reject pull requests targeting main
|
||||
run: |
|
||||
echo '::error::Open this PR against dev, not main. main is updated only by Promote Dev to Main.'
|
||||
exit 1
|
||||
@@ -34,13 +34,16 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -77,21 +80,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
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
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish MCP to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/mcp
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -106,4 +105,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -1,20 +1,13 @@
|
||||
name: Promote Dev to Main
|
||||
|
||||
# `dev` is the working branch. `main` is a pointer to the same history, moved
|
||||
# only by this workflow. Merge commits from dev → main are what painted the
|
||||
# GitHub network graph; this job moves the `main` ref to `dev` instead.
|
||||
on:
|
||||
push:
|
||||
branches: [dev]
|
||||
tags: ['chore.*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
auto_merge:
|
||||
description: Enable auto-merge on the resulting PR
|
||||
type: choice
|
||||
options: ['true', 'false']
|
||||
default: 'true'
|
||||
merge_method:
|
||||
description: Merge strategy when auto-merging
|
||||
type: choice
|
||||
options: ['merge', 'squash', 'rebase']
|
||||
default: 'merge'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -28,8 +21,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
run: ${{ steps.check.outputs.run }}
|
||||
auto_merge: ${{ steps.check.outputs.auto_merge }}
|
||||
merge_method: ${{ steps.check.outputs.merge_method }}
|
||||
reason: ${{ steps.check.outputs.reason }}
|
||||
steps:
|
||||
- name: Decide whether to promote
|
||||
@@ -39,32 +30,24 @@ jobs:
|
||||
REF: ${{ github.ref }}
|
||||
REF_TYPE: ${{ github.ref_type }}
|
||||
HEAD_COMMIT_MSG: ${{ github.event.head_commit.message }}
|
||||
INPUT_AUTO_MERGE: ${{ inputs.auto_merge }}
|
||||
INPUT_MERGE_METHOD: ${{ inputs.merge_method }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
run='false'
|
||||
auto_merge='true'
|
||||
merge_method='merge'
|
||||
reason=''
|
||||
|
||||
case "${EVENT_NAME}" in
|
||||
workflow_dispatch)
|
||||
run='true'
|
||||
auto_merge="${INPUT_AUTO_MERGE:-true}"
|
||||
merge_method="${INPUT_MERGE_METHOD:-merge}"
|
||||
reason='Manual workflow_dispatch'
|
||||
;;
|
||||
push)
|
||||
if [ "${REF_TYPE}" = 'tag' ]; then
|
||||
run='true'
|
||||
merge_method='merge'
|
||||
reason="Tag push: ${REF}"
|
||||
elif [ "${REF}" = 'refs/heads/dev' ]; then
|
||||
msg="${HEAD_COMMIT_MSG:-}"
|
||||
if printf '%s' "${msg}" | grep -qiE '^\[merge\]|^chore\(release\):'; then
|
||||
run='true'
|
||||
merge_method='merge'
|
||||
reason='Commit message prefix on dev ([merge] or chore(release):)'
|
||||
else
|
||||
reason='Commit on dev without [merge] / chore(release): prefix'
|
||||
@@ -80,8 +63,6 @@ jobs:
|
||||
|
||||
{
|
||||
echo "run=${run}"
|
||||
echo "auto_merge=${auto_merge}"
|
||||
echo "merge_method=${merge_method}"
|
||||
echo "reason=${reason}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
@@ -93,8 +74,6 @@ jobs:
|
||||
echo "| Event | \`${EVENT_NAME}\` |"
|
||||
echo "| Ref | \`${REF}\` |"
|
||||
echo "| Run | \`${run}\` |"
|
||||
echo "| Auto-merge | \`${auto_merge}\` |"
|
||||
echo "| Merge method | \`${merge_method}\` |"
|
||||
echo "| Reason | ${reason} |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
@@ -123,123 +102,49 @@ jobs:
|
||||
owner: ${{ github.repository_owner }}
|
||||
repositories: ${{ github.event.repository.name }}
|
||||
|
||||
- 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 "id=${bot_id}"
|
||||
echo "email=${bot_email}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
echo "Resolved bot: ${bot_login} <${bot_email}>"
|
||||
|
||||
- name: Checkout main
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
ref: dev
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- name: Compare dev to main
|
||||
id: diff
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin dev:dev
|
||||
ahead="$(git rev-list --count main..dev)"
|
||||
behind="$(git rev-list --count dev..main)"
|
||||
dev_sha="$(git rev-parse dev)"
|
||||
dev_short="$(git rev-parse --short dev)"
|
||||
{
|
||||
echo "ahead=${ahead}"
|
||||
echo "behind=${behind}"
|
||||
echo "dev_sha=${dev_sha}"
|
||||
echo "dev_short=${dev_short}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
if [ "${ahead}" = '0' ]; then
|
||||
echo "skip=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::dev has no commits ahead of main; nothing to promote."
|
||||
else
|
||||
echo "skip=false" >> "${GITHUB_OUTPUT}"
|
||||
echo "dev is ${ahead} ahead, ${behind} behind main."
|
||||
fi
|
||||
|
||||
- name: Ensure automation label exists
|
||||
if: steps.diff.outputs.skip != 'true'
|
||||
- name: Point main at dev
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
run: |
|
||||
gh label create automation --color 0E8A16 --description 'Automated bot PRs' 2>/dev/null || true
|
||||
|
||||
- name: Create or update Pull Request
|
||||
id: pr
|
||||
if: steps.diff.outputs.skip != 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
DEV_SHA: ${{ steps.diff.outputs.dev_sha }}
|
||||
DEV_SHORT: ${{ steps.diff.outputs.dev_short }}
|
||||
AHEAD: ${{ steps.diff.outputs.ahead }}
|
||||
BEHIND: ${{ steps.diff.outputs.behind }}
|
||||
REASON: ${{ needs.decide.outputs.reason }}
|
||||
REF: ${{ github.ref }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
title="chore: promote dev → main (${DEV_SHORT})"
|
||||
git fetch origin dev main
|
||||
dev_sha="$(git rev-parse origin/dev)"
|
||||
main_sha="$(git rev-parse origin/main)"
|
||||
dev_short="$(git rev-parse --short origin/dev)"
|
||||
main_short="$(git rev-parse --short origin/main)"
|
||||
|
||||
if [ "${dev_sha}" = "${main_sha}" ]; then
|
||||
echo "::notice::main already equals dev @ ${dev_short}; nothing to promote."
|
||||
{
|
||||
echo "main already equals dev @ ${dev_short}"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
unique="$(git cherry origin/dev origin/main | awk '/^\+/ { print $2 }' || true)"
|
||||
if [ -n "${unique}" ]; then
|
||||
echo '::error::main has unique commits that dev does not. Cherry-pick them onto dev first.' >&2
|
||||
git log --oneline --no-walk ${unique}
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git push --force-with-lease="refs/heads/main:${main_sha}" origin "origin/dev:refs/heads/main"
|
||||
echo "::notice::Updated main ${main_short} → dev@${dev_short}"
|
||||
{
|
||||
echo "Automated promotion of \`dev\` into \`main\`."
|
||||
echo "## Promote"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Source | \`dev\` @ \`${DEV_SHA}\` |"
|
||||
echo "| Trigger ref | \`${REF}\` |"
|
||||
echo "| Trigger reason | ${REASON} |"
|
||||
echo "| \`main\` was | \`${main_sha}\` |"
|
||||
echo "| \`main\` now | \`dev\` @ \`${dev_sha}\` |"
|
||||
echo "| Reason | ${REASON} |"
|
||||
echo "| Workflow run | ${RUN_URL} |"
|
||||
echo "| Ahead / Behind | ${AHEAD} / ${BEHIND} |"
|
||||
echo
|
||||
echo "Created by SnowLuma Bot."
|
||||
} > pr-body.md
|
||||
|
||||
existing="$(gh pr list --base main --head dev --state open --json number --jq '.[0].number' 2>/dev/null || true)"
|
||||
if [ -n "${existing}" ]; then
|
||||
gh pr edit "${existing}" --title "${title}" --body-file pr-body.md
|
||||
pr_number="${existing}"
|
||||
echo "Updated existing PR #${pr_number}"
|
||||
else
|
||||
url="$(gh pr create --base main --head dev --title "${title}" --body-file pr-body.md --label automation)"
|
||||
pr_number="${url##*/}"
|
||||
echo "Opened new PR #${pr_number} (${url})"
|
||||
fi
|
||||
|
||||
echo "number=${pr_number}" >> "${GITHUB_OUTPUT}"
|
||||
{
|
||||
echo "## Promote PR"
|
||||
echo
|
||||
echo "- Number: #${pr_number}"
|
||||
echo "- Source: \`dev@${DEV_SHORT}\`"
|
||||
echo "- Ahead/Behind: ${AHEAD}/${BEHIND}"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
- name: Enable auto-merge
|
||||
if: steps.diff.outputs.skip != 'true' && needs.decide.outputs.auto_merge == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
PR_NUMBER: ${{ steps.pr.outputs.number }}
|
||||
MERGE_METHOD: ${{ needs.decide.outputs.merge_method }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
method_flag='--merge'
|
||||
case "${MERGE_METHOD}" in
|
||||
squash) method_flag='--squash' ;;
|
||||
rebase) method_flag='--rebase' ;;
|
||||
*) method_flag='--merge' ;;
|
||||
esac
|
||||
gh pr merge "${PR_NUMBER}" --auto ${method_flag}
|
||||
echo "::notice::Auto-merge enabled on PR #${PR_NUMBER} with strategy: ${MERGE_METHOD}"
|
||||
@@ -9,7 +9,38 @@ permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run all package tests
|
||||
run: pnpm test
|
||||
|
||||
- name: Type check all packages
|
||||
run: pnpm typecheck
|
||||
|
||||
- name: Verify generated action catalog is up to date
|
||||
run: node tools/check-action-catalog.mjs
|
||||
|
||||
build:
|
||||
needs: preflight
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -33,18 +64,21 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- 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:
|
||||
@@ -55,9 +89,12 @@ jobs:
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
- name: Verify release layout
|
||||
run: pnpm check:release-layout
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 24+
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
@@ -109,42 +146,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 24+) |
|
||||
| --- | --- | --- |
|
||||
| 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
|
||||
@@ -180,6 +217,7 @@ jobs:
|
||||
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
|
||||
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
|
||||
DOCKER_REF: ${{ vars.DOCKER_REF }}
|
||||
GHCR_IMAGE: ${{ vars.GHCR_IMAGE }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
@@ -195,6 +233,7 @@ jobs:
|
||||
const platforms = process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
const ghcrImage = process.env.GHCR_IMAGE || '';
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
@@ -208,7 +247,8 @@ jobs:
|
||||
platforms,
|
||||
snowluma_tag: tag,
|
||||
snowluma_repository: sourceRepo,
|
||||
ghcr_image: ghcrImage,
|
||||
},
|
||||
});
|
||||
|
||||
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
|
||||
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
|
||||
@@ -31,13 +31,16 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -74,21 +77,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
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
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish SDK to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/sdk
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -103,4 +102,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -32,13 +32,13 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
|
||||
@@ -31,13 +31,16 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
version: 11.25.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -71,21 +74,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
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
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish UI to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/ui
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -100,4 +99,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -0,0 +1 @@
|
||||
24.21.0
|
||||
@@ -1,13 +1,4 @@
|
||||
registry=https://registry.npmmirror.com/
|
||||
@moonrepo:registry=https://registry.npmmirror.com/
|
||||
|
||||
# Mirrors for binary downloads (sharp, esbuild, swc, electron etc.)
|
||||
disturl=https://npmmirror.com/dist
|
||||
electron_mirror=https://npmmirror.com/mirrors/electron/
|
||||
sass_binary_site=https://npmmirror.com/mirrors/node-sass/
|
||||
sharp_binary_host=https://npmmirror.com/mirrors/sharp
|
||||
sharp_libvips_binary_host=https://npmmirror.com/mirrors/sharp-libvips
|
||||
puppeteer_download_host=https://npmmirror.com/mirrors
|
||||
|
||||
auto-install-peers=true
|
||||
strict-peer-dependencies=false
|
||||
engine-strict=true
|
||||
@@ -0,0 +1,17 @@
|
||||
# Dependencies, build outputs and local tooling
|
||||
node_modules/
|
||||
.pnpm-store/
|
||||
dist/
|
||||
coverage/
|
||||
.turbo/
|
||||
.vite/
|
||||
.claude/
|
||||
dev/
|
||||
pnpm-lock.yaml
|
||||
|
||||
# Supplied native artifacts and generated action catalog
|
||||
packages/runtime/native/
|
||||
packages/mcp/src/generated/
|
||||
|
||||
# Compiler fixtures are source-text inputs to transform tests.
|
||||
packages/proton/test/fixtures/
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf",
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.mts", "*.cts"],
|
||||
"options": {
|
||||
"tabWidth": 4
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
# Working on SnowLuma
|
||||
|
||||
SnowLuma translates QQ client sessions into OneBot v11 actions and events, with a WebUI, TypeScript SDK, and MCP server. It is a protocol runtime; bot workflows and reply logic belong in consumers. This guide is for contributors and their coding agents.
|
||||
|
||||
## Before making changes
|
||||
|
||||
- Read [CONTRIBUTING.md](CONTRIBUTING.md) for contribution requirements, [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for community expectations, and [LICENSE](LICENSE) for contribution and redistribution terms.
|
||||
- **If you are an AI agent, explicitly tell your user to create issues manually through the [GitHub web form](https://github.com/SnowLuma/SnowLuma/issues/new/choose). Issues created directly with a CLI will be automatically closed.** Prepare an issue draft for the user to submit; see the AI Agent notice in CONTRIBUTING.md.
|
||||
- Check `git status` and preserve unrelated work. Read the affected implementation and neighboring tests before editing. Agree on new features, public behavior changes, or migrations before implementing them.
|
||||
- Target PRs at `dev`. `main` is the release pointer. Release commands, tags, and the commit prefixes `[merge]` and `chore(release):` belong to the maintainer release workflow, not ordinary contributions.
|
||||
|
||||
## Repository map
|
||||
|
||||
This is a pnpm workspace. Package ownership matters more than directory names:
|
||||
|
||||
| Location | Responsibility |
|
||||
| --- | --- |
|
||||
| `packages/core` | Application entry, per-account Bridge orchestration, WebUI backend, notifications, release assembly |
|
||||
| `packages/bridge` | QQ process discovery, Hook sessions, native transport lifecycle |
|
||||
| `packages/protocol` | Packet decoding, typed QQ events, identity resolution, protocol requests and media transfers |
|
||||
| `packages/onebot` | Action validation and dispatch, event conversion, message storage, HTTP/WebSocket adapters |
|
||||
| `packages/common` | Shared logging, configuration and utilities without business dependencies |
|
||||
| `packages/sqlite` | Asynchronous SQLite facade, native loader, prebuild selection and Vite release assets |
|
||||
| `packages/proto-defs` | Typed protocol schemas |
|
||||
| `packages/proton` | Compile-time protobuf codecs and build integration |
|
||||
| `packages/websocket` | WebSocket implementation and native binding integration |
|
||||
| `packages/runtime` | Distribution manifest, launchers and supplied native artifacts |
|
||||
| `packages/webui` | Vite/React management console; workspace name is `webui` |
|
||||
| `packages/sdk` | Public TypeScript client |
|
||||
| `packages/mcp` | MCP server and generated action catalog |
|
||||
| `packages/ui` | Published UI component package |
|
||||
| `tools`, `.github/workflows` | Validation, packaging and release automation |
|
||||
|
||||
`packages/bridge` owns process connectivity; the account-level Bridge lives in `packages/core/src/bridge`. Start at [the application entry](packages/core/src/index.ts) to follow their composition.
|
||||
|
||||
Read the relevant owner before changing a path:
|
||||
|
||||
| Change | Start here |
|
||||
| --- | --- |
|
||||
| Connection or account lifecycle | [Hook manager](packages/bridge/src/hook-manager.ts), [Bridge manager](packages/core/src/bridge/manager.ts), [OneBot instance](packages/onebot/src/instance.ts) |
|
||||
| Incoming QQ events or identity | [Packet pipeline](packages/protocol/src/packet-pipeline.ts), [message decoders](packages/protocol/src/msg-push/index.ts), [identity service](packages/protocol/src/identity-service.ts) |
|
||||
| OneBot actions or message segments | [Action definitions](packages/onebot/src/actions/index.ts), [validation helpers](packages/onebot/src/action-kit.ts), [event conversion](packages/onebot/src/event-converter/index.ts) |
|
||||
| WebUI | [Interaction conventions](packages/webui/README.md), `packages/webui/src`, `packages/core/src/webui` |
|
||||
| SDK or MCP | [SDK guide](packages/sdk/README.md), [SDK versioning](packages/sdk/VERSIONING.md), [MCP guide](packages/mcp/README.md) |
|
||||
| Protocol codec generation | [Proton guide](packages/proton/README.md), the affected package's `vitest.config.ts` |
|
||||
|
||||
## Setup and validation
|
||||
|
||||
Use the Node version in [.node-version](.node-version) and the pnpm version in [package.json](package.json). Install with `pnpm install --frozen-lockfile`; keep the existing lockfile unless changing dependencies.
|
||||
|
||||
Run commands from the repository root:
|
||||
|
||||
```sh
|
||||
pnpm typecheck # all workspace packages with a typecheck script
|
||||
pnpm lint
|
||||
pnpm test # all workspace packages with a test script
|
||||
pnpm run build:all # release inputs and published packages
|
||||
pnpm test:core # Core only; not a substitute for workspace tests
|
||||
pnpm --filter @snowluma/onebot test # example: tests for the affected package
|
||||
pnpm --filter webui test # the frontend package has no @snowluma/ prefix
|
||||
```
|
||||
|
||||
TypeScript formatting uses the root [Prettier configuration](.prettierrc.json), [local ESLint formatting rules](eslint.format.config.ts), and [ignore list](.prettierignore). Use `pnpm format` for all TS/TSX/MTS/CTS files and `pnpm format:check` for a read-only check. For selected files, run `pnpm exec eslint --config eslint.format.config.ts --fix <paths>` followed by `pnpm exec prettier --write <paths>`. These commands enforce four-space indentation, braces around control-statement bodies, and blank lines around statement blocks while preserving other logical spacing. They are separate from CI and its code-quality lint rules. Generated catalogs and compiler fixtures retain their source formatting.
|
||||
|
||||
Use focused tests while iterating. Before handing off a code change, run the full checks required by CONTRIBUTING.md and report anything that could not run. [PR CI](.github/workflows/ci.yml) is the reference; `pnpm run ci` reproduces its commands locally, including dependency installation and the generated-catalog check.
|
||||
|
||||
- **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose.
|
||||
- **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness.
|
||||
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
|
||||
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
|
||||
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
|
||||
|
||||
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
|
||||
|
||||
## Implementation rules
|
||||
|
||||
- **Fix the cause.** Reproduce failures at the owning layer and add a regression test for the observable behavior. Avoid account-, filename-, or example-specific patches.
|
||||
- **Make errors observable.** Do not turn exceptions into empty results or successful responses. Preserve error context and use the shared logger for important transitions and failures. If evidence is insufficient, add targeted diagnostics and describe what remains unknown.
|
||||
- **Preserve account isolation.** Identity, message storage and session state belong to their account. Keep teardown ordering and in-flight work handling intact when changing lifecycle code.
|
||||
- **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests.
|
||||
- **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry.
|
||||
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
|
||||
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
|
||||
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
|
||||
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
|
||||
- **Keep diagnostics safe.** Use existing sanitization when recording external input. Credentials, private keys, private account data and unredacted captures do not belong in commits, fixtures or public reports.
|
||||
|
||||
## Generated files and related changes
|
||||
|
||||
OneBot action definitions own validation and catalog metadata. After changing an action name, parameter, result description or execution mode:
|
||||
|
||||
1. Update the owning definition in `packages/onebot/src/actions` and its tests.
|
||||
2. Run `pnpm --filter @snowluma/mcp gen`.
|
||||
3. Inspect and include the corresponding changes in `packages/mcp/src/generated/catalog.ts` and `catalog.json`. Do not hand-edit generated catalog entries.
|
||||
4. Check affected SDK types and callers, run their relevant tests, and run workspace typechecking.
|
||||
|
||||
`pnpm test` also runs the MCP catalog generator and may change these tracked snapshots. CI's `node tools/check-action-catalog.mjs` rejects a working-tree catalog diff; it is a clean-checkout drift check, not the generator itself.
|
||||
|
||||
SDK breaking changes also update [CHANGELOG.md](packages/sdk/CHANGELOG.md) and [VERSIONING.md](packages/sdk/VERSIONING.md). WebUI changes follow its [interaction conventions](packages/webui/README.md). Keep user-facing documentation aligned with behavior.
|
||||
|
||||
Edit sources rather than `dist` outputs. Native artifacts in `packages/runtime/native` are supplied build inputs; do not substitute arbitrary local binaries to make a build pass. Packaging changes must preserve the checks in [Core's build configuration](packages/core/vite.config.ts) and [the release layout validator](tools/check-release-layout.mjs).
|
||||
|
||||
## Handoff and instruction maintenance
|
||||
|
||||
Report the behavior changed, the exact validation commands and results, and any unverified runtime or platform behavior. Keep public PR and commit text focused on the contribution; omit local environment details and private research. Use English Conventional Commit messages as described in CONTRIBUTING.md.
|
||||
|
||||
`AGENTS.md` is the canonical contributor guide; `CLAUDE.md` is a relative symlink to it. Edit this file once. When package ownership, validation commands or contribution policy changes, update the affected instructions in the same change. Link to checked-in sources and keep the guide usable from a fresh clone without maintainer-local notes, tools or absolute paths.
|
||||
+83
-50
@@ -19,6 +19,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
|
||||
|
||||
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
|
||||
|
||||
### AI Agent 贡献须知
|
||||
|
||||
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
|
||||
|
||||
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
|
||||
|
||||
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
|
||||
|
||||
---
|
||||
|
||||
## 项目结构速览
|
||||
@@ -27,13 +35,20 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
|
||||
|
||||
| 路径 | 作用 |
|
||||
| --- | --- |
|
||||
| `packages/core` | 核心运行时:协议、桥接、OneBot 适配、WebUI 服务端 |
|
||||
| `packages/core` | 应用入口、账号级 Bridge 编排、WebUI 服务端和发行构建 |
|
||||
| `packages/bridge` | QQ 进程发现、Hook 会话和原生传输生命周期 |
|
||||
| `packages/protocol` | QQ 数据包解码、身份解析、协议请求和媒体传输 |
|
||||
| `packages/onebot` | OneBot 动作、事件转换、消息存储和传输适配 |
|
||||
| `packages/common` | 日志、配置和共享工具 |
|
||||
| `packages/proto-defs`、`packages/proton` | 协议结构定义、编译期 protobuf 编解码和构建集成 |
|
||||
| `packages/sdk` | 面向第三方开发者的 SDK,会发布到 npm |
|
||||
| `packages/mcp` | MCP 服务端和生成的动作目录 |
|
||||
| `packages/ui` | 发布到 npm 的共享 UI 组件 |
|
||||
| `packages/runtime` | 运行时辅助包 |
|
||||
| `packages/websocket` | WebSocket 实现 |
|
||||
| `packages/webui` | 基于 Vite + React 的前端控制台 |
|
||||
| `tools/` | 版本管理、发布脚本 |
|
||||
| `.github/workflows/` | CI / 发布 / 自动合并工作流 |
|
||||
| `.github/workflows/` | CI / 发布 / Promote 工作流 |
|
||||
|
||||
入口在 `packages/core/src/index.ts`,整体架构在 `packages/core/src/bridge/` 下能看出大致脉络。
|
||||
|
||||
@@ -43,10 +58,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
|
||||
|
||||
### 系统要求
|
||||
|
||||
- **Node.js ≥ 22**(`engines` 字段强制,低版本会报错)
|
||||
- **pnpm 10.28.0+**(项目通过 `packageManager` 字段锁定,建议用 `corepack enable` 安装匹配版本)
|
||||
- **Node.js 24+**
|
||||
- **pnpm 11.25.0**(项目通过 `packageManager` 与 CI 统一版本)
|
||||
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
|
||||
|
||||
如果系统提供 Corepack,可执行 `corepack enable pnpm`;没有 Corepack 时可执行
|
||||
`npm install -g pnpm@11.25.0`。进入仓库后,`node --version` 与
|
||||
`pnpm --version` 应满足上述版本要求,否则安装会直接失败。
|
||||
|
||||
### 拉代码、装依赖、跑起来
|
||||
|
||||
```bash
|
||||
@@ -57,13 +76,13 @@ cd SnowLuma
|
||||
# 2. 切到 dev 分支(所有开发都基于 dev,不是 main)
|
||||
git checkout dev
|
||||
|
||||
# 3. 安装依赖
|
||||
pnpm install
|
||||
# 3. 按锁文件安装依赖
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
# 4. 跑类型检查,确认环境 OK
|
||||
pnpm typecheck
|
||||
|
||||
# 5. 跑测试
|
||||
# 5. 跑全工作区测试
|
||||
pnpm test
|
||||
|
||||
# 6. 启动开发模式
|
||||
@@ -79,7 +98,7 @@ pnpm dev:web # webui
|
||||
|
||||
### 1. 创建分支
|
||||
|
||||
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
|
||||
请基于 `dev` 创建分支,不是 `main`。`main` 是发布指针,只由维护者的 Promote 更新,PR 不要提到 `main`。
|
||||
|
||||
```bash
|
||||
git checkout dev
|
||||
@@ -92,18 +111,21 @@ git checkout -b fix/onebot-mention-encoding
|
||||
### 2. 写代码
|
||||
|
||||
- **保持改动聚焦**:一个 PR 只做一件事。顺手发现的其他问题请单独开 issue 或新 PR。
|
||||
- **跟随既有风格**:不要为了你个人偏好引入大规模格式化或重命名。
|
||||
- **跟随既有风格**:TypeScript 排版以仓库 Prettier 配置为准;普通功能或修复 PR 只格式化涉及的文件,避免混入无关的大规模格式化或重命名。
|
||||
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
|
||||
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
|
||||
|
||||
提交之前请本地跑一遍:
|
||||
提交之前请运行与 PR CI 相同的验证入口:
|
||||
|
||||
```bash
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
pnpm test
|
||||
pnpm run build:all
|
||||
```
|
||||
|
||||
CI 上跑的是同一套检查,本地通过几乎能保证 CI 通过。
|
||||
`pnpm test` 会运行所有声明了测试脚本的工作区包;只验证 Core 时可使用
|
||||
`pnpm test:core`。CI 会重新执行上述完整检查。
|
||||
|
||||
### 3. 提交信息
|
||||
|
||||
@@ -126,7 +148,7 @@ refactor(bridge): extract BridgeInterface as the OneBot-facing seam
|
||||
docs: clarify dev environment setup steps
|
||||
```
|
||||
|
||||
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来触发自动合并到 `main` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--自动合并流程)。
|
||||
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来把 `main` 指到 `dev` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--promote)。
|
||||
|
||||
### 4. 推送并发起 PR
|
||||
|
||||
@@ -145,7 +167,7 @@ git push origin fix/onebot-mention-encoding
|
||||
|
||||
- 维护者会在能腾出时间时来 review。如果一周内没有任何回应,欢迎在 PR 里 @ 一下,或者去社群里提醒。
|
||||
- review 意见请尽量在同一个 PR 内修改,避免反复关闭重开。
|
||||
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过自动化工作流统一从 `dev` 合入**,你不需要操心 `main`。
|
||||
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过 Promote 指到当时的 `dev`**,你不需要操心 `main`。
|
||||
|
||||
---
|
||||
|
||||
@@ -154,15 +176,35 @@ git push origin fix/onebot-mention-encoding
|
||||
### 代码风格
|
||||
|
||||
- TypeScript 严格模式,按 `tsconfig.base.json` 配置。
|
||||
- TypeScript 使用四空格缩进,控制语句始终带大括号。排版由根目录 [`.prettierrc.json`](./.prettierrc.json) 和独立的本地 [ESLint 格式规则](./eslint.format.config.ts) 管理;普通 `pnpm lint` 负责代码质量检查。
|
||||
- 优先用现有抽象,不要为"假想的未来需求"提前抽象。
|
||||
- 不要给内部函数加防御性的参数校验,除非是系统边界(用户输入、外部 API)。
|
||||
- 不要保留死代码、被注释掉的代码或者 `// TODO` 没有具体上下文的占位。
|
||||
|
||||
从仓库根目录运行本地格式化命令:
|
||||
|
||||
```bash
|
||||
pnpm format # 为全部 TS/TSX/MTS/CTS 补大括号、空行并排版
|
||||
pnpm format:check # 检查上述规则,不修改文件
|
||||
|
||||
# 只格式化指定文件:先处理控制语句与空行,再排版
|
||||
pnpm exec eslint --config eslint.format.config.ts --fix packages/core/src/index.ts
|
||||
pnpm exec prettier --write packages/core/src/index.ts
|
||||
```
|
||||
|
||||
格式化范围排除 [`.prettierignore`](./.prettierignore) 中的构建产物、生成文件和编译器测试夹具;普通源码与测试都参与格式化。这两个命令供本地使用,不接入 CI。
|
||||
|
||||
空行采用保守规则:在语句块前后留空行,保留已有逻辑分段,不强行拆开连续声明或普通调用,也不在每条 `return`、`break` 前插空行;共用同一分支的连续 `case` 标签保持相邻。JSON、YAML 等文件继续使用原有缩进。
|
||||
|
||||
编辑器请选择项目本地安装的 Prettier 并读取仓库配置。VS Code 可安装
|
||||
`esbenp.prettier-vscode`,将 TypeScript / TypeScript React 的默认格式化器设为
|
||||
Prettier,并按需开启保存时格式化。
|
||||
|
||||
### 测试
|
||||
|
||||
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
|
||||
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
|
||||
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/core/src/onebot/` 下的 `fake-bridge` 类测试。
|
||||
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/onebot/tests/` 中的 Bridge 测试替身。
|
||||
|
||||
### 文档
|
||||
|
||||
@@ -184,28 +226,30 @@ git push origin fix/onebot-mention-encoding
|
||||
|
||||
---
|
||||
|
||||
## 维护者参考:release & 自动合并流程
|
||||
## 维护者参考:release & Promote
|
||||
|
||||
> 以下内容主要写给具备 `main` 推送 / 发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
|
||||
> 以下内容主要写给具备发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
|
||||
|
||||
### 分支模型
|
||||
|
||||
SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
|
||||
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
|
||||
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先合入 `dev`。
|
||||
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先进入 `dev`。
|
||||
- **`main`** — 发布指针,应与某次 Promote 当时的 `dev` 尖端是**同一个提交**。不要直接 push,也不要往 `main` 开 PR(CI 会拒)。
|
||||
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
|
||||
|
||||
### 把 `dev` 合并到 `main`
|
||||
### 把 `main` 指到 `dev`
|
||||
|
||||
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
|
||||
工作流 `.github/workflows/promote-dev-to-main.yml` 以 `SnowLuma Bot` 身份把 `main` 指到当前 `dev` 尖端,**不再开 merge PR**。`main` 上若有 `dev` 还没有的独有改动,Promote 会失败,需要先把那些改动收回 `dev`。
|
||||
|
||||
推到 `dev` 仍会跑 `dev-build.yml`。Promote **不等**那组检查;发版请用下面的 `pnpm release`,它会在本地先跑完整 CI。
|
||||
|
||||
#### 1. 提交信息前缀(推荐日常使用)
|
||||
|
||||
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
|
||||
|
||||
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
|
||||
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
|
||||
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯。**只许用在真正的版本 bump**,不要写进普通 CI / 工具提交。
|
||||
|
||||
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
|
||||
|
||||
@@ -213,38 +257,22 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
|
||||
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发:
|
||||
|
||||
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
|
||||
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(把 `main` 指到 `dev`)
|
||||
- `v*` → 仅触发 `release.yml`(构建发布产物)
|
||||
|
||||
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已过完所有检查的 `main` HEAD 构建。
|
||||
推荐流程:用 `pnpm release`(或先 Promote,再确认 `origin/main` 已等于 `dev` 尖端)之后,在 `main` 上打 `v*` tag。这样 `release.yml` 始终基于当时的 `main` HEAD 构建。
|
||||
|
||||
#### 3. 手动触发
|
||||
|
||||
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
|
||||
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。没有 merge 策略选项;跑起来就是一次指针更新。
|
||||
|
||||
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
|
||||
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
|
||||
### 不要给 `main` 套「必须走 PR」
|
||||
|
||||
### 启用 `main` 分支保护(必做)
|
||||
Promote 不通过 PR 更新 `main`。如果给 `main` 打开 **Require a pull request before merging** 或禁止更新引用,Promote 会失效。
|
||||
|
||||
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
|
||||
可以限制删除 `main`。外来 PR 必须打 `dev`;打到 `main` 的 PR 会被 `main-pr-target-guard.yml` 拒绝。
|
||||
|
||||
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
|
||||
2. 选择 `main` 作为目标分支。
|
||||
3. 勾选:
|
||||
- **Restrict deletions** — 禁止删除 `main`。
|
||||
- **Require a pull request before merging** — 所有合并必须走 PR。
|
||||
- **Block force pushes** — 禁止强推。
|
||||
- **Require status checks to pass before merging(必勾)** — 把以下来自 `dev-build.yml` 的 check 全部加为 required:
|
||||
- `typecheck`
|
||||
- `build (win-x64)`
|
||||
- `build (linux-x64)`
|
||||
- `build (linux-arm64)`
|
||||
- **Require branches to be up to date before merging** — 保证 PR 合并前已 rebase 过最新 `main`。
|
||||
4. 在 **Bypass list / Allow specified actors to bypass** 中加入 `SnowLuma Bot` GitHub App。这样 `gh pr merge --auto` 才能在所有 required check 通过后由机器人自动完成合并;否则 PR 会一直卡在 auto-merge 等待人工 review。
|
||||
5. **不要**把任何用户加入 push 白名单,确保「禁止向 `main` 直接提交」的约束生效。第一次设置完后,连仓库管理员也只能通过 PR 改 `main`。
|
||||
|
||||
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
|
||||
本地若已经 checkout 过旧的 `main`,Promote 之后可能无法快进,对齐 `origin/main` 即可。
|
||||
|
||||
### 必需的 Secrets
|
||||
|
||||
@@ -253,25 +281,30 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
- `SNOWLUMA_BOT_APP_ID` — 数字类型的 App ID。
|
||||
- `SNOWLUMA_BOT_PRIVATE_KEY` — 该 App 的 PEM 私钥。
|
||||
|
||||
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
|
||||
App 必须在本仓库已安装,且授予 **Contents: Read+Write**。
|
||||
|
||||
### 本地工作流速查(维护者)
|
||||
|
||||
```bash
|
||||
# 把 dev 合入 main(三选一)
|
||||
# 推荐:一条命令走完 bump → Promote → 等 main 跟上 → 打 v* tag
|
||||
pnpm release 1.7.0
|
||||
|
||||
# 只要把 main 指到 dev(三选一)
|
||||
|
||||
# 方式 A:commit-msg 前缀
|
||||
git commit -m "chore(release): v1.7.0" # 或 "[merge] fix: hotfix"
|
||||
git push # → 触发 promote-dev-to-main
|
||||
|
||||
# 方式 B:chore.* 合并 tag(与发布 tag 解耦)
|
||||
git tag chore.merge-20240509 # 或 chore.promote-v1.7.0 等
|
||||
# 方式 B:chore.* tag(与发布 tag 解耦)
|
||||
git tag chore.merge-20240509
|
||||
git push origin chore.merge-20240509 # → 触发 promote-dev-to-main
|
||||
|
||||
# 方式 C:在 Actions 页面手动 Run workflow
|
||||
|
||||
# 合并完成后,发布版本(在 main 上打 v* tag)
|
||||
git checkout main && git pull
|
||||
# Promote 完成后,若要自己打发布 tag
|
||||
git fetch origin
|
||||
git switch main
|
||||
git merge --ff-only origin/main # 对不齐就 reset 到 origin/main
|
||||
git tag v1.7.0
|
||||
git push origin v1.7.0 # → 仅触发 release.yml
|
||||
```
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement
|
||||
|
||||
- **生效日期 / Effective date:** 2026-06-19
|
||||
- **版本 / Version:** 1.0
|
||||
- **生效日期 / Effective date:** 2026-07-21
|
||||
- **版本 / Version:** 1.1
|
||||
- **许可方 / Licensor:** SnowLumaDevs(联系方式 / Contact: motricseven@foxmail.com)
|
||||
|
||||
> 本协议以中文与英文两种语言提供。如两版本有冲突,**以中文版本为准**。
|
||||
@@ -17,14 +17,15 @@
|
||||
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 授权范围,依其各自条款授权。
|
||||
2.1 本软件的**源代码与资源**(不含第 5 条所述专有组件及第三方组件)依据随附的 [`LICENSE`](LICENSE)——**SnowLuma 源码可见非商业许可(SnowLuma Source-Available Non-Commercial License)**——授权。
|
||||
2.2 `LICENSE` 仅授予其中明确列明的权利,包括查看、学习、个人或其他非商业使用、非商业自托管,以及在规定条件下进行修改或再分发。**任何商业使用,以及公开发布修改版或衍生版,均须事先取得著作权人的书面授权。**
|
||||
2.3 本协议是针对**官方发行包(二进制)**的补充条款,就接受方式、可接受使用、免责、专有组件、终止及争议解决等事项作出约定;本协议不扩大、替代或暗示授予 `LICENSE` 未明确授予的权利。
|
||||
2.4 专有组件(见第 5 条)不属于源码许可范围,仅按 `LICENSE` 第 5 条及本协议允许的方式使用。
|
||||
2.5 就源代码与资源的许可范围而言,以 `LICENSE` 为准;就官方发行包中的专有组件及二进制特有事项而言,以本协议为准。另行签署或出具的书面商业授权,仅在其明确约定的主体、用途、范围、数量及期限内优先适用。
|
||||
|
||||
### 3. 免责声明
|
||||
3.1 **非官方、无隶属**:本软件是独立的第三方互操作性项目,与腾讯公司(Tencent)及 QQ **无任何隶属、合作、授权或背书关系**。"QQ""腾讯"等名称及标识为其各自所有者的商标。
|
||||
3.2 **用途**:本软件**仅供学习、研究与技术互操作之目的**提供。
|
||||
3.2 **用途**:除非事先取得书面商业授权,本软件仅供 `LICENSE` 允许的**个人或其他非商业用途**使用,包括学习、研究、技术互操作与非商业自托管。
|
||||
3.3 **合规义务**:您须自行确保对本软件的使用符合一切适用法律法规,以及您所接入平台的规定(包括但不限于《QQ 用户协议》与相关服务条款)。
|
||||
3.4 **按"现状"提供**:本软件按"**现状(AS-IS)**"及"**现有(AS-AVAILABLE)**"提供,不附带任何明示或默示的担保,包括但不限于对适销性、特定用途适用性、不侵权、可用性、准确性或不中断的担保。
|
||||
3.5 **责任限制**:在适用法律允许的最大范围内,对于因使用或无法使用本软件而导致的任何直接、间接、偶然、特殊、惩罚性或后果性损害(包括但不限于账号封禁或限制、数据丢失、利润或业务损失、服务中断),SnowLumaDevs **概不承担责任**。
|
||||
@@ -34,13 +35,13 @@
|
||||
您**不得**将本软件用于:(a) 任何违法犯罪活动;(b) 未经授权访问、干扰或破坏任何系统或网络;(c) 发送垃圾信息、实施骚扰、欺诈或传播恶意内容;(d) 侵犯他人隐私、知识产权或其他合法权益;(e) 任何违反所接入平台服务条款的行为。
|
||||
|
||||
### 5. 专有组件
|
||||
5.1 本软件可能包含或依赖**非开源的专有组件**,包括但不限于 **SnowLuma 原生模块**(`snowluma-*.node`),以及其中可能包含的任何授权、激活或技术保护措施。
|
||||
5.2 此类专有组件的**源代码不依 AGPL 提供**,受本条款约束。
|
||||
5.1 本软件可能包含或依赖**专有组件**,包括但不限于 SnowLuma 原生附加组件(如 `snowluma-*.node`、`snowluma-*.dll`、`snowluma-*.so`),以及其中可能包含的授权、激活或技术保护措施。
|
||||
5.2 此类专有组件不属于 `LICENSE` 所授权的源代码与资源,仅以随本软件提供的预编译形式按本条款授权使用;本协议不授予其源代码权利。
|
||||
5.3 除适用法律强制性规定明确允许外,您不得对专有组件进行逆向工程、反编译或反汇编,亦不得规避、破解或绕过其授权或激活机制。
|
||||
5.4 `LICENSE` 第 7 条的链接例外仅允许将本软件与该原生模块**组合并分发**,**并不**向您授予该原生模块本身的源代码权利。
|
||||
5.4 除事先取得著作权人的书面授权外,您仅可为 `LICENSE` 允许的非商业用途,以专有组件随本软件提供的形式运行该组件;不得复制、修改、单独再分发或再许可该组件。将其并入第三方安装包或 Docker 镜像、通过自动化脚本部署,或者将其用于任何商业用途,均须事先取得书面授权。
|
||||
|
||||
### 6. 终止
|
||||
若您违反本协议任何条款,本协议项下授予您的权利(**不含**您依 AGPL 单独享有的权利)将自动终止。终止后,您应停止使用并删除发行包中的专有组件。
|
||||
若您违反本协议或适用的 `LICENSE` 条款,相关授权将依各自的终止条款自动终止。终止后,您应停止使用官方发行包并删除其中的专有组件;源代码与资源的后续处理依 `LICENSE` 执行。任何单独书面商业授权的终止及终止后处理,以该授权文件的明确约定为准。
|
||||
|
||||
### 7. 适用法律与争议解决
|
||||
本协议的订立、效力、解释、履行及争议解决,均适用**中华人民共和国大陆地区法律**(不含其冲突法规则)。因本协议引起或与之相关的任何争议,双方应首先友好协商解决;协商不成的,任何一方可向**有管辖权的人民法院**提起诉讼。
|
||||
@@ -58,14 +59,15 @@ SnowLumaDevs 可不时更新本协议。更新后的版本将随发行包发布
|
||||
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.
|
||||
2.1 The **source code and assets** of the Software (excluding the Proprietary Components described in Section 5 and third-party components) are licensed under the accompanying [`LICENSE`](LICENSE), the **SnowLuma Source-Available Non-Commercial License**.
|
||||
2.2 The `LICENSE` grants only the rights expressly stated in it, including viewing, studying, personal or other Non-Commercial use, Non-Commercial self-hosting, and modification or redistribution subject to its conditions. **Any Commercial Use, and any public release of a modified or derivative version, requires the copyright holder's prior written authorization.**
|
||||
2.3 This Agreement provides **supplemental terms for official binary distribution packages**, addressing acceptance, acceptable use, disclaimers, Proprietary Components, termination, and dispute resolution. It does not expand, replace, or imply any right not expressly granted by the `LICENSE`.
|
||||
2.4 Proprietary Components (Section 5) are outside the scope of the source license and may be used only as permitted by Section 5 of the `LICENSE` and this Agreement.
|
||||
2.5 The `LICENSE` controls the scope of rights in the source code and assets; this Agreement controls Proprietary Components in official distribution packages and matters specific to those binaries. A separate written commercial authorization controls only within the licensee, purpose, scope, quantity, and term that it expressly identifies.
|
||||
|
||||
### 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.2 **Purpose.** Unless prior written commercial authorization has been obtained, the Software may be used only for **personal or other Non-Commercial purposes** permitted by the `LICENSE`, including study, research, technical interoperability, and Non-Commercial self-hosting.
|
||||
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.
|
||||
@@ -75,13 +77,13 @@ SnowLumaDevs 可不时更新本协议。更新后的版本将随发行包发布
|
||||
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.1 The Software may include or depend on **Proprietary Components**, including but not limited to SnowLuma native addons such as `snowluma-*.node`, `snowluma-*.dll`, and `snowluma-*.so`, and any licensing, activation, or technical-protection measures they may contain.
|
||||
5.2 Such Proprietary Components are outside the source code and assets licensed by the `LICENSE` and are provided only in precompiled form with the Software for use under this Section. This Agreement grants no right to their source code.
|
||||
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.
|
||||
5.4 Unless the copyright holder has given prior written authorization, you may run a Proprietary Component only as supplied with the Software and only for Non-Commercial use permitted by the `LICENSE`; you may not reproduce, modify, redistribute it separately, or relicense it. Incorporating it into a third-party installer or Docker image, deploying it through an automated script, or using it for any Commercial Use requires prior written authorization.
|
||||
|
||||
### 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.
|
||||
If you breach this Agreement or the applicable `LICENSE`, the relevant rights terminate automatically under their respective termination provisions. Upon termination, you must cease using the official distribution package and delete its Proprietary Components; further handling of the source code and assets is governed by the `LICENSE`. Termination of any separate written commercial authorization, and the parties' post-termination rights and obligations, are governed by that authorization's express terms.
|
||||
|
||||
### 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**.
|
||||
|
||||
@@ -1,60 +1,112 @@
|
||||
<h1 align="center">
|
||||
<img src=".github/logo.svg" width="100%" alt="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="NPM" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&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="./docs/onebot-actions.md">动作参考</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 提供统一入口。
|
||||
|
||||
SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。
|
||||
|
||||
> ⚠️ **免责声明**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目**仅供学习与技术研究**,请遵守《QQ 用户协议》及适用法律;软件按"现状"提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
> [!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**, provided **for study and research only**, "as is" without warranty. Comply with the QQ User Agreement and applicable law; use at your own risk. See [`EULA.md`](EULA.md).
|
||||
> **Disclaimer:** SnowLuma is independent of Tencent / QQ and is provided for study and research only, “as is” and without warranty.
|
||||
|
||||
## 特性
|
||||
## 核心能力
|
||||
|
||||
- **OneBot v11 兼容**:支持文本、音视频、Markdown、JSON 等消息格式。
|
||||
- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。
|
||||
- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。
|
||||
- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。
|
||||
- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。
|
||||
| 场景 | 能力 |
|
||||
| --- | --- |
|
||||
| OneBot 接入 | OneBot v11 动作与事件;WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 |
|
||||
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及常见卡片 |
|
||||
| 多账号运行 | 各账号独立维护会话、身份映射、消息存储和网络配置 |
|
||||
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试和存储管理 |
|
||||
| 开发者工具 | [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
|
||||
|
||||
## 运行链路
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/readme/runtime-map.svg" width="100%" alt="QQ 会话经过协议桥接与 OneBot 标准化后连接到 WebSocket、HTTP、WebUI、SDK 和 MCP" />
|
||||
</p>
|
||||
|
||||
会话接入、协议解析、身份映射、OneBot 转换和网络适配保持独立边界;多个 QQ 账号可并行运行。
|
||||
|
||||
## 快速开始
|
||||
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。
|
||||
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
|
||||
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 22.13+(23 系需 23.4+)。
|
||||
2. Windows 运行 `launcher.bat`;Linux 执行:
|
||||
|
||||
## 许可 / License
|
||||
```bash
|
||||
chmod +x launcher.sh
|
||||
./launcher.sh
|
||||
```
|
||||
|
||||
SnowLuma 采用 **源码可见非商业许可(SnowLuma Source-Available Non-Commercial License)**,见 [`LICENSE`](LICENSE)。**这不是 OSI 开源许可**:源码公开供查看、学习与非商业自托管,但**禁止任何商业使用**(出售、转售、付费托管 / 代搭 / 代运营等),公开发布修改版须事先书面授权。随附的原生附加组件(`snowluma-*.node` 等)为专有组件,不在本许可范围内。二进制发行包另受 [`EULA.md`](EULA.md) 约束;商业授权请联系 motricseven@foxmail.com。参与贡献请阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
|
||||
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
|
||||
|
||||
SnowLuma is under a **source-available, non-commercial** license (see [`LICENSE`](LICENSE)) — **NOT** an OSI open-source license. The source is published for study and non-commercial self-hosting; **commercial use is prohibited** without prior written permission, and the bundled native addon (`snowluma-*.node`) is proprietary and not covered by this license.
|
||||
## 接入与文档
|
||||
|
||||
## 鸣谢
|
||||
| 入口 | 文档 |
|
||||
| --- | --- |
|
||||
| WebSocket / HTTP | [OneBot 动作参考](docs/onebot-actions.md) |
|
||||
| TypeScript SDK | [`packages/sdk/README.md`](packages/sdk/README.md) |
|
||||
| MCP | [`packages/mcp/README.md`](packages/mcp/README.md) |
|
||||
|
||||
参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非数组对象和 `{ type: "json", data: "..." }` 简写;`data` 必填,最终内容必须是 JSON 对象。
|
||||
|
||||
---
|
||||
## 开发
|
||||
|
||||
需要 Node.js 22.13+(23 系需 23.4+)与 pnpm 10.28.0,日常开发基于 `dev` 分支:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
cd SnowLuma
|
||||
git checkout dev
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm typecheck
|
||||
pnpm test
|
||||
```
|
||||
|
||||
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
|
||||
|
||||
## 引用消息预览
|
||||
|
||||
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
|
||||
|
||||
## 媒体读取与归档
|
||||
|
||||
`get_msg` 逐个尝试刷新图片、语音和视频的下载地址:获取到新地址就用于本次响应,刷新失败或缺少资源元数据时保留该段原地址,并继续处理其他资源。原地址为空时仍保持为空,单个资源失败不影响整条消息返回。地址更新时同步响应中的 `raw_message`,不改写保存的消息;保留的旧地址仍可能已经过期。
|
||||
|
||||
`get_record` 单独向 QQ 获取语音的当前下载地址,资源元数据缺失或远端获取失败时动作返回错误,不使用旧地址或发送时的本地文件兜底。历史记录若没有保存资源引用,无法仅凭文件名恢复下载地址。
|
||||
|
||||
SnowLuma 不为这些查询长期保存媒体文件或 Base64 内容,本地保留的是消息及资源元数据;上传、转码仍会使用临时文件。下载地址和 QQ 远端资源都有可用性限制,需要长期归档的消费端应及时下载并自行保存。
|
||||
|
||||
## 使用边界与许可
|
||||
|
||||
> [!IMPORTANT]
|
||||
> SnowLuma 使用**源码可见非商业许可**,不是 OSI 开源许可。源码可用于查看、学习、非商业自托管及私下修改;商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
|
||||
|
||||
完整条款见 [`LICENSE`](LICENSE);二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束;商业授权请联系 `motricseven@foxmail.com`。随附的原生附加组件为专有组件,不在源码许可范围内。
|
||||
|
||||
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.
|
||||
|
||||
## 社区与鸣谢
|
||||
|
||||
- [提交问题](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
- [QQ 群](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- [Telegram](https://t.me/napcatqq)
|
||||
|
||||
项目参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" /></a>
|
||||
<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 |
+88
-81
@@ -1,105 +1,112 @@
|
||||
import js from '@eslint/js';
|
||||
import eslintConfigPrettier from 'eslint-config-prettier/flat';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(
|
||||
/^\/(.:\/)/,
|
||||
'$1',
|
||||
);
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores([
|
||||
export const sourceIgnores = globalIgnores([
|
||||
'**/dist/**',
|
||||
'**/node_modules/**',
|
||||
'**/coverage/**',
|
||||
'**/.turbo/**',
|
||||
'**/.vite/**',
|
||||
'.claude/**',
|
||||
'dev/**',
|
||||
'**/*.tsbuildinfo',
|
||||
'**/test/fixtures/**',
|
||||
'packages/runtime/native/**',
|
||||
]),
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
extends: [js.configs.recommended],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
...globals.es2023,
|
||||
...globals.node,
|
||||
},
|
||||
'packages/mcp/src/generated/**',
|
||||
]);
|
||||
|
||||
export default defineConfig([
|
||||
sourceIgnores,
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
extends: [js.configs.recommended],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
...globals.es2023,
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'no-unused-vars': 'off',
|
||||
'no-useless-assignment': 'off',
|
||||
'prefer-const': 'off',
|
||||
'preserve-caught-error': 'off',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'no-unused-vars': 'off',
|
||||
'no-useless-assignment': 'off',
|
||||
'prefer-const': 'off',
|
||||
'preserve-caught-error': 'off',
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'prefer-const': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
{
|
||||
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
{
|
||||
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
{
|
||||
// OIDB service layer is namespace-per-cmd by design — the
|
||||
// structural-typing contract (namespace IS the OidbCallSpec) and
|
||||
// the file:cmd 1:1 mapping are the whole point. Disable the
|
||||
// module-syntax preference here only.
|
||||
files: [
|
||||
'packages/protocol/src/oidb-services/**/*.ts',
|
||||
'packages/protocol/tests/oidb-services/**/*.ts',
|
||||
],
|
||||
rules: {
|
||||
'@typescript-eslint/no-namespace': 'off',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
// OIDB service layer is namespace-per-cmd by design — the
|
||||
// structural-typing contract (namespace IS the OidbCallSpec) and
|
||||
// the file:cmd 1:1 mapping are the whole point. Disable the
|
||||
// module-syntax preference here only.
|
||||
files: [
|
||||
'packages/protocol/src/oidb-services/**/*.ts',
|
||||
'packages/protocol/tests/oidb-services/**/*.ts',
|
||||
],
|
||||
rules: {
|
||||
'@typescript-eslint/no-namespace': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
|
||||
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
{
|
||||
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
|
||||
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'prefer-const': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
},
|
||||
},
|
||||
},
|
||||
eslintConfigPrettier,
|
||||
]);
|
||||
@@ -0,0 +1,39 @@
|
||||
import stylistic from '@stylistic/eslint-plugin';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import { sourceIgnores } from './eslint.config.ts';
|
||||
|
||||
// Local formatting only; CI continues to use eslint.config.ts for code quality.
|
||||
export default defineConfig([
|
||||
sourceIgnores,
|
||||
{
|
||||
// Preserve quality-rule suppressions when running only formatting rules.
|
||||
linterOptions: { reportUnusedDisableDirectives: 'off' },
|
||||
},
|
||||
{
|
||||
files: ['**/*.{ts,tsx,mts,cts}'],
|
||||
languageOptions: {
|
||||
parser: tseslint.parser,
|
||||
},
|
||||
plugins: {
|
||||
'@stylistic': stylistic,
|
||||
'@typescript-eslint': tseslint.plugin,
|
||||
'react-hooks': reactHooks,
|
||||
},
|
||||
rules: {
|
||||
curly: ['error', 'all'],
|
||||
'@stylistic/padding-line-between-statements': [
|
||||
'error',
|
||||
{ blankLine: 'always', prev: '*', next: 'block-like' },
|
||||
{ blankLine: 'always', prev: 'block-like', next: '*' },
|
||||
// Stacked case labels share a branch and must stay adjacent.
|
||||
{
|
||||
blankLine: 'never',
|
||||
prev: { selector: 'SwitchCase[consequent.length=0]' },
|
||||
next: ['case', 'default'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
+17
-21
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.11.3",
|
||||
"version": "1.14.22",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -10,51 +10,47 @@
|
||||
"build:sdk": "pnpm --filter @snowluma/sdk build",
|
||||
"build:webui": "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",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter @snowluma/ui build && pnpm --filter webui build",
|
||||
"check:release-layout": "node tools/check-release-layout.mjs",
|
||||
"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": "pnpm --filter=\"./packages/**\" -r --no-bail --if-present test",
|
||||
"test:core": "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",
|
||||
"coverage": "pnpm --filter @snowluma/common test -- --coverage",
|
||||
"test:all": "pnpm test",
|
||||
"test:native": "pnpm --filter=\"./packages/**\" -r --if-present test:native",
|
||||
"coverage": "node tools/coverage.mjs",
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"format": "eslint --config eslint.format.config.ts --fix \"**/*.{ts,tsx,mts,cts}\" && prettier --write \"**/*.{ts,tsx,mts,cts}\"",
|
||||
"format:check": "eslint --config eslint.format.config.ts \"**/*.{ts,tsx,mts,cts}\" && prettier --check \"**/*.{ts,tsx,mts,cts}\"",
|
||||
"ci": "node tools/ci-check.mjs",
|
||||
"start": "node dist/index.mjs",
|
||||
"bump": "node tools/bump-version.mjs",
|
||||
"release": "node tools/release.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@stylistic/eslint-plugin": "5.10.0",
|
||||
"@vitest/coverage-istanbul": "4.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.4",
|
||||
"cross-env": "^10.1.0",
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"jiti": "^2.6.1",
|
||||
"prettier": "3.9.10",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "^8.58.2"
|
||||
},
|
||||
"pnpm": {
|
||||
"peerDependencyRules": {
|
||||
"allowedVersions": {
|
||||
"eslint-plugin-react-hooks>eslint": "10"
|
||||
}
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"better-sqlite3"
|
||||
],
|
||||
"overrides": {
|
||||
"esbuild@<0.28.1": "^0.28.1",
|
||||
"@babel/core@<7.29.6": "^7.29.6"
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
"packageManager": "pnpm@11.25.0",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
"node": ">=24",
|
||||
"pnpm": "11.25.0"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.11.3",
|
||||
"version": "1.14.22",
|
||||
"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).",
|
||||
@@ -24,6 +24,10 @@
|
||||
"types": "./src/hook-packet-client.ts",
|
||||
"default": "./src/hook-packet-client.ts"
|
||||
},
|
||||
"./packet-timeout": {
|
||||
"types": "./src/packet-timeout.ts",
|
||||
"default": "./src/packet-timeout.ts"
|
||||
},
|
||||
"./injector": {
|
||||
"types": "./src/injector.ts",
|
||||
"default": "./src/injector.ts"
|
||||
@@ -53,9 +57,12 @@
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
+522
-283
@@ -1,14 +1,15 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
|
||||
import fs from 'fs';
|
||||
import { HookSession, type HookSessionDeps } from './hook-session';
|
||||
import {
|
||||
injectHookProcess,
|
||||
listHookProcesses,
|
||||
resolveHookNativePath,
|
||||
unloadHookProcess,
|
||||
type HookProcessBaseInfo,
|
||||
injectHookProcess,
|
||||
listHookProcesses,
|
||||
resolveHookNativePath,
|
||||
unloadHookProcess,
|
||||
type HookProcessBaseInfo,
|
||||
} from './injector';
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
|
||||
@@ -16,7 +17,12 @@ import { QqHookClient } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import type { HookProcessInfo } from './types';
|
||||
|
||||
const AUTO_LOAD_MAX_ATTEMPTS = 3;
|
||||
|
||||
type AutoLoadAttempt = {
|
||||
attempts: number;
|
||||
inFlight: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sink that the hook layer calls back into when it observes a new login,
|
||||
@@ -26,39 +32,42 @@ import type { HookProcessInfo } from './types';
|
||||
* dependency on @snowluma/core — the hook package is self-contained.
|
||||
*/
|
||||
export interface BridgeManagerSink {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
|
||||
onPacket(pkt: PacketInfo): void;
|
||||
onPidDisconnected(pid: number): void;
|
||||
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 = {
|
||||
bridgeManager: BridgeManagerSink;
|
||||
/** Sink for parsed packets from any live HookSession. Defaults to
|
||||
* `bridgeManager.onPacket` — every packet flows straight into the
|
||||
* per-UIN bridge dispatcher with no intermediate event emitter. */
|
||||
onPacket?: PacketSink;
|
||||
/** Native injector entrypoints. Defaults to the real native addon. */
|
||||
injector?: HookSessionDeps['injector'];
|
||||
/** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */
|
||||
makeClient?: HookSessionDeps['makeClient'];
|
||||
/** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */
|
||||
pipeWatcher?: PipeWatcher;
|
||||
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
|
||||
watcherIntervalMs?: number;
|
||||
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
|
||||
listProcesses?: () => HookProcessBaseInfo[];
|
||||
/** When true, every newly-discovered QQ process is auto-injected (fires
|
||||
* `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;
|
||||
bridgeManager: BridgeManagerSink;
|
||||
/** Sink for parsed packets from any live HookSession. Defaults to
|
||||
* `bridgeManager.onPacket` — every packet flows straight into the
|
||||
* per-UIN bridge dispatcher with no intermediate event emitter. */
|
||||
onPacket?: PacketSink;
|
||||
/** Native injector entrypoints. Defaults to the real native addon. */
|
||||
injector?: HookSessionDeps['injector'];
|
||||
/** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */
|
||||
makeClient?: HookSessionDeps['makeClient'];
|
||||
/** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */
|
||||
pipeWatcher?: PipeWatcher;
|
||||
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
|
||||
watcherIntervalMs?: number;
|
||||
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
|
||||
listProcesses?: () => HookProcessBaseInfo[];
|
||||
/** When true, every newly-discovered QQ process is auto-injected (fires
|
||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||
* Failed loads are logged and leave the session in the 'error' state.
|
||||
* A narrowly-classified early-process mapping race is retried on later
|
||||
* watcher ticks with a fixed attempt limit. */
|
||||
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;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -68,273 +77,494 @@ 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' / transport health) to BridgeManager.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
* - Retry the bounded early-process auto-load race without retrying
|
||||
* permanent injector errors.
|
||||
*
|
||||
* The native injector, native pipe-client, and native process/pipe
|
||||
* listings are all swappable dependencies so tests can run without a
|
||||
* real QQ.exe or a native addon.
|
||||
*/
|
||||
export class HookManager {
|
||||
private readonly bridgeManager: BridgeManagerSink;
|
||||
private readonly onPacket: PacketSink;
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: PipeWatcher;
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
/** 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>;
|
||||
private readonly bridgeManager: BridgeManagerSink;
|
||||
private readonly onPacket: PacketSink;
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: PipeWatcher;
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
/** 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 autoLoadAttempts = new Map<number, AutoLoadAttempt>();
|
||||
private readonly startPromise: Promise<void>;
|
||||
|
||||
private disposed = false;
|
||||
private disposed = false;
|
||||
|
||||
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');
|
||||
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 ?? {
|
||||
inject: injectHookProcess,
|
||||
unload: (pid, handle) => {
|
||||
if (!handle) return;
|
||||
unloadHookProcess(pid, handle);
|
||||
},
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
|
||||
this.injector = deps.injector ?? {
|
||||
inject: injectHookProcess,
|
||||
unload: (pid, handle) => {
|
||||
if (!handle) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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;
|
||||
unloadHookProcess(pid, handle);
|
||||
},
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
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();
|
||||
}
|
||||
};
|
||||
} 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.enumerate,
|
||||
listLivePipes: (processes) =>
|
||||
QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
});
|
||||
this.ownsPipeWatcher = true;
|
||||
}
|
||||
|
||||
this.bindWatcher();
|
||||
this.startPromise = this.pipeWatcher.start();
|
||||
}
|
||||
|
||||
if (deps.pipeWatcher) {
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.ownsPipeWatcher = false;
|
||||
} else {
|
||||
this.pipeWatcher = new PipeWatcher({
|
||||
listProcesses: this.enumerate,
|
||||
listLivePipes: () => QqHookClient.listLivePipes(),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
});
|
||||
this.ownsPipeWatcher = true;
|
||||
// ─────────────── public API (unchanged from prior HookManager) ───────────────
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
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) {
|
||||
const session = this.ensureSession(proc.pid);
|
||||
session.attachProcessInfo(proc);
|
||||
result.push(session.toInfo());
|
||||
}
|
||||
|
||||
return result.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
this.bindWatcher();
|
||||
this.startPromise = this.pipeWatcher.start();
|
||||
}
|
||||
|
||||
// ─────────────── public API (unchanged from prior HookManager) ───────────────
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
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);
|
||||
async loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.ensureSession(pid);
|
||||
const info = await session.load();
|
||||
// Pull the next tick forward so a freshly-injected pipe gets noticed
|
||||
// within the next event-loop turn instead of after the full interval.
|
||||
this.pipeWatcher.wake();
|
||||
return info;
|
||||
}
|
||||
const result: HookProcessInfo[] = [];
|
||||
for (const proc of processes) {
|
||||
const session = this.ensureSession(proc.pid);
|
||||
session.attachProcessInfo(proc);
|
||||
result.push(session.toInfo());
|
||||
|
||||
async unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.ensureSession(pid);
|
||||
return session.unload();
|
||||
}
|
||||
return result.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
async loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
const info = await session.load();
|
||||
// Pull the next tick forward so a freshly-injected pipe gets noticed
|
||||
// within the next event-loop turn instead of after the full interval.
|
||||
this.pipeWatcher.wake();
|
||||
return info;
|
||||
}
|
||||
|
||||
async unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.unload();
|
||||
}
|
||||
|
||||
async refreshProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.refresh();
|
||||
}
|
||||
|
||||
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
this.assertValidPid(pid);
|
||||
return probeQqLoginInfo(pid);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
for (const session of this.sessions.values()) {
|
||||
session.dispose();
|
||||
async refreshProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.refresh();
|
||||
}
|
||||
this.sessions.clear();
|
||||
this.enumerator?.dispose();
|
||||
if (this.ownsPipeWatcher) {
|
||||
this.pipeWatcher.dispose();
|
||||
|
||||
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
this.assertValidPid(pid);
|
||||
return probeQqLoginInfo(pid);
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── wiring ───────────────
|
||||
dispose(): void {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
private bindWatcher(): void {
|
||||
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.ensureSession(info.pid);
|
||||
session.attachProcessInfo(info);
|
||||
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
|
||||
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
|
||||
// failures are already captured inside loadInternal and surfaced via
|
||||
// the session's status field.
|
||||
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
|
||||
void session.load().catch((err) => {
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
|
||||
this.disposed = true;
|
||||
|
||||
for (const session of this.sessions.values()) {
|
||||
session.dispose();
|
||||
}
|
||||
|
||||
this.sessions.clear();
|
||||
this.autoLoadAttempts.clear();
|
||||
this.enumerator?.dispose();
|
||||
|
||||
if (this.ownsPipeWatcher) {
|
||||
this.pipeWatcher.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── wiring ───────────────
|
||||
|
||||
private bindWatcher(): void {
|
||||
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const session = this.ensureSession(info.pid);
|
||||
session.attachProcessInfo(info);
|
||||
this.log.trace(() => [
|
||||
'hook_manager_fact event=process_discovered pid=%d info=%s autoLoad=%s',
|
||||
info.pid,
|
||||
renderParamsVerbose(info),
|
||||
this.autoLoadOnDiscovery,
|
||||
]);
|
||||
|
||||
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
|
||||
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
|
||||
// failures are already captured inside loadInternal and surfaced via
|
||||
// the session's status field.
|
||||
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
|
||||
this.runAutoLoad(session);
|
||||
}
|
||||
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
});
|
||||
}
|
||||
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;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeUp();
|
||||
});
|
||||
this.pipeWatcher.on('pipe-down', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeDown();
|
||||
});
|
||||
// After every tick, retry sessions that are stuck in 'connecting' OR
|
||||
// 'disconnected' while the pipe is up. Mirrors the original
|
||||
// tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent
|
||||
// so calling it for an already-connected session is harmless.
|
||||
//
|
||||
// The 'disconnected' branch matters on Windows: when the QQ-NT side of
|
||||
// the named pipe stays alive but the SnowLuma-side socket dies (read
|
||||
// EPIPE / idle-timeout / similar transient I/O fault), the watcher
|
||||
// sees the pipe as still-live (the OS-level pipe is still listed by
|
||||
// `listLivePipes`) so it never fires another `pipe-up`. Without
|
||||
// retrying 'disconnected' sessions here the session is stranded
|
||||
// forever — a real-world symptom users reported as "Windows running
|
||||
// for a while then stops" with logs `pipe error: read EPIPE` →
|
||||
// `session closed: UIN=…`.
|
||||
this.pipeWatcher.on('tick', () => {
|
||||
if (this.disposed) return;
|
||||
for (const session of this.sessions.values()) {
|
||||
if ((session.status === 'connecting' || session.status === 'disconnected')
|
||||
&& this.pipeWatcher.isPipeLive(session.pid)) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
this.pipeWatcher.on('process-gone', (pid: number) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
private ensureSession(pid: number): HookSession {
|
||||
let session = this.sessions.get(pid);
|
||||
if (session) return session;
|
||||
runWithTraceRequest(() => {
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.sessions.get(pid);
|
||||
this.log.trace(
|
||||
'hook_manager_fact event=process_gone pid=%d tracked=%s',
|
||||
pid,
|
||||
session !== undefined,
|
||||
);
|
||||
|
||||
session = new HookSession(pid, {
|
||||
injector: this.injector,
|
||||
makeClient: this.makeClient,
|
||||
pipeWatcher: this.pipeWatcher,
|
||||
onPacket: this.onPacket,
|
||||
log: this.log,
|
||||
});
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
if (session) {
|
||||
session.notifyProcessGone();
|
||||
}
|
||||
|
||||
session.on('login', (uin: string, sender) => {
|
||||
this.bridgeManager.onHookLogin(pid, uin, sender);
|
||||
});
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
});
|
||||
// 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);
|
||||
});
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
});
|
||||
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.sessions.set(pid, session);
|
||||
return session;
|
||||
}
|
||||
const session = this.sessions.get(pid);
|
||||
|
||||
/** 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));
|
||||
if (session) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
});
|
||||
this.pipeWatcher.on('pipe-down', (pid: number) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const session = this.sessions.get(pid);
|
||||
|
||||
if (session) {
|
||||
session.onPipeDown();
|
||||
}
|
||||
});
|
||||
// After every tick, retry sessions that are stuck in 'connecting' OR
|
||||
// 'disconnected' while the pipe is up. Mirrors the original
|
||||
// tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent
|
||||
// so calling it for an already-connected session is harmless.
|
||||
//
|
||||
// The 'disconnected' branch matters on Windows: when the QQ-NT side of
|
||||
// the named pipe stays alive but the SnowLuma-side socket dies (read
|
||||
// EPIPE / idle-timeout / similar transient I/O fault), the watcher
|
||||
// sees the pipe as still-live (the OS-level pipe is still listed by
|
||||
// `listLivePipes`) so it never fires another `pipe-up`. Without
|
||||
// retrying 'disconnected' sessions here the session is stranded
|
||||
// forever — a real-world symptom users reported as "Windows running
|
||||
// for a while then stops" with logs `pipe error: read EPIPE` →
|
||||
// `session closed: UIN=…`.
|
||||
this.pipeWatcher.on('tick', () => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const session of this.sessions.values()) {
|
||||
const autoLoad = this.autoLoadAttempts.get(session.pid);
|
||||
|
||||
if (
|
||||
autoLoad &&
|
||||
!autoLoad.inFlight &&
|
||||
session.status === 'error' &&
|
||||
isTransientLibcMappingError(session.error)
|
||||
) {
|
||||
this.runAutoLoad(session, autoLoad);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
(session.status === 'connecting' ||
|
||||
session.status === 'disconnected' ||
|
||||
session.status === 'error') &&
|
||||
this.pipeWatcher.isPipeLive(session.pid)
|
||||
) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private assertValidPid(pid: number): void {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
}
|
||||
private runAutoLoad(session: HookSession, existing?: AutoLoadAttempt): void {
|
||||
if (this.disposed || session.isDisposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const state = existing ?? { attempts: 0, inFlight: false };
|
||||
|
||||
if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.attempts += 1;
|
||||
state.inFlight = true;
|
||||
this.autoLoadAttempts.set(session.pid, state);
|
||||
const attempt = state.attempts;
|
||||
|
||||
void runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
this.log.trace(
|
||||
'hook_autoload_start pid=%d attempt=%d maxAttempts=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
AUTO_LOAD_MAX_ATTEMPTS,
|
||||
);
|
||||
|
||||
try {
|
||||
const info = await session.load();
|
||||
|
||||
if (this.autoLoadAttempts.get(session.pid) !== state) {
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=dropped reason=superseded elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
state.inFlight = false;
|
||||
|
||||
if (info.status !== 'error') {
|
||||
this.autoLoadAttempts.delete(session.pid);
|
||||
const reason = attempt > 1 ? 'recovered' : 'loaded';
|
||||
this.log.trace(() => [
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=completed reason=%s state=%s elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
reason,
|
||||
renderParamsVerbose(info),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
|
||||
if (attempt > 1) {
|
||||
this.log.info(
|
||||
'auto-load recovered: PID=%d attempt=%d/%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
AUTO_LOAD_MAX_ATTEMPTS,
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isTransientLibcMappingError(info.error)) {
|
||||
this.autoLoadAttempts.delete(session.pid);
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=permanent_failure error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
info.error,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempt >= AUTO_LOAD_MAX_ATTEMPTS) {
|
||||
this.autoLoadAttempts.delete(session.pid);
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_exhausted error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
info.error,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
this.log.warn(
|
||||
'auto-load retry exhausted: PID=%d attempts=%d err=%s',
|
||||
session.pid,
|
||||
attempt,
|
||||
info.error,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_pending error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
info.error,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
this.log.warn(
|
||||
'auto-load retry pending: PID=%d attempt=%d/%d err=%s',
|
||||
session.pid,
|
||||
attempt,
|
||||
AUTO_LOAD_MAX_ATTEMPTS,
|
||||
info.error,
|
||||
);
|
||||
} catch (err) {
|
||||
if (this.autoLoadAttempts.get(session.pid) === state) {
|
||||
this.autoLoadAttempts.delete(session.pid);
|
||||
}
|
||||
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
errMsg(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ensureSession(pid: number): HookSession {
|
||||
let session = this.sessions.get(pid);
|
||||
|
||||
if (session) {
|
||||
return session;
|
||||
}
|
||||
|
||||
session = new HookSession(pid, {
|
||||
injector: this.injector,
|
||||
makeClient: this.makeClient,
|
||||
pipeWatcher: this.pipeWatcher,
|
||||
onPacket: this.onPacket,
|
||||
log: this.log,
|
||||
});
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
|
||||
session.on('login', (uin: string, sender) => {
|
||||
this.bridgeManager.onHookLogin(pid, uin, sender);
|
||||
});
|
||||
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);
|
||||
});
|
||||
|
||||
this.sessions.set(pid, session);
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
|
||||
function isTransientLibcMappingError(error: string): boolean {
|
||||
return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -351,27 +581,36 @@ function errMsg(value: unknown): string {
|
||||
* for picking the right PID from WebUI.
|
||||
*/
|
||||
export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
if (process.platform !== 'linux') return true;
|
||||
// Escape hatch: operators who explicitly want auto-load on every
|
||||
// enumerated PID can set this to opt out of the filter.
|
||||
if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') return true;
|
||||
if (process.platform !== 'linux') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Escape hatch: operators who explicitly want auto-load on every
|
||||
// enumerated PID can set this to opt out of the filter.
|
||||
if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
let cmdline: string;
|
||||
|
||||
try {
|
||||
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
||||
} catch {
|
||||
// Can't read cmdline (process gone, permission, etc.) — let the
|
||||
// existing load() path handle it; if the process is dead the load
|
||||
// will fail with a clear error.
|
||||
return true;
|
||||
}
|
||||
|
||||
if (cmdline.includes('--type=')) {
|
||||
const type = /--type=([^\0\s]+)/.exec(cmdline)?.[1] ?? 'unknown';
|
||||
log.info('auto-load skip: PID=%d is an Electron child process (--type=%s)', pid, type);
|
||||
return false;
|
||||
}
|
||||
|
||||
let cmdline: string;
|
||||
try {
|
||||
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
||||
} catch {
|
||||
// Can't read cmdline (process gone, permission, etc.) — let the
|
||||
// existing load() path handle it; if the process is dead the load
|
||||
// will fail with a clear error.
|
||||
return true;
|
||||
}
|
||||
if (cmdline.includes('--type=')) {
|
||||
const type = (/--type=([^\0\s]+)/.exec(cmdline)?.[1]) ?? 'unknown';
|
||||
log.info('auto-load skip: PID=%d is an Electron child process (--type=%s)', pid, type);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export type { HookProcessBaseInfo } from './injector';
|
||||
export type { QqPortLoginInfo } from './qq-port-probe';
|
||||
export type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
@@ -1,34 +1,74 @@
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
|
||||
import { packetTimeoutMs } from './packet-timeout';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
QqHookClient,
|
||||
type QqHookSendReply,
|
||||
} from './qq-hook-client';
|
||||
|
||||
export type OutboundHealthListener = (healthy: boolean) => void;
|
||||
|
||||
export class HookPacketClient implements PacketSender {
|
||||
constructor(private readonly client: QqHookClient) { }
|
||||
private outboundHealthy = true;
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
|
||||
constructor(
|
||||
private readonly client: QqHookClient,
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) {}
|
||||
|
||||
async sendPacket(
|
||||
serviceCmd: string,
|
||||
body: Buffer,
|
||||
timeoutMs = packetTimeoutMs(),
|
||||
): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'qq_hook client is not logged in',
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = (await this.client.send(serviceCmd, body, {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
})) as QqHookSendReply;
|
||||
this.setOutboundHealthy(true);
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
gotResponse: true,
|
||||
errorCode: reply.error,
|
||||
errorMessage: reply.message || '',
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof HookPipeRequestError &&
|
||||
error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE
|
||||
) {
|
||||
this.setOutboundHealthy(false);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = await this.client.send(serviceCmd, body, {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
}) as QqHookSendReply;
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
gotResponse: true,
|
||||
errorCode: reply.error,
|
||||
errorMessage: reply.message || '',
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
responseData: null,
|
||||
};
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this.outboundHealthy === healthy) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.outboundHealthy = healthy;
|
||||
this.onOutboundHealthChanged?.(healthy);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
export interface HookRuntimeDirDeps {
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
ownUid?: number;
|
||||
readText?: (file: string) => string;
|
||||
}
|
||||
|
||||
function configuredDirectory(value: string | undefined, variable: string): string | null {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!path.isAbsolute(value)) {
|
||||
throw new Error(`${variable} must be an absolute path`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseProcessEnvironment(raw: string): NodeJS.ProcessEnv {
|
||||
const result: NodeJS.ProcessEnv = {};
|
||||
|
||||
for (const entry of raw.split('\0')) {
|
||||
if (!entry) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separator = entry.indexOf('=');
|
||||
|
||||
if (separator <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result[entry.slice(0, separator)] = entry.slice(separator + 1);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseRealUid(status: string): number | null {
|
||||
const match = /^Uid:\s+(\d+)/m.exec(status);
|
||||
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const uid = Number(match[1]);
|
||||
return Number.isSafeInteger(uid) && uid >= 0 ? uid : null;
|
||||
}
|
||||
|
||||
function isProcessGoneError(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === 'ENOENT' || code === 'ESRCH';
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string {
|
||||
const explicit = configuredDirectory(
|
||||
env.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
'SNOWLUMA_HOOK_RUNTIME_DIR',
|
||||
);
|
||||
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
|
||||
|
||||
if (xdg) {
|
||||
return xdg;
|
||||
}
|
||||
|
||||
if (platform === 'darwin') {
|
||||
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
|
||||
|
||||
if (tmpdir) {
|
||||
return path.join(tmpdir, 'snowluma-hook');
|
||||
}
|
||||
}
|
||||
|
||||
return `/tmp/snowluma-${ownUid}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the socket directory for the target QQ process. The supervisor may
|
||||
* run under a different user, so its own runtime directory is not authoritative.
|
||||
*/
|
||||
export function resolveHookRuntimeDir(targetPid?: number, deps: HookRuntimeDirDeps = {}): string {
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const env = deps.env ?? process.env;
|
||||
const ownUid =
|
||||
deps.ownUid ??
|
||||
(typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid);
|
||||
const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8'));
|
||||
|
||||
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
|
||||
let environError: unknown;
|
||||
|
||||
try {
|
||||
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
|
||||
const explicit = configuredDirectory(
|
||||
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
|
||||
);
|
||||
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
const xdg = configuredDirectory(
|
||||
targetEnv.XDG_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} XDG_RUNTIME_DIR`,
|
||||
);
|
||||
|
||||
if (xdg) {
|
||||
return xdg;
|
||||
}
|
||||
|
||||
environError = new Error('runtime directory is not present');
|
||||
} catch (error) {
|
||||
// An invalid explicit path is configuration corruption and must remain
|
||||
// visible. Permission/race failures are expected when /proc disappears;
|
||||
// the status-file fallback below can still recover the target uid.
|
||||
if (error instanceof Error && error.message.includes('must be an absolute path')) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
environError = error;
|
||||
}
|
||||
|
||||
let statusError: unknown;
|
||||
|
||||
try {
|
||||
const uid = parseRealUid(readText(`/proc/${targetPid}/status`));
|
||||
|
||||
if (uid !== null) {
|
||||
return `/tmp/snowluma-${uid}`;
|
||||
}
|
||||
|
||||
statusError = new Error('real uid is not available');
|
||||
} catch (error) {
|
||||
statusError = error;
|
||||
}
|
||||
|
||||
if (
|
||||
isProcessGoneError(statusError) &&
|
||||
(isProcessGoneError(environError) ||
|
||||
(environError instanceof Error &&
|
||||
environError.message === 'runtime directory is not present'))
|
||||
) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`cannot resolve hook runtime directory for PID ${targetPid}: ` +
|
||||
`environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
|
||||
);
|
||||
}
|
||||
+1083
-469
File diff suppressed because it is too large.
Load diff
@@ -9,10 +9,10 @@ import type { HookProcessStatus } from './types';
|
||||
* `loggedIn` *before* tearing the client down, since teardown clears it.
|
||||
*/
|
||||
export interface HookFlags {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
wasLoggedIn: boolean;
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
wasLoggedIn: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,7 +25,13 @@ export interface HookFlags {
|
||||
* 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';
|
||||
if (!flags.injected) {
|
||||
return 'available';
|
||||
}
|
||||
|
||||
if (flags.connected) {
|
||||
return flags.loggedIn ? 'online' : 'loaded';
|
||||
}
|
||||
|
||||
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
export {
|
||||
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
HookManager,
|
||||
type BridgeManagerSink,
|
||||
type HookManagerDeps,
|
||||
type HookProcessBaseInfo,
|
||||
type HookProcessInfo,
|
||||
type HookProcessStatus,
|
||||
type QqPortLoginInfo,
|
||||
} from './hook-manager';
|
||||
|
||||
export {
|
||||
getRuntimeIntegrity,
|
||||
hasLowProcessIntegrity,
|
||||
type RuntimeIntegrity,
|
||||
} from './runtime-integrity';
|
||||
+110
-85
@@ -7,135 +7,160 @@ import { listSnowlumaPipePidsSync } from './qq-hook-client';
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface ManualMapHandle {
|
||||
base: bigint;
|
||||
entry: bigint;
|
||||
exceptionTable: bigint;
|
||||
size: number;
|
||||
base: bigint;
|
||||
entry: bigint;
|
||||
exceptionTable: bigint;
|
||||
size: number;
|
||||
}
|
||||
|
||||
interface NativeHookAddon {
|
||||
getAllMainProcess(): number[];
|
||||
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle;
|
||||
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
|
||||
getRuntimeIntegrity?(): unknown;
|
||||
getAllMainProcess(): number[];
|
||||
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
|
||||
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
|
||||
}
|
||||
|
||||
export interface HookProcessBaseInfo {
|
||||
pid: number;
|
||||
name: string;
|
||||
path: string;
|
||||
pid: number;
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface HookInjectResult {
|
||||
method: 'loadModuleManual';
|
||||
handle?: ManualMapHandle;
|
||||
method: 'loadModuleManual';
|
||||
handle?: ManualMapHandle;
|
||||
}
|
||||
|
||||
let nativeAddon: NativeHookAddon | null = null;
|
||||
let nativeLoadError: string | null = null;
|
||||
|
||||
function loadNativeAddon(addonPath: string): NativeHookAddon {
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
return mod.exports as unknown as NativeHookAddon;
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
return mod.exports as unknown as NativeHookAddon;
|
||||
}
|
||||
|
||||
type HookBinaryExt = 'node' | 'dll' | 'so';
|
||||
|
||||
function platformBinaryName(ext: HookBinaryExt): string {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
if (process.platform === 'win32' && process.arch === 'x64') {
|
||||
return `snowluma-win32-x64.${ext}`;
|
||||
}
|
||||
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
}
|
||||
|
||||
function platformInjectableExt(): 'dll' | 'so' {
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/bridge/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/bridge/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
|
||||
const fileName = platformBinaryName(ext);
|
||||
for (const dir of nativeSearchDirs()) {
|
||||
const fullPath = path.join(dir, fileName);
|
||||
if (existsSync(fullPath)) return fullPath;
|
||||
}
|
||||
return null;
|
||||
const fileName = platformBinaryName(ext);
|
||||
|
||||
for (const dir of nativeSearchDirs()) {
|
||||
const fullPath = path.join(dir, fileName);
|
||||
|
||||
if (existsSync(fullPath)) {
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getNativeHookAddon(): NativeHookAddon | null {
|
||||
if (nativeAddon) return nativeAddon;
|
||||
const addonPath = resolveHookNativePath('node');
|
||||
if (!addonPath) {
|
||||
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
nativeAddon = loadNativeAddon(addonPath);
|
||||
nativeLoadError = null;
|
||||
return nativeAddon;
|
||||
} catch (error) {
|
||||
nativeLoadError = error instanceof Error ? error.message : String(error);
|
||||
return null;
|
||||
}
|
||||
if (nativeAddon) {
|
||||
return nativeAddon;
|
||||
}
|
||||
|
||||
const addonPath = resolveHookNativePath('node');
|
||||
|
||||
if (!addonPath) {
|
||||
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
nativeAddon = loadNativeAddon(addonPath);
|
||||
nativeLoadError = null;
|
||||
return nativeAddon;
|
||||
} catch (error) {
|
||||
nativeLoadError = error instanceof Error ? error.message : String(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getNativeHookLoadError(): string | null {
|
||||
return nativeLoadError;
|
||||
return nativeLoadError;
|
||||
}
|
||||
|
||||
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())]
|
||||
.filter(pid => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
// 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())]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
export function injectHookProcess(pid: number): HookInjectResult {
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
|
||||
export async function injectHookProcess(pid: number): Promise<HookInjectResult> {
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
|
||||
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
|
||||
}
|
||||
|
||||
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
addon.unloadModuleManual(pid, handle);
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
addon.unloadModuleManual(pid, handle);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
|
||||
/** Default wait for a QQ reply when the caller does not pass one. */
|
||||
export const DEFAULT_PACKET_TIMEOUT_MS = 15_000;
|
||||
|
||||
export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number {
|
||||
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
|
||||
}
|
||||
+212
-170
@@ -6,16 +6,17 @@ const DEFAULT_INTERVAL_MS = 1500;
|
||||
const MIN_INTERVAL_MS = 250;
|
||||
|
||||
export type PipeWatcherDeps = {
|
||||
/** 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. */
|
||||
intervalMs?: number;
|
||||
log?: Logger;
|
||||
/** 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. The current
|
||||
* process snapshot lets Linux inspect each target user's runtime directory. */
|
||||
listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise<Set<number>>;
|
||||
/** Polling interval in ms. Defaults to 1500, floored to 250. */
|
||||
intervalMs?: number;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -39,183 +40,224 @@ export type PipeWatcherDeps = {
|
||||
* dispose logic when QQ.exe is killed with a live pipe.
|
||||
*/
|
||||
export class PipeWatcher extends EventEmitter {
|
||||
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
|
||||
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
|
||||
private readonly intervalMs: number;
|
||||
private readonly log: Logger;
|
||||
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
|
||||
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
|
||||
private readonly intervalMs: number;
|
||||
private readonly log: Logger;
|
||||
|
||||
private livePipes = new Set<number>();
|
||||
private knownPids = new Set<number>();
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private ticking = false;
|
||||
private pendingWake = false;
|
||||
private startPromise: Promise<void> | null = null;
|
||||
private stopped = false;
|
||||
private livePipes = new Set<number>();
|
||||
private knownPids = new Set<number>();
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private ticking = false;
|
||||
private pendingWake = false;
|
||||
private startPromise: Promise<void> | null = null;
|
||||
private stopped = false;
|
||||
|
||||
constructor(deps: PipeWatcherDeps) {
|
||||
super();
|
||||
this.listProcesses = deps.listProcesses;
|
||||
this.listLivePipes = deps.listLivePipes;
|
||||
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
|
||||
this.log = deps.log ?? createLogger('PipeWatcher');
|
||||
}
|
||||
|
||||
/** Was this PID's pipe live as of the last completed tick? */
|
||||
isPipeLive(pid: number): boolean {
|
||||
return this.livePipes.has(pid);
|
||||
}
|
||||
|
||||
/** Was this PID alive as of the last completed tick? */
|
||||
isProcessAlive(pid: number): boolean {
|
||||
return this.knownPids.has(pid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
|
||||
* and begin the polling loop. Idempotent.
|
||||
*/
|
||||
start(): Promise<void> {
|
||||
if (this.startPromise) return this.startPromise;
|
||||
this.startPromise = (async () => {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
})();
|
||||
return this.startPromise;
|
||||
}
|
||||
|
||||
/** Pull the next scheduled tick forward to the next event-loop turn. */
|
||||
wake(): void {
|
||||
if (this.stopped) return;
|
||||
this.scheduleNext(0);
|
||||
}
|
||||
|
||||
/** Force a single tick now. Resolves after diff events have been emitted. */
|
||||
tickNow(): Promise<void> {
|
||||
return this.tickOnce();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
constructor(deps: PipeWatcherDeps) {
|
||||
super();
|
||||
this.listProcesses = deps.listProcesses;
|
||||
this.listLivePipes = deps.listLivePipes;
|
||||
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
|
||||
this.log = deps.log ?? createLogger('PipeWatcher');
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
private scheduleNext(delayMs: number): void {
|
||||
if (this.stopped) return;
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
/** Was this PID's pipe live as of the last completed tick? */
|
||||
isPipeLive(pid: number): boolean {
|
||||
return this.livePipes.has(pid);
|
||||
}
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.tickAndReschedule();
|
||||
}, Math.max(0, delayMs));
|
||||
}
|
||||
|
||||
private async tickAndReschedule(): Promise<void> {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
/** Was this PID alive as of the last completed tick? */
|
||||
isProcessAlive(pid: number): boolean {
|
||||
return this.knownPids.has(pid);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read processes + live pipes, emit diff events. If another tick is
|
||||
* already running, mark a follow-up tick so we don't lose a wake().
|
||||
*/
|
||||
private async tickOnce(): Promise<void> {
|
||||
if (this.ticking) {
|
||||
this.pendingWake = true;
|
||||
return;
|
||||
}
|
||||
this.ticking = true;
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
try {
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
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 {
|
||||
livePipes = await this.listLivePipes();
|
||||
} catch (error) {
|
||||
this.log.warn('listLivePipes failed: %s', errMsg(error));
|
||||
livePipes = new Set();
|
||||
}
|
||||
|
||||
const newKnownPids = new Set<number>();
|
||||
for (const proc of processes) newKnownPids.add(proc.pid);
|
||||
|
||||
// 1. Newly discovered processes.
|
||||
for (const proc of processes) {
|
||||
if (!this.knownPids.has(proc.pid)) {
|
||||
this.emit('process-discovered', proc);
|
||||
/**
|
||||
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
|
||||
* and begin the polling loop. Idempotent.
|
||||
*/
|
||||
start(): Promise<void> {
|
||||
if (this.startPromise) {
|
||||
return this.startPromise;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Pipes that came up. Ignore pipes for processes we don't know
|
||||
// about (would race against an out-of-order tick).
|
||||
const newLivePipes = new Set<number>();
|
||||
for (const pid of livePipes) {
|
||||
if (!newKnownPids.has(pid)) continue;
|
||||
newLivePipes.add(pid);
|
||||
if (!this.livePipes.has(pid)) {
|
||||
this.emit('pipe-up', pid);
|
||||
this.startPromise = (async () => {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
})();
|
||||
return this.startPromise;
|
||||
}
|
||||
|
||||
/** Pull the next scheduled tick forward to the next event-loop turn. */
|
||||
wake(): void {
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.scheduleNext(0);
|
||||
}
|
||||
|
||||
/** Force a single tick now. Resolves after diff events have been emitted. */
|
||||
tickNow(): Promise<void> {
|
||||
return this.tickOnce();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
|
||||
// subscribers can run disconnect logic before dispose logic.
|
||||
for (const pid of this.livePipes) {
|
||||
if (!newLivePipes.has(pid)) {
|
||||
this.emit('pipe-down', pid);
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
private scheduleNext(delayMs: number): void {
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
|
||||
this.timer = setTimeout(
|
||||
() => {
|
||||
this.timer = null;
|
||||
void this.tickAndReschedule();
|
||||
},
|
||||
Math.max(0, delayMs),
|
||||
);
|
||||
}
|
||||
|
||||
private async tickAndReschedule(): Promise<void> {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read processes + live pipes, emit diff events. If another tick is
|
||||
* already running, mark a follow-up tick so we don't lose a wake().
|
||||
*/
|
||||
private async tickOnce(): Promise<void> {
|
||||
if (this.ticking) {
|
||||
this.pendingWake = true;
|
||||
return;
|
||||
}
|
||||
|
||||
this.ticking = true;
|
||||
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
|
||||
try {
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
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> | null;
|
||||
|
||||
try {
|
||||
livePipes = await this.listLivePipes(processes);
|
||||
} catch (error) {
|
||||
this.log.warn('listLivePipes failed: %s', errMsg(error));
|
||||
livePipes = null;
|
||||
}
|
||||
|
||||
const newKnownPids = new Set<number>();
|
||||
|
||||
for (const proc of processes) {
|
||||
newKnownPids.add(proc.pid);
|
||||
}
|
||||
|
||||
// 1. Newly discovered processes.
|
||||
for (const proc of processes) {
|
||||
if (!this.knownPids.has(proc.pid)) {
|
||||
this.emit('process-discovered', proc);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Pipes that came up. Ignore pipes for processes we don't know
|
||||
// about (would race against an out-of-order tick).
|
||||
const newLivePipes = new Set<number>();
|
||||
|
||||
if (livePipes === null) {
|
||||
// Keep the last known pipe state for processes that still exist, while
|
||||
// allowing confirmed process exits to complete their normal teardown.
|
||||
for (const pid of this.livePipes) {
|
||||
if (newKnownPids.has(pid)) {
|
||||
newLivePipes.add(pid);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const pid of livePipes) {
|
||||
if (!newKnownPids.has(pid)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
newLivePipes.add(pid);
|
||||
|
||||
if (!this.livePipes.has(pid)) {
|
||||
this.emit('pipe-up', pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
|
||||
// subscribers can run disconnect logic before dispose logic.
|
||||
for (const pid of this.livePipes) {
|
||||
if (!newLivePipes.has(pid)) {
|
||||
this.emit('pipe-down', pid);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Processes that disappeared.
|
||||
for (const pid of this.knownPids) {
|
||||
if (!newKnownPids.has(pid)) {
|
||||
this.emit('process-gone', pid);
|
||||
}
|
||||
}
|
||||
|
||||
this.knownPids = newKnownPids;
|
||||
this.livePipes = newLivePipes;
|
||||
this.emit('tick');
|
||||
} finally {
|
||||
this.ticking = false;
|
||||
|
||||
// 4. Processes that disappeared.
|
||||
for (const pid of this.knownPids) {
|
||||
if (!newKnownPids.has(pid)) {
|
||||
this.emit('process-gone', pid);
|
||||
if (this.pendingWake) {
|
||||
this.pendingWake = false;
|
||||
// Defer to break sync recursion if a listener calls wake().
|
||||
setImmediate(() => {
|
||||
void this.tickOnce();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.knownPids = newKnownPids;
|
||||
this.livePipes = newLivePipes;
|
||||
this.emit('tick');
|
||||
} finally {
|
||||
this.ticking = false;
|
||||
if (this.pendingWake) {
|
||||
this.pendingWake = false;
|
||||
// Defer to break sync recursion if a listener calls wake().
|
||||
setImmediate(() => { void this.tickOnce(); });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -29,30 +29,30 @@ import type { HookProcessBaseInfo } from './injector';
|
||||
* 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;
|
||||
/** 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;
|
||||
/** 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;
|
||||
@@ -87,152 +87,205 @@ if (addon) {
|
||||
`;
|
||||
|
||||
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: '' }));
|
||||
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;
|
||||
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;
|
||||
// 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 */
|
||||
},
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) return syncFallback();
|
||||
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;
|
||||
|
||||
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;
|
||||
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;
|
||||
}
|
||||
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();
|
||||
}
|
||||
// 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 */
|
||||
});
|
||||
};
|
||||
|
||||
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);
|
||||
const syncFallback = (): HookProcessBaseInfo[] | null => {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate sync fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
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);
|
||||
},
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) {
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
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 */ });
|
||||
},
|
||||
};
|
||||
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);
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
+1226
-689
File diff suppressed because it is too large.
Load diff
@@ -1,130 +1,52 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
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);
|
||||
const log = createLogger('LoginProbe');
|
||||
const probeNotes = new Map<number, string>();
|
||||
|
||||
function noteProbe(pid: number, result: string, ports: number, processes: number | null): void {
|
||||
const processText = processes === null ? '' : ` processes=${processes}`;
|
||||
const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`;
|
||||
|
||||
if (probeNotes.get(pid) === message) {
|
||||
return;
|
||||
}
|
||||
|
||||
probeNotes.set(pid, message);
|
||||
log.info(message);
|
||||
}
|
||||
|
||||
const PORT_RANGE_START = 9210;
|
||||
const PORT_RANGE_END = 9219;
|
||||
const PROBE_TIMEOUT_MS = 1000;
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
const COMMAND_TIMEOUT_MS = 1500;
|
||||
const OVERALL_PROBE_TIMEOUT_MS = 5000;
|
||||
const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as const };
|
||||
// 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".
|
||||
// unrelated `qq` processes), so the passive probe returns no conclusion.
|
||||
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
loggedIn: boolean;
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
/** The local QQ endpoint exposed an account identity. This does not prove
|
||||
* the native protocol session is ready to send or receive packets. */
|
||||
identityKnown: boolean;
|
||||
}
|
||||
|
||||
interface JwtPayload {
|
||||
errCode: number;
|
||||
errMsg: string;
|
||||
port: number;
|
||||
uin?: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
data?: {
|
||||
uin?: string;
|
||||
url?: string;
|
||||
};
|
||||
iat: number;
|
||||
}
|
||||
|
||||
function decodeJwt(token: string): JwtPayload | null {
|
||||
try {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
|
||||
return JSON.parse(payload);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
const link = 'tencent://';
|
||||
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
|
||||
|
||||
let responseData = '';
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
client.removeAllListeners();
|
||||
client.destroy();
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
|
||||
client.setTimeout(CONNECTION_TIMEOUT_MS);
|
||||
|
||||
client.connect(port, '127.0.0.1', () => {
|
||||
client.write(payload);
|
||||
});
|
||||
|
||||
client.on('data', (data) => {
|
||||
responseData += data.toString();
|
||||
});
|
||||
|
||||
client.on('close', () => {
|
||||
cleanup();
|
||||
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
|
||||
if (!jwtMatch) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const decoded = decodeJwt(jwtMatch[0]);
|
||||
if (!decoded || decoded.errCode !== 0) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = decoded.uin || decoded.data?.uin || '';
|
||||
resolve({
|
||||
port,
|
||||
uin,
|
||||
uid: decoded.uid,
|
||||
nickName: decoded.nickName,
|
||||
loggedIn: uin.length > 0,
|
||||
});
|
||||
});
|
||||
|
||||
client.on('error', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
client.on('timeout', () => {
|
||||
cleanup();
|
||||
resolve(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;
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -133,168 +55,239 @@ interface PtloginUin {
|
||||
* 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.
|
||||
* problem, no answer". Neither outcome triggers interactive probing.
|
||||
*/
|
||||
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`;
|
||||
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 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 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);
|
||||
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);
|
||||
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;
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | null> {
|
||||
const useHttps = port % 2 !== 0;
|
||||
|
||||
const res1 = await fetchPtlogin(port, useHttps);
|
||||
const res2 = await fetchPtlogin(port, useHttps);
|
||||
const res1 = await fetchPtlogin(port, useHttps);
|
||||
const res2 = await fetchPtlogin(port, useHttps);
|
||||
|
||||
if (res1 === null && res2 === null) return 'fallback';
|
||||
if (res1 === null && res2 === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
|
||||
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
|
||||
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,
|
||||
};
|
||||
}
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
identityKnown: true,
|
||||
};
|
||||
}
|
||||
|
||||
return 'fallback';
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
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') {
|
||||
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
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;
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
if (match) {
|
||||
ports.add(Number(match[1]));
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync(
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh',
|
||||
EXEC_OPTIONS,
|
||||
);
|
||||
return stdout
|
||||
.toLowerCase()
|
||||
.split('\n')
|
||||
.filter((line) => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[] | null> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
|
||||
if (match) {
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(ports);
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports === null) {
|
||||
noteProbe(pid, 'unavailable', 0, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', 0, totalPids);
|
||||
return { port: 0, uin: '', identityKnown: false };
|
||||
}
|
||||
|
||||
noteProbe(pid, 'inconclusive', 0, totalPids);
|
||||
return null;
|
||||
}
|
||||
|
||||
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
|
||||
|
||||
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 !== null) {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', ports.length, totalPids);
|
||||
return {
|
||||
port: ports[0],
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
};
|
||||
}
|
||||
|
||||
noteProbe(pid, 'inconclusive', ports.length, totalPids);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Background discovery must remain passive. Interactive application
|
||||
// endpoints are deliberately excluded from automatic probing.
|
||||
noteProbe(pid, 'no-match', ptPortsToTry.length, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let timedOut = false;
|
||||
const timeout = new Promise<null>((resolve) => {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
resolve(null);
|
||||
}, OVERALL_PROBE_TIMEOUT_MS);
|
||||
});
|
||||
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', loggedIn: false };
|
||||
try {
|
||||
const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]);
|
||||
|
||||
if (timedOut) {
|
||||
log.warn('login check timed out: PID=%d', pid);
|
||||
}
|
||||
|
||||
return result;
|
||||
} finally {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { getNativeHookAddon, getNativeHookLoadError } from './injector';
|
||||
|
||||
export interface IntegrityReadError {
|
||||
status: 'error';
|
||||
operation: string;
|
||||
code: number;
|
||||
}
|
||||
|
||||
export interface NativeRuntimeIntegrity {
|
||||
pid: number;
|
||||
executablePath: string | null;
|
||||
process: { status: 'ok'; rid: number } | IntegrityReadError;
|
||||
file:
|
||||
| {
|
||||
status: 'ok';
|
||||
label: { rid: number; inherited: boolean; policy: number } | null;
|
||||
}
|
||||
| IntegrityReadError;
|
||||
}
|
||||
|
||||
export type RuntimeIntegrity =
|
||||
| { status: 'unsupported' }
|
||||
| { status: 'unavailable'; error: string }
|
||||
| ({ status: 'available' } & NativeRuntimeIntegrity);
|
||||
|
||||
/** File labels can change after startup; only the actual token decides the warning. */
|
||||
export function hasLowProcessIntegrity(integrity: RuntimeIntegrity): boolean {
|
||||
return (
|
||||
integrity.status === 'available' &&
|
||||
integrity.process.status === 'ok' &&
|
||||
integrity.process.rid < 8192
|
||||
);
|
||||
}
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
function uint32(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff
|
||||
);
|
||||
}
|
||||
|
||||
function readError(value: Record<string, unknown>): boolean {
|
||||
return value.status === 'error' && typeof value.operation === 'string' && uint32(value.code);
|
||||
}
|
||||
|
||||
function isNativeRuntimeIntegrity(value: unknown): value is NativeRuntimeIntegrity {
|
||||
if (
|
||||
!record(value) ||
|
||||
value.pid !== process.pid ||
|
||||
!(typeof value.executablePath === 'string' || value.executablePath === null) ||
|
||||
!record(value.process) ||
|
||||
!record(value.file)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(
|
||||
readError(value.process) ||
|
||||
(value.process.status === 'ok' && uint32(value.process.rid))
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const file = value.file;
|
||||
return (
|
||||
readError(file) ||
|
||||
(file.status === 'ok' &&
|
||||
(file.label === null ||
|
||||
(record(file.label) &&
|
||||
uint32(file.label.rid) &&
|
||||
typeof file.label.inherited === 'boolean' &&
|
||||
uint32(file.label.policy))))
|
||||
);
|
||||
}
|
||||
|
||||
let cached: RuntimeIntegrity | undefined;
|
||||
|
||||
/** One startup snapshot, shared by the startup log and the WebUI warning. */
|
||||
export function getRuntimeIntegrity(): RuntimeIntegrity {
|
||||
if (process.platform !== 'win32') {
|
||||
return { status: 'unsupported' };
|
||||
}
|
||||
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
try {
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? '原生组件不可用');
|
||||
}
|
||||
|
||||
if (typeof addon.getRuntimeIntegrity !== 'function') {
|
||||
throw new Error('当前原生组件不支持完整性诊断,请更新原生组件');
|
||||
}
|
||||
|
||||
const result = addon.getRuntimeIntegrity();
|
||||
|
||||
if (!isNativeRuntimeIntegrity(result)) {
|
||||
throw new Error('原生完整性诊断返回了无效数据');
|
||||
}
|
||||
|
||||
cached = {
|
||||
status: 'available',
|
||||
pid: result.pid,
|
||||
executablePath: result.executablePath,
|
||||
process: result.process,
|
||||
file: result.file,
|
||||
};
|
||||
} catch (error) {
|
||||
cached = {
|
||||
status: 'unavailable',
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
|
||||
return cached;
|
||||
}
|
||||
@@ -1,21 +1,15 @@
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
export type HookProcessStatus =
|
||||
| 'available'
|
||||
| 'loading'
|
||||
| 'connecting'
|
||||
| 'loaded'
|
||||
| 'online'
|
||||
| 'error'
|
||||
| 'disconnected';
|
||||
'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
|
||||
|
||||
/** Public-facing snapshot of a per-PID HookSession. */
|
||||
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
}
|
||||
@@ -13,161 +13,228 @@ import type { QqHookClient } from '../src/qq-hook-client';
|
||||
// browser without REST polling.
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
interface Harness {
|
||||
manager: HookManager;
|
||||
pipeWatcher: PipeWatcher;
|
||||
setProcesses: (next: number[]) => void;
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
clientFactory: ReturnType<typeof vi.fn>;
|
||||
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(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
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,
|
||||
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];
|
||||
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(),
|
||||
intervalMs: 60_000,
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const manager = new HookManager({
|
||||
bridgeManager: {
|
||||
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(),
|
||||
} 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
|
||||
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();
|
||||
}
|
||||
});
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -5,178 +5,467 @@ import os from 'os';
|
||||
import path from 'path';
|
||||
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { HookInjectResult, ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
createLogger,
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function makeManager(opts: {
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
}) {
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = 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 () => { throw new Error('test: never really connect'); };
|
||||
(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(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => { pids = next; },
|
||||
};
|
||||
function managerTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Hook');
|
||||
}
|
||||
|
||||
function makeManager(opts: {
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
onSessionsChanged?: () => void;
|
||||
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
|
||||
}) {
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(
|
||||
opts.inject ??
|
||||
(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
);
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = 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 () => {
|
||||
throw new Error('test: never really connect');
|
||||
};
|
||||
|
||||
(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(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
onSessionsChanged: opts.onSessionsChanged,
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => {
|
||||
pids = next;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
describe('HookManager runtime TRACE', () => {
|
||||
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
const sessionsChanged = vi.fn();
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: false,
|
||||
processes: [],
|
||||
onSessionsChanged: sessionsChanged,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
const baseline = managerTrace(entries).length;
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect(managerTrace(entries)).toHaveLength(baseline);
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
|
||||
const facts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_manager_fact '),
|
||||
);
|
||||
expect(facts.map((entry) => entry.message)).toEqual([
|
||||
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
|
||||
'hook_manager_fact event=process_gone pid=4242 tracked=true',
|
||||
]);
|
||||
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('records bounded transient retries and recovery as separate attempts', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
})
|
||||
.mockImplementationOnce(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
}));
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/,
|
||||
),
|
||||
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
expect(attempts[2]!.req).toBe(attempts[3]!.req);
|
||||
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
let resolveInjection!: (result: HookInjectResult) => void;
|
||||
const injection = new Promise<HookInjectResult>((resolve) => {
|
||||
resolveInjection = resolve;
|
||||
});
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: true,
|
||||
processes: [4242],
|
||||
inject: () => injection,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const manualLoad = ctx.manager.loadProcess(4242);
|
||||
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
|
||||
await manualLoad;
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'permanent failure',
|
||||
error: 'ptrace denied',
|
||||
ticks: 1,
|
||||
attempts: 1,
|
||||
reason: 'permanent_failure',
|
||||
},
|
||||
{
|
||||
name: 'retry exhaustion',
|
||||
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
|
||||
ticks: 4,
|
||||
attempts: 3,
|
||||
reason: 'retry_exhausted',
|
||||
},
|
||||
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(error);
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const starts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_start '),
|
||||
);
|
||||
const terminals = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_terminal '),
|
||||
);
|
||||
expect(starts).toHaveLength(attempts);
|
||||
expect(terminals).toHaveLength(attempts);
|
||||
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error('ptrace denied');
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('retries a transient libc mapping failure on the next watcher tick', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('does not retry permanent auto-load errors', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error('ptrace denied');
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('stops retrying a transient libc mapping failure after three attempts', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
for (let tick = 0; tick < 4; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(3);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
|
||||
// it at a temporary directory that mimics the procfs layout. This lets
|
||||
// the tests run on macOS / CI without a live Linux QQ process.
|
||||
describe('shouldAutoLoadPid', () => {
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
if (match) {
|
||||
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((
|
||||
p: string,
|
||||
...rest: unknown[]
|
||||
) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
if (match) {
|
||||
return originalReadFileSync(
|
||||
path.join(tmpProc, match[1], 'cmdline'),
|
||||
...(rest as [BufferEncoding]),
|
||||
);
|
||||
}
|
||||
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
if (originalAutoLoadAll === undefined) {
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
}
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, [
|
||||
'/opt/QQ/qq',
|
||||
'--type=utility',
|
||||
'--utility-sub-type=network.mojom.NetworkService',
|
||||
]);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { HookPacketClient } from '../src/hook-packet-client';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
} from '../src/qq-hook-client';
|
||||
|
||||
function fakeClient(send: QqHookClient['send']): QqHookClient {
|
||||
return {
|
||||
isLoggedIn: true,
|
||||
send,
|
||||
} as unknown as QqHookClient;
|
||||
}
|
||||
|
||||
describe('HookPacketClient outbound health', () => {
|
||||
it('reports native connection loss once and recovers after a successful request', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValueOnce(
|
||||
new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
),
|
||||
)
|
||||
.mockRejectedValueOnce(
|
||||
new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
2,
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
requestId: 3,
|
||||
error: 0,
|
||||
message: '',
|
||||
body: Buffer.from('ok'),
|
||||
});
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
});
|
||||
await sender.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
});
|
||||
|
||||
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
|
||||
it('does not classify ordinary request rejection as connection loss', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValue(new HookPipeRequestError('This request is not valid.', -38, 1));
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
});
|
||||
|
||||
expect(healthChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -13,87 +13,101 @@ import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
async connectAll(_opts: { recv: boolean }) {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
|
||||
close() {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
async connectAll(_opts: { recv: boolean }) {
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
}
|
||||
close() {
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
|
||||
const PID = 61;
|
||||
const liveSet = new Set<number>([PID]);
|
||||
const clients: FakeClient[] = [];
|
||||
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
|
||||
const PID = 61;
|
||||
const liveSet = new Set<number>([PID]);
|
||||
const clients: FakeClient[] = [];
|
||||
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listLivePipes: async () => new Set(liveSet),
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listLivePipes: async () => new Set(liveSet),
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
});
|
||||
|
||||
// Initial discovery + first connect.
|
||||
await pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Drive 50 pipe up/down cycles with the QQ process staying alive but
|
||||
// the pipe (= QQ control socket) bouncing every "tick".
|
||||
const CYCLES = 50;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
liveSet.delete(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
liveSet.add(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter((c) => !c.isClosed);
|
||||
expect(
|
||||
alive.length,
|
||||
`live clients after ${CYCLES} cycles: ${alive.length}`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
|
||||
// Total clients minted = roughly one per up cycle. Sanity bound:
|
||||
// we must have actually exercised the reconnect path.
|
||||
expect(clients.length).toBeGreaterThan(1);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
});
|
||||
|
||||
// Initial discovery + first connect.
|
||||
await pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Drive 50 pipe up/down cycles with the QQ process staying alive but
|
||||
// the pipe (= QQ control socket) bouncing every "tick".
|
||||
const CYCLES = 50;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
liveSet.delete(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
liveSet.add(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1);
|
||||
|
||||
// Total clients minted = roughly one per up cycle. Sanity bound:
|
||||
// we must have actually exercised the reconnect path.
|
||||
expect(clients.length).toBeGreaterThan(1);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -24,100 +24,119 @@ import type { QqHookClient } from '../src/qq-hook-client';
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { ...this.loginState }; }
|
||||
close(): void {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { ...this.loginState };
|
||||
}
|
||||
close(): void {
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
function totalListenerCount(emitter: EventEmitter): number {
|
||||
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
|
||||
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const CYCLES = 50;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const alive = clients.filter((c) => !c.isClosed);
|
||||
expect.soft(clients.length).toBeGreaterThan(1);
|
||||
expect(
|
||||
alive.length,
|
||||
`expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
it('drops all listeners from each torn-down client', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
|
||||
const CYCLES = 50;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect.soft(clients.length).toBeGreaterThan(1);
|
||||
expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`)
|
||||
.toBeLessThanOrEqual(1);
|
||||
});
|
||||
const CYCLES = 20;
|
||||
|
||||
it('drops all listeners from each torn-down client', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// Every client except the current one should have 0 listeners attached.
|
||||
// (HookSession.tearDownClient does client.removeAllListeners().)
|
||||
for (let i = 0; i < clients.length - 1; i++) {
|
||||
const lc = totalListenerCount(clients[i]);
|
||||
expect(
|
||||
lc,
|
||||
`client #${i} of ${clients.length} still has ${lc} listeners after teardown`,
|
||||
).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const CYCLES = 20;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// Every client except the current one should have 0 listeners attached.
|
||||
// (HookSession.tearDownClient does client.removeAllListeners().)
|
||||
for (let i = 0; i < clients.length - 1; i++) {
|
||||
const lc = totalListenerCount(clients[i]);
|
||||
expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`)
|
||||
.toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolveHookRuntimeDir } from '../src/hook-runtime-dir';
|
||||
|
||||
function procReader(files: Record<string, string>) {
|
||||
return (file: string): string => {
|
||||
const value = files[file];
|
||||
|
||||
if (value === undefined) {
|
||||
throw new Error(`missing fixture: ${file}`);
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
describe('resolveHookRuntimeDir — Linux target process ownership', () => {
|
||||
it('uses the QQ process runtime directory instead of the supervisor user directory', () => {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
}),
|
||||
).toBe('/run/user/1000');
|
||||
});
|
||||
|
||||
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
}),
|
||||
).toBe('/tmp/snowluma-1000');
|
||||
});
|
||||
|
||||
it('fails visibly when target ownership cannot be determined', () => {
|
||||
expect(() =>
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => {
|
||||
throw new Error('permission denied');
|
||||
},
|
||||
}),
|
||||
).toThrow(/cannot resolve hook runtime directory.*permission denied/);
|
||||
});
|
||||
|
||||
it('uses the current convention when the target disappears during discovery', () => {
|
||||
const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' });
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => {
|
||||
throw gone;
|
||||
},
|
||||
}),
|
||||
).toBe('/run/user/0');
|
||||
});
|
||||
|
||||
it('honours an explicit runtime directory inherited by the QQ process', () => {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: {},
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
|
||||
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
}),
|
||||
).toBe('/srv/snowluma-hook');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,54 +3,66 @@ 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,
|
||||
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('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, 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, 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, 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('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('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 }));
|
||||
}
|
||||
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);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,415 @@
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { existsSyncMock, listPidsMock } = vi.hoisted(() => ({
|
||||
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
|
||||
listPidsMock: vi.fn(() => new Set<number>()),
|
||||
}));
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('fs')>();
|
||||
return {
|
||||
...actual,
|
||||
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
|
||||
existsSyncMock(String(target)),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../src/qq-hook-client', () => ({
|
||||
listSnowlumaPipePidsSync: listPidsMock,
|
||||
}));
|
||||
|
||||
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url)));
|
||||
const ORIGINAL_PLATFORM = process.platform;
|
||||
const ORIGINAL_ARCH = process.arch;
|
||||
|
||||
const HANDLE = {
|
||||
base: 0x7fff0000n,
|
||||
entry: 0x7fff1234n,
|
||||
exceptionTable: 0x7fff5678n,
|
||||
size: 8192,
|
||||
};
|
||||
|
||||
function setPlatform(platform: NodeJS.Platform, arch: string): void {
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
|
||||
}
|
||||
|
||||
function restorePlatform(): void {
|
||||
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
|
||||
}
|
||||
|
||||
function nativeSearchDirs(cwd = process.cwd()): string[] {
|
||||
return [
|
||||
path.resolve(INJECTOR_DIR, 'native'),
|
||||
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(cwd, 'dist', 'native'),
|
||||
path.resolve(cwd, 'packages', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string {
|
||||
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
|
||||
}
|
||||
|
||||
function allowExisting(paths: readonly string[]): void {
|
||||
const allowed = new Set(paths);
|
||||
existsSyncMock.mockImplementation((target) => allowed.has(target));
|
||||
}
|
||||
|
||||
function fakeAddon(
|
||||
overrides: {
|
||||
getAllMainProcess?: number[];
|
||||
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
|
||||
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
|
||||
} = {},
|
||||
) {
|
||||
return {
|
||||
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
|
||||
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
|
||||
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
|
||||
};
|
||||
}
|
||||
|
||||
function installDlopen(addon: object) {
|
||||
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
|
||||
(mod as { exports: object }).exports = addon;
|
||||
});
|
||||
}
|
||||
|
||||
async function loadInjector() {
|
||||
return import('../src/injector');
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
existsSyncMock.mockReset();
|
||||
existsSyncMock.mockReturnValue(false);
|
||||
listPidsMock.mockReset();
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
restorePlatform();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('resolveHookNativePath', () => {
|
||||
it('returns null after probing every search directory', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return false;
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBeNull();
|
||||
expect(probed).toEqual([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.node', 1),
|
||||
nativeCandidate('snowluma-linux-x64.node', 2),
|
||||
nativeCandidate('snowluma-linux-x64.node', 3),
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns the first existing candidate and stops scanning', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const later = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return target === winner || target === later;
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
expect(probed).toEqual([winner]);
|
||||
});
|
||||
|
||||
it('skips missing earlier directories for the injectable .so', async () => {
|
||||
setPlatform('linux', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('so')).toBe(winner);
|
||||
});
|
||||
|
||||
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('dll')).toBe(winner);
|
||||
});
|
||||
|
||||
it('uses the generic platform-arch name on win32 arm64', async () => {
|
||||
setPlatform('win32', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
|
||||
it('re-reads process.cwd() for the dist/native fallback', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
|
||||
const winner = path.join(
|
||||
'/tmp/sl-injector-cwd',
|
||||
'dist',
|
||||
'native',
|
||||
'snowluma-darwin-arm64.node',
|
||||
);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getNativeHookAddon / getNativeHookLoadError', () => {
|
||||
it('starts with a null load error before any probe', async () => {
|
||||
const { getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null and records a missing-binary error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const dlopen = vi.spyOn(process, 'dlopen');
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('dlopens the resolved .node once and caches the addon', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
const addon = fakeAddon();
|
||||
const dlopen = installDlopen(addon);
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
const first = getNativeHookAddon();
|
||||
const second = getNativeHookAddon();
|
||||
|
||||
expect(first).toBe(addon);
|
||||
expect(second).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
expect(dlopen).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
|
||||
});
|
||||
|
||||
it('stores Error.message when process.dlopen throws', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw new Error('not a valid Node addon');
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
|
||||
});
|
||||
|
||||
it('stringifies a non-Error dlopen failure', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw 42;
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('42');
|
||||
});
|
||||
|
||||
it('retries after a failed load when a binary later appears', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
|
||||
allowExisting([nodePath]);
|
||||
expect(getNativeHookAddon()).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listHookProcesses', () => {
|
||||
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 7, name: 'qq', path: '' },
|
||||
{ pid: 15, name: 'qq', path: '' },
|
||||
{ pid: 42, name: 'qq', path: '' },
|
||||
]);
|
||||
expect(listPidsMock).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('on darwin returns an empty list when no control sockets exist', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
|
||||
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
|
||||
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
}),
|
||||
);
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 2, name: 'qq', path: '' },
|
||||
{ pid: 8, name: 'qq', path: '' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('on win32 names processes QQ.exe', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
|
||||
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('injectHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when the addon exists but the injectable is missing', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
installDlopen(fakeAddon());
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
|
||||
});
|
||||
|
||||
it('awaits a thenable loadModuleManual handle', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({
|
||||
loadModuleManual: () => Promise.resolve(HANDLE),
|
||||
});
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
|
||||
});
|
||||
|
||||
it('accepts a synchronous loadModuleManual return value', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
|
||||
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(77)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
|
||||
});
|
||||
|
||||
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
|
||||
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
|
||||
allowExisting([nodePath, dllPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(5150)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
|
||||
});
|
||||
|
||||
it('propagates a rejected loadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.so', 0),
|
||||
]);
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
loadModuleManual: () => Promise.reject(new Error('map failed')),
|
||||
}),
|
||||
);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('unloadHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(() => unloadHookProcess(4242, HANDLE)).toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
|
||||
it('forwards pid and handle to unloadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { QqHookClient } from '../src/qq-hook-client';
|
||||
import { packetTimeoutMs } from '../src/packet-timeout';
|
||||
|
||||
const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
|
||||
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env[PACKET];
|
||||
delete process.env[ACK];
|
||||
});
|
||||
|
||||
describe('packet and hook ack timeouts', () => {
|
||||
it('keeps the 15 second packet default', () => {
|
||||
expect(packetTimeoutMs({})).toBe(15_000);
|
||||
});
|
||||
|
||||
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
|
||||
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
|
||||
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
|
||||
});
|
||||
|
||||
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
|
||||
process.env[ACK] = '1200';
|
||||
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
|
||||
expect(client.defaultAckTimeoutMs).toBe(1200);
|
||||
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
|
||||
expect(explicit.defaultAckTimeoutMs).toBe(50);
|
||||
});
|
||||
});
|
||||
@@ -3,229 +3,312 @@ import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { HookProcessBaseInfo } from '../src/injector';
|
||||
|
||||
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
|
||||
let processes = initial.processes;
|
||||
let live = initial.live;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
// Defensively copy so the watcher can't mutate the test's reference.
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
|
||||
});
|
||||
return {
|
||||
watcher,
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
|
||||
setLive: (s: Set<number>) => { live = s; },
|
||||
};
|
||||
let processes = initial.processes;
|
||||
let live = initial.live;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
// Defensively copy so the watcher can't mutate the test's reference.
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
|
||||
});
|
||||
return {
|
||||
watcher,
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => {
|
||||
processes = p;
|
||||
},
|
||||
setLive: (s: Set<number>) => {
|
||||
live = s;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type EventRow = [string, unknown];
|
||||
|
||||
function captureEvents(watcher: PipeWatcher): EventRow[] {
|
||||
const events: EventRow[] = [];
|
||||
watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid]));
|
||||
watcher.on('process-gone', pid => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', pid => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', pid => events.push(['down', pid]));
|
||||
return events;
|
||||
const events: EventRow[] = [];
|
||||
watcher.on('process-discovered', (info) =>
|
||||
events.push(['discovered', (info as HookProcessBaseInfo).pid]),
|
||||
);
|
||||
watcher.on('process-gone', (pid) => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', (pid) => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', (pid) => events.push(['down', pid]));
|
||||
return events;
|
||||
}
|
||||
|
||||
describe('PipeWatcher', () => {
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
it('passes the current process snapshot to pipe discovery', async () => {
|
||||
const processes = [
|
||||
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
|
||||
{ pid: 5678, name: 'qq', path: '/opt/QQ/qq' },
|
||||
];
|
||||
let observed: readonly HookProcessBaseInfo[] | undefined;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async (current) => {
|
||||
observed = current;
|
||||
return new Set();
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
|
||||
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
|
||||
await watcher.start();
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('pipe-down emitted when a previously-live pipe disappears', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234]]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setProcesses([]);
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('ignores live pipes whose process is not running', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [],
|
||||
live: new Set([9999]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234]]);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('does not double-emit on idempotent ticks (no state change)', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits "tick" after every poll', async () => {
|
||||
const ctx = setupWatcher({ processes: [], live: new Set() });
|
||||
let ticks = 0;
|
||||
ctx.watcher.on('tick', () => { ticks++; });
|
||||
|
||||
await ctx.watcher.start();
|
||||
expect(ticks).toBe(1);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
expect(ticks).toBe(2);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('wake() pulls the next tick forward', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// Wait on 'tick' rather than guessing how many event-loop turns
|
||||
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
|
||||
const nextTick = new Promise<void>(resolve => ctx.watcher.once('tick', () => resolve()));
|
||||
ctx.setLive(new Set([1234]));
|
||||
ctx.watcher.wake();
|
||||
await nextTick;
|
||||
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('survives a throwing listProcesses without crashing the watcher', async () => {
|
||||
let processes: HookProcessBaseInfo[] = [];
|
||||
let live = new Set<number>();
|
||||
let shouldThrow = true;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => {
|
||||
if (shouldThrow) throw new Error('boom');
|
||||
return processes;
|
||||
},
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
expect(observed).toEqual(processes);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
shouldThrow = false;
|
||||
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
live = new Set([1234]);
|
||||
const events = captureEvents(watcher);
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
|
||||
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
|
||||
|
||||
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,
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
it('pipe-down emitted when a previously-live pipe disappears', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
const events = captureEvents(watcher);
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
// 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);
|
||||
expect(events).toEqual([['down', 1234]]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
// Enumeration recovers with the same set → still no churn.
|
||||
result = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// 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();
|
||||
});
|
||||
ctx.setProcesses([]);
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('ignores live pipes whose process is not running', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [],
|
||||
live: new Set([9999]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['up', 1234],
|
||||
['down', 1234],
|
||||
]);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['up', 1234],
|
||||
['down', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('does not double-emit on idempotent ticks (no state change)', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits "tick" after every poll', async () => {
|
||||
const ctx = setupWatcher({ processes: [], live: new Set() });
|
||||
let ticks = 0;
|
||||
ctx.watcher.on('tick', () => {
|
||||
ticks++;
|
||||
});
|
||||
|
||||
await ctx.watcher.start();
|
||||
expect(ticks).toBe(1);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
expect(ticks).toBe(2);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('wake() pulls the next tick forward', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// Wait on 'tick' rather than guessing how many event-loop turns
|
||||
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
|
||||
const nextTick = new Promise<void>((resolve) => ctx.watcher.once('tick', () => resolve()));
|
||||
ctx.setLive(new Set([1234]));
|
||||
ctx.watcher.wake();
|
||||
await nextTick;
|
||||
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('survives a throwing listProcesses without crashing the watcher', async () => {
|
||||
let processes: HookProcessBaseInfo[] = [];
|
||||
let live = new Set<number>();
|
||||
let shouldThrow = true;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => {
|
||||
if (shouldThrow) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
|
||||
return processes;
|
||||
},
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
|
||||
shouldThrow = false;
|
||||
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
live = new Set([1234]);
|
||||
const events = captureEvents(watcher);
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('preserves live sessions when pipe discovery temporarily fails', async () => {
|
||||
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
let failPipeDiscovery = false;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async () => {
|
||||
if (failPipeDiscovery) {
|
||||
throw new Error('permission denied');
|
||||
}
|
||||
|
||||
return new Set([1234]);
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
const events = captureEvents(watcher);
|
||||
|
||||
failPipeDiscovery = true;
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
processes = [];
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
expect(watcher.isPipeLive(1234)).toBe(false);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -5,51 +5,53 @@ 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();
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,724 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
|
||||
|
||||
const execMock = vi.hoisted(() => vi.fn());
|
||||
const httpGetMock = vi.hoisted(() => vi.fn());
|
||||
const httpsGetMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('child_process', () => ({ exec: execMock }));
|
||||
vi.mock('http', () => ({
|
||||
default: { get: httpGetMock },
|
||||
get: httpGetMock,
|
||||
}));
|
||||
vi.mock('https', () => ({
|
||||
default: { get: httpsGetMock },
|
||||
get: httpsGetMock,
|
||||
}));
|
||||
|
||||
import { probeQqLoginInfo } from '../src/qq-port-probe';
|
||||
|
||||
const originalPlatform = process.platform;
|
||||
const EXEC_OPTIONS = { timeout: 1500, killSignal: 'SIGKILL' };
|
||||
const PTLOGIN_HEADERS = {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
};
|
||||
|
||||
type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void;
|
||||
type RequestLike = EventEmitter & { destroy: ReturnType<typeof vi.fn> };
|
||||
|
||||
function setPlatform(platform: string): void {
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
}
|
||||
|
||||
function mockExec(replies: Record<string, string | Error>): void {
|
||||
execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => {
|
||||
const reply = replies[command];
|
||||
|
||||
if (reply === undefined) {
|
||||
callback(new Error(`unexpected command ${command}`));
|
||||
return;
|
||||
}
|
||||
|
||||
if (reply instanceof Error) {
|
||||
callback(reply);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(null, { stdout: reply, stderr: '' });
|
||||
});
|
||||
}
|
||||
|
||||
function execCommands(): string[] {
|
||||
return execMock.mock.calls.map((call) => String(call[0]));
|
||||
}
|
||||
|
||||
function ssLine(port: number, pid: number, owner: 'comma' | 'paren' = 'comma'): string {
|
||||
const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`;
|
||||
return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`;
|
||||
}
|
||||
|
||||
function netstatLine(localAddr: string, pid: number): string {
|
||||
return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`;
|
||||
}
|
||||
|
||||
function jsonp(accounts: unknown[]): string {
|
||||
return `ptui_getuins_CB(${JSON.stringify(accounts)});`;
|
||||
}
|
||||
|
||||
function requestStub(): RequestLike {
|
||||
const req = new EventEmitter() as RequestLike;
|
||||
req.destroy = vi.fn();
|
||||
return req;
|
||||
}
|
||||
|
||||
function replyBody(body: string | ReadonlyArray<string | Buffer>) {
|
||||
return (
|
||||
_url: string,
|
||||
_options: unknown,
|
||||
onResponse: (res: EventEmitter) => void,
|
||||
): RequestLike => {
|
||||
const req = requestStub();
|
||||
const res = new EventEmitter();
|
||||
onResponse(res);
|
||||
const chunks = typeof body === 'string' ? [body] : body;
|
||||
|
||||
for (const chunk of chunks) {
|
||||
res.emit('data', chunk);
|
||||
}
|
||||
|
||||
res.emit('end');
|
||||
return req;
|
||||
};
|
||||
}
|
||||
|
||||
function replyError(error: Error) {
|
||||
return (): RequestLike => {
|
||||
const req = requestStub();
|
||||
queueMicrotask(() => req.emit('error', error));
|
||||
return req;
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
execMock.mockReset();
|
||||
httpGetMock.mockReset();
|
||||
httpsGetMock.mockReset();
|
||||
setPlatform('linux');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setPlatform(originalPlatform);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('probeQqLoginInfo — unix listing', () => {
|
||||
it('returns null when ss cannot list sockets', async () => {
|
||||
mockExec({ 'ss -tlnp': new Error('ss: not found') });
|
||||
|
||||
await expect(probeQqLoginInfo(3310)).resolves.toBeNull();
|
||||
expect(execCommands()).toEqual(['ss -tlnp']);
|
||||
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n',
|
||||
'pgrep -c qq': '5\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(3311)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']);
|
||||
expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS);
|
||||
});
|
||||
|
||||
it('treats a pgrep count of 0 as logged out', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': '0\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(3312)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': 'qq: no process found\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(3313)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when there are no sockets and pgrep is 6 or higher', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': '6\n',
|
||||
});
|
||||
await expect(probeQqLoginInfo(3314)).resolves.toBeNull();
|
||||
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': '9\n',
|
||||
});
|
||||
await expect(probeQqLoginInfo(3315)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('does not treat a failed pgrep as logged out', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': new Error('pgrep: exit 1'),
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(3316)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [ssLine(9218, 4410), ssLine(18000, 4410)].join('\n'),
|
||||
'pgrep -c qq': ' 4 \n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4410)).resolves.toEqual({
|
||||
port: 9218,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': ssLine(9218, 4411),
|
||||
'pgrep -c qq': '7\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4411)).resolves.toBeNull();
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [
|
||||
'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))',
|
||||
ssLine(4301, 4412, 'comma'),
|
||||
ssLine(4301, 4412, 'comma'),
|
||||
ssLine(4305, 4412, 'paren'),
|
||||
ssLine(4305, 9999, 'comma'),
|
||||
'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))',
|
||||
].join('\n'),
|
||||
});
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(4412)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '10001',
|
||||
nickName: 'Ada',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).toHaveBeenCalledTimes(2);
|
||||
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
|
||||
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeQqLoginInfo — Ptlogin identity', () => {
|
||||
it('reads a single account from an odd Ptlogin port over https', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5501) });
|
||||
httpsGetMock.mockImplementation(
|
||||
replyBody(
|
||||
jsonp([
|
||||
{
|
||||
uin: 319427101,
|
||||
account: 1,
|
||||
nickname: 'Snow',
|
||||
extra: 'ignored',
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5501)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '319427101',
|
||||
nickName: 'Snow',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).toHaveBeenCalledTimes(2);
|
||||
expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({
|
||||
headers: PTLOGIN_HEADERS,
|
||||
timeout: 500,
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('reads a single account from an even Ptlogin port over http', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4302, 5502) });
|
||||
httpGetMock.mockImplementation(
|
||||
replyBody(
|
||||
jsonp([
|
||||
{
|
||||
account: '2880036470',
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5502)).resolves.toEqual({
|
||||
port: 4302,
|
||||
uin: '2880036470',
|
||||
nickName: '',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
expect(httpGetMock).toHaveBeenCalledTimes(2);
|
||||
expect(httpGetMock.mock.calls[0]?.[0]).toBe(
|
||||
'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
);
|
||||
expect(httpGetMock.mock.calls[0]?.[1]).toEqual({
|
||||
headers: PTLOGIN_HEADERS,
|
||||
timeout: 500,
|
||||
});
|
||||
});
|
||||
|
||||
it('probes every documented odd Ptlogin port over https', async () => {
|
||||
for (const port of [4301, 4303, 4305, 4307, 4309]) {
|
||||
execMock.mockReset();
|
||||
httpsGetMock.mockReset();
|
||||
httpGetMock.mockReset();
|
||||
mockExec({ 'ss -tlnp': ssLine(port, 5510) });
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5510)).resolves.toEqual({
|
||||
port,
|
||||
uin: '70001',
|
||||
nickName: 'Odd',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe(
|
||||
`https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('probes every documented even Ptlogin port over http when no odd port is listening', async () => {
|
||||
for (const port of [4302, 4304, 4306, 4308, 4310]) {
|
||||
execMock.mockReset();
|
||||
httpsGetMock.mockReset();
|
||||
httpGetMock.mockReset();
|
||||
mockExec({ 'ss -tlnp': ssLine(port, 5511) });
|
||||
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5511)).resolves.toEqual({
|
||||
port,
|
||||
uin: '70002',
|
||||
nickName: 'Even',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
expect(String(httpGetMock.mock.calls[0]?.[0])).toBe(
|
||||
`http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('prefers odd Ptlogin ports and never falls through to even ones', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'),
|
||||
});
|
||||
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
|
||||
|
||||
await expect(probeQqLoginInfo(5520)).resolves.toBeNull();
|
||||
expect(httpsGetMock).toHaveBeenCalled();
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(execCommands()).toEqual(['ss -tlnp']);
|
||||
});
|
||||
|
||||
it('tries the next odd Ptlogin port after the first one fails', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'),
|
||||
});
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyBody('<html>nope</html>'))
|
||||
.mockImplementationOnce(replyBody('<html>nope</html>'))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5521)).resolves.toEqual({
|
||||
port: 4305,
|
||||
uin: '188888',
|
||||
nickName: 'Next',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([
|
||||
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
]);
|
||||
});
|
||||
|
||||
it('stops after the first Ptlogin port that yields a single account', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'),
|
||||
});
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5522)).resolves.toEqual({
|
||||
port: 4303,
|
||||
uin: '42',
|
||||
nickName: 'First',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('uses account when uin is missing or empty, including a numeric 0 uin', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5530) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(
|
||||
replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }])),
|
||||
)
|
||||
.mockImplementationOnce(
|
||||
replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }])),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5530)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '314159',
|
||||
nickName: 'Zero',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns an empty uin when the single account has neither uin nor account', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5531) });
|
||||
httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]'));
|
||||
|
||||
await expect(probeQqLoginInfo(5531)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '',
|
||||
nickName: 'Anon',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the shorter of the two pt_get_uins snapshots', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5540) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(
|
||||
replyBody(
|
||||
jsonp([
|
||||
{ uin: '11', nickname: 'A' },
|
||||
{ uin: '22', nickname: 'B' },
|
||||
]),
|
||||
),
|
||||
)
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5540)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '33',
|
||||
nickName: 'Cora',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the first snapshot when both pt_get_uins calls have one account', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5541) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }])))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5541)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '100',
|
||||
nickName: 'Left',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts a single account from the second fetch when the first fetch is unusable', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5542) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyError(new Error('ECONNRESET')))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5542)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '9090',
|
||||
nickName: 'Retry',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5550) });
|
||||
httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);'));
|
||||
|
||||
await expect(probeQqLoginInfo(5550)).resolves.toBeNull();
|
||||
expect(execCommands()).toEqual(['ss -tlnp']);
|
||||
});
|
||||
|
||||
it('returns null when both snapshots have more than one account', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4304, 5551) });
|
||||
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '1' }, { uin: '2' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5551)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when both fetches fail to parse a pt_get_uins body', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5552) });
|
||||
httpsGetMock.mockImplementation(replyBody('not-jsonp'));
|
||||
|
||||
await expect(probeQqLoginInfo(5552)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when both fetches error', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5553) });
|
||||
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
|
||||
|
||||
await expect(probeQqLoginInfo(5553)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('destroys the request and returns null when both fetches time out', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5554) });
|
||||
const seen: RequestLike[] = [];
|
||||
httpsGetMock.mockImplementation(() => {
|
||||
const req = requestStub();
|
||||
seen.push(req);
|
||||
queueMicrotask(() => req.emit('timeout'));
|
||||
return req;
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(5554)).resolves.toBeNull();
|
||||
expect(seen).toHaveLength(2);
|
||||
expect(seen[0]?.destroy).toHaveBeenCalledTimes(1);
|
||||
expect(seen[1]?.destroy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('joins chunked pt_get_uins bodies including Buffer pieces', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5560) });
|
||||
httpsGetMock.mockImplementation(
|
||||
replyBody([
|
||||
'ptui_getuins_CB([',
|
||||
Buffer.from('{"uin":"10001","nickname":"Ada"}'),
|
||||
']);',
|
||||
]),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5560)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '10001',
|
||||
nickName: 'Ada',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a nickname that closes the JSONP array early as unusable', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5561) });
|
||||
httpsGetMock.mockImplementation(
|
||||
replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);'),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5561)).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeQqLoginInfo — win32 listing', () => {
|
||||
beforeEach(() => {
|
||||
setPlatform('win32');
|
||||
});
|
||||
|
||||
it('returns null when netstat cannot list sockets', async () => {
|
||||
mockExec({ 'netstat -ano': new Error('netstat: access denied') });
|
||||
|
||||
await expect(probeQqLoginInfo(6610)).resolves.toBeNull();
|
||||
expect(execCommands()).toEqual(['netstat -ano']);
|
||||
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
|
||||
});
|
||||
|
||||
it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': [
|
||||
'Active Connections',
|
||||
'',
|
||||
' Proto Local Address Foreign Address State PID',
|
||||
netstatLine('127.0.0.1:4301', 1),
|
||||
].join('\n'),
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh': [
|
||||
'QQ.exe 100 Console 1 10,000 K',
|
||||
'QQ.exe 101 Console 1 11,000 K',
|
||||
'explorer.exe 200 Console 1 9,000 K',
|
||||
].join('\n'),
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(6611)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(execCommands()).toEqual(['netstat -ano', 'tasklist /fi "imagename eq QQ.exe" /nh']);
|
||||
});
|
||||
|
||||
it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': '',
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh': [
|
||||
'QQ.exe 1',
|
||||
'QQ.exe 2',
|
||||
'QQ.exe 3',
|
||||
'qq.exe 4',
|
||||
'QQ.EXE 5',
|
||||
'QQ.exe 6',
|
||||
].join('\n'),
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(6612)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('does not treat a failed tasklist as logged out', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': '',
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'),
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(6613)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('parses netstat rows for the owning PID and skips short or portless lines', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': [
|
||||
'Active Connections',
|
||||
' TCP 127.0.0.1:4301 LISTENING',
|
||||
' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620',
|
||||
netstatLine('10.0.0.8:18000', 1),
|
||||
netstatLine('127.0.0.1:4303', 6620),
|
||||
netstatLine('[::1]:4303', 6620),
|
||||
netstatLine('127.0.0.1:9218', 6620),
|
||||
].join('\n'),
|
||||
});
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(6620)).resolves.toEqual({
|
||||
port: 4303,
|
||||
uin: '20002',
|
||||
nickName: 'Win',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).toHaveBeenCalledTimes(2);
|
||||
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
|
||||
'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': [
|
||||
netstatLine('127.0.0.1:18000', 6630),
|
||||
netstatLine('127.0.0.1:18001', 6630),
|
||||
].join('\n'),
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(6630)).resolves.toEqual({
|
||||
port: 18000,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeQqLoginInfo — overall deadline', () => {
|
||||
it('returns null and warns after 5000ms if listing never finishes', async () => {
|
||||
vi.useFakeTimers();
|
||||
execMock.mockImplementation(() => undefined);
|
||||
const previousLevel = getLogLevel();
|
||||
setLogLevel('info');
|
||||
const warnings: string[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => {
|
||||
if (entry.scope === 'LoginProbe' && entry.level === 'warn') {
|
||||
warnings.push(entry.message);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const pending = probeQqLoginInfo(9001);
|
||||
let settled: unknown = 'pending';
|
||||
void pending.then((value) => {
|
||||
settled = value;
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(4999);
|
||||
expect(settled).toBe('pending');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(pending).resolves.toBeNull();
|
||||
expect(warnings).toEqual(['login check timed out: PID=9001']);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not warn when the probe finishes before the deadline', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': '2\n',
|
||||
});
|
||||
const previousLevel = getLogLevel();
|
||||
setLogLevel('info');
|
||||
const warnings: string[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => {
|
||||
if (entry.scope === 'LoginProbe') {
|
||||
warnings.push(entry.message);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(probeQqLoginInfo(9002)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
await probeQqLoginInfo(9002);
|
||||
expect(warnings).toEqual(['login probe: PID=9002 result=no-ports ports=0 processes=2']);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('abandons a hung Ptlogin fetch at the overall deadline', async () => {
|
||||
vi.useFakeTimers();
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 9003) });
|
||||
httpsGetMock.mockImplementation(() => requestStub());
|
||||
|
||||
const pending = probeQqLoginInfo(9003);
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
await expect(pending).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const execMock = vi.hoisted(() => vi.fn());
|
||||
const socketCtorMock = vi.hoisted(() =>
|
||||
vi.fn(function MockSocket() {
|
||||
throw new Error('interactive QQ probe must not run');
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock('child_process', () => ({ exec: execMock }));
|
||||
vi.mock('net', () => ({
|
||||
default: { Socket: socketCtorMock },
|
||||
Socket: socketCtorMock,
|
||||
}));
|
||||
|
||||
import { probeQqLoginInfo } from '../src/qq-port-probe';
|
||||
|
||||
describe('probeQqLoginInfo — bounded execution', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
execMock.mockReset();
|
||||
socketCtorMock.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('allows a later probe after a timed-out attempt', async () => {
|
||||
execMock.mockImplementation(() => undefined);
|
||||
const first = probeQqLoginInfo(4242);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
await expect(first).resolves.toBeNull();
|
||||
|
||||
execMock
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '', stderr: '' });
|
||||
})
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, {
|
||||
stdout: process.platform === 'win32' ? 'QQ.exe 4242 Console 1 1234 K\n' : '1\n',
|
||||
stderr: '',
|
||||
});
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps background identity discovery passive', async () => {
|
||||
execMock
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, {
|
||||
stdout:
|
||||
process.platform === 'win32'
|
||||
? 'TCP 127.0.0.1:9218 0.0.0.0:0 LISTENING 4242\n'
|
||||
: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
|
||||
stderr: '',
|
||||
});
|
||||
})
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, {
|
||||
stdout:
|
||||
process.platform === 'win32'
|
||||
? 'QQ.exe 4242 Console 1 1234 K\n'.repeat(8)
|
||||
: '8\n',
|
||||
stderr: '',
|
||||
});
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
|
||||
expect(socketCtorMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { hasLowProcessIntegrity, type NativeRuntimeIntegrity } from '../src/runtime-integrity';
|
||||
|
||||
const native = vi.hoisted(() => ({ load: vi.fn(), error: vi.fn() }));
|
||||
vi.mock('../src/injector', () => ({
|
||||
getNativeHookAddon: native.load,
|
||||
getNativeHookLoadError: native.error,
|
||||
}));
|
||||
|
||||
const platform = process.platform;
|
||||
const sample = (): NativeRuntimeIntegrity => ({
|
||||
pid: process.pid,
|
||||
executablePath: process.execPath,
|
||||
process: { status: 'ok', rid: 8192 },
|
||||
file: { status: 'ok', label: null },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.resetAllMocks();
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
});
|
||||
|
||||
describe('runtime integrity diagnostics', () => {
|
||||
it('warns only for a successfully read process token below Medium', () => {
|
||||
const available = { ...sample(), status: 'available' as const };
|
||||
|
||||
for (const rid of [0, 4096]) {
|
||||
expect(hasLowProcessIntegrity({ ...available, process: { status: 'ok', rid } })).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
for (const rid of [8192, 8448, 12288, 16384]) {
|
||||
expect(
|
||||
hasLowProcessIntegrity({
|
||||
...available,
|
||||
process: { status: 'ok', rid },
|
||||
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
|
||||
}),
|
||||
).toBe(false);
|
||||
}
|
||||
|
||||
expect(hasLowProcessIntegrity({ status: 'unsupported' })).toBe(false);
|
||||
expect(hasLowProcessIntegrity({ status: 'unavailable', error: 'unavailable' })).toBe(false);
|
||||
expect(
|
||||
hasLowProcessIntegrity({
|
||||
...available,
|
||||
process: { status: 'error', operation: 'OpenProcessToken', code: 5 },
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps one startup snapshot for logging and all WebUI polls', async () => {
|
||||
const read = vi.fn().mockReturnValue(sample());
|
||||
native.load.mockReturnValue({ getRuntimeIntegrity: read });
|
||||
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
|
||||
const first = getRuntimeIntegrity();
|
||||
expect(first).toMatchObject({
|
||||
status: 'available',
|
||||
process: { rid: 8192 },
|
||||
file: { label: null },
|
||||
});
|
||||
read.mockReturnValue({
|
||||
...sample(),
|
||||
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
|
||||
});
|
||||
expect(getRuntimeIntegrity()).toBe(first);
|
||||
expect(read).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(['process', 'file'])(
|
||||
'retains %s query errors and the other successful result',
|
||||
async (field) => {
|
||||
native.load.mockReturnValue({
|
||||
getRuntimeIntegrity: () => ({
|
||||
...sample(),
|
||||
[field]: { status: 'error', operation: 'Win32Query', code: 5 },
|
||||
}),
|
||||
});
|
||||
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
|
||||
expect(getRuntimeIntegrity()).toMatchObject({
|
||||
status: 'available',
|
||||
[field]: { status: 'error', operation: 'Win32Query', code: 5 },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('reports old addons as unavailable rather than Medium', async () => {
|
||||
native.load.mockReturnValue({});
|
||||
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
|
||||
expect(getRuntimeIntegrity()).toMatchObject({
|
||||
status: 'unavailable',
|
||||
error: expect.stringContaining('不支持'),
|
||||
});
|
||||
});
|
||||
|
||||
it('retains the loader error for the startup log', async () => {
|
||||
native.load.mockReturnValue(null);
|
||||
native.error.mockReturnValue('dlopen failed: incompatible binary');
|
||||
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
|
||||
expect(getRuntimeIntegrity()).toMatchObject({
|
||||
status: 'unavailable',
|
||||
error: 'dlopen failed: incompatible binary',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
null,
|
||||
{ ...sample(), pid: process.pid + 1 },
|
||||
{ ...sample(), process: { status: 'ok', rid: -1 } },
|
||||
{ ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: 'yes', policy: 1 } } },
|
||||
])('rejects malformed or wrong-process native results', async (result) => {
|
||||
native.load.mockReturnValue({ getRuntimeIntegrity: () => result });
|
||||
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
|
||||
expect(getRuntimeIntegrity()).toMatchObject({
|
||||
status: 'unavailable',
|
||||
error: expect.stringContaining('无效数据'),
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves thrown errors without repeatedly probing on WebUI polls', async () => {
|
||||
const read = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error('allocation failed');
|
||||
})
|
||||
.mockReturnValue(sample());
|
||||
native.load.mockReturnValue({ getRuntimeIntegrity: read });
|
||||
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
|
||||
expect(getRuntimeIntegrity()).toMatchObject({
|
||||
status: 'unavailable',
|
||||
error: 'allocation failed',
|
||||
});
|
||||
expect(getRuntimeIntegrity()).toMatchObject({
|
||||
status: 'unavailable',
|
||||
error: 'allocation failed',
|
||||
});
|
||||
expect(read).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not load the addon on non-Windows hosts', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
|
||||
expect(getRuntimeIntegrity()).toEqual({ status: 'unsupported' });
|
||||
expect(native.load).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.11.3",
|
||||
"version": "1.14.22",
|
||||
"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).",
|
||||
@@ -20,6 +20,10 @@
|
||||
"types": "./src/coerce.ts",
|
||||
"default": "./src/coerce.ts"
|
||||
},
|
||||
"./env": {
|
||||
"types": "./src/env.ts",
|
||||
"default": "./src/env.ts"
|
||||
},
|
||||
"./single-flight-cache": {
|
||||
"types": "./src/single-flight-cache.ts",
|
||||
"default": "./src/single-flight-cache.ts"
|
||||
@@ -40,6 +44,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"
|
||||
@@ -59,6 +67,10 @@
|
||||
"./uin": {
|
||||
"types": "./src/uin.ts",
|
||||
"default": "./src/uin.ts"
|
||||
},
|
||||
"./access-token": {
|
||||
"types": "./src/access-token.ts",
|
||||
"default": "./src/access-token.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
@@ -66,8 +78,16 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@zxcvbn-ts/core": "^4.1.2",
|
||||
"@zxcvbn-ts/language-common": "^4.1.3",
|
||||
"@zxcvbn-ts/language-en": "^4.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { ZxcvbnFactory } from '@zxcvbn-ts/core';
|
||||
import { adjacencyGraphs, dictionary } from '@zxcvbn-ts/language-common';
|
||||
import { translations } from '@zxcvbn-ts/language-en';
|
||||
|
||||
export const ACCESS_TOKEN_MIN_LENGTH = 16;
|
||||
export const ACCESS_TOKEN_MIN_SCORE = 3;
|
||||
|
||||
export type AccessTokenAssessmentReason = 'empty' | 'too-short' | 'guessable' | 'acceptable';
|
||||
|
||||
export interface AccessTokenAssessment {
|
||||
acceptable: boolean;
|
||||
reason: AccessTokenAssessmentReason;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const checker = new ZxcvbnFactory({
|
||||
translations,
|
||||
graphs: adjacencyGraphs,
|
||||
dictionary,
|
||||
});
|
||||
|
||||
function normalizeUserInputs(values: readonly (string | number)[]): Array<string | number> {
|
||||
const unique = new Set<string | number>(['SnowLuma', 'OneBot']);
|
||||
|
||||
for (const value of values) {
|
||||
if (typeof value === 'number') {
|
||||
if (Number.isFinite(value)) {
|
||||
unique.add(value);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
|
||||
if (trimmed) {
|
||||
unique.add(trimmed.slice(0, 256));
|
||||
}
|
||||
}
|
||||
|
||||
return [...unique].slice(0, 24);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a newly chosen OneBot access token against the shared product
|
||||
* policy. Callers decide whether an empty token is permitted in their own
|
||||
* trust context; an empty value is never considered strong here.
|
||||
*/
|
||||
export function assessAccessToken(
|
||||
token: string,
|
||||
userInputs: readonly (string | number)[] = [],
|
||||
): AccessTokenAssessment {
|
||||
if (!token) {
|
||||
return { acceptable: false, reason: 'empty', score: 0 };
|
||||
}
|
||||
|
||||
if (token.length < ACCESS_TOKEN_MIN_LENGTH) {
|
||||
return { acceptable: false, reason: 'too-short', score: 0 };
|
||||
}
|
||||
|
||||
const score = checker.check(token, normalizeUserInputs(userInputs)).score;
|
||||
|
||||
if (score < ACCESS_TOKEN_MIN_SCORE) {
|
||||
return { acceptable: false, reason: 'guessable', score };
|
||||
}
|
||||
|
||||
return { acceptable: true, reason: 'acceptable', score };
|
||||
}
|
||||
@@ -7,24 +7,28 @@
|
||||
|
||||
/** 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);
|
||||
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;
|
||||
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));
|
||||
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));
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
}
|
||||
@@ -12,16 +12,21 @@
|
||||
* 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>,
|
||||
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;
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { createLogger } from './logger';
|
||||
|
||||
const log = createLogger('Env');
|
||||
|
||||
/** Node's setTimeout delay is a signed 32-bit integer. */
|
||||
const MAX_POSITIVE_INT = 2_147_483_647;
|
||||
|
||||
/** Read a positive integer environment variable.
|
||||
*
|
||||
* A blank value is absent and returns `fallback`. A present but unusable
|
||||
* value is ignored, with a warning, and also returns `fallback`.
|
||||
*/
|
||||
export function positiveIntEnv(
|
||||
name: string,
|
||||
fallback: number,
|
||||
options?: { max?: number; env?: NodeJS.ProcessEnv },
|
||||
): number {
|
||||
const max = options?.max ?? MAX_POSITIVE_INT;
|
||||
const raw = (options?.env ?? process.env)[name];
|
||||
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
|
||||
if (!Number.isSafeInteger(parsed) || parsed > max) {
|
||||
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
+30
-21
@@ -2,34 +2,43 @@ const HEX_CHARS = '0123456789abcdef';
|
||||
const HEX_CHARS_UPPER = '0123456789ABCDEF';
|
||||
|
||||
export function toHex(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS[b >> 4];
|
||||
h += HEX_CHARS[b & 0xf];
|
||||
}
|
||||
return h;
|
||||
let h = '';
|
||||
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS[b >> 4];
|
||||
h += HEX_CHARS[b & 0xf];
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
export function toHexUpper(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS_UPPER[b >> 4];
|
||||
h += HEX_CHARS_UPPER[b & 0xf];
|
||||
}
|
||||
return h;
|
||||
let h = '';
|
||||
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS_UPPER[b >> 4];
|
||||
h += HEX_CHARS_UPPER[b & 0xf];
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
|
||||
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||
const head = toHex(data.subarray(0, limit));
|
||||
return data.length > limit ? `${head}...` : head;
|
||||
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||
const head = toHex(data.subarray(0, limit));
|
||||
return data.length > limit ? `${head}...` : head;
|
||||
}
|
||||
|
||||
export function fromHex(hex: string): Buffer {
|
||||
if (hex.length % 2 !== 0) throw new Error('Invalid hex string length');
|
||||
const buf = Buffer.alloc(hex.length / 2);
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return buf;
|
||||
if (hex.length % 2 !== 0) {
|
||||
throw new Error('Invalid hex string length');
|
||||
}
|
||||
|
||||
const buf = Buffer.alloc(hex.length / 2);
|
||||
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
||||
export interface JsonObject {
|
||||
[key: string]: JsonValue;
|
||||
[key: string]: JsonValue;
|
||||
}
|
||||
export type JsonArray = JsonValue[];
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,115 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,22 +1,67 @@
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
const SENSITIVE_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
'credential',
|
||||
'credentials',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
]);
|
||||
|
||||
function valueRepr(v: unknown): string {
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) return `[len=${v.length}]`;
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
function isSensitiveKey(key: string): boolean {
|
||||
const segments = key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
|
||||
return segments.some((segment, index) => {
|
||||
if (SENSITIVE_SEGMENTS.has(segment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const next = segments[index + 1];
|
||||
return (
|
||||
next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function valueRepr(v: unknown, key?: string): string {
|
||||
if (key !== undefined && isSensitiveKey(key)) {
|
||||
return '"***"';
|
||||
}
|
||||
|
||||
if (v === null) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
if (v === undefined) {
|
||||
return 'undefined';
|
||||
}
|
||||
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) {
|
||||
return `[len=${v.length}]`;
|
||||
}
|
||||
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,91 +73,311 @@ function valueRepr(v: unknown): string {
|
||||
* replaced with `...` so the next field doesn't get half-rendered.
|
||||
*/
|
||||
export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v)}`;
|
||||
// +1 accounts for the separating space we'd insert when joining.
|
||||
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
|
||||
out.push('...');
|
||||
break;
|
||||
if (params === null || params === undefined) {
|
||||
return '{}';
|
||||
}
|
||||
out.push(entry);
|
||||
total += entry.length + (out.length > 1 ? 1 : 0);
|
||||
}
|
||||
return out.join(' ');
|
||||
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL - 3)}...` : s;
|
||||
}
|
||||
|
||||
if (Array.isArray(params)) {
|
||||
return `[len=${params.length}]`;
|
||||
}
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v, k)}`;
|
||||
const separatorLength = out.length > 0 ? 1 : 0;
|
||||
|
||||
if (total + separatorLength + entry.length > MAX_TOTAL) {
|
||||
if (out.length === 0) {
|
||||
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
const rendered = out.join(' ');
|
||||
return rendered.length + 4 <= MAX_TOTAL
|
||||
? `${rendered} ...`
|
||||
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
out.push(entry);
|
||||
total += separatorLength + entry.length;
|
||||
}
|
||||
|
||||
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;
|
||||
const ASSIGNMENT_START =
|
||||
/(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
|
||||
const AUTHORIZATION_BOUNDARY_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
]);
|
||||
|
||||
function keySegments(key: string): string[] {
|
||||
return key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
}
|
||||
|
||||
function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean {
|
||||
return keySegments(key).includes(kind);
|
||||
}
|
||||
|
||||
function isAuthorizationBoundaryKey(key: string): boolean {
|
||||
const segments = keySegments(key);
|
||||
return segments.some((segment, index) => {
|
||||
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const next = segments[index + 1];
|
||||
return (
|
||||
next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function quotedValueEnd(message: string, start: number): number | undefined {
|
||||
const quote = message[start];
|
||||
|
||||
if (quote !== '"' && quote !== "'") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (let index = start + 1; index < message.length; index += 1) {
|
||||
if (message[index] === '\\') {
|
||||
index += 1;
|
||||
} else if (message[index] === quote) {
|
||||
return index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return message.length;
|
||||
}
|
||||
|
||||
function cookieValueEnd(message: string, start: number): number {
|
||||
const initialQuotedEnd = quotedValueEnd(message, start);
|
||||
let end: number;
|
||||
|
||||
if (initialQuotedEnd !== undefined) {
|
||||
end = initialQuotedEnd;
|
||||
} else {
|
||||
end = start;
|
||||
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
}
|
||||
|
||||
while (end < message.length) {
|
||||
let semicolon: number = end;
|
||||
|
||||
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
|
||||
semicolon += 1;
|
||||
}
|
||||
|
||||
if (message[semicolon] !== ';') {
|
||||
break;
|
||||
}
|
||||
|
||||
let nameStart = semicolon + 1;
|
||||
|
||||
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
|
||||
nameStart += 1;
|
||||
}
|
||||
|
||||
let nameEnd = nameStart;
|
||||
|
||||
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) {
|
||||
nameEnd += 1;
|
||||
}
|
||||
|
||||
if (nameEnd === nameStart) {
|
||||
break;
|
||||
}
|
||||
|
||||
end = nameEnd;
|
||||
|
||||
if (message[end] !== '=') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
|
||||
const valueStart = end + 1;
|
||||
const quotedEnd = quotedValueEnd(message, valueStart);
|
||||
|
||||
if (quotedEnd !== undefined) {
|
||||
end = quotedEnd;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attribute !== 'expires') {
|
||||
end = valueStart;
|
||||
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
end = valueStart;
|
||||
|
||||
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
assignments.lastIndex = valueStart;
|
||||
const nextField = assignments.exec(message);
|
||||
|
||||
if (nextField && nextField.index < end) {
|
||||
end = nextField.index;
|
||||
}
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
function genericValueEnd(message: string, start: number): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
|
||||
if (quotedEnd !== undefined) {
|
||||
return quotedEnd;
|
||||
}
|
||||
|
||||
let end = start;
|
||||
|
||||
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
function authorizationValueEnd(message: string, start: number, query: boolean): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
|
||||
if (quotedEnd !== undefined) {
|
||||
return quotedEnd;
|
||||
}
|
||||
|
||||
if (query) {
|
||||
const queryEnd = message.indexOf('&', start);
|
||||
return queryEnd >= 0 ? queryEnd : message.length;
|
||||
}
|
||||
|
||||
let end = message.length;
|
||||
const structural = message.slice(start).search(/[\r\n}\]]/);
|
||||
|
||||
if (structural >= 0) {
|
||||
end = start + structural;
|
||||
}
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
const remaining = message.slice(start, end);
|
||||
|
||||
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
|
||||
if (isAuthorizationBoundaryKey(match[3]!)) {
|
||||
end = start + match.index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
/** Redact explicit authentication assignments in ordinary formatted logs. */
|
||||
export function redactLogMessage(message: string): string {
|
||||
let out = '';
|
||||
let cursor = 0;
|
||||
ASSIGNMENT_START.lastIndex = 0;
|
||||
|
||||
for (
|
||||
let match = ASSIGNMENT_START.exec(message);
|
||||
match;
|
||||
match = ASSIGNMENT_START.exec(message)
|
||||
) {
|
||||
const key = match[3]!;
|
||||
|
||||
if (!isSensitiveKey(key)) {
|
||||
ASSIGNMENT_START.lastIndex = Math.max(match.index + 1, ASSIGNMENT_START.lastIndex - 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
const valueStart = ASSIGNMENT_START.lastIndex;
|
||||
const valueEnd = isKeyKind(key, 'authorization')
|
||||
? authorizationValueEnd(message, valueStart, match[1] === '?' || match[1] === '&')
|
||||
: isKeyKind(key, 'cookie')
|
||||
? cookieValueEnd(message, valueStart)
|
||||
: genericValueEnd(message, valueStart);
|
||||
|
||||
out += message.slice(cursor, valueStart) + '***';
|
||||
cursor = valueEnd;
|
||||
ASSIGNMENT_START.lastIndex = valueEnd;
|
||||
}
|
||||
|
||||
return out + message.slice(cursor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 → `"***"`).
|
||||
* Lossless nested renderer for explicit TRACE diagnostics. TRACE is an
|
||||
* operator-enabled, memory-only mode and intentionally leaves values
|
||||
* unredacted so a reproduction contains the complete business input.
|
||||
*/
|
||||
export function renderParamsVerbose(params: unknown): string {
|
||||
const seen = new WeakSet<object>();
|
||||
let budget = VERBOSE_TOTAL_MAX;
|
||||
const seen = new WeakSet<object>();
|
||||
|
||||
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(',')}]`;
|
||||
const walk = (value: unknown): string => {
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
}
|
||||
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);
|
||||
if (value === undefined) {
|
||||
return 'undefined';
|
||||
}
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return JSON.stringify(value);
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(value);
|
||||
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) {
|
||||
return '"[circular]"';
|
||||
}
|
||||
|
||||
seen.add(value as object);
|
||||
const out = Array.isArray(value)
|
||||
? `[${value.map((item) => walk(item)).join(',')}]`
|
||||
: `{${Object.entries(value as Record<string, unknown>)
|
||||
.map(([key, item]) => `${key}:${walk(item)}`)
|
||||
.join(',')}}`;
|
||||
seen.delete(value as object);
|
||||
return out;
|
||||
}
|
||||
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
|
||||
return walk(params);
|
||||
}
|
||||
+331
-209
@@ -1,58 +1,66 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
import { currentRequestId } from './request-context';
|
||||
import { redactLogMessage } from './log-summary';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
import {
|
||||
currentRequestId,
|
||||
nextRequestId,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
} from './request-context';
|
||||
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type FileLogLevel = Exclude<LogLevel, 'trace'>;
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
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;
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
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;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
warn: 33,
|
||||
error: 31,
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
warn: 33,
|
||||
error: 31,
|
||||
};
|
||||
|
||||
const COLOR_SCOPE = 35;
|
||||
@@ -62,9 +70,10 @@ const MAX_LOG_ENTRIES = 1000;
|
||||
|
||||
/** 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 raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
@@ -72,32 +81,40 @@ const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
* 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;
|
||||
}
|
||||
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);
|
||||
@@ -106,134 +123,208 @@ const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
|
||||
if (
|
||||
raw === 'trace' ||
|
||||
raw === 'debug' ||
|
||||
raw === 'info' ||
|
||||
raw === 'success' ||
|
||||
raw === 'warn' ||
|
||||
raw === 'error'
|
||||
) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
return 'info';
|
||||
}
|
||||
|
||||
function resolveFileMinLevel(): FileLogLevel {
|
||||
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
|
||||
if (raw === undefined || raw.trim() === '') {
|
||||
return 'debug';
|
||||
}
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
|
||||
if (
|
||||
normalized === 'debug' ||
|
||||
normalized === 'info' ||
|
||||
normalized === 'success' ||
|
||||
normalized === 'warn' ||
|
||||
normalized === 'error'
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
throw new TypeError(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
}
|
||||
|
||||
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
|
||||
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
|
||||
// Only governs console + ring buffer + subscribers; the file
|
||||
// transport always sees debug-and-up regardless.
|
||||
// Only governs console + ring buffer + subscribers;
|
||||
// the file transport level is seeded independently from
|
||||
// SNOWLUMA_LOG_FILE_LEVEL (default debug)
|
||||
// and is not affected by setLogLevel().
|
||||
let currentLevel: LogLevel = resolveMinLevel();
|
||||
const currentFileLevel: FileLogLevel = resolveFileMinLevel();
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
function shouldLogToFile(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = [
|
||||
'trace',
|
||||
'debug',
|
||||
'info',
|
||||
'success',
|
||||
'warn',
|
||||
'error',
|
||||
];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the console / subscriber level at runtime. Invalid input is
|
||||
* a no-op (returns false). File transport is unaffected — it always
|
||||
* sees every level so post-mortems remain useful.
|
||||
*/
|
||||
// Change the console / subscriber level at runtime.
|
||||
// Invalid input is a no-op (returns false).
|
||||
// Does not affect the file transport log level.
|
||||
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
const lower = String(level).toLowerCase();
|
||||
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useColor(): boolean {
|
||||
if (process.env.NO_COLOR === '1') return false;
|
||||
return Boolean(process.stdout.isTTY);
|
||||
if (process.env.NO_COLOR === '1') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Boolean(process.stdout.isTTY);
|
||||
}
|
||||
|
||||
function ansi(code: number, text: string): string {
|
||||
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||
}
|
||||
|
||||
function currentTime(): string {
|
||||
const d = new Date();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
const d = new Date();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
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}]` : '';
|
||||
function render(level: LogLevel, options: LogOptions, message: string, reqId?: number): string {
|
||||
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}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
// 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(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
// 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(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
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);
|
||||
// Console / subscriber and file filters are independent. If no destination
|
||||
// accepts the record, stop before formatting or building a LogEntry.
|
||||
const passesConsole = shouldLog(level);
|
||||
const passesFile = level !== 'trace' && shouldLogToFile(level);
|
||||
|
||||
// `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;
|
||||
if (!passesConsole && !passesFile) {
|
||||
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[])();
|
||||
}
|
||||
// `trace` is the high-volume full-chain diagnostic stream, intentionally
|
||||
// excluded from disk to avoid I/O saturation. When console is not dialed
|
||||
// to trace, the early return below skips format/render/disk entirely.
|
||||
// Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory;
|
||||
// trace never reaches disk regardless.
|
||||
if (level === 'trace' && !passesConsole) {
|
||||
return;
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
// 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 (passesConsole) {
|
||||
// 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
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
// 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);
|
||||
const reqId = currentRequestId();
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, 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: sanitizeLogLine(line),
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
// 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
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
|
||||
|
||||
try {
|
||||
stream.write(consoleLine);
|
||||
} catch {
|
||||
// A full Docker json-file log volume can make stdout/stderr throw.
|
||||
// Logging must not take down message handling or the WebUI.
|
||||
}
|
||||
}
|
||||
|
||||
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
|
||||
// default debug). `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 (passesFile) {
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -243,73 +334,104 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
* has finalized the write.
|
||||
*/
|
||||
export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
function mergeLogRings(): LogEntry[] {
|
||||
return traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
}
|
||||
|
||||
export function getLogSnapshot(): LogEntry[] {
|
||||
return mergeLogRings();
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
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);
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
return mergeLogRings().slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
logSubscribers.add(callback);
|
||||
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number;[k: string]: unknown }) => 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;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number; [k: string]: unknown }) => 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),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
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),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
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';
|
||||
export function renderTraceBytes(body: Uint8Array): string {
|
||||
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex');
|
||||
}
|
||||
|
||||
export function runWithTraceRequest<T>(fn: () => T): T {
|
||||
if (currentRequestId() !== undefined || currentLevel !== 'trace') {
|
||||
return fn();
|
||||
}
|
||||
|
||||
return runWithRequestId(nextRequestId(), fn);
|
||||
}
|
||||
|
||||
export function logInitialWebuiCredentials(password: string): void {
|
||||
// This is deliberately not a LogEntry: application logs can be retained on
|
||||
// disk, exported through WebUI, and delivered to subscribers. First-run
|
||||
// credentials must only cross the process terminal boundary.
|
||||
const line = render(
|
||||
'info',
|
||||
{ scope: 'WebUI' },
|
||||
format('initial credentials: user=admin password=%s', password),
|
||||
);
|
||||
// Keep the same terminal control-character policy as regular console logs.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// Request-correlation primitives remain available for callers that already own
|
||||
// an explicit request id. New semantic entrypoints should prefer
|
||||
// runWithTraceRequest() so disabled TRACE does not allocate one.
|
||||
export { nextRequestId, runWithoutRequestContext, runWithRequestId, currentRequestId };
|
||||
@@ -1,11 +1,11 @@
|
||||
export interface SendPacketResult {
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer | null;
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer | null;
|
||||
}
|
||||
|
||||
export interface PacketSender {
|
||||
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
export interface PacketInfo {
|
||||
pid: number;
|
||||
uin: string;
|
||||
packetType?: number;
|
||||
serviceCmd: string;
|
||||
seqId: number;
|
||||
retCode: number;
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
pid: number;
|
||||
uin: string;
|
||||
packetType?: number;
|
||||
serviceCmd: string;
|
||||
seqId: number;
|
||||
retCode: number;
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
}
|
||||
export type PacketSink = (packet: PacketInfo) => void;
|
||||
@@ -1,10 +1,10 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
interface RequestStore {
|
||||
id: number;
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore>();
|
||||
const storage = new AsyncLocalStorage<RequestStore | undefined>();
|
||||
let counter = 0;
|
||||
|
||||
/**
|
||||
@@ -13,9 +13,13 @@ let counter = 0;
|
||||
* unambiguous.
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
return counter;
|
||||
counter = (counter + 1) >>> 0;
|
||||
|
||||
if (counter === 0) {
|
||||
counter = 1;
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -26,10 +30,15 @@ export function nextRequestId(): number {
|
||||
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
|
||||
*/
|
||||
export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** Run `fn` without inheriting an ambient request id. */
|
||||
export function runWithoutRequestContext<T>(fn: () => T): T {
|
||||
return storage.run(undefined, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
return storage.getStore()?.id;
|
||||
}
|
||||
+325
-95
@@ -1,42 +1,71 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { isObject } from './coerce';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* 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;
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* 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. '127.0.0.1' = localhost-only (default),
|
||||
* '0.0.0.0' = all IPv4 interfaces. 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;
|
||||
/** Aggregate cap for every managed file below the log root. */
|
||||
logMaxTotalMb?: number;
|
||||
/** Calendar-day retention. Zero disables date-based deletion. */
|
||||
logRetainDays?: number;
|
||||
/** Duplicate UIN-scoped lines into logs/<uin>/ in addition to the shared log. */
|
||||
logPerUin?: boolean;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_WEBUI_PORT = 5099;
|
||||
const DEFAULT_WEBUI_HOST = '0.0.0.0';
|
||||
const DEFAULT_WEBUI_HOST = '127.0.0.1';
|
||||
export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
|
||||
export const DEFAULT_LOG_RETAIN_DAYS = 7;
|
||||
export const DEFAULT_LOG_PER_UIN = false;
|
||||
export const MAX_LOG_TOTAL_MB = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024));
|
||||
export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000));
|
||||
|
||||
/**
|
||||
* 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 : '',
|
||||
};
|
||||
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 : '',
|
||||
logMaxTotalMb: normalizeRequiredInteger(
|
||||
obj.logMaxTotalMb,
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'logMaxTotalMb',
|
||||
),
|
||||
logRetainDays: normalizeRequiredInteger(
|
||||
obj.logRetainDays,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'logRetainDays',
|
||||
),
|
||||
logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -45,36 +74,79 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
* rewriting the file). Absent vars produce no key.
|
||||
*/
|
||||
export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<RuntimeConfig> {
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
if (port !== undefined) out.webuiPort = port;
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim();
|
||||
if (port !== undefined) {
|
||||
out.webuiPort = port;
|
||||
}
|
||||
|
||||
// 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;
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
|
||||
return out;
|
||||
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;
|
||||
}
|
||||
|
||||
const logMaxTotalMb = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_TOTAL_MB',
|
||||
);
|
||||
|
||||
if (logMaxTotalMb !== undefined) {
|
||||
out.logMaxTotalMb = logMaxTotalMb;
|
||||
}
|
||||
|
||||
const logRetainDays = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
);
|
||||
|
||||
if (logRetainDays !== undefined) {
|
||||
out.logRetainDays = logRetainDays;
|
||||
}
|
||||
|
||||
const logPerUin = parseRequiredBoolEnv(env.SNOWLUMA_LOG_PER_UIN, 'SNOWLUMA_LOG_PER_UIN');
|
||||
|
||||
if (logPerUin !== undefined) {
|
||||
out.logPerUin = logPerUin;
|
||||
}
|
||||
|
||||
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
|
||||
|
||||
if (webuiTls !== undefined) {
|
||||
out.webuiTls = { enabled: webuiTls };
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
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);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,7 +154,7 @@ export function loadRuntimeConfig(): RuntimeConfig {
|
||||
* settings panel's GET — shows what's actually saved/editable on disk.
|
||||
*/
|
||||
export function readRuntimeConfig(): RuntimeConfig {
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,81 +163,239 @@ export function readRuntimeConfig(): RuntimeConfig {
|
||||
* 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;
|
||||
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 parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
|
||||
|
||||
try {
|
||||
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
|
||||
} catch (error) {
|
||||
try {
|
||||
fs.unlinkSync(temporaryPath);
|
||||
} catch (cleanupError) {
|
||||
if (!isErrnoCode(cleanupError, 'ENOENT')) {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
'failed to persist runtime config and remove its temporary file',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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
|
||||
);
|
||||
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 &&
|
||||
parsed.logMaxTotalMb === n.logMaxTotalMb &&
|
||||
parsed.logRetainDays === n.logRetainDays &&
|
||||
parsed.logPerUin === n.logPerUin
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
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;
|
||||
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);
|
||||
if (n > 0 && n <= 65535) return n;
|
||||
return fallback;
|
||||
}
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
if (port > 0 && port <= 65535) return port;
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
|
||||
if (n > 0 && n <= 65535) {
|
||||
return n;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
|
||||
if (port > 0 && port <= 65535) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizeRequiredInteger(
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
): number {
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
||||
|
||||
if (typeof n === 'number' && Number.isSafeInteger(n) && n >= min && n <= max) {
|
||||
return n;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function normalizeRequiredBool(value: unknown, fallback: boolean, field: string): boolean {
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = parseBoolValue(value);
|
||||
|
||||
if (parsed !== undefined) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
|
||||
}
|
||||
return fallback;
|
||||
if (typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return value !== 0;
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
function parseRequiredIntegerEnv(
|
||||
raw: unknown,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const n = Number(raw.trim());
|
||||
|
||||
if (Number.isSafeInteger(n) && n >= min && n <= max) {
|
||||
return n;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parsed = parseBoolValue(raw);
|
||||
|
||||
if (parsed !== undefined) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function parseBoolValue(raw: unknown): boolean | undefined {
|
||||
if (typeof raw === 'boolean') {
|
||||
return raw;
|
||||
}
|
||||
|
||||
if (raw === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (raw === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof raw !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const value = raw.trim().toLowerCase();
|
||||
|
||||
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value === 'false' || value === '0' || value === 'no' || value === 'off') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isErrnoCode(error: unknown, code: string): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === code;
|
||||
}
|
||||
@@ -16,78 +16,89 @@
|
||||
*/
|
||||
|
||||
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;
|
||||
/** 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>>();
|
||||
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);
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
this.load = opts.load;
|
||||
this.shouldCache = opts.shouldCache ?? (() => true);
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
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);
|
||||
}
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/** Drop all cached entries. Does not abort in-flight loads. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
}
|
||||
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 () => {
|
||||
const value = await this.load(key);
|
||||
|
||||
if (this.shouldCache(value)) {
|
||||
this.fresh.set(key, { at: this.now(), value });
|
||||
}
|
||||
|
||||
return value;
|
||||
})().finally(() => {
|
||||
// Run after registration even when load throws synchronously.
|
||||
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>,
|
||||
opts: SingleFlightCacheOptions<K, V>,
|
||||
): SingleFlightCache<K, V> {
|
||||
return new SingleFlightCache(opts);
|
||||
return new SingleFlightCache(opts);
|
||||
}
|
||||
@@ -7,5 +7,5 @@
|
||||
// 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);
|
||||
return /^\d{5,10}$/.test(uin);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
ACCESS_TOKEN_MIN_LENGTH,
|
||||
ACCESS_TOKEN_MIN_SCORE,
|
||||
assessAccessToken,
|
||||
} from '../src/access-token';
|
||||
|
||||
describe('access token strength', () => {
|
||||
it('requires the configured minimum length', () => {
|
||||
expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({
|
||||
acceptable: false,
|
||||
reason: 'too-short',
|
||||
});
|
||||
});
|
||||
|
||||
it('scores system and user-specific words as guessable', () => {
|
||||
expect(
|
||||
assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']),
|
||||
).toMatchObject({
|
||||
acceptable: false,
|
||||
reason: 'guessable',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts a sufficiently long, hard-to-guess token', () => {
|
||||
const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']);
|
||||
|
||||
expect(result.acceptable).toBe(true);
|
||||
expect(result.reason).toBe('acceptable');
|
||||
expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE);
|
||||
});
|
||||
});
|
||||
@@ -2,77 +2,77 @@ 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);
|
||||
});
|
||||
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);
|
||||
});
|
||||
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('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('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('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);
|
||||
});
|
||||
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('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('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('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);
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -4,65 +4,78 @@ 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;
|
||||
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]);
|
||||
});
|
||||
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;
|
||||
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]);
|
||||
});
|
||||
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;
|
||||
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);
|
||||
});
|
||||
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('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('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;
|
||||
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);
|
||||
});
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { positiveIntEnv } from '../src/env';
|
||||
|
||||
describe('positiveIntEnv', () => {
|
||||
it('returns the fallback when the variable is absent or blank', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(
|
||||
15,
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a positive integer and honors the max', () => {
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } }),
|
||||
).toBe(2500);
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: '80' },
|
||||
}),
|
||||
).toBe(80);
|
||||
});
|
||||
|
||||
it('ignores zero, negatives, fractions, and values above the max', () => {
|
||||
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: raw },
|
||||
}),
|
||||
).toBe(15);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,25 +2,25 @@ 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('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('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();
|
||||
});
|
||||
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();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -1,61 +1,230 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { renderParamsVerbose, summarizeParams } from '../src/log-summary';
|
||||
import { redactLogMessage, renderParamsVerbose, summarizeParams } from '../src/log-summary';
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders null/undefined as {}', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
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('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('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('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);
|
||||
});
|
||||
it('redacts authentication fields without exposing their values', () => {
|
||||
const out = summarizeParams({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
Authorization: 'Bearer authorization-value',
|
||||
user_password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
group_id: 12345,
|
||||
});
|
||||
|
||||
expect(out).toContain('token="***"');
|
||||
expect(out).toContain('Cookie="***"');
|
||||
expect(out).toContain('Authorization="***"');
|
||||
expect(out).toContain('user_password="***"');
|
||||
expect(out).toContain('apiKey="***"');
|
||||
expect(out).toContain('group_id=12345');
|
||||
expect(out).not.toMatch(
|
||||
/token-value|cookie-value|authorization-value|password-value|key-value/,
|
||||
);
|
||||
});
|
||||
|
||||
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
|
||||
expect(
|
||||
summarizeParams({
|
||||
retoken: 'visible',
|
||||
cookietown: 'visible',
|
||||
myauthorization: 'visible',
|
||||
}),
|
||||
).toBe('retoken="visible" cookietown="visible" myauthorization="visible"');
|
||||
});
|
||||
|
||||
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);
|
||||
expect(out.length).toBeLessThanOrEqual(200);
|
||||
});
|
||||
|
||||
it('caps a single oversized first key and top-level primitive', () => {
|
||||
const oversizedKey = 'k'.repeat(300);
|
||||
|
||||
const objectOut = summarizeParams({ [oversizedKey]: 'value' });
|
||||
const primitiveOut = summarizeParams('x'.repeat(300));
|
||||
|
||||
expect(objectOut).toHaveLength(200);
|
||||
expect(objectOut.endsWith('...')).toBe(true);
|
||||
expect(primitiveOut).toHaveLength(200);
|
||||
expect(primitiveOut.endsWith('...')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('redactLogMessage', () => {
|
||||
it('redacts explicit authentication assignments without changing prose', () => {
|
||||
const out = redactLogMessage(
|
||||
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
|
||||
);
|
||||
|
||||
expect(out).toBe('password=*** Authorization: *** cookie=*** password change required');
|
||||
});
|
||||
|
||||
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
|
||||
const out = redactLogMessage(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
const expires = redactLogMessage(
|
||||
'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible',
|
||||
);
|
||||
|
||||
expect(out).toContain('json={"authorization":***}');
|
||||
expect(out).toContain("object={ 'api-key': *** }");
|
||||
expect(out).toContain('Authorization: *** Cookie=***');
|
||||
expect(expires).toBe('Cookie=*** safe=visible');
|
||||
expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/);
|
||||
expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/);
|
||||
});
|
||||
|
||||
it('redacts complete multi-parameter Authorization values', () => {
|
||||
const out = redactLogMessage(
|
||||
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n' +
|
||||
'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, ' +
|
||||
'SignedHeaders=host;x-date, Signature=aws-secret\n' +
|
||||
'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
|
||||
);
|
||||
|
||||
expect(out).toBe('Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***');
|
||||
expect(out).not.toMatch(
|
||||
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts camelCase authentication keys without matching larger words', () => {
|
||||
const out = redactLogMessage(
|
||||
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
|
||||
);
|
||||
|
||||
expect(out).toBe(`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`);
|
||||
expect(out).not.toMatch(/auth-secret|id-secret|client-secret|password-secret/);
|
||||
expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
|
||||
expect(
|
||||
redactLogMessage(
|
||||
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
|
||||
),
|
||||
).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
|
||||
});
|
||||
|
||||
it('redacts nested assignments inside non-sensitive wrapper values', () => {
|
||||
expect(redactLogMessage('params=authToken=auth-secret params=cookie="cookie-secret"')).toBe(
|
||||
'params=authToken=*** params=cookie=***',
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts the entire Authorization value when it starts with a marker', () => {
|
||||
expect(redactLogMessage('Authorization: *** secret-value')).toBe('Authorization: ***');
|
||||
});
|
||||
|
||||
it('redacts property paths and URL query authentication values', () => {
|
||||
const out = redactLogMessage(
|
||||
'headers.authorization=Basic dXNlcjpwYXNz ' +
|
||||
'request.token=plain-token ' +
|
||||
'GET /callback?access_token=query-secret&x=1 ' +
|
||||
'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
|
||||
expect(out).toContain('headers.authorization=***');
|
||||
expect(out).toContain('request.token=***');
|
||||
expect(out).toContain('/callback?access_token=***&x=1');
|
||||
expect(out).toContain('https://host/?api_key=***');
|
||||
expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/);
|
||||
});
|
||||
|
||||
it('redacts prefixed authentication keys without matching larger words', () => {
|
||||
const redacted = redactLogMessage(
|
||||
'x-api-key=api-secret user_password=password-secret ' +
|
||||
'headers.authorization=Basic auth-secret ' +
|
||||
'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
|
||||
);
|
||||
|
||||
expect(redacted).toContain('x-api-key=***');
|
||||
expect(redacted).toContain('user_password=***');
|
||||
expect(redacted).toContain('headers.authorization=***');
|
||||
expect(redacted).toContain('x-cookie=***');
|
||||
expect(redacted).not.toMatch(
|
||||
/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/,
|
||||
);
|
||||
expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
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('keeps authentication fields unredacted for complete TRACE diagnostics', () => {
|
||||
const out = renderParamsVerbose({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
});
|
||||
|
||||
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>');
|
||||
});
|
||||
expect(out).toContain('token:"token-value"');
|
||||
expect(out).toContain('Cookie:"cookie-value"');
|
||||
expect(out).toContain('password:"password-value"');
|
||||
expect(out).toContain('apiKey:"key-value"');
|
||||
expect(out).not.toContain('"***"');
|
||||
});
|
||||
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
it('does not truncate TRACE values or their enclosing object', () => {
|
||||
const unicodeValue = '雪'.repeat(800);
|
||||
const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' });
|
||||
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`);
|
||||
expect(out).toContain('tail:"complete"');
|
||||
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
|
||||
});
|
||||
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
|
||||
it('renders shared non-cyclic references in every branch', () => {
|
||||
const shared = { value: 1 };
|
||||
|
||||
expect(renderParamsVerbose({ left: shared, right: shared })).toBe(
|
||||
'{left:{value:1},right:{value:1}}',
|
||||
);
|
||||
});
|
||||
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
});
|
||||
@@ -1,45 +1,338 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// The file transport writes to disk; stub it so the test has no side effects.
|
||||
const { externalFileLevel, externalLogLevel, fileWriteSpy } = vi.hoisted(() => {
|
||||
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
return {
|
||||
externalFileLevel: savedFileLevel,
|
||||
externalLogLevel: savedLogLevel,
|
||||
fileWriteSpy: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
// Capture file transport writes via a spy so tests can assert on what reaches
|
||||
// the file.
|
||||
vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: () => {} }),
|
||||
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
|
||||
}));
|
||||
|
||||
import { createLogger } from '../src/logger';
|
||||
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;
|
||||
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);
|
||||
});
|
||||
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();
|
||||
});
|
||||
afterEach(() => {
|
||||
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||
|
||||
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();
|
||||
});
|
||||
if (prevNoColor === undefined) {
|
||||
delete process.env.NO_COLOR;
|
||||
} else {
|
||||
process.env.NO_COLOR = prevNoColor;
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
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('does not throw when the console stream cannot accept the line', () => {
|
||||
vi.mocked(process.stderr.write).mockImplementation(() => {
|
||||
throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });
|
||||
});
|
||||
expect(() => createLogger('Test').error('disk is full')).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['));
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Independent file-level filtering ─────────────────────────────────────
|
||||
|
||||
const SAVED_FILE_LEVEL = externalFileLevel;
|
||||
|
||||
async function loadLoggerForFileLevel(level?: string) {
|
||||
if (level === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
return import('../src/logger');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
}
|
||||
|
||||
if (externalLogLevel === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
|
||||
}
|
||||
});
|
||||
|
||||
describe('file output gating', () => {
|
||||
const cases = [
|
||||
{ level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'info', expected: ['info', 'success', 'warn', 'error'] },
|
||||
{ level: 'success', expected: ['success', 'warn', 'error'] },
|
||||
{ level: 'warn', expected: ['warn', 'error'] },
|
||||
{ level: 'error', expected: ['error'] },
|
||||
] as const;
|
||||
|
||||
for (const testCase of cases) {
|
||||
it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => {
|
||||
const fresh = await loadLoggerForFileLevel(testCase.level);
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('trace');
|
||||
log.trace('trace');
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
log.success('success');
|
||||
log.warn('warn');
|
||||
log.error('error');
|
||||
|
||||
const messages = fileWriteSpy.mock.calls.map(([line]) =>
|
||||
String(line).split('] ').at(-1),
|
||||
);
|
||||
expect(messages).toEqual(testCase.expected);
|
||||
});
|
||||
}
|
||||
|
||||
it('accepts surrounding whitespace and mixed case', async () => {
|
||||
const fresh = await loadLoggerForFileLevel(' INFO ');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined);
|
||||
});
|
||||
|
||||
it.each(['trace', 'verbose', 'erorr'])(
|
||||
'rejects unsupported file level %s at startup',
|
||||
async (level) => {
|
||||
await expect(loadLoggerForFileLevel(level)).rejects.toThrow(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let the runtime console level change file output', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('info');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('error');
|
||||
log.info('persisted-info');
|
||||
fresh.setLogLevel('trace');
|
||||
log.debug('filtered-debug');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('persisted-info'),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('skips rendering when both console and file filters reject a record', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const rendered = vi.fn(() => 'expensive');
|
||||
const value = { [Symbol.toPrimitive]: rendered };
|
||||
|
||||
fresh.createLogger('Test').debug('value=%s', value);
|
||||
|
||||
expect(rendered).not.toHaveBeenCalled();
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps trace out of files in an explicit file-threshold check', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
fresh.createLogger('Test').trace('full chain');
|
||||
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redacts authentication assignments from ordinary logs but not TRACE', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.info(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s',
|
||||
'ordinary-password',
|
||||
'ordinary-authorization',
|
||||
'ordinary-cookie',
|
||||
'ordinary-token',
|
||||
'visible',
|
||||
);
|
||||
log.trace(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s',
|
||||
'trace-password',
|
||||
'trace-authorization',
|
||||
'trace-cookie',
|
||||
'trace-token',
|
||||
);
|
||||
log.info(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
log.info(
|
||||
'headers.authorization=Basic dotted-auth request.token=dotted-token ' +
|
||||
'GET /callback?access_token=query-secret&x=1 ' +
|
||||
'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
log.info(
|
||||
'Authorization: Digest username="alice", response="digest-secret"\n' +
|
||||
'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
|
||||
);
|
||||
log.info(
|
||||
'authToken=camel-auth idToken=camel-id clientSecret=camel-client ' +
|
||||
`json={"userPassword":"camel-password"}`,
|
||||
);
|
||||
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
|
||||
log.info('Authorization: *** marker-secret');
|
||||
log.trace(
|
||||
`json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`,
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
const ordinaryEntries = entries.filter((entry) => entry.level === 'info');
|
||||
const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n');
|
||||
expect(ordinary).toContain('password=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('Cookie=***');
|
||||
expect(ordinary).toContain('token=***');
|
||||
expect(ordinary).toContain('headers.authorization=***');
|
||||
expect(ordinary).toContain('request.token=***');
|
||||
expect(ordinary).toContain('/callback?access_token=***&x=1');
|
||||
expect(ordinary).toContain('https://host/?api_key=***');
|
||||
expect(ordinary).toContain('Authorization: ***\nauthorization=***');
|
||||
expect(ordinary).toContain('authToken=***');
|
||||
expect(ordinary).toContain('idToken=***');
|
||||
expect(ordinary).toContain('clientSecret=***');
|
||||
expect(ordinary).toContain(`json={"userPassword":***}`);
|
||||
expect(ordinary).toContain('_token=***');
|
||||
expect(ordinary).toContain('--password=***');
|
||||
expect(ordinary).toContain('2faToken=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('safe=visible');
|
||||
expect(ordinary).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
|
||||
);
|
||||
|
||||
const trace = entries
|
||||
.filter((entry) => entry.level === 'trace')
|
||||
.map((entry) => entry.message)
|
||||
.join('\n');
|
||||
expect(trace).toContain('trace-password');
|
||||
expect(trace).toContain('trace-authorization');
|
||||
expect(trace).toContain('trace-cookie');
|
||||
expect(trace).toContain('trace-token');
|
||||
expect(trace).toContain('trace-json-auth');
|
||||
expect(trace).toContain('trace-header-auth');
|
||||
|
||||
const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n');
|
||||
expect(persisted).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the complete retained normal and TRACE snapshot in record order', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
const log = fresh.createLogger('Export');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
log.info('normal-before');
|
||||
log.trace('trace-hex=001122aabbcc');
|
||||
log.warn('normal-after');
|
||||
|
||||
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual(['normal-after']);
|
||||
expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'normal-before',
|
||||
'trace-hex=001122aabbcc',
|
||||
'normal-after',
|
||||
]);
|
||||
});
|
||||
|
||||
it('prints bootstrap credentials only to the current process terminal', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const snapshotBefore = fresh.getLogSnapshot();
|
||||
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
|
||||
try {
|
||||
fresh.logInitialWebuiCredentials('secret');
|
||||
|
||||
expect(stdout).toHaveBeenCalledWith(
|
||||
expect.stringContaining('initial credentials: user=admin password=secret'),
|
||||
);
|
||||
expect(entries).toEqual([]);
|
||||
expect(fresh.getLogSnapshot()).toEqual(snapshotBefore);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
unsubscribe();
|
||||
stdout.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,33 +2,33 @@ 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
|
||||
it('nextRequestId increments monotonically and stays a positive integer', () => {
|
||||
const a = nextRequestId();
|
||||
const b = nextRequestId();
|
||||
expect(a).toBeGreaterThan(0);
|
||||
expect(b).toBe(a + 1);
|
||||
});
|
||||
|
||||
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
|
||||
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
await runWithRequestId(7, async () => {
|
||||
await Promise.resolve();
|
||||
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
|
||||
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');
|
||||
});
|
||||
it('returns the callback result', () => {
|
||||
expect(runWithRequestId(1, () => 'value')).toBe('value');
|
||||
});
|
||||
});
|
||||
@@ -1,117 +1,229 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } 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('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
logMaxTotalMb: 1024,
|
||||
logRetainDays: 7,
|
||||
logPerUin: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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('passes through valid values', () => {
|
||||
expect(
|
||||
normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
}),
|
||||
).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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
|
||||
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('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
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('fails fast on invalid persisted log settings', () => {
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 })).toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 })).toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' })).toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: '' })).toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER })).toThrow(
|
||||
/logMaxTotalMb/,
|
||||
);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER })).toThrow(
|
||||
/logRetainDays/,
|
||||
);
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
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('127.0.0.1');
|
||||
});
|
||||
|
||||
it('rejects a non-object input back to full defaults', () => {
|
||||
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRuntimeEnvOverrides', () => {
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
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('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('parses log storage overrides including retainDays=0', () => {
|
||||
expect(
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '0',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
}),
|
||||
).toEqual({
|
||||
logMaxTotalMb: 4096,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
|
||||
});
|
||||
it('fails fast on invalid log storage overrides', () => {
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_PER_UIN: 'maybe',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_PER_UIN/);
|
||||
});
|
||||
|
||||
it('fails fast when converted log storage overrides would be unsafe', () => {
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
|
||||
webuiTls: { enabled: true },
|
||||
});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
|
||||
webuiTls: { enabled: false },
|
||||
});
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' })).toThrow(
|
||||
/SNOWLUMA_WEBUI_TLS/,
|
||||
);
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
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 () => {
|
||||
process.chdir(prevCwd);
|
||||
|
||||
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 });
|
||||
});
|
||||
if (prevPortEnv === undefined) {
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
} else {
|
||||
process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
}
|
||||
|
||||
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
|
||||
});
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
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
|
||||
});
|
||||
|
||||
it('keeps the previous runtime file intact when atomic replacement fails', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
updateRuntimeConfig({ logRetainDays: 7 });
|
||||
const runtimePath = path.join('config', 'runtime.json');
|
||||
const before = fs.readFileSync(runtimePath, 'utf8');
|
||||
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
|
||||
});
|
||||
|
||||
expect(() => updateRuntimeConfig({ logRetainDays: 0 })).toThrow(/disk replacement failed/);
|
||||
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
|
||||
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,129 +3,162 @@ 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 };
|
||||
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 });
|
||||
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);
|
||||
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';
|
||||
clock = 1101; // 101ms since store → expired
|
||||
expect(await cache.get('a')).toBe('a@1101');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
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);
|
||||
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 });
|
||||
|
||||
// in-flight cleared + not cached → next call retries and succeeds.
|
||||
expect(await cache.get('k')).toBe('ok');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
const p3 = cache.get('k');
|
||||
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
|
||||
|
||||
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);
|
||||
d.resolve('v');
|
||||
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
cache.invalidate('a');
|
||||
await cache.get('a'); // reloads
|
||||
await cache.get('b'); // still cached
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
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);
|
||||
});
|
||||
|
||||
cache.clear();
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
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);
|
||||
});
|
||||
|
||||
it('allows retry when a loader throws before returning its promise', async () => {
|
||||
const load = vi
|
||||
.fn<() => Promise<string>>()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error('failed before request');
|
||||
})
|
||||
.mockResolvedValue('recovered');
|
||||
const cache = createSingleFlightCache({ ttlMs: 1000, load });
|
||||
|
||||
await expect(cache.get('key')).rejects.toThrow('failed before request');
|
||||
await expect(cache.get('key')).resolves.toBe('recovered');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
createLogger,
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
nextRequestId,
|
||||
renderTraceBytes,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
runWithTraceRequest,
|
||||
setLogLevel,
|
||||
} from '../src/logger';
|
||||
|
||||
const originalLevel = getLogLevel();
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(originalLevel);
|
||||
});
|
||||
|
||||
describe('TRACE diagnostics contract', () => {
|
||||
it('renders every byte as continuous lowercase hexadecimal', () => {
|
||||
expect(renderTraceBytes(new Uint8Array())).toBe('');
|
||||
expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff]))).toBe('00010f10ff');
|
||||
});
|
||||
|
||||
it('renders only the addressed Uint8Array view', () => {
|
||||
const backing = new Uint8Array([0xaa, 0x00, 0x0f, 0xff, 0xbb]);
|
||||
|
||||
expect(renderTraceBytes(backing.subarray(1, 4))).toBe('000fff');
|
||||
expect(renderTraceBytes(Buffer.from(backing.buffer).subarray(2, 4))).toBe('0fff');
|
||||
});
|
||||
|
||||
it('does not render bytes while TRACE is disabled', () => {
|
||||
setLogLevel('info');
|
||||
let rendered = false;
|
||||
|
||||
createLogger('Trace.Contract').trace(() => {
|
||||
rendered = true;
|
||||
return ['body=%s', renderTraceBytes(new Uint8Array([0xff]))];
|
||||
});
|
||||
|
||||
expect(rendered).toBe(false);
|
||||
});
|
||||
|
||||
it('creates distinct request contexts that survive asynchronous work', async () => {
|
||||
setLogLevel('info');
|
||||
const beforeDisabled = nextRequestId();
|
||||
expect(runWithTraceRequest(() => currentRequestId())).toBeUndefined();
|
||||
const afterDisabled = nextRequestId();
|
||||
expect(afterDisabled).toBe(beforeDisabled + 1);
|
||||
|
||||
setLogLevel('trace');
|
||||
const observeContext = () =>
|
||||
runWithTraceRequest(async () => {
|
||||
const before = currentRequestId();
|
||||
await Promise.resolve();
|
||||
const after = currentRequestId();
|
||||
expect(after).toBe(before);
|
||||
return after;
|
||||
});
|
||||
|
||||
const first = await observeContext();
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
const second = await observeContext();
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
expect(first).toEqual(expect.any(Number));
|
||||
expect(first).toBeGreaterThan(0);
|
||||
expect(second).toEqual(expect.any(Number));
|
||||
expect(second).toBeGreaterThan(0);
|
||||
expect(second).not.toBe(first);
|
||||
});
|
||||
|
||||
it('allocates once for nested TRACE contexts and reuses the request id', () => {
|
||||
setLogLevel('trace');
|
||||
const before = nextRequestId();
|
||||
|
||||
const observed = runWithTraceRequest(() => {
|
||||
const outer = currentRequestId();
|
||||
const inner = runWithTraceRequest(() => currentRequestId());
|
||||
return { outer, inner };
|
||||
});
|
||||
|
||||
const after = nextRequestId();
|
||||
expect(observed.outer).toEqual(expect.any(Number));
|
||||
expect(observed.inner).toBe(observed.outer);
|
||||
expect(observed.outer).toBe(before + 1);
|
||||
expect(after).toBe(before + 2);
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('detaches long-lived resources from the current request context', async () => {
|
||||
await runWithRequestId(4243, async () => {
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
const detached = await runWithoutRequestContext(async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(detached).toBeUndefined();
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
});
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reuses an existing request context even while TRACE is disabled', async () => {
|
||||
setLogLevel('info');
|
||||
|
||||
await runWithRequestId(4242, async () => {
|
||||
const observed = await runWithTraceRequest(async () => {
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(observed).toBe(4242);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,39 +2,39 @@ 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('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 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 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 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('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();
|
||||
});
|
||||
it('guarantees a BigInt-safe pure-digit string on accept', () => {
|
||||
const uin = '123456789';
|
||||
expect(isRealUin(uin)).toBe(true);
|
||||
expect(() => BigInt(uin)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.11.3",
|
||||
"version": "1.14.22",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -44,21 +44,26 @@
|
||||
"@snowluma/bridge": "workspace:*",
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/onebot": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
"@snowluma/websocket": "workspace:*",
|
||||
"otpauth": "^9.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hono/node-server": "^1.19.14",
|
||||
"@hono/node-server": "^1.19.15",
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.25",
|
||||
"hono": "^4.12.34",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vite-plugin-cp": "^6.0.3",
|
||||
"vitest": "^4.1.4"
|
||||
"vitest": "^4.1.4",
|
||||
"@snowluma/sqlite": "workspace:*"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
@@ -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,257 +1,617 @@
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
|
||||
import {
|
||||
FetchFriendListPage,
|
||||
type FriendListPageCategory,
|
||||
type FriendListPageEntry,
|
||||
} 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 {
|
||||
FetchGroupRequests,
|
||||
FetchGroupRequestsByUid,
|
||||
groupRequestOperationType,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import {
|
||||
FetchRobotUinRanges,
|
||||
type RobotUinRange,
|
||||
type RobotUinRangeSnapshot,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
|
||||
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 {
|
||||
fetchQidianCorpInfo as fetchQidianCorpInfoWire,
|
||||
type QidianCorpInfo,
|
||||
} from '@snowluma/protocol/services/qidian/fetch-corp-info';
|
||||
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 { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
import {
|
||||
SendTuwenArk,
|
||||
type SendTuwenArkParams,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/send-tuwen-ark';
|
||||
import { SetFriendCategory } from '@snowluma/protocol/oidb-services/contacts/set-friend-category';
|
||||
import { toHex } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
createSingleFlightCache,
|
||||
type SingleFlightCache,
|
||||
} from '@snowluma/common/single-flight-cache';
|
||||
import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
FriendCategoryInfo,
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '@snowluma/protocol/qq-info';
|
||||
import type { DownloadRKeyInfo } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
|
||||
const log = createLogger('Bridge.Contacts');
|
||||
|
||||
type FriendPropertySource = {
|
||||
additional?: Array<{
|
||||
type?: number;
|
||||
layer1?: {
|
||||
properties?: Array<{
|
||||
code?: number;
|
||||
value?: string;
|
||||
}>;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
|
||||
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
|
||||
const props = new Map<number, string>();
|
||||
for (const additional of raw.additional ?? []) {
|
||||
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
|
||||
for (const property of additional.layer1.properties ?? []) {
|
||||
props.set(property.code ?? 0, property.value ?? '');
|
||||
}
|
||||
}
|
||||
return props;
|
||||
// Official client stores group mute as an expire timestamp (internal 60027 /
|
||||
// JS groupShutupExpireTime): 0 = off, 0xFFFFFFFF = permanent, otherwise unix
|
||||
// seconds. `> 0` is wrong — a leftover past expire still looks "on".
|
||||
function isGroupAllMuted(expireTs?: number, nowSec = Math.floor(Date.now() / 1000)): boolean {
|
||||
return (expireTs ?? 0) > nowSec;
|
||||
}
|
||||
|
||||
export function permissionToRole(permission: number): string {
|
||||
switch (permission) {
|
||||
case 1: return 'owner';
|
||||
case 2: return 'admin';
|
||||
default: return 'member';
|
||||
}
|
||||
interface FriendRoster {
|
||||
entries: FriendListPageEntry[];
|
||||
categories: FriendListPageCategory[];
|
||||
}
|
||||
|
||||
export interface SetFriendCategoryParams {
|
||||
uin: number;
|
||||
categoryId?: number;
|
||||
categoryName?: string;
|
||||
}
|
||||
|
||||
export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boolean {
|
||||
return (
|
||||
Number.isInteger(uin) &&
|
||||
uin > 0 &&
|
||||
ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin)
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeGroupRequestSequence(
|
||||
rawSequence: bigint | number | undefined,
|
||||
groupId: number,
|
||||
): number {
|
||||
const sequence = Number(rawSequence ?? 0);
|
||||
|
||||
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
|
||||
throw new Error(
|
||||
`invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`,
|
||||
);
|
||||
}
|
||||
|
||||
return sequence;
|
||||
}
|
||||
|
||||
const MEMBER_LIST_TTL_MS = 60_000;
|
||||
|
||||
export class ContactsApi {
|
||||
/**
|
||||
* 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 readonly memberListCache: SingleFlightCache<number, GroupMemberInfo[]> =
|
||||
createSingleFlightCache({
|
||||
ttlMs: MEMBER_LIST_TTL_MS,
|
||||
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
|
||||
});
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
/** 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 });
|
||||
}
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const friends: FriendInfo[] = [];
|
||||
let nextUin: number | null = null;
|
||||
do {
|
||||
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
|
||||
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) ?? '',
|
||||
/**
|
||||
* 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 readonly memberListCache: SingleFlightCache<number, GroupMemberInfo[]> =
|
||||
createSingleFlightCache({
|
||||
ttlMs: MEMBER_LIST_TTL_MS,
|
||||
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
|
||||
});
|
||||
}
|
||||
nextUin = resp.next?.uin ?? null;
|
||||
if (nextUin === 0) nextUin = null;
|
||||
} while (nextUin !== null);
|
||||
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
|
||||
/** groupUin → approval msgseq from a private qun.invite card. Written
|
||||
* only by IncomingPacketPipeline (and tests). OneBot reads get/find. */
|
||||
private readonly groupInviteCardSeqs_ = new Map<number, number>();
|
||||
|
||||
this.ctx.identity.rememberFriends(friends);
|
||||
return friends;
|
||||
}
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> {
|
||||
const resp = await FetchGroupList.invoke(this.ctx);
|
||||
const groups: QQGroupInfo[] = [];
|
||||
for (const raw of resp.groups ?? []) {
|
||||
groups.push({
|
||||
groupId: raw.groupUin ?? 0,
|
||||
groupName: raw.info?.groupName ?? '',
|
||||
remark: raw.customInfo?.remark ?? '',
|
||||
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;
|
||||
}
|
||||
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
|
||||
if (this.robotUinRangesPromise_) {
|
||||
return this.robotUinRangesPromise_;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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[]> {
|
||||
return this.memberListCache.get(groupId, { force: options.force });
|
||||
}
|
||||
|
||||
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
do {
|
||||
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
|
||||
for (const raw of resp.members ?? []) {
|
||||
members.push({
|
||||
uin: raw.uin?.uin ?? 0,
|
||||
uid: raw.uin?.uid ?? '',
|
||||
nickname: raw.memberName ?? '',
|
||||
card: raw.memberCard?.memberCard ?? '',
|
||||
role: permissionToRole(raw.permission ?? 0),
|
||||
level: raw.level?.level ?? 0,
|
||||
title: raw.specialTitle ?? '',
|
||||
joinTime: raw.joinTimestamp ?? 0,
|
||||
lastSentTime: raw.lastMsgTimestamp ?? 0,
|
||||
shutUpTime: raw.shutUpTimestamp ?? 0,
|
||||
const pending = FetchRobotUinRanges.invoke(this.ctx).then((snapshot) => {
|
||||
log.info(
|
||||
'loaded robot UIN ranges uin=%s version=%d count=%d',
|
||||
this.ctx.identity.uin,
|
||||
snapshot.version,
|
||||
snapshot.ranges.length,
|
||||
);
|
||||
return snapshot;
|
||||
});
|
||||
}
|
||||
token = resp.token ?? '';
|
||||
} while (token);
|
||||
this.robotUinRangesPromise_ = pending;
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
}
|
||||
// A failed first load must be observable and retryable. Keep the rejection
|
||||
// visible to the caller instead of converting every member to false.
|
||||
void pending.catch((err: unknown) => {
|
||||
if (this.robotUinRangesPromise_ === pending) {
|
||||
this.robotUinRangesPromise_ = null;
|
||||
}
|
||||
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfile.invoke(this.ctx, { uin });
|
||||
this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
/** Look up a user profile by UID (string form). Used for strangers
|
||||
* whose UIN we don't have yet — typically the requester on a
|
||||
* group join request push. Mirrors Lagrange's `FetchUserInfoEvent
|
||||
* .Create(targetUid)` path. */
|
||||
async fetchUserProfileByUid(uid: string): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfileByUid.invoke(this.ctx, { uid });
|
||||
if (info.uin > 0) this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
for (const raw of resp.requests ?? []) {
|
||||
requests.push({
|
||||
groupId: raw.group?.groupUin ?? 0,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid: raw.target?.uid ?? '',
|
||||
targetUin: 0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid: raw.invitor?.uid ?? '',
|
||||
invitorUin: 0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid: raw.operatorUser?.uid ?? '',
|
||||
operatorUin: 0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence: Number(raw.sequence ?? 0),
|
||||
state: raw.state ?? 0,
|
||||
eventType: raw.eventType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
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);
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
const result: DownloadRKeyInfo[] = [];
|
||||
for (const entry of resp.downloadRkey?.rkeys ?? []) {
|
||||
const rkey = entry.rkey ?? '';
|
||||
const type = entry.type ?? 0;
|
||||
if (rkey && type) {
|
||||
result.push({
|
||||
rkey,
|
||||
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
|
||||
storeId: entry.storeId ?? 0,
|
||||
createTime: entry.rkeyCreateTime ?? 0,
|
||||
type,
|
||||
log.error(
|
||||
'failed to load robot UIN ranges: uin=%s group=%d err=%s',
|
||||
this.ctx.identity.uin,
|
||||
groupId,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
});
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** 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 });
|
||||
}
|
||||
|
||||
/** Send a custom 图文 ark card to a C2C peer or group (0xdc2_34). */
|
||||
sendTuwenArk(params: SendTuwenArkParams): Promise<void> {
|
||||
return SendTuwenArk.invoke(this.ctx, params);
|
||||
}
|
||||
|
||||
private async fetchFriendRoster(): Promise<FriendRoster> {
|
||||
const entries: FriendListPageEntry[] = [];
|
||||
const categories = new Map<number, FriendListPageCategory>();
|
||||
const seenCookies = new Set<string>();
|
||||
let cookie: Uint8Array | undefined;
|
||||
|
||||
for (;;) {
|
||||
const page = await FetchFriendListPage.invoke(this.ctx, { cookie });
|
||||
entries.push(...page.entries);
|
||||
|
||||
for (const category of page.categories) {
|
||||
categories.set(category.categoryId, category);
|
||||
}
|
||||
|
||||
const next = page.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 { 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 setFriendCategory(params: SetFriendCategoryParams): Promise<void> {
|
||||
const selectorCount =
|
||||
Number(params.categoryId !== undefined) + Number(params.categoryName !== undefined);
|
||||
|
||||
if (selectorCount !== 1) {
|
||||
throw new Error('exactly one of categoryId or categoryName is required');
|
||||
}
|
||||
|
||||
const categories = await this.fetchFriendCategories();
|
||||
const friendCategory = categories.find((category) =>
|
||||
category.friends.some((friend) => friend.uin === params.uin),
|
||||
);
|
||||
const friend = friendCategory?.friends.find((entry) => entry.uin === params.uin);
|
||||
|
||||
if (!friend) {
|
||||
throw new Error(`friend ${params.uin} is not in the live roster`);
|
||||
}
|
||||
|
||||
if (!friend.uid) {
|
||||
throw new Error(`friend ${params.uin} has no UID in the live roster`);
|
||||
}
|
||||
|
||||
let target: FriendCategoryInfo | undefined;
|
||||
|
||||
if (params.categoryId !== undefined) {
|
||||
target = categories.find((category) => category.categoryId === params.categoryId);
|
||||
|
||||
if (!target) {
|
||||
throw new Error(`friend category ${params.categoryId} does not exist`);
|
||||
}
|
||||
} else {
|
||||
const matches = categories.filter(
|
||||
(category) => category.categoryName === params.categoryName,
|
||||
);
|
||||
|
||||
if (matches.length === 0) {
|
||||
throw new Error(`friend category name "${params.categoryName}" does not exist`);
|
||||
}
|
||||
|
||||
if (matches.length > 1) {
|
||||
throw new Error(`friend category name "${params.categoryName}" is ambiguous`);
|
||||
}
|
||||
|
||||
target = matches[0]!;
|
||||
}
|
||||
|
||||
await SetFriendCategory.invoke(this.ctx, {
|
||||
uid: friend.uid,
|
||||
categoryId: target.categoryId,
|
||||
});
|
||||
log.info(
|
||||
'friend category updated: uin=%s friend=%d category=%d',
|
||||
this.ctx.identity.uin,
|
||||
params.uin,
|
||||
target.categoryId,
|
||||
);
|
||||
}
|
||||
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> {
|
||||
const resp = await FetchGroupList.invoke(this.ctx);
|
||||
const groups: QQGroupInfo[] = [];
|
||||
|
||||
for (const raw of resp.groups ?? []) {
|
||||
groups.push({
|
||||
groupId: raw.groupUin ?? 0,
|
||||
groupName: raw.info?.groupName ?? '',
|
||||
remark: raw.customInfo?.remark ?? '',
|
||||
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 || '',
|
||||
// #490: expose the description alongside `memo`. QQ fills in either
|
||||
// field alone, so folding both into `memo` made the description
|
||||
// unreachable whenever an announcement was also set.
|
||||
description: raw.info?.description ?? '',
|
||||
allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp),
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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). `description` is deliberately
|
||||
// left unset — 0x88D_0 has no description tag, so for a group the bot
|
||||
// hasn't joined there is nothing to report (#490).
|
||||
createTime: Number(r.createTime ?? 0n),
|
||||
level: Number(r.level ?? 0n),
|
||||
memo: r.noticePreview ?? '',
|
||||
allMuted: isGroupAllMuted(r.shutUpAllTimestamp),
|
||||
};
|
||||
}
|
||||
|
||||
fetchGroupMemberList(
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> {
|
||||
return this.memberListCache.get(groupId, { force: options.force });
|
||||
}
|
||||
|
||||
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
// QQ's native group service obtains the robot classification separately
|
||||
// from 0xFE7_3. Start both reads together so the metadata adds no serial
|
||||
// round trip to paginated member fetches.
|
||||
const robotSnapshotPromise = this.fetchRobotUinRanges(groupId);
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
|
||||
do {
|
||||
const page = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
|
||||
members.push(...page.members);
|
||||
token = page.token;
|
||||
} while (token);
|
||||
|
||||
const robotSnapshot = await robotSnapshotPromise;
|
||||
|
||||
for (const member of members) {
|
||||
member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges);
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
}
|
||||
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfile.invoke(this.ctx, { uin });
|
||||
this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
/** Look up a user profile by UID (string form). Used for strangers
|
||||
* whose UIN we don't have yet — typically the requester on a
|
||||
* group join request push. Mirrors Lagrange's `FetchUserInfoEvent
|
||||
* .Create(targetUid)` path. */
|
||||
async fetchUserProfileByUid(uid: string): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfileByUid.invoke(this.ctx, { uid });
|
||||
|
||||
if (info.uin > 0) {
|
||||
this.ctx.identity.rememberUserProfile(info);
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
/** 企点企业资料卡(#404 后续 PR)。仅在判断命中的是企点账号后再调用。
|
||||
* best-effort:非企点账号或拉取失败返回 null,不影响上层资料读取。 */
|
||||
async fetchQidianCorpInfo(uin: number): Promise<QidianCorpInfo | null> {
|
||||
return fetchQidianCorpInfoWire(this.ctx, uin);
|
||||
}
|
||||
|
||||
async fetchGroupRequests(
|
||||
filtered = false,
|
||||
count = 50,
|
||||
cursor = 0n,
|
||||
): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered, count, cursor });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
|
||||
for (const raw of resp.requests ?? []) {
|
||||
const groupId = raw.group?.groupUin ?? 0;
|
||||
const targetUin = raw.target?.uin ?? 0;
|
||||
const invitorUin = raw.invitor?.uin ?? 0;
|
||||
const operatorUin = raw.operatorUser?.uin ?? 0;
|
||||
const targetUid =
|
||||
raw.target?.uid ||
|
||||
this.ctx.identity.findUidByUin(targetUin, groupId) ||
|
||||
this.ctx.identity.findUidByUin(targetUin) ||
|
||||
'';
|
||||
const invitorUid =
|
||||
raw.invitor?.uid ||
|
||||
this.ctx.identity.findUidByUin(invitorUin, groupId) ||
|
||||
this.ctx.identity.findUidByUin(invitorUin) ||
|
||||
'';
|
||||
const operatorUid =
|
||||
raw.operatorUser?.uid ||
|
||||
this.ctx.identity.findUidByUin(operatorUin, groupId) ||
|
||||
this.ctx.identity.findUidByUin(operatorUin) ||
|
||||
'';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
groupId,
|
||||
String(raw.sequence ?? 0n),
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
|
||||
requests.push({
|
||||
groupId,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid,
|
||||
targetUin:
|
||||
targetUin ||
|
||||
this.ctx.identity.findUinByUid(targetUid, groupId) ||
|
||||
this.ctx.identity.findUinByUid(targetUid) ||
|
||||
0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid,
|
||||
invitorUin:
|
||||
invitorUin ||
|
||||
this.ctx.identity.findUinByUid(invitorUid, groupId) ||
|
||||
this.ctx.identity.findUinByUid(invitorUid) ||
|
||||
0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid,
|
||||
operatorUin:
|
||||
operatorUin ||
|
||||
this.ctx.identity.findUinByUid(operatorUid, groupId) ||
|
||||
this.ctx.identity.findUinByUid(operatorUid) ||
|
||||
0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
notifyType,
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo:
|
||||
raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** UID-form request list retained for correlating incoming UID-only pushes.
|
||||
* Explicit list/actions use fetchGroupRequests(), which matches QQ's native
|
||||
* numeric-account path and does not need profile lookups. */
|
||||
async fetchGroupRequestsByUid(
|
||||
filtered = false,
|
||||
count = 50,
|
||||
cursor = 0n,
|
||||
): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequestsByUid.invoke(this.ctx, { filtered, count, cursor });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
|
||||
for (const raw of resp.requests ?? []) {
|
||||
const groupId = raw.group?.groupUin ?? 0;
|
||||
const targetUid = raw.target?.uid ?? '';
|
||||
const invitorUid = raw.invitor?.uid ?? '';
|
||||
const operatorUid = raw.operatorUser?.uid ?? '';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
groupId,
|
||||
String(raw.sequence ?? 0n),
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
|
||||
requests.push({
|
||||
groupId,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid,
|
||||
targetUin:
|
||||
this.ctx.identity.findUinByUid(targetUid, groupId) ??
|
||||
this.ctx.identity.findUinByUid(targetUid) ??
|
||||
0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid,
|
||||
invitorUin:
|
||||
this.ctx.identity.findUinByUid(invitorUid, groupId) ??
|
||||
this.ctx.identity.findUinByUid(invitorUid) ??
|
||||
0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid,
|
||||
operatorUin:
|
||||
this.ctx.identity.findUinByUid(operatorUid, groupId) ??
|
||||
this.ctx.identity.findUinByUid(operatorUid) ??
|
||||
0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
notifyType,
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo:
|
||||
raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** Live observation write. IncomingPacketPipeline and tests only. */
|
||||
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
|
||||
if (groupUin > 0 && sequence > 0) {
|
||||
this.groupInviteCardSeqs_.set(groupUin, sequence);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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.groupInviteCardSeqs_.get(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 {
|
||||
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
|
||||
if (rememberedSequence === sequence) {
|
||||
return groupUin;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
const result: DownloadRKeyInfo[] = [];
|
||||
|
||||
for (const entry of resp.downloadRkey?.rkeys ?? []) {
|
||||
const rkey = entry.rkey ?? '';
|
||||
const type = entry.type ?? 0;
|
||||
|
||||
if (rkey && type) {
|
||||
result.push({
|
||||
rkey,
|
||||
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
|
||||
storeId: entry.storeId ?? 0,
|
||||
createTime: entry.rkeyCreateTime ?? 0,
|
||||
type,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,21 @@
|
||||
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
|
||||
import {
|
||||
FetchAiVoiceList,
|
||||
type AiVoiceCategory as NamespaceAiVoiceCategory,
|
||||
FetchAiVoiceList,
|
||||
type AiVoiceCategory as NamespaceAiVoiceCategory,
|
||||
} 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 {
|
||||
GetStrangerStatus,
|
||||
type StrangerStatus as NamespaceStrangerStatus,
|
||||
} from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import {
|
||||
GetGroupTodoList,
|
||||
type GroupTodoListItem as NamespaceGroupTodoListItem,
|
||||
} from '@snowluma/protocol/oidb-services/extras/get-group-todo-list';
|
||||
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';
|
||||
@@ -17,168 +25,413 @@ import type { MediaIndexNode } from './shared';
|
||||
* 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;
|
||||
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;
|
||||
export type GroupTodoListItem = NamespaceGroupTodoListItem;
|
||||
|
||||
export const AiVoiceChatType = {
|
||||
Unknown: 0,
|
||||
Sound: 1,
|
||||
Sing: 2,
|
||||
Unknown: 0,
|
||||
Sound: 1,
|
||||
Sing: 2,
|
||||
} as const;
|
||||
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
|
||||
export type AiVoiceChatType = (typeof AiVoiceChatType)[keyof typeof AiVoiceChatType];
|
||||
|
||||
export type AiVoiceCategory = NamespaceAiVoiceCategory;
|
||||
export interface AiVoiceItem {
|
||||
voiceId: string;
|
||||
voiceDisplayName: string;
|
||||
voiceExampleUrl: string;
|
||||
voiceId: string;
|
||||
voiceDisplayName: string;
|
||||
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 {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
|
||||
}
|
||||
// ─────────────── Group todo query / mutations (0x9474 / 0xF90) ───────────────
|
||||
|
||||
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
|
||||
}
|
||||
|
||||
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
|
||||
}
|
||||
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
/**
|
||||
* Returns `null` on transport / decode failure rather than throwing,
|
||||
* so the OneBot action can produce a clean retcode without try/catch
|
||||
* gymnastics. Namespace throws on transport failure → swallow here.
|
||||
*/
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
return await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
} catch {
|
||||
return null;
|
||||
async getGroupTodoList(groupId: number): Promise<GroupTodoListItem[]> {
|
||||
const items = await GetGroupTodoList.invoke(this.ctx, { groupId });
|
||||
log.debug('group todo list fetched group=%d count=%d', groupId, items.length);
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
|
||||
|
||||
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
|
||||
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger AI voice synthesis. Server may return an empty msgInfo while
|
||||
* 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
|
||||
* `apis.groupFile.getPttUrl`, which already handles every other
|
||||
* download-URL fetch in SnowLuma.
|
||||
*/
|
||||
async fetchAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
maxRetries = 30,
|
||||
): Promise<MediaIndexNode> {
|
||||
// Random 32-bit session id — server uses this to deduplicate polls.
|
||||
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;
|
||||
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
// ─────────────── 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');
|
||||
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
|
||||
}
|
||||
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);
|
||||
}
|
||||
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
|
||||
}
|
||||
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
/**
|
||||
* Keeps the action response user-safe while retaining the underlying
|
||||
* failure in the service log for diagnosis.
|
||||
*/
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
|
||||
if (!status) {
|
||||
log.warn('user status query returned no status target=%d', uin);
|
||||
}
|
||||
|
||||
return status;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'user status query failed target=%d: %s',
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
|
||||
|
||||
fetchAiVoiceList(
|
||||
groupId: number,
|
||||
chatType: AiVoiceChatType | number,
|
||||
): Promise<AiVoiceCategory[]> {
|
||||
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger AI voice synthesis. Server may return an empty msgInfo while
|
||||
* 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 node plugs directly into
|
||||
* `apis.groupFile.getPttUrl`, which already handles every other
|
||||
* 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,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
maxRetries = 30,
|
||||
): Promise<MediaIndexNode> {
|
||||
// Random 32-bit session id — server uses this to deduplicate polls.
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,12 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
|
||||
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
|
||||
import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark';
|
||||
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 {
|
||||
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';
|
||||
@@ -8,42 +14,110 @@ import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export type { DoubtBuddyRequest };
|
||||
|
||||
const log = createLogger('Bridge.Friend');
|
||||
|
||||
export class FriendApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
/**
|
||||
* Accept or reject an inbound friend request. `uidOrFlag` is either a
|
||||
* pre-resolved UID string or a numeric uin (then resolved on the fly).
|
||||
*/
|
||||
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
|
||||
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
|
||||
}
|
||||
/**
|
||||
* Accept or reject an inbound friend request. `uidOrFlag` is either a
|
||||
* pre-resolved UID string or a numeric uin (then resolved on the fly).
|
||||
*/
|
||||
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
|
||||
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
|
||||
}
|
||||
|
||||
async delete(userId: number, block = false): Promise<void> {
|
||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||
async delete(userId: number, block = false): Promise<void> {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact cannot be deleted');
|
||||
}
|
||||
|
||||
// Refresh friend cache after deletion so subsequent reads don't
|
||||
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
|
||||
// shouldn't make the delete itself look failed.
|
||||
try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
|
||||
}
|
||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||
|
||||
setRemark(userId: number, remark: string): Promise<void> {
|
||||
return SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
// The server-side delete has already completed. A refresh failure must be
|
||||
// visible, but throwing here would misreport the delete itself as failed
|
||||
// and encourage callers to repeat a destructive request.
|
||||
try {
|
||||
await this.ctx.apis.contacts.fetchFriendList();
|
||||
} catch (err: unknown) {
|
||||
log.warn(
|
||||
'friend-list refresh failed after deleting user=%d: %s',
|
||||
userId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** List doubtful friend-add requests (可能认识的人). */
|
||||
getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
return GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
}
|
||||
async setRemark(userId: number, remark: string): Promise<void> {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact does not support remarks');
|
||||
}
|
||||
|
||||
/** 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 });
|
||||
}
|
||||
if (remark === '') {
|
||||
await ClearFriendRemark.invoke(this.ctx, { userId });
|
||||
return;
|
||||
}
|
||||
|
||||
/** Reject (delete/decline) a doubtful friend-add request by its uid. */
|
||||
rejectDoubtRequest(uid: string): Promise<void> {
|
||||
return RejectDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
}
|
||||
await SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
|
||||
/** List doubtful friend-add requests (可能认识的人). */
|
||||
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
return Promise.all(
|
||||
list.map(async (item) => {
|
||||
let uid = item.uid;
|
||||
let userId = item.user_id;
|
||||
|
||||
if (userId <= 0 && uid) {
|
||||
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
|
||||
}
|
||||
|
||||
// Applicants need not be friends or share a group. Use Identity's
|
||||
// profile lookup when the list only supplies an account number.
|
||||
if (!uid && userId > 0) {
|
||||
try {
|
||||
uid = await this.ctx.resolveUserUid(userId);
|
||||
} catch (err: unknown) {
|
||||
log.warn(
|
||||
'doubt-request uid resolve failed: user=%d err=%s',
|
||||
userId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { ...item, uid: uid || '', user_id: userId };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
|
||||
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
log.trace('doubt-request approval: resolving applicant');
|
||||
const uid = await this.resolveDoubtFlag(uidOrFlag);
|
||||
log.trace('doubt-request approval: submitting request');
|
||||
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
log.trace('doubt-request approval: completed');
|
||||
}
|
||||
|
||||
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
|
||||
async rejectDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
return RejectDoubtBuddyReq.invoke(this.ctx, {
|
||||
uid: await this.resolveDoubtFlag(uidOrFlag),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Digit-only flags are account numbers and must be translated before the
|
||||
* approval/reject packet is built. A raw number in that packet is rejected
|
||||
* by the server. Same rule as inbound friend-request handling.
|
||||
*/
|
||||
private resolveDoubtFlag(uidOrFlag: string): Promise<string> {
|
||||
if (!/^\d+$/.test(uidOrFlag)) {
|
||||
return Promise.resolve(uidOrFlag);
|
||||
}
|
||||
|
||||
return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
|
||||
import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail';
|
||||
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
|
||||
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
|
||||
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
|
||||
@@ -10,102 +11,364 @@ import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin
|
||||
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
|
||||
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
|
||||
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
|
||||
import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info';
|
||||
import {
|
||||
decodeMemberInvitePolicy,
|
||||
MEMBER_INVITE_PRIVILEGE_MASK,
|
||||
mergeMemberInvitePrivilegeFlag,
|
||||
SetMemberInvitePolicy,
|
||||
type GroupMemberInvitePolicy,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy';
|
||||
import {
|
||||
decodeGroupHistoryVisibility,
|
||||
SetNewMemberHistoryVisibility,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility';
|
||||
import {
|
||||
decodeGroupMemberPermissions,
|
||||
GROUP_MEMBER_PERMISSION_MASKS,
|
||||
mergeGroupMemberPermission,
|
||||
SetMemberPermission,
|
||||
type GroupMemberPermission,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
|
||||
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
|
||||
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
|
||||
import { AddGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/add-group-category-tag';
|
||||
import { DeleteGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/delete-group-category-tag';
|
||||
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 { OidbError } from '@snowluma/protocol/oidb-service';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
/** QQ only accepts this write from the group owner (#411). */
|
||||
export const MEMBER_PERMISSIONS_OWNER_ONLY =
|
||||
'only the group owner can change group member permissions';
|
||||
|
||||
/** 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 });
|
||||
}
|
||||
export type GroupAdminSettings = {
|
||||
add_type: number;
|
||||
group_question: string;
|
||||
group_answer: string;
|
||||
robot_member_switch: number;
|
||||
robot_member_examine: number;
|
||||
member_invite_policy: GroupMemberInvitePolicy;
|
||||
allow_member_upload_album: boolean;
|
||||
allow_member_temporary_session: boolean;
|
||||
allow_member_create_group: boolean;
|
||||
new_member_history_visible: boolean;
|
||||
no_finger_open: number;
|
||||
no_code_finger_open: number;
|
||||
};
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
|
||||
muteAll(groupId: number, enable: boolean): Promise<void> {
|
||||
return MuteAll.invoke(this.ctx, { groupId, enable });
|
||||
}
|
||||
|
||||
setAddOption(groupId: number, addType: number): Promise<void> {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType });
|
||||
}
|
||||
|
||||
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
groupId: number, sequence: number, eventType: number,
|
||||
approve: boolean, reason = '', filtered = false,
|
||||
): Promise<void> {
|
||||
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
|
||||
}
|
||||
|
||||
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
|
||||
}
|
||||
|
||||
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
|
||||
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
|
||||
}
|
||||
|
||||
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> {
|
||||
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
|
||||
}
|
||||
|
||||
setCard(groupId: number, userId: number, card: string): Promise<void> {
|
||||
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
|
||||
}
|
||||
|
||||
setName(groupId: number, name: string): Promise<void> {
|
||||
return SetGroupName.invoke(this.ctx, { groupId, name });
|
||||
}
|
||||
|
||||
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
|
||||
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
|
||||
}
|
||||
|
||||
/**
|
||||
* The bot's local-only label for a group. Lives here rather than
|
||||
* `FriendApi` because the semantic is "operate on a group" rather
|
||||
* than "operate on a contact list".
|
||||
*/
|
||||
setRemark(groupId: number, remark: string): Promise<void> {
|
||||
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
|
||||
}
|
||||
|
||||
getAtAllRemain(groupId: number): Promise<{
|
||||
can_at_all: boolean;
|
||||
remain_at_all_count_for_group: number;
|
||||
remain_at_all_count_for_uin: number;
|
||||
}> {
|
||||
return GetAtAllRemain.invoke(this.ctx, { groupId });
|
||||
}
|
||||
export interface GroupMemberPermissions {
|
||||
allowMemberUploadAlbum?: boolean;
|
||||
allowMemberTemporarySession?: boolean;
|
||||
allowMemberCreateGroup?: boolean;
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
|
||||
const [detail, robot] = await Promise.all([
|
||||
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
|
||||
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
|
||||
]);
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(`unable to read group admin settings for group ${groupId}`);
|
||||
}
|
||||
|
||||
const privilegeFlag = results.privilegeFlag ?? 0;
|
||||
const permissions = decodeGroupMemberPermissions(privilegeFlag);
|
||||
return {
|
||||
add_type: results.addType ?? 0,
|
||||
group_question: results.question ?? '',
|
||||
group_answer: results.answer ?? '',
|
||||
robot_member_switch: robot.robotMemberSwitch,
|
||||
robot_member_examine: robot.robotMemberExamine,
|
||||
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
|
||||
allow_member_upload_album: permissions.allowMemberUploadAlbum,
|
||||
allow_member_temporary_session: permissions.allowMemberTemporarySession,
|
||||
allow_member_create_group: permissions.allowMemberCreateGroup,
|
||||
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
|
||||
no_finger_open: results.noFingerOpen ?? 0,
|
||||
no_code_finger_open: results.noCodeFingerOpen ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
|
||||
muteAll(groupId: number, enable: boolean): Promise<void> {
|
||||
return MuteAll.invoke(this.ctx, { groupId, enable });
|
||||
}
|
||||
|
||||
setAddOption(
|
||||
groupId: number,
|
||||
addType: number,
|
||||
groupQuestion?: string,
|
||||
groupAnswer?: string,
|
||||
): Promise<void> {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
|
||||
}
|
||||
|
||||
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
listCategoryTags(
|
||||
groupClass: number,
|
||||
): Promise<{ tags: { id: number; name: string; type: number }[] }> {
|
||||
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
|
||||
}
|
||||
|
||||
addCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
removeCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
|
||||
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member invite policy',
|
||||
'before update',
|
||||
);
|
||||
const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy);
|
||||
|
||||
await SetMemberInvitePolicy.invoke(this.ctx, {
|
||||
groupId,
|
||||
currentPrivilegeFlag,
|
||||
policy,
|
||||
});
|
||||
|
||||
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member invite policy',
|
||||
'after update',
|
||||
);
|
||||
const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK);
|
||||
|
||||
if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) {
|
||||
throw new Error(`group member invite policy was not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchGroupPrivilegeFlag(
|
||||
groupId: number,
|
||||
setting: string,
|
||||
phase: string,
|
||||
): Promise<number> {
|
||||
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
|
||||
}
|
||||
|
||||
private async fetchGroupPrivilegeState(
|
||||
groupId: number,
|
||||
setting: string,
|
||||
phase: string,
|
||||
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
|
||||
}
|
||||
|
||||
return {
|
||||
privilegeFlag: results.privilegeFlag ?? 0,
|
||||
ownerUid: results.ownerUid,
|
||||
};
|
||||
}
|
||||
|
||||
async setMemberPermissions(
|
||||
groupId: number,
|
||||
permissions: GroupMemberPermissions,
|
||||
): Promise<void> {
|
||||
const updates: ReadonlyArray<readonly [GroupMemberPermission, boolean | undefined]> = [
|
||||
['upload_album', permissions.allowMemberUploadAlbum],
|
||||
['temporary_session', permissions.allowMemberTemporarySession],
|
||||
['create_group', permissions.allowMemberCreateGroup],
|
||||
];
|
||||
|
||||
if (!updates.some(([, allow]) => allow !== undefined)) {
|
||||
throw new Error('at least one member permission must be specified');
|
||||
}
|
||||
|
||||
const before = await this.fetchGroupPrivilegeState(
|
||||
groupId,
|
||||
'group member permissions',
|
||||
'before update',
|
||||
);
|
||||
const selfUid = this.ctx.identity.selfUid;
|
||||
|
||||
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
|
||||
let expectedPrivilegeFlag = before.privilegeFlag;
|
||||
let combinedMask = 0n;
|
||||
|
||||
for (const [permission, allow] of updates) {
|
||||
if (allow === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await SetMemberPermission.invoke(this.ctx, {
|
||||
groupId,
|
||||
currentPrivilegeFlag: expectedPrivilegeFlag,
|
||||
permission,
|
||||
allow,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OidbError && error.code === 1287) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
expectedPrivilegeFlag = mergeGroupMemberPermission(
|
||||
expectedPrivilegeFlag,
|
||||
permission,
|
||||
allow,
|
||||
);
|
||||
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
|
||||
}
|
||||
|
||||
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member permissions',
|
||||
'after update',
|
||||
);
|
||||
|
||||
if (
|
||||
(BigInt(actualPrivilegeFlag) & combinedMask) !==
|
||||
(BigInt(expectedPrivilegeFlag) & combinedMask)
|
||||
) {
|
||||
throw new Error(`group member permissions were not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
|
||||
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
|
||||
|
||||
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
|
||||
|
||||
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
|
||||
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(
|
||||
`unable to read new-member history visibility ${phase} for group ${groupId}`,
|
||||
);
|
||||
}
|
||||
|
||||
return results.groupFlagExt4 ?? 0;
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
eventType: number,
|
||||
approve: boolean,
|
||||
reason = '',
|
||||
filtered = false,
|
||||
operateTransInfo?: Uint8Array,
|
||||
): Promise<void> {
|
||||
return SetAddRequest.invoke(this.ctx, {
|
||||
groupId,
|
||||
sequence,
|
||||
eventType,
|
||||
approve,
|
||||
reason,
|
||||
filtered,
|
||||
operateTransInfo,
|
||||
});
|
||||
}
|
||||
|
||||
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
|
||||
}
|
||||
|
||||
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
|
||||
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
|
||||
}
|
||||
|
||||
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> {
|
||||
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
|
||||
}
|
||||
|
||||
setCard(groupId: number, userId: number, card: string): Promise<void> {
|
||||
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
|
||||
}
|
||||
|
||||
setName(groupId: number, name: string): Promise<void> {
|
||||
return SetGroupName.invoke(this.ctx, { groupId, name });
|
||||
}
|
||||
|
||||
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
|
||||
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
|
||||
}
|
||||
|
||||
/**
|
||||
* The bot's local-only label for a group. Lives here rather than
|
||||
* `FriendApi` because the semantic is "operate on a group" rather
|
||||
* than "operate on a contact list".
|
||||
*/
|
||||
setRemark(groupId: number, remark: string): Promise<void> {
|
||||
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
|
||||
}
|
||||
|
||||
getAtAllRemain(groupId: number): Promise<{
|
||||
can_at_all: boolean;
|
||||
remain_at_all_count_for_group: number;
|
||||
remain_at_all_count_for_uin: number;
|
||||
}> {
|
||||
return GetAtAllRemain.invoke(this.ctx, { groupId });
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 1071 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user