commit b3ffbae00578c00f3e5eea578f8c84041d8796bc Author: 手瓜一十雪 Date: Sat May 2 19:06:29 2026 +0800 Initial commit diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml new file mode 100644 index 00000000..976d9aca --- /dev/null +++ b/.github/workflows/dev-build.yml @@ -0,0 +1,94 @@ +name: Dev Build + +on: + push: + branches: + - '**' + tags-ignore: + - 'v*' + +jobs: + build: + runs-on: windows-latest + permissions: + actions: write + contents: read + strategy: + fail-fast: false + matrix: + include: + - name: "standard" + script: "build" + suffix: "" + - name: "webui" + script: "build:all" + suffix: "-WebUI" + steps: + - name: Delete old artifacts + uses: actions/github-script@v7 + with: + script: | + let page = 1; + while (true) { + const { data: { artifacts } } = await github.rest.actions.listArtifactsForRepo({ + owner: context.repo.owner, + repo: context.repo.repo, + per_page: 100, + page, + }); + if (artifacts.length === 0) break; + for (const artifact of artifacts) { + await github.rest.actions.deleteArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: artifact.id, + }); + console.log(`Deleted artifact: ${artifact.name}`); + } + page++; + } + + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.28.0 + run_install: false + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Build project + run: pnpm run ${{ matrix.script }} + + - name: Verify native files + shell: pwsh + run: | + if (!(Test-Path "dist\native\snowluma-win32-x64.node")) { throw "Missing dist\native\snowluma-win32-x64.node" } + if (!(Test-Path "dist\native\snowluma-win32-x64.dll")) { throw "Missing dist\native\snowluma-win32-x64.dll" } + + - name: Bundle runtime dependencies + working-directory: dist + run: npm install --omit=dev + + - name: Package artifact + shell: pwsh + run: | + Copy-Item (Get-Command node).Source -Destination "dist\node.exe" + Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev${{ matrix.suffix }}.zip" + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: SnowLuma-dev-${{ github.sha }}${{ matrix.suffix }} + path: SnowLuma-dev${{ matrix.suffix }}.zip + retention-days: 3 + overwrite: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..5beeb53d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,66 @@ +name: Build and Release + +on: + push: + tags: + - 'v*' + +permissions: + contents: write + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - name: "win-x64" + script: "build" + - name: "win-x64-webui" + script: "build:all" + runs-on: windows-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.28.0 + run_install: false + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Build project + run: pnpm run ${{ matrix.script }} + + - name: Verify native files + shell: pwsh + run: | + if (!(Test-Path "dist\native\snowluma-win32-x64.node")) { throw "Missing dist\native\snowluma-win32-x64.node" } + if (!(Test-Path "dist\native\snowluma-win32-x64.dll")) { throw "Missing dist\native\snowluma-win32-x64.dll" } + + - name: Bundle runtime dependencies + working-directory: dist + run: npm install --omit=dev + + - name: Package release + shell: pwsh + run: | + Copy-Item (Get-Command node).Source -Destination "dist\node.exe" + Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.zip" + + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + files: SnowLuma-*.zip + generate_release_notes: true + draft: false + prerelease: ${{ contains(github.ref_name, '-') }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..f4b98ca1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +out +build +build-* +CMakePresets.json + +# Compiled files +*.o +*.obj +*.exe +*.so +*.dylib +*.a +*.lib + +# CMake +CMakeCache.txt +CMakeFiles/ +cmake_install.cmake +compile_commands.json +_deps/ +.claude + +# Runtime generated +config.json +/node_modules +/dist +/.vscode diff --git a/README.md b/README.md new file mode 100644 index 00000000..ad1c5572 --- /dev/null +++ b/README.md @@ -0,0 +1,22 @@ +# ❄️ SnowLuma +> Next Remote Protocol Framework. + + +## 关于项目 +项目处于开发初期,仅支持部分功能,持续高速迭代中,仅支持有头。 + +## 鸣谢 +[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto + +[NapCatQQ](https://github.com/NapNeko/NapCatQQ) - Scaner/Packet + +## 辅助编程 + +推荐 Opus4.6 + Gemini3.1pro 对本项目辅助开发 + +本项目大量使用Ai技术。 + +## 加入我们 +[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe) + +[SnowLuma-Tg](https://t.me/napcatqq) \ No newline at end of file diff --git a/launcher/launcher.bat b/launcher/launcher.bat new file mode 100644 index 00000000..ea696c21 --- /dev/null +++ b/launcher/launcher.bat @@ -0,0 +1,2 @@ +node ./index.mjs +pause \ No newline at end of file diff --git a/launcher/native/snowluma_native-linux-x64.node b/launcher/native/snowluma_native-linux-x64.node new file mode 100644 index 00000000..2d1f0be1 Binary files /dev/null and b/launcher/native/snowluma_native-linux-x64.node differ diff --git a/launcher/native/snowluma_native-win32-x64.node b/launcher/native/snowluma_native-win32-x64.node new file mode 100644 index 00000000..8c2082f2 Binary files /dev/null and b/launcher/native/snowluma_native-win32-x64.node differ diff --git a/launcher/package.json b/launcher/package.json new file mode 100644 index 00000000..2e74f5d0 --- /dev/null +++ b/launcher/package.json @@ -0,0 +1,9 @@ +{ + "name": "snowluma", + "version": "0.1.0", + "type": "module", + "main": "index.mjs", + "dependencies": { + "ws": "^8.20.0" + } +} diff --git a/native/snowluma-win32-x64.dll b/native/snowluma-win32-x64.dll new file mode 100644 index 00000000..310aa8bf Binary files /dev/null and b/native/snowluma-win32-x64.dll differ diff --git a/native/snowluma-win32-x64.node b/native/snowluma-win32-x64.node new file mode 100644 index 00000000..36ea579c Binary files /dev/null and b/native/snowluma-win32-x64.node differ diff --git a/package.json b/package.json new file mode 100644 index 00000000..0baefb3a --- /dev/null +++ b/package.json @@ -0,0 +1,42 @@ +{ + "name": "snowluma", + "version": "0.1.0", + "description": "SnowLuma - NTQQ packet sniffer with Node.js native addon", + "type": "module", + "main": "dist/index.mjs", + "scripts": { + "testtypes": "tsc --noEmit", + "test": "vitest run", + "test:watch": "vitest", + "build": "vite build", + "build:webui": "pnpm --filter webui build", + "build:all": "cross-env BUILD_WEBUI=true vite build && pnpm --filter webui build", + "dev": "pnpm --parallel run dev", + "dev:core": "tsx src/index.ts", + "dev:web": "pnpm --filter webui dev", + "start": "node dist/index.mjs" + }, + "dependencies": { + "ws": "^8.20.0" + }, + "devDependencies": { + "@hono/node-server": "^1.19.14", + "@rollup/plugin-node-resolve": "^16.0.3", + "@types/node": "^24.12.2", + "@types/ws": "^8.18.1", + "cross-env": "^10.1.0", + "hono": "^4.12.14", + "tsx": "^4.21.0", + "typescript": "^6.0.2", + "vite": "catalog:", + "vite-plugin-cp": "^6.0.3", + "vitest": "^4.1.4" + }, + "pnpm": { + "peerDependencyRules": { + "allowedVersions": { + "eslint-plugin-react-hooks>eslint": "10" + } + } + } +} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 00000000..2b8c797e --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,4287 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +catalogs: + default: + typescript: + specifier: ~6.0.2 + version: 6.0.2 + vite: + specifier: ^8.0.8 + version: 8.0.8 + +overrides: + tar: ^7.5.13 + +importers: + + .: + dependencies: + ws: + specifier: ^8.20.0 + version: 8.20.0 + devDependencies: + '@hono/node-server': + specifier: ^1.19.14 + version: 1.19.14(hono@4.12.14) + '@rollup/plugin-node-resolve': + specifier: ^16.0.3 + version: 16.0.3 + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + '@types/ws': + specifier: ^8.18.1 + version: 8.18.1 + cross-env: + specifier: ^10.1.0 + version: 10.1.0 + hono: + specifier: ^4.12.14 + version: 4.12.14 + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^6.0.2 + version: 6.0.2 + vite: + specifier: 'catalog:' + version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + vite-plugin-cp: + specifier: ^6.0.3 + version: 6.0.3 + vitest: + specifier: ^4.1.4 + version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + + webui: + dependencies: + '@heroui/react': + specifier: ^3.0.2 + version: 3.0.2(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)(tailwindcss@4.2.2) + '@heroui/styles': + specifier: ^3.0.2 + version: 3.0.2(tailwind-merge@3.5.0)(tailwindcss@4.2.2) + clsx: + specifier: ^2.1.1 + version: 2.1.1 + framer-motion: + specifier: ^12.38.0 + version: 12.38.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + lucide-react: + specifier: ^1.8.0 + version: 1.8.0(react@19.2.5) + react: + specifier: ^19.2.5 + version: 19.2.5 + react-dom: + specifier: ^19.2.5 + version: 19.2.5(react@19.2.5) + tailwind-merge: + specifier: ^3.5.0 + version: 3.5.0 + devDependencies: + '@eslint/js': + specifier: ^10.0.1 + version: 10.0.1(eslint@10.2.0(jiti@2.6.1)) + '@tailwindcss/vite': + specifier: ^4.2.2 + version: 4.2.2(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + '@types/node': + specifier: ^25.6.0 + version: 25.6.0 + '@types/react': + specifier: ^19.2.14 + version: 19.2.14 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.14) + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + eslint: + specifier: ^10.2.0 + version: 10.2.0(jiti@2.6.1) + eslint-plugin-react-hooks: + specifier: ^7.0.1 + version: 7.0.1(eslint@10.2.0(jiti@2.6.1)) + eslint-plugin-react-refresh: + specifier: ^0.5.2 + version: 0.5.2(eslint@10.2.0(jiti@2.6.1)) + globals: + specifier: ^17.5.0 + version: 17.5.0 + sass: + specifier: ^1.99.0 + version: 1.99.0 + tailwindcss: + specifier: ^4.2.2 + version: 4.2.2 + typescript: + specifier: 'catalog:' + version: 6.0.2 + typescript-eslint: + specifier: ^8.58.2 + version: 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + vite: + specifier: 'catalog:' + version: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + +packages: + + '@adobe/react-spectrum-ui@1.2.1': + resolution: {integrity: sha512-wcrbEE2O/9WnEn6avBnaVRRx88S5PLFsPLr4wffzlbMfXeQsy+RMQwaJd3cbzrn18/j04Isit7f7Emfn0dhrJA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0 + + '@adobe/react-spectrum-workflow@2.3.5': + resolution: {integrity: sha512-b53VIPwPWKb/T5gzE3qs+QlGP5gVrw/LnWV3xMksDU+CRl3rzOKUwxIGiZO8ICyYh1WiyqY4myGlPU/nAynBUg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0 + + '@adobe/react-spectrum@3.47.0': + resolution: {integrity: sha512-EDQuMzz0kUeiMUUlxoeLFQyyxOXaAC7qlBw2PYOUfFLYd87xcV7VVV0JxiYx8zGk1IIY3UgQHgXrS1fv7CgezQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@babel/code-frame@7.29.0': + resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} + engines: {node: '>=6.9.0'} + + '@babel/compat-data@7.29.0': + resolution: {integrity: sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==} + engines: {node: '>=6.9.0'} + + '@babel/core@7.29.0': + resolution: {integrity: sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==} + engines: {node: '>=6.9.0'} + + '@babel/generator@7.29.1': + resolution: {integrity: sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-compilation-targets@7.28.6': + resolution: {integrity: sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-globals@7.28.0': + resolution: {integrity: sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-imports@7.28.6': + resolution: {integrity: sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-transforms@7.28.6': + resolution: {integrity: sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-string-parser@7.27.1': + resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.28.5': + resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-option@7.27.1': + resolution: {integrity: sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==} + engines: {node: '>=6.9.0'} + + '@babel/helpers@7.29.2': + resolution: {integrity: sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.2': + resolution: {integrity: sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/runtime@7.29.2': + resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==} + engines: {node: '>=6.9.0'} + + '@babel/template@7.28.6': + resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==} + engines: {node: '>=6.9.0'} + + '@babel/traverse@7.29.0': + resolution: {integrity: sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==} + engines: {node: '>=6.9.0'} + + '@babel/types@7.29.0': + resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==} + engines: {node: '>=6.9.0'} + + '@emnapi/core@1.9.2': + resolution: {integrity: sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==} + + '@emnapi/runtime@1.9.2': + resolution: {integrity: sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==} + + '@emnapi/wasi-threads@1.2.1': + resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} + + '@epic-web/invariant@1.0.0': + resolution: {integrity: sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==} + + '@esbuild/aix-ppc64@0.27.7': + resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.27.7': + resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.27.7': + resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.27.7': + resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.27.7': + resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.27.7': + resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.27.7': + resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.27.7': + resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.27.7': + resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.27.7': + resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.27.7': + resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.27.7': + resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.27.7': + resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.27.7': + resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.27.7': + resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.27.7': + resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.27.7': + resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.27.7': + resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.27.7': + resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.27.7': + resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.27.7': + resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.27.7': + resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.27.7': + resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.27.7': + resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.27.7': + resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.27.7': + resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@eslint-community/eslint-utils@4.9.1': + resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.23.5': + resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/config-helpers@0.5.5': + resolution: {integrity: sha512-eIJYKTCECbP/nsKaaruF6LW967mtbQbsw4JTtSVkUQc9MneSkbrgPJAbKl9nWr0ZeowV8BfsarBmPpBzGelA2w==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/core@1.2.1': + resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/js@10.0.1': + resolution: {integrity: sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + peerDependencies: + eslint: ^10.0.0 + peerDependenciesMeta: + eslint: + optional: true + + '@eslint/object-schema@3.0.5': + resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/plugin-kit@0.7.1': + resolution: {integrity: sha512-rZAP3aVgB9ds9KOeUSL+zZ21hPmo8dh6fnIFwRQj5EAZl9gzR7wxYbYXYysAM8CTqGmUGyp2S4kUdV17MnGuWQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@formatjs/ecma402-abstract@2.3.6': + resolution: {integrity: sha512-HJnTFeRM2kVFVr5gr5kH1XP6K0JcJtE7Lzvtr3FS/so5f1kpsqqqxy5JF+FRaO6H2qmcMfAUIox7AJteieRtVw==} + + '@formatjs/fast-memoize@2.2.7': + resolution: {integrity: sha512-Yabmi9nSvyOMrlSeGGWDiH7rf3a7sIwplbvo/dlz9WCIjzIQAfy1RMf4S0X3yG724n5Ghu2GmEl5NJIV6O9sZQ==} + + '@formatjs/icu-messageformat-parser@2.11.4': + resolution: {integrity: sha512-7kR78cRrPNB4fjGFZg3Rmj5aah8rQj9KPzuLsmcSn4ipLXQvC04keycTI1F7kJYDwIXtT2+7IDEto842CfZBtw==} + + '@formatjs/icu-skeleton-parser@1.8.16': + resolution: {integrity: sha512-H13E9Xl+PxBd8D5/6TVUluSpxGNvFSlN/b3coUp0e0JpuWXXnQDiavIpY3NnvSp4xhEMoXyyBvVfdFX8jglOHQ==} + + '@formatjs/intl-localematcher@0.6.2': + resolution: {integrity: sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA==} + + '@heroui/react@3.0.2': + resolution: {integrity: sha512-HWcYFurH+OnLITgIvQKyCd6BhYLApyzg0qqL3T5xemK5hgo1Nr+wQGQ5JSNVfBAmF4tWSS9TOzr24UHEO+21Ww==} + peerDependencies: + react: '>=19.0.0' + react-dom: '>=19.0.0' + tailwindcss: '>=4.0.0' + + '@heroui/styles@3.0.2': + resolution: {integrity: sha512-UGohTT5WVgVUqosujtUegGevtNkmKLi/V29+zhT4a1lwCQxY5sD2PMtInk1ImBSqtxzfrb5uPoxySb5v1LptYQ==} + peerDependencies: + tailwindcss: '>=4.0.0' + + '@hono/node-server@1.19.14': + resolution: {integrity: sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==} + engines: {node: '>=18.14.1'} + peerDependencies: + hono: ^4 + + '@humanfs/core@0.19.1': + resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.7': + resolution: {integrity: sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.4.3': + resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} + engines: {node: '>=18.18'} + + '@internationalized/date@3.12.1': + resolution: {integrity: sha512-6IedsVWXyq4P9Tj+TxuU8WGWM70hYLl12nbYU8jkikVpa6WXapFazPUcHUMDMoWftIDE2ILDkFFte6W2nFCkRQ==} + + '@internationalized/message@3.1.9': + resolution: {integrity: sha512-x03MSVTaB/4JHtW1VAYaY/2cCuBrHbWM6ZvlgpKdnSdW28tZbqpR673RJrVJyXWRw1bpgYN89Tz7ohX5tgNgPA==} + + '@internationalized/number@3.6.6': + resolution: {integrity: sha512-iFgmQaXHE0vytNfpLZWOC2mEJCBRzcUxt53Xf/yCXG93lRvqas237i3r7X4RKMwO3txiyZD4mQjKAByFv6UGSQ==} + + '@internationalized/string@3.2.8': + resolution: {integrity: sha512-NdbMQUSfXLYIQol5VyMtinm9pZDciiMfN7RtmSuSB78io1hqwJ0naYfxyW6vgxWBkzWymQa/3uLDlbfmshtCaA==} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@napi-rs/wasm-runtime@1.1.4': + resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==} + peerDependencies: + '@emnapi/core': ^1.7.1 + '@emnapi/runtime': ^1.7.1 + + '@oxc-project/types@0.124.0': + resolution: {integrity: sha512-VBFWMTBvHxS11Z5Lvlr3IWgrwhMTXV+Md+EQF0Xf60+wAdsGFTBx7X7K/hP4pi8N7dcm1RvcHwDxZ16Qx8keUg==} + + '@parcel/watcher-android-arm64@2.5.6': + resolution: {integrity: sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [android] + + '@parcel/watcher-darwin-arm64@2.5.6': + resolution: {integrity: sha512-Z2ZdrnwyXvvvdtRHLmM4knydIdU9adO3D4n/0cVipF3rRiwP+3/sfzpAwA/qKFL6i1ModaabkU7IbpeMBgiVEA==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [darwin] + + '@parcel/watcher-darwin-x64@2.5.6': + resolution: {integrity: sha512-HgvOf3W9dhithcwOWX9uDZyn1lW9R+7tPZ4sug+NGrGIo4Rk1hAXLEbcH1TQSqxts0NYXXlOWqVpvS1SFS4fRg==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [darwin] + + '@parcel/watcher-freebsd-x64@2.5.6': + resolution: {integrity: sha512-vJVi8yd/qzJxEKHkeemh7w3YAn6RJCtYlE4HPMoVnCpIXEzSrxErBW5SJBgKLbXU3WdIpkjBTeUNtyBVn8TRng==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [freebsd] + + '@parcel/watcher-linux-arm-glibc@2.5.6': + resolution: {integrity: sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ==} + engines: {node: '>= 10.0.0'} + cpu: [arm] + os: [linux] + + '@parcel/watcher-linux-arm-musl@2.5.6': + resolution: {integrity: sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==} + engines: {node: '>= 10.0.0'} + cpu: [arm] + os: [linux] + + '@parcel/watcher-linux-arm64-glibc@2.5.6': + resolution: {integrity: sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [linux] + + '@parcel/watcher-linux-arm64-musl@2.5.6': + resolution: {integrity: sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [linux] + + '@parcel/watcher-linux-x64-glibc@2.5.6': + resolution: {integrity: sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [linux] + + '@parcel/watcher-linux-x64-musl@2.5.6': + resolution: {integrity: sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [linux] + + '@parcel/watcher-win32-arm64@2.5.6': + resolution: {integrity: sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [win32] + + '@parcel/watcher-win32-ia32@2.5.6': + resolution: {integrity: sha512-k35yLp1ZMwwee3Ez/pxBi5cf4AoBKYXj00CZ80jUz5h8prpiaQsiRPKQMxoLstNuqe2vR4RNPEAEcjEFzhEz/g==} + engines: {node: '>= 10.0.0'} + cpu: [ia32] + os: [win32] + + '@parcel/watcher-win32-x64@2.5.6': + resolution: {integrity: sha512-hbQlYcCq5dlAX9Qx+kFb0FHue6vbjlf0FrNzSKdYK2APUf7tGfGxQCk2ihEREmbR6ZMc0MVAD5RIX/41gpUzTw==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [win32] + + '@parcel/watcher@2.5.6': + resolution: {integrity: sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==} + engines: {node: '>= 10.0.0'} + + '@radix-ui/react-avatar@1.1.11': + resolution: {integrity: sha512-0Qk603AHGV28BOBO34p7IgD5m+V5Sg/YovfayABkoDDBM5d3NCx0Mp4gGrjzLGes1jV5eNOE1r3itqOR33VC6Q==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-compose-refs@1.1.2': + resolution: {integrity: sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-context@1.1.3': + resolution: {integrity: sha512-ieIFACdMpYfMEjF0rEf5KLvfVyIkOz6PDGyNnP+u+4xQ6jny3VCgA4OgXOwNx2aUkxn8zx9fiVcM8CfFYv9Lxw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-primitive@2.1.4': + resolution: {integrity: sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-slot@1.2.4': + resolution: {integrity: sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-callback-ref@1.1.1': + resolution: {integrity: sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-is-hydrated@0.1.0': + resolution: {integrity: sha512-U+UORVEq+cTnRIaostJv9AGdV3G6Y+zbVd+12e18jQ5A3c0xL03IhnHuiU4UV69wolOQp5GfR58NW/EgdQhwOA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-layout-effect@1.1.1': + resolution: {integrity: sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@react-aria/autocomplete@3.0.0-rc.6': + resolution: {integrity: sha512-uymUNJ8NW+dX7lmgkHE+SklAbxwktycAJcI5lBBw6KPZyc0EdMHC+/Fc5CUz3enIAhNwd2oxxogcSHknquMzQA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/button@3.15.0': + resolution: {integrity: sha512-p8KehQ+OmhvhYmsjkp4K/Yv0tufyEBOHu6woJlRYL6kq5m6GKY5MZp8pyO26FpSiOyjhnZe6wbTyvCifvaokwQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/collections@3.1.0': + resolution: {integrity: sha512-OwWoxHaAN0jNw7oo17TfTPY2KZksDme4p5a8KCnNBfm/a0zo+y4wiOUaFpGDmDT6HxwznyBcu3x3oSN7orTtvA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/combobox@3.16.0': + resolution: {integrity: sha512-yPPLduVUluCBuIFSZ+WgBMgl5oH7A5oQTemSpvf9ZmJ2oABIe+h6VQcwkEtMdokveHrdbmWIB9BL0E5jdDczAA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/dnd@3.12.0': + resolution: {integrity: sha512-FqAaxIMCgpq83UQhJRpSR+o3K4XQQYbJMKxhBWGL84Wn1p6m8QmWGvRKAiHeUoQXlY8R6KNxlMR/KjJvV8/lBA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/focus@3.22.0': + resolution: {integrity: sha512-ZfDOVuVhqDsM9mkNji3QUZ/d40JhlVgXrDkrfXylM1035QCrcTHN7m2DpbE95sU2A8EQb4wikvt5jM6K/73BPg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/i18n@3.12.16': + resolution: {integrity: sha512-Km2CAz6MFQOUEaattaW+2jBdWOHUF8WX7VQoNbjlqElCP58nSaqi9yxTWUDRhAcn8/xFUnkFh4MFweNgtrHuEA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/interactions@3.28.0': + resolution: {integrity: sha512-OXwdU1EWFdMxmr/K1CXNGJzmNlCClByb+PuCaqUyzBymHPCGVhawirLIon/CrIN5psh3AiWpHSh4H0WeJdVpng==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/listbox@3.16.0': + resolution: {integrity: sha512-Jv6aTJECRntBvG+0ZQtXniAtHEQjvEi2QSm35FxRcsB8kgv7TmcinUOSZuHe5r8RDY2djILwdrqmfy6ApX0MDA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/live-announcer@3.5.0': + resolution: {integrity: sha512-1b+Txq00WQ/PJPCsZT+CI5qP86DrfFGPuJL5ifKtdMVXrxNGJWrfu7jTj6q9AbAOOXLG11BJ6blILu7sZeRPxg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/overlays@3.32.0': + resolution: {integrity: sha512-H9meBB14/M0bDwk8gZl8Fu8bwZN2El9LDlk5cNkgAozbEiRuQvTFOeE3RoP6XI6bwEnSBvb0ovPmx3/kNyOehQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/searchfield@3.9.0': + resolution: {integrity: sha512-B8oOFhwGDotb7enoQ0bmXjhVkx8BkzK/ZnMmr4aF2ezexSFpG/ELkWqJPlfwknCwoBgBzhmpIKZvkoxQHR/iIw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/slider@3.9.0': + resolution: {integrity: sha512-FdowBjuYOT1OfAo6iEBGoz/EFJ0paRt3Gk/om+NwBF98yeqjHB7qZAkucGIswpixDfMNLYhGoiwiGYIYerhCxw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/ssr@3.9.10': + resolution: {integrity: sha512-hvTm77Pf+pMBhuBm760Li0BVIO38jv1IBws1xFm1NoL26PU+fe+FMW5+VZWyANR6nYL65joaJKZqOdTQMkO9IQ==} + engines: {node: '>= 12'} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/textfield@3.19.0': + resolution: {integrity: sha512-P5Da8QFV/bCp3oCXQAqaTWhXNtx4vWEjvoqa49oG5TM1blodLjFrzNyiRM7TmQU0VLwiQPAQrqD4yaDLXZ0Nqg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/toolbar@3.0.0-beta.24': + resolution: {integrity: sha512-B2Rmpko7Ghi2RbNfsGdbR7I+RQBDhPGVE4bU3/EwHz+P/vNe5LyGPTeSwqaOMsQTF9lKNCkY8424dVTCr6RUMg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/utils@3.33.1': + resolution: {integrity: sha512-kIx1Sj6bbAT0pdqCegHuPanR9zrLn5zMRiM7LN12rgRf55S19ptd9g3ncahArifYTRkfEU9VIn+q0HjfMqS9/w==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-aria/virtualizer@4.2.0': + resolution: {integrity: sha512-j4Dj/PMQK+d/2E2Dxyr5ifPdg8IG/NYsfZJtPnvKHXeKlI3vj7F/InamujwCuEFHZBK3YmxlRPRGcoMdS66qfw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-spectrum/button@3.18.0': + resolution: {integrity: sha512-SmjsXt+mLK2cf8PGstNZvLBfjqE5TjHW15yPIATI6ddqMdcC9JZ3ldnBTdFji9P/B6Rlop4ajnAdDV6bpxLtXA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-spectrum/combobox@3.17.0': + resolution: {integrity: sha512-HuJjm7m5W/lvpak0KQXAdqkvO17GpIfQ6/AuddnXEyltWhl481oRok04b9VQKdZAy9xrmmpReFcvXJ4zFDIGvg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-spectrum/form@3.8.0': + resolution: {integrity: sha512-zNFA1zRFvoEZAhK6HxWyo2yUDlUXqCaaySxHvuCaevq4Zw3DKndbxq72ax9YDaUAvYlhgnb/bI616JBCZUAhdA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-spectrum/provider@3.11.0': + resolution: {integrity: sha512-W2Gxbj8AcG5OR2K5Ua3K8qQqxdsiytEiz+2rhr6oQyBM8VafEgDcNPYSOTtfjrQM3snl2Uhp8LzwN0jwQe/6nQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-spectrum/searchfield@3.9.0': + resolution: {integrity: sha512-so1IeolnYPsgjoIJmoGakUuQv+Ij5NVoWx2VTBc3o2sUva1GkxtFp6Woiow2Qqw0mFyoTwwoKi6zQJHLMqHhvQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-spectrum/slider@3.9.0': + resolution: {integrity: sha512-FTsfWfn6+BkXi8ZDcd7mBQs/KbKYJRHV6aQ64pC4gCnMw54eFcKSuCtlCtdGw3exLPQtGHCNVWGznOjgc8PtGw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-spectrum/table@3.18.0': + resolution: {integrity: sha512-ckvjjz/Tp8Y/Ck/OOOXX/dTs8PtoWCy7+QDBxWzNpqvxcLiLviudNKJFhGfeyGGDi3IOMWRSaG5yWN9wrvItNQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/autocomplete@3.0.0-beta.4': + resolution: {integrity: sha512-K2Uy7XEdseFvgwRQ8CyrYEHMupjVKEszddOapP8deNz4hntYvT1aRm0m+sKa5Kl/4kvg9c/3NZpQcrky/vRZIg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/combobox@3.14.0': + resolution: {integrity: sha512-WYWJK9IzWKDqnFk1HF6FGISrhPh/bzYkRLgd40Psyke5dwYusOrEUzG161P8v9vxAzs621pYB4hz2UhrRWsMPQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/flags@3.2.0': + resolution: {integrity: sha512-HcfFk5sUpSVUgjOHUSi4izUWbiya+iTt2/PAviW+cKmCJOy507CQ3VG3Yu0Rqs0cr66yt3foDKy0MRNQ2zmGmQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/grid@3.12.0': + resolution: {integrity: sha512-MLCN3hyxRpaj4tUnQyc+aFR2/QBP2rmFcXGdADHO1c0kvxd9Vk+bEe88uA9MJTz2VClQ+AN7yRGCTIuME+QvNQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/layout@4.7.0': + resolution: {integrity: sha512-63VvOKI8KXeD3SO7yt41511CdZ+9wK2LVY2mpY+c87ML5fVVgMTc/o1IsYWI07rW3IjEFcWoW93eItgMbJCXyg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/searchfield@3.6.0': + resolution: {integrity: sha512-cSSDXynj3oQdILHSthEaB2pAIXG0POHKqjZZ07k6L/A0fkyhkwAbR/hyg+idHCH7Ah9hWnS+YhicWE1b6nw1zg==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/selection@3.21.0': + resolution: {integrity: sha512-SBafuZoJgDr7L9dCgMjat1Mx85xOnRO7E5UCtAj6TF/7yhisJVnrNkfnryOH2CunPyXCUgfUlUebkxeXjbW+lw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/slider@3.8.0': + resolution: {integrity: sha512-TonYUZZ9BENheuT1VPL8tJl3ltM3DKzw0aDKpfQudqMz3c9L11Efq+ZrBaIUIwNvA/W0kfrCRJ30byFEkNTyCQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/table@3.16.0': + resolution: {integrity: sha512-xuvkFuRj8SYE36T+hEed+30oPCzbkcGNduVBAOJGr9K0z7y/a3OxFdOnAv/OsCvKW1sLK231oTSFvZ36zRFndA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/utils@3.11.0': + resolution: {integrity: sha512-8LZpYowJ9eZmmYLpudbo/eclIRnbhWIJZ994ncmlKlouNzKohtM8qTC6B1w1pwUbiwGdUoyzLuQbeaIor5Dvcw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-stately/virtualizer@4.5.0': + resolution: {integrity: sha512-Yf1xA9U7PuuaHgxWExwO5MrWCqzDZZTPCzo9YCcsilkOFk2GxMcGNysM71funj+d4CMqsWjCNmgNhZQjBXKjNw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/autocomplete@3.0.0-alpha.38': + resolution: {integrity: sha512-0XrlVC8drzcrCNzybbkZdLcTofXEzBsHuaFevt5awW1J0xBJ+SMLIQMDeUYrvKjjwXUBlCtjJJpOvitGt4Z+KA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/button@3.16.0': + resolution: {integrity: sha512-Z5///n2Y1jtF0gokBq2Y1K1cpOwsWZ24HPeAm3eEmZrbBXMrxC2oEA5ZThsSHuIGsqiyNJiQ2scsDftmr+PkZw==} + peerDependencies: + '@react-spectrum/provider': ^3.0.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/color@3.1.4': + resolution: {integrity: sha512-s+Xj4pvNBlJPpQ1Gr7bO1j4/tuwMUfdS9xIVFuiW5RvDsSybKTUJ/gqPzTxms94VDCRhLFocVn2STNdD2Erf6A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/combobox@3.15.0': + resolution: {integrity: sha512-iWV9UfLg1P0XhEqPTbnhsVMHFwc0RnrZjHfCLwgilH0Af0z1CQ8RyWiT8cOd1eqbkOAiVgCv29Xs8PAxaQBHSg==} + peerDependencies: + '@react-spectrum/provider': ^3.0.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/form@3.8.0': + resolution: {integrity: sha512-ff38E4/5xLxqVemicLw+GefRoWBJEAro+hDwFZ5sde6kslktYt2LHJ7+IkID6yQYy+T3qxXgIdfxX+O1rlpWvw==} + peerDependencies: + '@react-spectrum/provider': ^3.0.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/grid@3.4.0': + resolution: {integrity: sha512-h+u3hKli9gVwfYx6cabkTNZrP+HQ97vAmTugGIk5IAfouE6kjhoDaDzVD0VUvIWqc12LIkrqe1LdBMZ0ofbV6A==} + peerDependencies: + '@react-spectrum/provider': ^3.0.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/searchfield@3.7.0': + resolution: {integrity: sha512-/JBVYkXLB4EozPEfgpYW7C9tzw4xUmdVmuf7g+8ip/AsFgsyW/FjdLpbaXESXR78D0nppWaNxUxcdUXcuo+eEg==} + peerDependencies: + '@react-spectrum/provider': ^3.0.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/shared@3.33.1': + resolution: {integrity: sha512-oJHtjvLG43VjwemQDadlR5g/8VepK56B/xKO2XORPHt9zlW6IZs3tZrYlvH29BMvoqC7RtE7E5UjgbnbFtDGag==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/shared@3.34.0': + resolution: {integrity: sha512-gp6xo/s2lX54AlTjOiqwDnxA7UW79BNvI9dB9pr3LZTzRKCd1ZA+ZbgKw/ReIiWuvvVw/8QFJpnqeeFyLocMcQ==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/slider@3.9.0': + resolution: {integrity: sha512-gbQWB8LnucC+jhDi5Imd2ZDPbVuiHt0xzObGHWq6GTZ3slLgTvGQaHNO5h9+h7dZH0iFQOVNb6+TlyTsnjFuAw==} + peerDependencies: + '@react-spectrum/provider': ^3.0.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@react-types/table@3.14.0': + resolution: {integrity: sha512-emTYu9biFFlVEN208EmYpnO3bzi0f7q+07rnerUWRRRqXQpgNW/G5Tc6ifgCUXLp+KjwzLIeoDl4hs3ZnG5NSA==} + peerDependencies: + '@react-spectrum/provider': ^3.0.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@rolldown/binding-android-arm64@1.0.0-rc.15': + resolution: {integrity: sha512-YYe6aWruPZDtHNpwu7+qAHEMbQ/yRl6atqb/AhznLTnD3UY99Q1jE7ihLSahNWkF4EqRPVC4SiR4O0UkLK02tA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.0.0-rc.15': + resolution: {integrity: sha512-oArR/ig8wNTPYsXL+Mzhs0oxhxfuHRfG7Ikw7jXsw8mYOtk71W0OkF2VEVh699pdmzjPQsTjlD1JIOoHkLP1Fg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.0.0-rc.15': + resolution: {integrity: sha512-YzeVqOqjPYvUbJSWJ4EDL8ahbmsIXQpgL3JVipmN+MX0XnXMeWomLN3Fb+nwCmP/jfyqte5I3XRSm7OfQrbyxw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.0.0-rc.15': + resolution: {integrity: sha512-9Erhx956jeQ0nNTyif1+QWAXDRD38ZNjr//bSHrt6wDwB+QkAfl2q6Mn1k6OBPerznjRmbM10lgRb1Pli4xZPw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.0.0-rc.15': + resolution: {integrity: sha512-cVwk0w8QbZJGTnP/AHQBs5yNwmpgGYStL88t4UIaqcvYJWBfS0s3oqVLZPwsPU6M0zlW4GqjP0Zq5MnAGwFeGA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.0.0-rc.15': + resolution: {integrity: sha512-eBZ/u8iAK9SoHGanqe/jrPnY0JvBN6iXbVOsbO38mbz+ZJsaobExAm1Iu+rxa4S1l2FjG0qEZn4Rc6X8n+9M+w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@rolldown/binding-linux-arm64-musl@1.0.0-rc.15': + resolution: {integrity: sha512-ZvRYMGrAklV9PEkgt4LQM6MjQX2P58HPAuecwYObY2DhS2t35R0I810bKi0wmaYORt6m/2Sm+Z+nFgb0WhXNcQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@rolldown/binding-linux-ppc64-gnu@1.0.0-rc.15': + resolution: {integrity: sha512-VDpgGBzgfg5hLg+uBpCLoFG5kVvEyafmfxGUV0UHLcL5irxAK7PKNeC2MwClgk6ZAiNhmo9FLhRYgvMmedLtnQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + + '@rolldown/binding-linux-s390x-gnu@1.0.0-rc.15': + resolution: {integrity: sha512-y1uXY3qQWCzcPgRJATPSOUP4tCemh4uBdY7e3EZbVwCJTY3gLJWnQABgeUetvED+bt1FQ01OeZwvhLS2bpNrAQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + + '@rolldown/binding-linux-x64-gnu@1.0.0-rc.15': + resolution: {integrity: sha512-023bTPBod7J3Y/4fzAN6QtpkSABR0rigtrwaP+qSEabUh5zf6ELr9Nc7GujaROuPY3uwdSIXWrvhn1KxOvurWA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@rolldown/binding-linux-x64-musl@1.0.0-rc.15': + resolution: {integrity: sha512-witB2O0/hU4CgfOOKUoeFgQ4GktPi1eEbAhaLAIpgD6+ZnhcPkUtPsoKKHRzmOoWPZue46IThdSgdo4XneOLYw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@rolldown/binding-openharmony-arm64@1.0.0-rc.15': + resolution: {integrity: sha512-UCL68NJ0Ud5zRipXZE9dF5PmirzJE4E4BCIOOssEnM7wLDsxjc6Qb0sGDxTNRTP53I6MZpygyCpY8Aa8sPfKPg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-wasm32-wasi@1.0.0-rc.15': + resolution: {integrity: sha512-ApLruZq/ig+nhaE7OJm4lDjayUnOHVUa77zGeqnqZ9pn0ovdVbbNPerVibLXDmWeUZXjIYIT8V3xkT58Rm9u5Q==} + engines: {node: '>=14.0.0'} + cpu: [wasm32] + + '@rolldown/binding-win32-arm64-msvc@1.0.0-rc.15': + resolution: {integrity: sha512-KmoUoU7HnN+Si5YWJigfTws1jz1bKBYDQKdbLspz0UaqjjFkddHsqorgiW1mxcAj88lYUE6NC/zJNwT+SloqtA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.0.0-rc.15': + resolution: {integrity: sha512-3P2A8L+x75qavWLe/Dll3EYBJLQmtkJN8rfh+U/eR3MqMgL/h98PhYI+JFfXuDPgPeCB7iZAKiqii5vqOvnA0g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.0-rc.15': + resolution: {integrity: sha512-UromN0peaE53IaBRe9W7CjrZgXl90fqGpK+mIZbA3qSTeYqg3pqpROBdIPvOG3F5ereDHNwoHBI2e50n1BDr1g==} + + '@rolldown/pluginutils@1.0.0-rc.7': + resolution: {integrity: sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==} + + '@rollup/plugin-node-resolve@16.0.3': + resolution: {integrity: sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==} + engines: {node: '>=14.0.0'} + peerDependencies: + rollup: ^2.78.0||^3.0.0||^4.0.0 + peerDependenciesMeta: + rollup: + optional: true + + '@rollup/pluginutils@5.3.0': + resolution: {integrity: sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q==} + engines: {node: '>=14.0.0'} + peerDependencies: + rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0 + peerDependenciesMeta: + rollup: + optional: true + + '@spectrum-icons/ui@3.7.0': + resolution: {integrity: sha512-86iQSDfJb3Ama1WSJ/mEiFy4DJT7e/v4pSmEuX4aKKMzbNYft+O40N18S2POUnmblrb7MQneLC/pgIp1SDBwEQ==} + peerDependencies: + '@adobe/react-spectrum': ^3.47.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@spectrum-icons/workflow@4.3.0': + resolution: {integrity: sha512-ILuhgWh9jMXaEVMRuOYgTAjMc22cKyvCtUDyZmc8OEMfOYuejj+Gcp5t6DhaCfE0M9rORtVxCrRgsO2WyEgfUw==} + peerDependencies: + '@adobe/react-spectrum': ^3.47.0 + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@swc/helpers@0.5.21': + resolution: {integrity: sha512-jI/VAmtdjB/RnI8GTnokyX7Ug8c+g+ffD6QRLa6XQewtnGyukKkKSk3wLTM3b5cjt1jNh9x0jfVlagdN2gDKQg==} + + '@tailwindcss/node@4.2.2': + resolution: {integrity: sha512-pXS+wJ2gZpVXqFaUEjojq7jzMpTGf8rU6ipJz5ovJV6PUGmlJ+jvIwGrzdHdQ80Sg+wmQxUFuoW1UAAwHNEdFA==} + + '@tailwindcss/oxide-android-arm64@4.2.2': + resolution: {integrity: sha512-dXGR1n+P3B6748jZO/SvHZq7qBOqqzQ+yFrXpoOWWALWndF9MoSKAT3Q0fYgAzYzGhxNYOoysRvYlpixRBBoDg==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [android] + + '@tailwindcss/oxide-darwin-arm64@4.2.2': + resolution: {integrity: sha512-iq9Qjr6knfMpZHj55/37ouZeykwbDqF21gPFtfnhCCKGDcPI/21FKC9XdMO/XyBM7qKORx6UIhGgg6jLl7BZlg==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [darwin] + + '@tailwindcss/oxide-darwin-x64@4.2.2': + resolution: {integrity: sha512-BlR+2c3nzc8f2G639LpL89YY4bdcIdUmiOOkv2GQv4/4M0vJlpXEa0JXNHhCHU7VWOKWT/CjqHdTP8aUuDJkuw==} + engines: {node: '>= 20'} + cpu: [x64] + os: [darwin] + + '@tailwindcss/oxide-freebsd-x64@4.2.2': + resolution: {integrity: sha512-YUqUgrGMSu2CDO82hzlQ5qSb5xmx3RUrke/QgnoEx7KvmRJHQuZHZmZTLSuuHwFf0DJPybFMXMYf+WJdxHy/nQ==} + engines: {node: '>= 20'} + cpu: [x64] + os: [freebsd] + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.2.2': + resolution: {integrity: sha512-FPdhvsW6g06T9BWT0qTwiVZYE2WIFo2dY5aCSpjG/S/u1tby+wXoslXS0kl3/KXnULlLr1E3NPRRw0g7t2kgaQ==} + engines: {node: '>= 20'} + cpu: [arm] + os: [linux] + + '@tailwindcss/oxide-linux-arm64-gnu@4.2.2': + resolution: {integrity: sha512-4og1V+ftEPXGttOO7eCmW7VICmzzJWgMx+QXAJRAhjrSjumCwWqMfkDrNu1LXEQzNAwz28NCUpucgQPrR4S2yw==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + + '@tailwindcss/oxide-linux-arm64-musl@4.2.2': + resolution: {integrity: sha512-oCfG/mS+/+XRlwNjnsNLVwnMWYH7tn/kYPsNPh+JSOMlnt93mYNCKHYzylRhI51X+TbR+ufNhhKKzm6QkqX8ag==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + + '@tailwindcss/oxide-linux-x64-gnu@4.2.2': + resolution: {integrity: sha512-rTAGAkDgqbXHNp/xW0iugLVmX62wOp2PoE39BTCGKjv3Iocf6AFbRP/wZT/kuCxC9QBh9Pu8XPkv/zCZB2mcMg==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + + '@tailwindcss/oxide-linux-x64-musl@4.2.2': + resolution: {integrity: sha512-XW3t3qwbIwiSyRCggeO2zxe3KWaEbM0/kW9e8+0XpBgyKU4ATYzcVSMKteZJ1iukJ3HgHBjbg9P5YPRCVUxlnQ==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + + '@tailwindcss/oxide-wasm32-wasi@4.2.2': + resolution: {integrity: sha512-eKSztKsmEsn1O5lJ4ZAfyn41NfG7vzCg496YiGtMDV86jz1q/irhms5O0VrY6ZwTUkFy/EKG3RfWgxSI3VbZ8Q==} + engines: {node: '>=14.0.0'} + cpu: [wasm32] + bundledDependencies: + - '@napi-rs/wasm-runtime' + - '@emnapi/core' + - '@emnapi/runtime' + - '@tybys/wasm-util' + - '@emnapi/wasi-threads' + - tslib + + '@tailwindcss/oxide-win32-arm64-msvc@4.2.2': + resolution: {integrity: sha512-qPmaQM4iKu5mxpsrWZMOZRgZv1tOZpUm+zdhhQP0VhJfyGGO3aUKdbh3gDZc/dPLQwW4eSqWGrrcWNBZWUWaXQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [win32] + + '@tailwindcss/oxide-win32-x64-msvc@4.2.2': + resolution: {integrity: sha512-1T/37VvI7WyH66b+vqHj/cLwnCxt7Qt3WFu5Q8hk65aOvlwAhs7rAp1VkulBJw/N4tMirXjVnylTR72uI0HGcA==} + engines: {node: '>= 20'} + cpu: [x64] + os: [win32] + + '@tailwindcss/oxide@4.2.2': + resolution: {integrity: sha512-qEUA07+E5kehxYp9BVMpq9E8vnJuBHfJEC0vPC5e7iL/hw7HR61aDKoVoKzrG+QKp56vhNZe4qwkRmMC0zDLvg==} + engines: {node: '>= 20'} + + '@tailwindcss/vite@4.2.2': + resolution: {integrity: sha512-mEiF5HO1QqCLXoNEfXVA1Tzo+cYsrqV7w9Juj2wdUFyW07JRenqMG225MvPwr3ZD9N1bFQj46X7r33iHxLUW0w==} + peerDependencies: + vite: ^5.2.0 || ^6 || ^7 || ^8 + + '@tybys/wasm-util@0.10.1': + resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/debug@4.1.13': + resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/esrecurse@4.3.1': + resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} + + '@types/estree@1.0.8': + resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} + + '@types/fs-extra@11.0.4': + resolution: {integrity: sha512-yTbItCNreRooED33qjunPthRcSjERP1r4MqCZc7wv0u2sUkzTFp45tgUfS5+r7FrZPdmCCNflLhVSP/o+SemsQ==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/jsonfile@6.1.4': + resolution: {integrity: sha512-D5qGUYwjvnNNextdU59/+fI+spnwtTFmyQP0h+PfIOSkNfpU6AOICUOkm4i0OnSk+NyjdPJrxCDro0sJsWlRpQ==} + + '@types/ms@2.1.0': + resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} + + '@types/node@24.12.2': + resolution: {integrity: sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==} + + '@types/node@25.6.0': + resolution: {integrity: sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==} + + '@types/react-dom@19.2.3': + resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==} + peerDependencies: + '@types/react': ^19.2.0 + + '@types/react@19.2.14': + resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} + + '@types/resolve@1.20.2': + resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==} + + '@types/ws@8.18.1': + resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + + '@typescript-eslint/eslint-plugin@8.58.2': + resolution: {integrity: sha512-aC2qc5thQahutKjP+cl8cgN9DWe3ZUqVko30CMSZHnFEHyhOYoZSzkGtAI2mcwZ38xeImDucI4dnqsHiOYuuCw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/parser': ^8.58.2 + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/parser@8.58.2': + resolution: {integrity: sha512-/Zb/xaIDfxeJnvishjGdcR4jmr7S+bda8PKNhRGdljDM+elXhlvN0FyPSsMnLmJUrVG9aPO6dof80wjMawsASg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/project-service@8.58.2': + resolution: {integrity: sha512-Cq6UfpZZk15+r87BkIh5rDpi38W4b+Sjnb8wQCPPDDweS/LRCFjCyViEbzHk5Ck3f2QDfgmlxqSa7S7clDtlfg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/scope-manager@8.58.2': + resolution: {integrity: sha512-SgmyvDPexWETQek+qzZnrG6844IaO02UVyOLhI4wpo82dpZJY9+6YZCKAMFzXb7qhx37mFK1QcPQ18tud+vo6Q==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/tsconfig-utils@8.58.2': + resolution: {integrity: sha512-3SR+RukipDvkkKp/d0jP0dyzuls3DbGmwDpVEc5wqk5f38KFThakqAAO0XMirWAE+kT00oTauTbzMFGPoAzB0A==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/type-utils@8.58.2': + resolution: {integrity: sha512-Z7EloNR/B389FvabdGeTo2XMs4W9TjtPiO9DAsmT0yom0bwlPyRjkJ1uCdW1DvrrrYP50AJZ9Xc3sByZA9+dcg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/types@8.58.2': + resolution: {integrity: sha512-9TukXyATBQf/Jq9AMQXfvurk+G5R2MwfqQGDR2GzGz28HvY/lXNKGhkY+6IOubwcquikWk5cjlgPvD2uAA7htQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/typescript-estree@8.58.2': + resolution: {integrity: sha512-ELGuoofuhhoCvNbQjFFiobFcGgcDCEm0ThWdmO4Z0UzLqPXS3KFvnEZ+SHewwOYHjM09tkzOWXNTv9u6Gqtyuw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/utils@8.58.2': + resolution: {integrity: sha512-QZfjHNEzPY8+l0+fIXMvuQ2sJlplB4zgDZvA+NmvZsZv3EQwOcc1DuIU1VJUTWZ/RKouBMhDyNaBMx4sWvrzRA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/visitor-keys@8.58.2': + resolution: {integrity: sha512-f1WO2Lx8a9t8DARmcWAUPJbu0G20bJlj8L4z72K00TMeJAoyLr/tHhI/pzYBLrR4dXWkcxO1cWYZEOX8DKHTqA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@vitejs/plugin-react@6.0.1': + resolution: {integrity: sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 + babel-plugin-react-compiler: ^1.0.0 + vite: ^8.0.0 + peerDependenciesMeta: + '@rolldown/plugin-babel': + optional: true + babel-plugin-react-compiler: + optional: true + + '@vitest/expect@4.1.4': + resolution: {integrity: sha512-iPBpra+VDuXmBFI3FMKHSFXp3Gx5HfmSCE8X67Dn+bwephCnQCaB7qWK2ldHa+8ncN8hJU8VTMcxjPpyMkUjww==} + + '@vitest/mocker@4.1.4': + resolution: {integrity: sha512-R9HTZBhW6yCSGbGQnDnH3QHfJxokKN4KB+Yvk9Q1le7eQNYwiCyKxmLmurSpFy6BzJanSLuEUDrD+j97Q+ZLPg==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.4': + resolution: {integrity: sha512-ddmDHU0gjEUyEVLxtZa7xamrpIefdEETu3nZjWtHeZX4QxqJ7tRxSteHVXJOcr8jhiLoGAhkK4WJ3WqBpjx42A==} + + '@vitest/runner@4.1.4': + resolution: {integrity: sha512-xTp7VZ5aXP5ZJrn15UtJUWlx6qXLnGtF6jNxHepdPHpMfz/aVPx+htHtgcAL2mDXJgKhpoo2e9/hVJsIeFbytQ==} + + '@vitest/snapshot@4.1.4': + resolution: {integrity: sha512-MCjCFgaS8aZz+m5nTcEcgk/xhWv0rEH4Yl53PPlMXOZ1/Ka2VcZU6CJ+MgYCZbcJvzGhQRjVrGQNZqkGPttIKw==} + + '@vitest/spy@4.1.4': + resolution: {integrity: sha512-XxNdAsKW7C+FLydqFJLb5KhJtl3PGCMmYwFRfhvIgxJvLSXhhVI1zM8f1qD3Zg7RCjTSzDVyct6sghs9UEgBEQ==} + + '@vitest/utils@4.1.4': + resolution: {integrity: sha512-13QMT+eysM5uVGa1rG4kegGYNp6cnQcsTc67ELFbhNLQO+vgsygtYJx2khvdt4gVQqSSpC/KT5FZZxUpP3Oatw==} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn@8.16.0: + resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv@6.14.0: + resolution: {integrity: sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==} + + aria-hidden@1.2.6: + resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==} + engines: {node: '>=10'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + base-log-factory@2.1.4: + resolution: {integrity: sha512-FK1tHOB+rXvlBcGYYhSNR2QS2juEG4SZ1ekXQRQ2XscYNtDxllzqkzfgBFr12EVrKb2/07NLdbr0cSwVoc378A==} + + baseline-browser-mapping@2.10.19: + resolution: {integrity: sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g==} + engines: {node: '>=6.0.0'} + hasBin: true + + blf-colorful-appender@1.0.6: + resolution: {integrity: sha512-MdwOI17J8iOC2XKi5b4VagAJg308R4QesRoCAPw/w7ihzwkTst91LvkTAF3GvPJCEaHXptiUS2UsFkCNiBIEGg==} + + blf-debug-appender@1.0.5: + resolution: {integrity: sha512-ftNcGiVW2nxzG0WJ8Hcs58CbygPl2vMuLDDSxsfhGZmVl2NFGmZOuXhDDeJifvWmP0FHzP/L8dblxn65eQjgEA==} + + brace-expansion@5.0.5: + resolution: {integrity: sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==} + engines: {node: 18 || 20 || >=22} + + browserslist@4.28.2: + resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + caniuse-lite@1.0.30001788: + resolution: {integrity: sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ==} + + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + + chokidar@4.0.3: + resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} + engines: {node: '>= 14.16.0'} + + client-only@0.0.1: + resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} + + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + + commander@14.0.3: + resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} + engines: {node: '>=20'} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + cross-env@10.1.0: + resolution: {integrity: sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==} + engines: {node: '>=20'} + hasBin: true + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + date-manip@2.0.6: + resolution: {integrity: sha512-QGLawF3lq5NOqJ5+pIgvrmE1jL8W9iwwHPAdKyV6gydtmDPngty+87YpSpzMPk9lAMnBIXcf57OKSDEjfuyRyw==} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + deepmerge@4.3.1: + resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} + engines: {node: '>=0.10.0'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + dom-helpers@5.2.1: + resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==} + + electron-to-chromium@1.5.339: + resolution: {integrity: sha512-Is+0BBHJ4NrdpAYiperrmp53pLywG/yV/6lIMTAnhxvzj/Cmn5Q/ogSHC6AKe7X+8kPLxxFk0cs5oc/3j/fxIg==} + + enhanced-resolve@5.20.1: + resolution: {integrity: sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==} + engines: {node: '>=10.13.0'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-module-lexer@2.0.0: + resolution: {integrity: sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==} + + esbuild@0.27.7: + resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==} + engines: {node: '>=18'} + hasBin: true + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-plugin-react-hooks@7.0.1: + resolution: {integrity: sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==} + engines: {node: '>=18'} + peerDependencies: + eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 + + eslint-plugin-react-refresh@0.5.2: + resolution: {integrity: sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==} + peerDependencies: + eslint: ^9 || ^10 + + eslint-scope@9.1.2: + resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@5.0.1: + resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint@10.2.0: + resolution: {integrity: sha512-+L0vBFYGIpSNIt/KWTpFonPrqYvgKw1eUI5Vn7mEogrQcWtWYtNQ7dNqC+px/J0idT3BAkiWrhfS7k+Tum8TUA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@11.2.0: + resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + estree-walker@2.0.2: + resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + expect-type@1.3.0: + resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} + engines: {node: '>=12.0.0'} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + figlet@1.11.0: + resolution: {integrity: sha512-EEx3OS/l2bFqcUNN2NM9FPJp8vAMrgbCxsbl2hbcJNNxOEwVe3mEzrhan7TbJQViZa8mMqhihlbCaqD+LyYKTQ==} + engines: {node: '>= 17.0.0'} + hasBin: true + + file-entry-cache@8.0.0: + resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} + engines: {node: '>=16.0.0'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@4.0.1: + resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} + engines: {node: '>=16'} + + flatted@3.4.2: + resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + + framer-motion@12.38.0: + resolution: {integrity: sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g==} + peerDependencies: + '@emotion/is-prop-valid': '*' + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@emotion/is-prop-valid': + optional: true + react: + optional: true + react-dom: + optional: true + + fs-extra@11.3.4: + resolution: {integrity: sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==} + engines: {node: '>=14.14'} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + gensync@1.0.0-beta.2: + resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} + engines: {node: '>=6.9.0'} + + get-tsconfig@4.14.0: + resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + globals@17.5.0: + resolution: {integrity: sha512-qoV+HK2yFl/366t2/Cb3+xxPUo5BuMynomoDmiaZBIdbs+0pYbjfZU+twLhGKp4uCZ/+NbtpVepH5bGCxRyy2g==} + engines: {node: '>=18'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + hasown@2.0.2: + resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} + engines: {node: '>= 0.4'} + + hermes-estree@0.25.1: + resolution: {integrity: sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==} + + hermes-parser@0.25.1: + resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==} + + hono@4.12.14: + resolution: {integrity: sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==} + engines: {node: '>=16.9.0'} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + ignore@7.0.5: + resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==} + engines: {node: '>= 4'} + + immutable@5.1.5: + resolution: {integrity: sha512-t7xcm2siw+hlUM68I+UEOK+z84RzmN59as9DZ7P1l0994DKUWV7UXBMQZVxaoMSRQ+PBZbHCOoBt7a2wxOMt+A==} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + input-otp@1.4.2: + resolution: {integrity: sha512-l3jWwYNvrEa6NTCt7BECfCm48GvwuZzkoeG3gBL2w4CHeOXW3eKFmf9UNYkNfYc3mxMrthMnxjIE07MT0zLBQA==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc + + intl-messageformat@10.7.18: + resolution: {integrity: sha512-m3Ofv/X/tV8Y3tHXLohcuVuhWKo7BBq62cqY15etqmLxg2DZ34AGGgQDeR+SCta2+zICb1NX83af0GJmbQ1++g==} + + is-core-module@2.16.1: + resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} + engines: {node: '>= 0.4'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-module@1.0.0: + resolution: {integrity: sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==} + + is-what-type@1.1.4: + resolution: {integrity: sha512-120PeT8LdXO7m503rQtOapWA7lHBtWErN+asRxKyxF/SFGeqLEAZhlItjNynNVABHteRMSjomQCdAnxEJldMMQ==} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jiti@2.6.1: + resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} + hasBin: true + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + jsonfile@6.2.0: + resolution: {integrity: sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==} + + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + lightningcss-android-arm64@1.32.0: + resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.32.0: + resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.32.0: + resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.32.0: + resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.32.0: + resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.32.0: + resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-arm64-musl@1.32.0: + resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-x64-gnu@1.32.0: + resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-linux-x64-musl@1.32.0: + resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-win32-arm64-msvc@1.32.0: + resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.32.0: + resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.32.0: + resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} + engines: {node: '>= 12.0.0'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + loose-envify@1.4.0: + resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} + hasBin: true + + lru-cache@5.1.1: + resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + + lucide-react@1.8.0: + resolution: {integrity: sha512-WuvlsjngSk7TnTBJ1hsCy3ql9V9VOdcPkd3PKcSmM34vJD8KG6molxz7m7zbYFgICwsanQWmJ13JlYs4Zp7Arw==} + peerDependencies: + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + minimatch@10.2.5: + resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} + engines: {node: 18 || 20 || >=22} + + motion-dom@12.38.0: + resolution: {integrity: sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA==} + + motion-utils@12.36.0: + resolution: {integrity: sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.11: + resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + node-addon-api@7.1.1: + resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==} + + node-releases@2.0.37: + resolution: {integrity: sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==} + + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + + obug@2.1.1: + resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} + + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.4: + resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} + engines: {node: '>=12'} + + postcss@8.5.10: + resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==} + engines: {node: ^10 || ^12 || >=14} + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prop-types@15.8.1: + resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + react-aria-components@1.16.0: + resolution: {integrity: sha512-MjHbTLpMFzzD2Tv5KbeXoZwPczuUWZcRavVvQQlNHRtXHH38D+sToMEYpNeir7Wh3K/XWtzeX3EujfJW6QNkrw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + react-aria-components@1.17.0: + resolution: {integrity: sha512-0EyisMgvsFJ2aML3crDYv2tW5vT2Ryf8PGzY/g63JjDdCbLshlwazhS8JNtPF1vkTkungJJ6sVJbKyX+YKSoFA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + react-aria@3.48.0: + resolution: {integrity: sha512-jQjd4rBEIMqecBaAKYJbVGK6EqIHLa5znVQ7jwFyK5vCyljoj6KhgtiahmcIPsG5vG5vEDLw+ba+bEWn6A2P4w==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + react-dom@19.2.5: + resolution: {integrity: sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==} + peerDependencies: + react: ^19.2.5 + + react-is@16.13.1: + resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} + + react-stately@3.46.0: + resolution: {integrity: sha512-OdxhWvHgs2L4OJGIs7hnuTr5WjjMM6enhNEAMRqiekhF8+ITvA2LRwNftOZwcogaoCslGYq5S2VQTQwnm0GbCA==} + peerDependencies: + react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 + + react-transition-group@4.4.5: + resolution: {integrity: sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==} + peerDependencies: + react: '>=16.6.0' + react-dom: '>=16.6.0' + + react@19.2.5: + resolution: {integrity: sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==} + engines: {node: '>=0.10.0'} + + readdirp@4.1.2: + resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} + engines: {node: '>= 14.18.0'} + + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + + resolve@1.22.12: + resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} + engines: {node: '>= 0.4'} + hasBin: true + + rolldown@1.0.0-rc.15: + resolution: {integrity: sha512-Ff31guA5zT6WjnGp0SXw76X6hzGRk/OQq2hE+1lcDe+lJdHSgnSX6nK3erbONHyCbpSj9a9E+uX/OvytZoWp2g==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + sass@1.99.0: + resolution: {integrity: sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==} + engines: {node: '>=14.0.0'} + hasBin: true + + scheduler@0.27.0: + resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + + semver@7.7.4: + resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==} + engines: {node: '>=10'} + hasBin: true + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.1.0: + resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + + tailwind-merge@3.4.0: + resolution: {integrity: sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==} + + tailwind-merge@3.5.0: + resolution: {integrity: sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==} + + tailwind-variants@3.2.2: + resolution: {integrity: sha512-Mi4kHeMTLvKlM98XPnK+7HoBPmf4gygdFmqQPaDivc3DpYS6aIY6KiG/PgThrGvii5YZJqRsPz0aPyhoFzmZgg==} + engines: {node: '>=16.x', pnpm: '>=7.x'} + peerDependencies: + tailwind-merge: '>=3.0.0' + tailwindcss: '*' + peerDependenciesMeta: + tailwind-merge: + optional: true + + tailwindcss@4.2.2: + resolution: {integrity: sha512-KWBIxs1Xb6NoLdMVqhbhgwZf2PGBpPEiwOqgI4pFIYbNTfBXiKYyWoTsXgBQ9WFg/OlhnvHaY+AEpW7wSmFo2Q==} + + tapable@2.3.2: + resolution: {integrity: sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==} + engines: {node: '>=6'} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.1.1: + resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} + engines: {node: '>=18'} + + tinyglobby@0.2.16: + resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} + engines: {node: '>=12.0.0'} + + tinyrainbow@3.1.0: + resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} + engines: {node: '>=14.0.0'} + + ts-api-utils@2.5.0: + resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} + engines: {node: '>=18.12'} + peerDependencies: + typescript: '>=4.8.4' + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + tsx@4.21.0: + resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==} + engines: {node: '>=18.0.0'} + hasBin: true + + tw-animate-css@1.4.0: + resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + typescript-eslint@8.58.2: + resolution: {integrity: sha512-V8iSng9mRbdZjl54VJ9NKr6ZB+dW0J3TzRXRGcSbLIej9jV86ZRtlYeTKDR/QLxXykocJ5icNzbsl2+5TzIvcQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + typescript@6.0.2: + resolution: {integrity: sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@7.16.0: + resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + + undici-types@7.19.2: + resolution: {integrity: sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==} + + universalify@2.0.1: + resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} + engines: {node: '>= 10.0.0'} + + update-browserslist-db@1.2.3: + resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + use-sync-external-store@1.6.0: + resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + + vite-plugin-cp@6.0.3: + resolution: {integrity: sha512-qxKGH3v9wPwUDbDchJf4IH4mRE1zkLWgzZSxwrl8LapwUWm48IFS7SlbRmcF4NquC/fESA5cHFge9E2Ps+woxg==} + engines: {node: '>=14.18.0', vite: '>=3.1.0'} + + vite@8.0.8: + resolution: {integrity: sha512-dbU7/iLVa8KZALJyLOBOQ88nOXtNG8vxKuOT4I2mD+Ya70KPceF4IAmDsmU0h1Qsn5bPrvsY9HJstCRh3hG6Uw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.1.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@4.1.4: + resolution: {integrity: sha512-tFuJqTxKb8AvfyqMfnavXdzfy3h3sWZRWwfluGbkeR7n0HUev+FmNgZ8SDrRBTVrVCjgH5cA21qGbCffMNtWvg==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.4 + '@vitest/browser-preview': 4.1.4 + '@vitest/browser-webdriverio': 4.1.4 + '@vitest/coverage-istanbul': 4.1.4 + '@vitest/coverage-v8': 4.1.4 + '@vitest/ui': 4.1.4 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + vp-runtime-helper@1.0.10: + resolution: {integrity: sha512-2HUCkqI0uwgBti1/+utRu7Hvk/I3HeowBQfRlEL3487r+LpW1w91kk6uTZbwOd6I2Sj3aAxBE0HxYNC/NLbuhA==} + engines: {node: '>=14.18.0', vite: '>=3.1.0'} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + ws@8.20.0: + resolution: {integrity: sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + yallist@3.1.1: + resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + + zod-validation-error@4.0.2: + resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==} + engines: {node: '>=18.0.0'} + peerDependencies: + zod: ^3.25.0 || ^4.0.0 + + zod@4.3.6: + resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==} + +snapshots: + + '@adobe/react-spectrum-ui@1.2.1(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@adobe/react-spectrum-workflow@2.3.5(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@adobe/react-spectrum@3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@internationalized/date': 3.12.1 + '@react-types/shared': 3.34.0(react@19.2.5) + '@spectrum-icons/ui': 3.7.0(@adobe/react-spectrum@3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@spectrum-icons/workflow': 4.3.0(@adobe/react-spectrum@3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + client-only: 0.0.1 + clsx: 2.1.1 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-aria-components: 1.17.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + react-transition-group: 4.4.5(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + use-sync-external-store: 1.6.0(react@19.2.5) + + '@babel/code-frame@7.29.0': + dependencies: + '@babel/helper-validator-identifier': 7.28.5 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/compat-data@7.29.0': {} + + '@babel/core@7.29.0': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/generator': 7.29.1 + '@babel/helper-compilation-targets': 7.28.6 + '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.0) + '@babel/helpers': 7.29.2 + '@babel/parser': 7.29.2 + '@babel/template': 7.28.6 + '@babel/traverse': 7.29.0 + '@babel/types': 7.29.0 + '@jridgewell/remapping': 2.3.5 + convert-source-map: 2.0.0 + debug: 4.4.3 + gensync: 1.0.0-beta.2 + json5: 2.2.3 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + '@babel/generator@7.29.1': + dependencies: + '@babel/parser': 7.29.2 + '@babel/types': 7.29.0 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 + + '@babel/helper-compilation-targets@7.28.6': + dependencies: + '@babel/compat-data': 7.29.0 + '@babel/helper-validator-option': 7.27.1 + browserslist: 4.28.2 + lru-cache: 5.1.1 + semver: 6.3.1 + + '@babel/helper-globals@7.28.0': {} + + '@babel/helper-module-imports@7.28.6': + dependencies: + '@babel/traverse': 7.29.0 + '@babel/types': 7.29.0 + transitivePeerDependencies: + - supports-color + + '@babel/helper-module-transforms@7.28.6(@babel/core@7.29.0)': + dependencies: + '@babel/core': 7.29.0 + '@babel/helper-module-imports': 7.28.6 + '@babel/helper-validator-identifier': 7.28.5 + '@babel/traverse': 7.29.0 + transitivePeerDependencies: + - supports-color + + '@babel/helper-string-parser@7.27.1': {} + + '@babel/helper-validator-identifier@7.28.5': {} + + '@babel/helper-validator-option@7.27.1': {} + + '@babel/helpers@7.29.2': + dependencies: + '@babel/template': 7.28.6 + '@babel/types': 7.29.0 + + '@babel/parser@7.29.2': + dependencies: + '@babel/types': 7.29.0 + + '@babel/runtime@7.29.2': {} + + '@babel/template@7.28.6': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/parser': 7.29.2 + '@babel/types': 7.29.0 + + '@babel/traverse@7.29.0': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/generator': 7.29.1 + '@babel/helper-globals': 7.28.0 + '@babel/parser': 7.29.2 + '@babel/template': 7.28.6 + '@babel/types': 7.29.0 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + '@babel/types@7.29.0': + dependencies: + '@babel/helper-string-parser': 7.27.1 + '@babel/helper-validator-identifier': 7.28.5 + + '@emnapi/core@1.9.2': + dependencies: + '@emnapi/wasi-threads': 1.2.1 + tslib: 2.8.1 + optional: true + + '@emnapi/runtime@1.9.2': + dependencies: + tslib: 2.8.1 + optional: true + + '@emnapi/wasi-threads@1.2.1': + dependencies: + tslib: 2.8.1 + optional: true + + '@epic-web/invariant@1.0.0': {} + + '@esbuild/aix-ppc64@0.27.7': + optional: true + + '@esbuild/android-arm64@0.27.7': + optional: true + + '@esbuild/android-arm@0.27.7': + optional: true + + '@esbuild/android-x64@0.27.7': + optional: true + + '@esbuild/darwin-arm64@0.27.7': + optional: true + + '@esbuild/darwin-x64@0.27.7': + optional: true + + '@esbuild/freebsd-arm64@0.27.7': + optional: true + + '@esbuild/freebsd-x64@0.27.7': + optional: true + + '@esbuild/linux-arm64@0.27.7': + optional: true + + '@esbuild/linux-arm@0.27.7': + optional: true + + '@esbuild/linux-ia32@0.27.7': + optional: true + + '@esbuild/linux-loong64@0.27.7': + optional: true + + '@esbuild/linux-mips64el@0.27.7': + optional: true + + '@esbuild/linux-ppc64@0.27.7': + optional: true + + '@esbuild/linux-riscv64@0.27.7': + optional: true + + '@esbuild/linux-s390x@0.27.7': + optional: true + + '@esbuild/linux-x64@0.27.7': + optional: true + + '@esbuild/netbsd-arm64@0.27.7': + optional: true + + '@esbuild/netbsd-x64@0.27.7': + optional: true + + '@esbuild/openbsd-arm64@0.27.7': + optional: true + + '@esbuild/openbsd-x64@0.27.7': + optional: true + + '@esbuild/openharmony-arm64@0.27.7': + optional: true + + '@esbuild/sunos-x64@0.27.7': + optional: true + + '@esbuild/win32-arm64@0.27.7': + optional: true + + '@esbuild/win32-ia32@0.27.7': + optional: true + + '@esbuild/win32-x64@0.27.7': + optional: true + + '@eslint-community/eslint-utils@4.9.1(eslint@10.2.0(jiti@2.6.1))': + dependencies: + eslint: 10.2.0(jiti@2.6.1) + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.2': {} + + '@eslint/config-array@0.23.5': + dependencies: + '@eslint/object-schema': 3.0.5 + debug: 4.4.3 + minimatch: 10.2.5 + transitivePeerDependencies: + - supports-color + + '@eslint/config-helpers@0.5.5': + dependencies: + '@eslint/core': 1.2.1 + + '@eslint/core@1.2.1': + dependencies: + '@types/json-schema': 7.0.15 + + '@eslint/js@10.0.1(eslint@10.2.0(jiti@2.6.1))': + optionalDependencies: + eslint: 10.2.0(jiti@2.6.1) + + '@eslint/object-schema@3.0.5': {} + + '@eslint/plugin-kit@0.7.1': + dependencies: + '@eslint/core': 1.2.1 + levn: 0.4.1 + + '@formatjs/ecma402-abstract@2.3.6': + dependencies: + '@formatjs/fast-memoize': 2.2.7 + '@formatjs/intl-localematcher': 0.6.2 + decimal.js: 10.6.0 + tslib: 2.8.1 + + '@formatjs/fast-memoize@2.2.7': + dependencies: + tslib: 2.8.1 + + '@formatjs/icu-messageformat-parser@2.11.4': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/icu-skeleton-parser': 1.8.16 + tslib: 2.8.1 + + '@formatjs/icu-skeleton-parser@1.8.16': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + tslib: 2.8.1 + + '@formatjs/intl-localematcher@0.6.2': + dependencies: + tslib: 2.8.1 + + '@heroui/react@3.0.2(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)(tailwindcss@4.2.2)': + dependencies: + '@heroui/styles': 3.0.2(tailwind-merge@3.4.0)(tailwindcss@4.2.2) + '@radix-ui/react-avatar': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/i18n': 3.12.16(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/ssr': 3.9.10(react@19.2.5) + '@react-aria/utils': 3.33.1(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/utils': 3.11.0(react@19.2.5) + '@react-types/color': 3.1.4(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/shared': 3.33.1(react@19.2.5) + input-otp: 1.4.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-aria-components: 1.16.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + tailwind-merge: 3.4.0 + tailwind-variants: 3.2.2(tailwind-merge@3.4.0)(tailwindcss@4.2.2) + tailwindcss: 4.2.2 + transitivePeerDependencies: + - '@react-spectrum/provider' + - '@types/react' + - '@types/react-dom' + + '@heroui/styles@3.0.2(tailwind-merge@3.4.0)(tailwindcss@4.2.2)': + dependencies: + tailwind-variants: 3.2.2(tailwind-merge@3.4.0)(tailwindcss@4.2.2) + tailwindcss: 4.2.2 + tw-animate-css: 1.4.0 + transitivePeerDependencies: + - tailwind-merge + + '@heroui/styles@3.0.2(tailwind-merge@3.5.0)(tailwindcss@4.2.2)': + dependencies: + tailwind-variants: 3.2.2(tailwind-merge@3.5.0)(tailwindcss@4.2.2) + tailwindcss: 4.2.2 + tw-animate-css: 1.4.0 + transitivePeerDependencies: + - tailwind-merge + + '@hono/node-server@1.19.14(hono@4.12.14)': + dependencies: + hono: 4.12.14 + + '@humanfs/core@0.19.1': {} + + '@humanfs/node@0.16.7': + dependencies: + '@humanfs/core': 0.19.1 + '@humanwhocodes/retry': 0.4.3 + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/retry@0.4.3': {} + + '@internationalized/date@3.12.1': + dependencies: + '@swc/helpers': 0.5.21 + + '@internationalized/message@3.1.9': + dependencies: + '@swc/helpers': 0.5.21 + intl-messageformat: 10.7.18 + + '@internationalized/number@3.6.6': + dependencies: + '@swc/helpers': 0.5.21 + + '@internationalized/string@3.2.8': + dependencies: + '@swc/helpers': 0.5.21 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + + '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)': + dependencies: + '@emnapi/core': 1.9.2 + '@emnapi/runtime': 1.9.2 + '@tybys/wasm-util': 0.10.1 + optional: true + + '@oxc-project/types@0.124.0': {} + + '@parcel/watcher-android-arm64@2.5.6': + optional: true + + '@parcel/watcher-darwin-arm64@2.5.6': + optional: true + + '@parcel/watcher-darwin-x64@2.5.6': + optional: true + + '@parcel/watcher-freebsd-x64@2.5.6': + optional: true + + '@parcel/watcher-linux-arm-glibc@2.5.6': + optional: true + + '@parcel/watcher-linux-arm-musl@2.5.6': + optional: true + + '@parcel/watcher-linux-arm64-glibc@2.5.6': + optional: true + + '@parcel/watcher-linux-arm64-musl@2.5.6': + optional: true + + '@parcel/watcher-linux-x64-glibc@2.5.6': + optional: true + + '@parcel/watcher-linux-x64-musl@2.5.6': + optional: true + + '@parcel/watcher-win32-arm64@2.5.6': + optional: true + + '@parcel/watcher-win32-ia32@2.5.6': + optional: true + + '@parcel/watcher-win32-x64@2.5.6': + optional: true + + '@parcel/watcher@2.5.6': + dependencies: + detect-libc: 2.1.2 + is-glob: 4.0.3 + node-addon-api: 7.1.1 + picomatch: 4.0.4 + optionalDependencies: + '@parcel/watcher-android-arm64': 2.5.6 + '@parcel/watcher-darwin-arm64': 2.5.6 + '@parcel/watcher-darwin-x64': 2.5.6 + '@parcel/watcher-freebsd-x64': 2.5.6 + '@parcel/watcher-linux-arm-glibc': 2.5.6 + '@parcel/watcher-linux-arm-musl': 2.5.6 + '@parcel/watcher-linux-arm64-glibc': 2.5.6 + '@parcel/watcher-linux-arm64-musl': 2.5.6 + '@parcel/watcher-linux-x64-glibc': 2.5.6 + '@parcel/watcher-linux-x64-musl': 2.5.6 + '@parcel/watcher-win32-arm64': 2.5.6 + '@parcel/watcher-win32-ia32': 2.5.6 + '@parcel/watcher-win32-x64': 2.5.6 + optional: true + + '@radix-ui/react-avatar@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-context': 1.1.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.4(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-is-hydrated': 0.1.0(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + + '@radix-ui/react-compose-refs@1.1.2(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-context@1.1.3(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-primitive@2.1.4(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-slot': 1.2.4(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + + '@radix-ui/react-slot@1.2.4(@types/react@19.2.14)(react@19.2.5)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-callback-ref@1.1.1(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-is-hydrated@0.1.0(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + use-sync-external-store: 1.6.0(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + + '@radix-ui/react-use-layout-effect@1.1.1(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + + '@react-aria/autocomplete@3.0.0-rc.6(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-aria/combobox': 3.16.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/focus': 3.22.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/i18n': 3.12.16(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/interactions': 3.28.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/listbox': 3.16.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/searchfield': 3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/textfield': 3.19.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/utils': 3.33.1(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/autocomplete': 3.0.0-beta.4(react@19.2.5) + '@react-stately/combobox': 3.14.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/autocomplete': 3.0.0-alpha.38(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/button': 3.16.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/shared': 3.33.1(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + transitivePeerDependencies: + - '@react-spectrum/provider' + + '@react-aria/button@3.15.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/collections@3.1.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/combobox@3.16.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/dnd@3.12.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-types/shared': 3.34.0(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/focus@3.22.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/i18n@3.12.16(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@internationalized/date': 3.12.1 + '@internationalized/message': 3.1.9 + '@internationalized/number': 3.6.6 + '@internationalized/string': 3.2.8 + '@react-aria/ssr': 3.9.10(react@19.2.5) + '@react-aria/utils': 3.33.1(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/shared': 3.33.1(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/interactions@3.28.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-types/shared': 3.34.0(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/listbox@3.16.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/live-announcer@3.5.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/overlays@3.32.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/searchfield@3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/slider@3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-types/shared': 3.34.0(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/ssr@3.9.10(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + + '@react-aria/textfield@3.19.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/toolbar@3.0.0-beta.24(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-aria/focus': 3.22.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/i18n': 3.12.16(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/utils': 3.33.1(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/shared': 3.33.1(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/utils@3.33.1(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-aria/ssr': 3.9.10(react@19.2.5) + '@react-stately/flags': 3.2.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/utils': 3.11.0(react@19.2.5) + '@react-types/shared': 3.33.1(react@19.2.5) + '@swc/helpers': 0.5.21 + clsx: 2.1.1 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-aria/virtualizer@4.2.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + + '@react-spectrum/button@3.18.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-spectrum/combobox@3.17.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-spectrum/form@3.8.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-spectrum/searchfield@3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-spectrum/slider@3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-spectrum/table@3.18.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/autocomplete@3.0.0-beta.4(react@19.2.5)': + dependencies: + '@react-stately/utils': 3.11.0(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + + '@react-stately/combobox@3.14.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/flags@3.2.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/grid@3.12.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/layout@4.7.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/searchfield@3.6.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/selection@3.21.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/slider@3.8.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/table@3.16.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-stately/utils@3.11.0(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + + '@react-stately/virtualizer@4.5.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + '@react-types/autocomplete@3.0.0-alpha.38(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-types/combobox': 3.15.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/searchfield': 3.7.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/shared': 3.33.1(react@19.2.5) + react: 19.2.5 + transitivePeerDependencies: + - '@react-spectrum/provider' + - react-dom + + '@react-types/button@3.16.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-aria/button': 3.15.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/button': 3.18.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/provider': 3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-types/color@3.1.4(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-types/shared': 3.33.1(react@19.2.5) + '@react-types/slider': 3.9.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + transitivePeerDependencies: + - '@react-spectrum/provider' + - react-dom + + '@react-types/combobox@3.15.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-aria/combobox': 3.16.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/combobox': 3.17.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/provider': 3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/combobox': 3.14.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-types/form@3.8.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-spectrum/form': 3.8.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/provider': 3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/shared': 3.34.0(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-types/grid@3.4.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-spectrum/provider': 3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/grid': 3.12.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-types/searchfield@3.7.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-aria/searchfield': 3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/provider': 3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/searchfield': 3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/searchfield': 3.6.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-types/shared@3.33.1(react@19.2.5)': + dependencies: + react: 19.2.5 + + '@react-types/shared@3.34.0(react@19.2.5)': + dependencies: + react: 19.2.5 + + '@react-types/slider@3.9.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-aria/slider': 3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/provider': 3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/slider': 3.9.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/slider': 3.8.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@react-types/table@3.14.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@react-spectrum/provider': 3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-spectrum/table': 3.18.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/table': 3.16.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/shared': 3.34.0(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@rolldown/binding-android-arm64@1.0.0-rc.15': + optional: true + + '@rolldown/binding-darwin-arm64@1.0.0-rc.15': + optional: true + + '@rolldown/binding-darwin-x64@1.0.0-rc.15': + optional: true + + '@rolldown/binding-freebsd-x64@1.0.0-rc.15': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.0.0-rc.15': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.0.0-rc.15': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.0.0-rc.15': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.0.0-rc.15': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.0.0-rc.15': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.0.0-rc.15': + optional: true + + '@rolldown/binding-linux-x64-musl@1.0.0-rc.15': + optional: true + + '@rolldown/binding-openharmony-arm64@1.0.0-rc.15': + optional: true + + '@rolldown/binding-wasm32-wasi@1.0.0-rc.15': + dependencies: + '@emnapi/core': 1.9.2 + '@emnapi/runtime': 1.9.2 + '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2) + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.0.0-rc.15': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.0.0-rc.15': + optional: true + + '@rolldown/pluginutils@1.0.0-rc.15': {} + + '@rolldown/pluginutils@1.0.0-rc.7': {} + + '@rollup/plugin-node-resolve@16.0.3': + dependencies: + '@rollup/pluginutils': 5.3.0 + '@types/resolve': 1.20.2 + deepmerge: 4.3.1 + is-module: 1.0.0 + resolve: 1.22.12 + + '@rollup/pluginutils@5.3.0': + dependencies: + '@types/estree': 1.0.8 + estree-walker: 2.0.2 + picomatch: 4.0.4 + + '@spectrum-icons/ui@3.7.0(@adobe/react-spectrum@3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@adobe/react-spectrum-ui': 1.2.1(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@babel/runtime': 7.29.2 + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@spectrum-icons/workflow@4.3.0(@adobe/react-spectrum@3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@adobe/react-spectrum': 3.47.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@adobe/react-spectrum-workflow': 2.3.5(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + '@standard-schema/spec@1.1.0': {} + + '@swc/helpers@0.5.21': + dependencies: + tslib: 2.8.1 + + '@tailwindcss/node@4.2.2': + dependencies: + '@jridgewell/remapping': 2.3.5 + enhanced-resolve: 5.20.1 + jiti: 2.6.1 + lightningcss: 1.32.0 + magic-string: 0.30.21 + source-map-js: 1.2.1 + tailwindcss: 4.2.2 + + '@tailwindcss/oxide-android-arm64@4.2.2': + optional: true + + '@tailwindcss/oxide-darwin-arm64@4.2.2': + optional: true + + '@tailwindcss/oxide-darwin-x64@4.2.2': + optional: true + + '@tailwindcss/oxide-freebsd-x64@4.2.2': + optional: true + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.2.2': + optional: true + + '@tailwindcss/oxide-linux-arm64-gnu@4.2.2': + optional: true + + '@tailwindcss/oxide-linux-arm64-musl@4.2.2': + optional: true + + '@tailwindcss/oxide-linux-x64-gnu@4.2.2': + optional: true + + '@tailwindcss/oxide-linux-x64-musl@4.2.2': + optional: true + + '@tailwindcss/oxide-wasm32-wasi@4.2.2': + optional: true + + '@tailwindcss/oxide-win32-arm64-msvc@4.2.2': + optional: true + + '@tailwindcss/oxide-win32-x64-msvc@4.2.2': + optional: true + + '@tailwindcss/oxide@4.2.2': + optionalDependencies: + '@tailwindcss/oxide-android-arm64': 4.2.2 + '@tailwindcss/oxide-darwin-arm64': 4.2.2 + '@tailwindcss/oxide-darwin-x64': 4.2.2 + '@tailwindcss/oxide-freebsd-x64': 4.2.2 + '@tailwindcss/oxide-linux-arm-gnueabihf': 4.2.2 + '@tailwindcss/oxide-linux-arm64-gnu': 4.2.2 + '@tailwindcss/oxide-linux-arm64-musl': 4.2.2 + '@tailwindcss/oxide-linux-x64-gnu': 4.2.2 + '@tailwindcss/oxide-linux-x64-musl': 4.2.2 + '@tailwindcss/oxide-wasm32-wasi': 4.2.2 + '@tailwindcss/oxide-win32-arm64-msvc': 4.2.2 + '@tailwindcss/oxide-win32-x64-msvc': 4.2.2 + + '@tailwindcss/vite@4.2.2(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))': + dependencies: + '@tailwindcss/node': 4.2.2 + '@tailwindcss/oxide': 4.2.2 + tailwindcss: 4.2.2 + vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + + '@tybys/wasm-util@0.10.1': + dependencies: + tslib: 2.8.1 + optional: true + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/debug@4.1.13': + dependencies: + '@types/ms': 2.1.0 + + '@types/deep-eql@4.0.2': {} + + '@types/esrecurse@4.3.1': {} + + '@types/estree@1.0.8': {} + + '@types/fs-extra@11.0.4': + dependencies: + '@types/jsonfile': 6.1.4 + '@types/node': 24.12.2 + + '@types/json-schema@7.0.15': {} + + '@types/jsonfile@6.1.4': + dependencies: + '@types/node': 24.12.2 + + '@types/ms@2.1.0': {} + + '@types/node@24.12.2': + dependencies: + undici-types: 7.16.0 + + '@types/node@25.6.0': + dependencies: + undici-types: 7.19.2 + + '@types/react-dom@19.2.3(@types/react@19.2.14)': + dependencies: + '@types/react': 19.2.14 + + '@types/react@19.2.14': + dependencies: + csstype: 3.2.3 + + '@types/resolve@1.20.2': {} + + '@types/ws@8.18.1': + dependencies: + '@types/node': 24.12.2 + + '@typescript-eslint/eslint-plugin@8.58.2(@typescript-eslint/parser@8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2))(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2)': + dependencies: + '@eslint-community/regexpp': 4.12.2 + '@typescript-eslint/parser': 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + '@typescript-eslint/scope-manager': 8.58.2 + '@typescript-eslint/type-utils': 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + '@typescript-eslint/utils': 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + '@typescript-eslint/visitor-keys': 8.58.2 + eslint: 10.2.0(jiti@2.6.1) + ignore: 7.0.5 + natural-compare: 1.4.0 + ts-api-utils: 2.5.0(typescript@6.0.2) + typescript: 6.0.2 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2)': + dependencies: + '@typescript-eslint/scope-manager': 8.58.2 + '@typescript-eslint/types': 8.58.2 + '@typescript-eslint/typescript-estree': 8.58.2(typescript@6.0.2) + '@typescript-eslint/visitor-keys': 8.58.2 + debug: 4.4.3 + eslint: 10.2.0(jiti@2.6.1) + typescript: 6.0.2 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/project-service@8.58.2(typescript@6.0.2)': + dependencies: + '@typescript-eslint/tsconfig-utils': 8.58.2(typescript@6.0.2) + '@typescript-eslint/types': 8.58.2 + debug: 4.4.3 + typescript: 6.0.2 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/scope-manager@8.58.2': + dependencies: + '@typescript-eslint/types': 8.58.2 + '@typescript-eslint/visitor-keys': 8.58.2 + + '@typescript-eslint/tsconfig-utils@8.58.2(typescript@6.0.2)': + dependencies: + typescript: 6.0.2 + + '@typescript-eslint/type-utils@8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2)': + dependencies: + '@typescript-eslint/types': 8.58.2 + '@typescript-eslint/typescript-estree': 8.58.2(typescript@6.0.2) + '@typescript-eslint/utils': 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + debug: 4.4.3 + eslint: 10.2.0(jiti@2.6.1) + ts-api-utils: 2.5.0(typescript@6.0.2) + typescript: 6.0.2 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/types@8.58.2': {} + + '@typescript-eslint/typescript-estree@8.58.2(typescript@6.0.2)': + dependencies: + '@typescript-eslint/project-service': 8.58.2(typescript@6.0.2) + '@typescript-eslint/tsconfig-utils': 8.58.2(typescript@6.0.2) + '@typescript-eslint/types': 8.58.2 + '@typescript-eslint/visitor-keys': 8.58.2 + debug: 4.4.3 + minimatch: 10.2.5 + semver: 7.7.4 + tinyglobby: 0.2.16 + ts-api-utils: 2.5.0(typescript@6.0.2) + typescript: 6.0.2 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2)': + dependencies: + '@eslint-community/eslint-utils': 4.9.1(eslint@10.2.0(jiti@2.6.1)) + '@typescript-eslint/scope-manager': 8.58.2 + '@typescript-eslint/types': 8.58.2 + '@typescript-eslint/typescript-estree': 8.58.2(typescript@6.0.2) + eslint: 10.2.0(jiti@2.6.1) + typescript: 6.0.2 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/visitor-keys@8.58.2': + dependencies: + '@typescript-eslint/types': 8.58.2 + eslint-visitor-keys: 5.0.1 + + '@vitejs/plugin-react@6.0.1(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))': + dependencies: + '@rolldown/pluginutils': 1.0.0-rc.7 + vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + + '@vitest/expect@4.1.4': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.4 + '@vitest/utils': 4.1.4 + chai: 6.2.2 + tinyrainbow: 3.1.0 + + '@vitest/mocker@4.1.4(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))': + dependencies: + '@vitest/spy': 4.1.4 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + + '@vitest/pretty-format@4.1.4': + dependencies: + tinyrainbow: 3.1.0 + + '@vitest/runner@4.1.4': + dependencies: + '@vitest/utils': 4.1.4 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.4': + dependencies: + '@vitest/pretty-format': 4.1.4 + '@vitest/utils': 4.1.4 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.4': {} + + '@vitest/utils@4.1.4': + dependencies: + '@vitest/pretty-format': 4.1.4 + convert-source-map: 2.0.0 + tinyrainbow: 3.1.0 + + acorn-jsx@5.3.2(acorn@8.16.0): + dependencies: + acorn: 8.16.0 + + acorn@8.16.0: {} + + ajv@6.14.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + aria-hidden@1.2.6: + dependencies: + tslib: 2.8.1 + + assertion-error@2.0.1: {} + + balanced-match@4.0.4: {} + + base-log-factory@2.1.4: + dependencies: + date-manip: 2.0.6 + is-what-type: 1.1.4 + + baseline-browser-mapping@2.10.19: {} + + blf-colorful-appender@1.0.6: + dependencies: + base-log-factory: 2.1.4 + picocolors: 1.1.1 + + blf-debug-appender@1.0.5: + dependencies: + '@types/debug': 4.1.13 + base-log-factory: 2.1.4 + blf-colorful-appender: 1.0.6 + date-manip: 2.0.6 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + brace-expansion@5.0.5: + dependencies: + balanced-match: 4.0.4 + + browserslist@4.28.2: + dependencies: + baseline-browser-mapping: 2.10.19 + caniuse-lite: 1.0.30001788 + electron-to-chromium: 1.5.339 + node-releases: 2.0.37 + update-browserslist-db: 1.2.3(browserslist@4.28.2) + + caniuse-lite@1.0.30001788: {} + + chai@6.2.2: {} + + chokidar@4.0.3: + dependencies: + readdirp: 4.1.2 + + client-only@0.0.1: {} + + clsx@2.1.1: {} + + commander@14.0.3: {} + + convert-source-map@2.0.0: {} + + cross-env@10.1.0: + dependencies: + '@epic-web/invariant': 1.0.0 + cross-spawn: 7.0.6 + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + csstype@3.2.3: {} + + date-manip@2.0.6: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decimal.js@10.6.0: {} + + deep-is@0.1.4: {} + + deepmerge@4.3.1: {} + + detect-libc@2.1.2: {} + + dom-helpers@5.2.1: + dependencies: + '@babel/runtime': 7.29.2 + csstype: 3.2.3 + + electron-to-chromium@1.5.339: {} + + enhanced-resolve@5.20.1: + dependencies: + graceful-fs: 4.2.11 + tapable: 2.3.2 + + es-errors@1.3.0: {} + + es-module-lexer@2.0.0: {} + + esbuild@0.27.7: + optionalDependencies: + '@esbuild/aix-ppc64': 0.27.7 + '@esbuild/android-arm': 0.27.7 + '@esbuild/android-arm64': 0.27.7 + '@esbuild/android-x64': 0.27.7 + '@esbuild/darwin-arm64': 0.27.7 + '@esbuild/darwin-x64': 0.27.7 + '@esbuild/freebsd-arm64': 0.27.7 + '@esbuild/freebsd-x64': 0.27.7 + '@esbuild/linux-arm': 0.27.7 + '@esbuild/linux-arm64': 0.27.7 + '@esbuild/linux-ia32': 0.27.7 + '@esbuild/linux-loong64': 0.27.7 + '@esbuild/linux-mips64el': 0.27.7 + '@esbuild/linux-ppc64': 0.27.7 + '@esbuild/linux-riscv64': 0.27.7 + '@esbuild/linux-s390x': 0.27.7 + '@esbuild/linux-x64': 0.27.7 + '@esbuild/netbsd-arm64': 0.27.7 + '@esbuild/netbsd-x64': 0.27.7 + '@esbuild/openbsd-arm64': 0.27.7 + '@esbuild/openbsd-x64': 0.27.7 + '@esbuild/openharmony-arm64': 0.27.7 + '@esbuild/sunos-x64': 0.27.7 + '@esbuild/win32-arm64': 0.27.7 + '@esbuild/win32-ia32': 0.27.7 + '@esbuild/win32-x64': 0.27.7 + + escalade@3.2.0: {} + + escape-string-regexp@4.0.0: {} + + eslint-plugin-react-hooks@7.0.1(eslint@10.2.0(jiti@2.6.1)): + dependencies: + '@babel/core': 7.29.0 + '@babel/parser': 7.29.2 + eslint: 10.2.0(jiti@2.6.1) + hermes-parser: 0.25.1 + zod: 4.3.6 + zod-validation-error: 4.0.2(zod@4.3.6) + transitivePeerDependencies: + - supports-color + + eslint-plugin-react-refresh@0.5.2(eslint@10.2.0(jiti@2.6.1)): + dependencies: + eslint: 10.2.0(jiti@2.6.1) + + eslint-scope@9.1.2: + dependencies: + '@types/esrecurse': 4.3.1 + '@types/estree': 1.0.8 + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint-visitor-keys@5.0.1: {} + + eslint@10.2.0(jiti@2.6.1): + dependencies: + '@eslint-community/eslint-utils': 4.9.1(eslint@10.2.0(jiti@2.6.1)) + '@eslint-community/regexpp': 4.12.2 + '@eslint/config-array': 0.23.5 + '@eslint/config-helpers': 0.5.5 + '@eslint/core': 1.2.1 + '@eslint/plugin-kit': 0.7.1 + '@humanfs/node': 0.16.7 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.3 + '@types/estree': 1.0.8 + ajv: 6.14.0 + cross-spawn: 7.0.6 + debug: 4.4.3 + escape-string-regexp: 4.0.0 + eslint-scope: 9.1.2 + eslint-visitor-keys: 5.0.1 + espree: 11.2.0 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 8.0.0 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + minimatch: 10.2.5 + natural-compare: 1.4.0 + optionator: 0.9.4 + optionalDependencies: + jiti: 2.6.1 + transitivePeerDependencies: + - supports-color + + espree@11.2.0: + dependencies: + acorn: 8.16.0 + acorn-jsx: 5.3.2(acorn@8.16.0) + eslint-visitor-keys: 5.0.1 + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + + estree-walker@2.0.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.8 + + esutils@2.0.3: {} + + expect-type@1.3.0: {} + + fast-deep-equal@3.1.3: {} + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + + fdir@6.5.0(picomatch@4.0.4): + optionalDependencies: + picomatch: 4.0.4 + + figlet@1.11.0: + dependencies: + commander: 14.0.3 + + file-entry-cache@8.0.0: + dependencies: + flat-cache: 4.0.1 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@4.0.1: + dependencies: + flatted: 3.4.2 + keyv: 4.5.4 + + flatted@3.4.2: {} + + framer-motion@12.38.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + motion-dom: 12.38.0 + motion-utils: 12.36.0 + tslib: 2.8.1 + optionalDependencies: + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + fs-extra@11.3.4: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.0 + universalify: 2.0.1 + + fsevents@2.3.3: + optional: true + + function-bind@1.1.2: {} + + gensync@1.0.0-beta.2: {} + + get-tsconfig@4.14.0: + dependencies: + resolve-pkg-maps: 1.0.0 + + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + globals@17.5.0: {} + + graceful-fs@4.2.11: {} + + hasown@2.0.2: + dependencies: + function-bind: 1.1.2 + + hermes-estree@0.25.1: {} + + hermes-parser@0.25.1: + dependencies: + hermes-estree: 0.25.1 + + hono@4.12.14: {} + + ignore@5.3.2: {} + + ignore@7.0.5: {} + + immutable@5.1.5: {} + + imurmurhash@0.1.4: {} + + input-otp@1.4.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + intl-messageformat@10.7.18: + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/fast-memoize': 2.2.7 + '@formatjs/icu-messageformat-parser': 2.11.4 + tslib: 2.8.1 + + is-core-module@2.16.1: + dependencies: + hasown: 2.0.2 + + is-extglob@2.1.1: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-module@1.0.0: {} + + is-what-type@1.1.4: {} + + isexe@2.0.0: {} + + jiti@2.6.1: {} + + js-tokens@4.0.0: {} + + jsesc@3.1.0: {} + + json-buffer@3.0.1: {} + + json-schema-traverse@0.4.1: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + json5@2.2.3: {} + + jsonfile@6.2.0: + dependencies: + universalify: 2.0.1 + optionalDependencies: + graceful-fs: 4.2.11 + + keyv@4.5.4: + dependencies: + json-buffer: 3.0.1 + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + + lightningcss-android-arm64@1.32.0: + optional: true + + lightningcss-darwin-arm64@1.32.0: + optional: true + + lightningcss-darwin-x64@1.32.0: + optional: true + + lightningcss-freebsd-x64@1.32.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.32.0: + optional: true + + lightningcss-linux-arm64-gnu@1.32.0: + optional: true + + lightningcss-linux-arm64-musl@1.32.0: + optional: true + + lightningcss-linux-x64-gnu@1.32.0: + optional: true + + lightningcss-linux-x64-musl@1.32.0: + optional: true + + lightningcss-win32-arm64-msvc@1.32.0: + optional: true + + lightningcss-win32-x64-msvc@1.32.0: + optional: true + + lightningcss@1.32.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.32.0 + lightningcss-darwin-arm64: 1.32.0 + lightningcss-darwin-x64: 1.32.0 + lightningcss-freebsd-x64: 1.32.0 + lightningcss-linux-arm-gnueabihf: 1.32.0 + lightningcss-linux-arm64-gnu: 1.32.0 + lightningcss-linux-arm64-musl: 1.32.0 + lightningcss-linux-x64-gnu: 1.32.0 + lightningcss-linux-x64-musl: 1.32.0 + lightningcss-win32-arm64-msvc: 1.32.0 + lightningcss-win32-x64-msvc: 1.32.0 + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + loose-envify@1.4.0: + dependencies: + js-tokens: 4.0.0 + + lru-cache@5.1.1: + dependencies: + yallist: 3.1.1 + + lucide-react@1.8.0(react@19.2.5): + dependencies: + react: 19.2.5 + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + minimatch@10.2.5: + dependencies: + brace-expansion: 5.0.5 + + motion-dom@12.38.0: + dependencies: + motion-utils: 12.36.0 + + motion-utils@12.36.0: {} + + ms@2.1.3: {} + + nanoid@3.3.11: {} + + natural-compare@1.4.0: {} + + node-addon-api@7.1.1: + optional: true + + node-releases@2.0.37: {} + + object-assign@4.1.1: {} + + obug@2.1.1: {} + + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + path-exists@4.0.0: {} + + path-key@3.1.1: {} + + path-parse@1.0.7: {} + + pathe@2.0.3: {} + + picocolors@1.1.1: {} + + picomatch@4.0.4: {} + + postcss@8.5.10: + dependencies: + nanoid: 3.3.11 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + prelude-ls@1.2.1: {} + + prop-types@15.8.1: + dependencies: + loose-envify: 1.4.0 + object-assign: 4.1.1 + react-is: 16.13.1 + + punycode@2.3.1: {} + + react-aria-components@1.16.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + '@internationalized/date': 3.12.1 + '@internationalized/string': 3.2.8 + '@react-aria/autocomplete': 3.0.0-rc.6(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/collections': 3.1.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/dnd': 3.12.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/focus': 3.22.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/interactions': 3.28.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/live-announcer': 3.5.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/overlays': 3.32.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/ssr': 3.9.10(react@19.2.5) + '@react-aria/textfield': 3.19.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/toolbar': 3.0.0-beta.24(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/utils': 3.33.1(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-aria/virtualizer': 4.2.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/autocomplete': 3.0.0-beta.4(react@19.2.5) + '@react-stately/layout': 4.7.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/selection': 3.21.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/table': 3.16.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-stately/utils': 3.11.0(react@19.2.5) + '@react-stately/virtualizer': 4.5.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/form': 3.8.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/grid': 3.4.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@react-types/shared': 3.33.1(react@19.2.5) + '@react-types/table': 3.14.0(@react-spectrum/provider@3.11.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@swc/helpers': 0.5.21 + client-only: 0.0.1 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + use-sync-external-store: 1.6.0(react@19.2.5) + transitivePeerDependencies: + - '@react-spectrum/provider' + + react-aria-components@1.17.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + '@internationalized/date': 3.12.1 + '@react-types/shared': 3.34.0(react@19.2.5) + '@swc/helpers': 0.5.21 + client-only: 0.0.1 + react: 19.2.5 + react-aria: 3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + + react-aria@3.48.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + '@internationalized/date': 3.12.1 + '@internationalized/number': 3.6.6 + '@internationalized/string': 3.2.8 + '@react-types/shared': 3.34.0(react@19.2.5) + '@swc/helpers': 0.5.21 + aria-hidden: 1.2.6 + clsx: 2.1.1 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-stately: 3.46.0(react@19.2.5) + use-sync-external-store: 1.6.0(react@19.2.5) + + react-dom@19.2.5(react@19.2.5): + dependencies: + react: 19.2.5 + scheduler: 0.27.0 + + react-is@16.13.1: {} + + react-stately@3.46.0(react@19.2.5): + dependencies: + '@internationalized/date': 3.12.1 + '@internationalized/number': 3.6.6 + '@internationalized/string': 3.2.8 + '@react-types/shared': 3.34.0(react@19.2.5) + '@swc/helpers': 0.5.21 + react: 19.2.5 + use-sync-external-store: 1.6.0(react@19.2.5) + + react-transition-group@4.4.5(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + '@babel/runtime': 7.29.2 + dom-helpers: 5.2.1 + loose-envify: 1.4.0 + prop-types: 15.8.1 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + + react@19.2.5: {} + + readdirp@4.1.2: {} + + resolve-pkg-maps@1.0.0: {} + + resolve@1.22.12: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.16.1 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + + rolldown@1.0.0-rc.15: + dependencies: + '@oxc-project/types': 0.124.0 + '@rolldown/pluginutils': 1.0.0-rc.15 + optionalDependencies: + '@rolldown/binding-android-arm64': 1.0.0-rc.15 + '@rolldown/binding-darwin-arm64': 1.0.0-rc.15 + '@rolldown/binding-darwin-x64': 1.0.0-rc.15 + '@rolldown/binding-freebsd-x64': 1.0.0-rc.15 + '@rolldown/binding-linux-arm-gnueabihf': 1.0.0-rc.15 + '@rolldown/binding-linux-arm64-gnu': 1.0.0-rc.15 + '@rolldown/binding-linux-arm64-musl': 1.0.0-rc.15 + '@rolldown/binding-linux-ppc64-gnu': 1.0.0-rc.15 + '@rolldown/binding-linux-s390x-gnu': 1.0.0-rc.15 + '@rolldown/binding-linux-x64-gnu': 1.0.0-rc.15 + '@rolldown/binding-linux-x64-musl': 1.0.0-rc.15 + '@rolldown/binding-openharmony-arm64': 1.0.0-rc.15 + '@rolldown/binding-wasm32-wasi': 1.0.0-rc.15 + '@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.15 + '@rolldown/binding-win32-x64-msvc': 1.0.0-rc.15 + + sass@1.99.0: + dependencies: + chokidar: 4.0.3 + immutable: 5.1.5 + source-map-js: 1.2.1 + optionalDependencies: + '@parcel/watcher': 2.5.6 + + scheduler@0.27.0: {} + + semver@6.3.1: {} + + semver@7.7.4: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + siginfo@2.0.0: {} + + source-map-js@1.2.1: {} + + stackback@0.0.2: {} + + std-env@4.1.0: {} + + supports-preserve-symlinks-flag@1.0.0: {} + + tailwind-merge@3.4.0: {} + + tailwind-merge@3.5.0: {} + + tailwind-variants@3.2.2(tailwind-merge@3.4.0)(tailwindcss@4.2.2): + dependencies: + tailwindcss: 4.2.2 + optionalDependencies: + tailwind-merge: 3.4.0 + + tailwind-variants@3.2.2(tailwind-merge@3.5.0)(tailwindcss@4.2.2): + dependencies: + tailwindcss: 4.2.2 + optionalDependencies: + tailwind-merge: 3.5.0 + + tailwindcss@4.2.2: {} + + tapable@2.3.2: {} + + tinybench@2.9.0: {} + + tinyexec@1.1.1: {} + + tinyglobby@0.2.16: + dependencies: + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 + + tinyrainbow@3.1.0: {} + + ts-api-utils@2.5.0(typescript@6.0.2): + dependencies: + typescript: 6.0.2 + + tslib@2.8.1: {} + + tsx@4.21.0: + dependencies: + esbuild: 0.27.7 + get-tsconfig: 4.14.0 + optionalDependencies: + fsevents: 2.3.3 + + tw-animate-css@1.4.0: {} + + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + typescript-eslint@8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2): + dependencies: + '@typescript-eslint/eslint-plugin': 8.58.2(@typescript-eslint/parser@8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2))(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + '@typescript-eslint/parser': 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + '@typescript-eslint/typescript-estree': 8.58.2(typescript@6.0.2) + '@typescript-eslint/utils': 8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) + eslint: 10.2.0(jiti@2.6.1) + typescript: 6.0.2 + transitivePeerDependencies: + - supports-color + + typescript@6.0.2: {} + + undici-types@7.16.0: {} + + undici-types@7.19.2: {} + + universalify@2.0.1: {} + + update-browserslist-db@1.2.3(browserslist@4.28.2): + dependencies: + browserslist: 4.28.2 + escalade: 3.2.0 + picocolors: 1.1.1 + + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + + use-sync-external-store@1.6.0(react@19.2.5): + dependencies: + react: 19.2.5 + + vite-plugin-cp@6.0.3: + dependencies: + fs-extra: 11.3.4 + is-what-type: 1.1.4 + tinyglobby: 0.2.16 + vp-runtime-helper: 1.0.10 + transitivePeerDependencies: + - supports-color + + vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0): + dependencies: + lightningcss: 1.32.0 + picomatch: 4.0.4 + postcss: 8.5.10 + rolldown: 1.0.0-rc.15 + tinyglobby: 0.2.16 + optionalDependencies: + '@types/node': 24.12.2 + esbuild: 0.27.7 + fsevents: 2.3.3 + jiti: 2.6.1 + sass: 1.99.0 + tsx: 4.21.0 + + vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0): + dependencies: + lightningcss: 1.32.0 + picomatch: 4.0.4 + postcss: 8.5.10 + rolldown: 1.0.0-rc.15 + tinyglobby: 0.2.16 + optionalDependencies: + '@types/node': 25.6.0 + esbuild: 0.27.7 + fsevents: 2.3.3 + jiti: 2.6.1 + sass: 1.99.0 + tsx: 4.21.0 + + vitest@4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)): + dependencies: + '@vitest/expect': 4.1.4 + '@vitest/mocker': 4.1.4(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + '@vitest/pretty-format': 4.1.4 + '@vitest/runner': 4.1.4 + '@vitest/snapshot': 4.1.4 + '@vitest/spy': 4.1.4 + '@vitest/utils': 4.1.4 + es-module-lexer: 2.0.0 + expect-type: 1.3.0 + magic-string: 0.30.21 + obug: 2.1.1 + pathe: 2.0.3 + picomatch: 4.0.4 + std-env: 4.1.0 + tinybench: 2.9.0 + tinyexec: 1.1.1 + tinyglobby: 0.2.16 + tinyrainbow: 3.1.0 + vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.12.2 + transitivePeerDependencies: + - msw + + vp-runtime-helper@1.0.10: + dependencies: + '@types/fs-extra': 11.0.4 + base-log-factory: 2.1.4 + blf-debug-appender: 1.0.5 + figlet: 1.11.0 + fs-extra: 11.3.4 + picocolors: 1.1.1 + transitivePeerDependencies: + - supports-color + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + word-wrap@1.2.5: {} + + ws@8.20.0: {} + + yallist@3.1.1: {} + + yocto-queue@0.1.0: {} + + zod-validation-error@4.0.2(zod@4.3.6): + dependencies: + zod: 4.3.6 + + zod@4.3.6: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 00000000..784b2496 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,9 @@ +packages: + - 'webui' + +catalog: + vite: ^8.0.8 + typescript: ~6.0.2 + +overrides: + tar: ^7.5.13 diff --git a/src/bridge/bridge-actions.ts b/src/bridge/bridge-actions.ts new file mode 100644 index 00000000..29b2da33 --- /dev/null +++ b/src/bridge/bridge-actions.ts @@ -0,0 +1,1244 @@ +// Admin / action operations extracted from Bridge. + +import type { Bridge } from './bridge'; +import type { PacketInfo } from '../protocol/types'; +import { protoDecode, protoEncode } from '../protobuf/decode'; +import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from './bridge-oidb'; +import { fetchHighwaySession, uploadHighwayHttp } from './highway/highway-client'; +import { computeHashes, computeMd5, loadBinarySource } from './highway/utils'; +import { buildSendElems } from './builders/element-builder'; +import { parseMsgPush } from './handlers/msg-push-handler'; +import type { ForwardNodePayload, MessageElement } from './events'; +import { PushMsgSchema } from './proto/message'; +import { + OidbMuteMemberSchema, + OidbMuteAllSchema, + OidbKickMemberSchema, + OidbLeaveGroupSchema, + OidbFriendRequestActionSchema, + OidbDeleteFriendSchema, + OidbGroupRequestActionSchema, + OidbPokeSchema, + OidbEssenceSchema, + OidbSetAdminSchema, + OidbRenameMemberSchema, + OidbRenameGroupSchema, + OidbSpecialTitleSchema, + OidbLikeSchema, + OidbGroupReactionSchema, + OidbSetFriendRemarkSchema, + OidbGroupFileCountViewReqSchema, + OidbGroupFileCountViewRespSchema, + OidbGroupFileViewReqSchema, + OidbGroupFileViewRespSchema, + OidbGroupFileReqSchema, + OidbGroupFileRespSchema, + OidbGroupFileFolderReqSchema, + OidbGroupFileFolderRespSchema, + OidbPrivateFileDownloadReqSchema, + OidbPrivateFileDownloadRespSchema, + OidbPrivateFileUploadReqSchema, + OidbPrivateFileUploadRespSchema, + NTV2RichMediaReqSchema, + NTV2RichMediaRespSchema, + GroupRecallRequestSchema, + C2CRecallRequestSchema, +} from './proto/oidb-action'; +import { FileUploadExtSchema } from './proto/highway'; +import { + LongMsgResultSchema, + RecvLongMsgReqSchema, + RecvLongMsgRespSchema, + SendLongMsgReqSchema, + SendLongMsgRespSchema, +} from './proto/longmsg'; +import { gzipSync, gunzipSync } from 'zlib'; + +export interface GroupFileInfo { + fileId: string; + fileName: string; + busId: number; + fileSize: number; + uploadTime: number; + deadTime: number; + modifyTime: number; + downloadTimes: number; + uploader: number; + uploaderName: string; +} + +export interface GroupFolderInfo { + folderId: string; + folderName: string; + createTime: number; + creator: number; + creatorName: string; + totalFileCount: number; +} + +export interface GroupFilesResult { + files: GroupFileInfo[]; + folders: GroupFolderInfo[]; +} + +export interface UploadFileResult { + fileId: string | null; + fileHash?: string | null; +} + +export interface MediaIndexNode { + info?: { + fileSize?: number; + fileHash?: string; + fileSha1?: string; + fileName?: string; + width?: number; + height?: number; + time?: number; + original?: number; + type?: { + type?: number; + picFormat?: number; + videoFormat?: number; + voiceFormat?: number; + }; + }; + fileUuid?: string; + storeId?: number; + uploadTime?: number; + ttl?: number; + subType?: number; +} + +const forwardResCache = new Map(); + +function toInt(value: unknown): number { + if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); + if (typeof value === 'bigint') { + const n = Number(value); + return Number.isFinite(n) ? Math.trunc(n) : 0; + } + if (typeof value === 'string' && value.trim()) { + const n = Number(value); + return Number.isFinite(n) ? Math.trunc(n) : 0; + } + return 0; +} + +function ensureRetCodeZero(operation: string, code: unknown, msg: unknown, wording: unknown): void { + const retCode = toInt(code); + if (retCode === 0) return; + const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error'; + throw new Error(`${operation} failed: code=${retCode} msg=${text}`); +} + +function normalizeDirectory(dir?: string): string { + if (!dir || !dir.trim()) return '/'; + return dir; +} + +function bytesToHexUpper(data: unknown): string { + if (!(data instanceof Uint8Array) || data.length === 0) return ''; + return Buffer.from(data).toString('hex').toUpperCase(); +} + +function normalizeUploadFileName(name: string, fallback: string): string { + const trimmed = name.trim(); + if (trimmed) return trimmed; + const safeFallback = fallback.trim(); + return safeFallback || 'file.bin'; +} + +function md5First10MB(bytes: Uint8Array): Uint8Array { + const limit = Math.min(bytes.length, 10 * 1024 * 1024); + return computeMd5(bytes.subarray(0, limit)); +} + +function buildGroupFileUploadExt( + senderUin: number, + groupId: number, + fileName: string, + fileSize: number, + md5: Uint8Array, + fileId: string, + uploadKey: Uint8Array, + checkKey: Uint8Array, + uploadHost: string, + uploadPort: number, +): Uint8Array { + return protoEncode({ + unknown1: 100, + unknown2: 1, + entry: { + busiBuff: { + busId: 102, + senderUin: BigInt(senderUin), + receiverUin: BigInt(groupId), + groupCode: BigInt(groupId), + }, + fileEntry: { + fileSize: BigInt(Math.max(0, fileSize)), + md5, + md5S2: md5, + checkKey, + fileId, + uploadKey, + }, + clientInfo: { + clientType: 3, + appId: '100', + terminalType: 3, + clientVer: '1.1.1', + unknown: 4, + }, + fileNameInfo: { + fileName, + }, + host: { + hosts: [ + { + url: { + host: uploadHost, + unknown: 1, + }, + port: uploadPort, + }, + ], + }, + }, + unknown200: 0, + }, FileUploadExtSchema); +} + +function buildPrivateFileUploadExt( + senderUin: number, + fileName: string, + fileSize: number, + md5: Uint8Array, + sha1: Uint8Array, + fileId: string, + uploadKey: Uint8Array, + uploadHost: string, + uploadPort: number, +): Uint8Array { + return protoEncode({ + unknown1: 100, + unknown2: 1, + entry: { + busiBuff: { + busId: 102, + senderUin: BigInt(senderUin), + receiverUin: 0n, + groupCode: 0n, + }, + fileEntry: { + fileSize: BigInt(Math.max(0, fileSize)), + md5, + md5S2: md5, + checkKey: sha1, + fileId, + uploadKey, + }, + clientInfo: { + clientType: 3, + appId: '100', + terminalType: 3, + clientVer: '1.1.1', + unknown: 4, + }, + fileNameInfo: { + fileName, + }, + host: { + hosts: [ + { + url: { + host: uploadHost, + unknown: 1, + }, + port: uploadPort, + }, + ], + }, + }, + unknown3: 0, + unknown200: 1, + }, FileUploadExtSchema); +} + +async function resolveSelfUid(bridge: Bridge): Promise { + let selfUid = bridge.qqInfo.selfUid; + if (selfUid) return selfUid; + + const selfUin = toInt(bridge.qqInfo.uin); + if (selfUin <= 0) { + throw new Error('self uid is unavailable'); + } + selfUid = await resolveUserUid(bridge, selfUin); + return selfUid; +} + +function normalizeMediaNode(node: MediaIndexNode): Record { + const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : ''; + if (!fileUuid) throw new Error('media node fileUuid is required'); + + const info = node.info ?? {}; + const type = info.type ?? {}; + + return { + info: { + fileSize: toInt(info.fileSize), + fileHash: typeof info.fileHash === 'string' ? info.fileHash : '', + fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '', + fileName: typeof info.fileName === 'string' ? info.fileName : '', + type: { + type: toInt(type.type), + picFormat: toInt(type.picFormat), + videoFormat: toInt(type.videoFormat), + voiceFormat: toInt(type.voiceFormat), + }, + width: toInt(info.width), + height: toInt(info.height), + time: toInt(info.time), + original: toInt(info.original), + }, + fileUuid, + storeId: toInt(node.storeId), + uploadTime: toInt(node.uploadTime), + ttl: toInt(node.ttl), + subType: toInt(node.subType), + }; +} + +async function fetchNtv2DownloadUrl( + bridge: Bridge, + serviceCmd: string, + oidbCmd: number, + payload: Record, +): Promise { + const resp = await sendOidbAndDecode( + bridge, + serviceCmd, + oidbCmd, + 200, + payload, + NTV2RichMediaReqSchema, + NTV2RichMediaRespSchema, + true, + ); + + ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined); + const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : ''; + const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : ''; + const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : ''; + + if (!domain || !path) { + throw new Error('ntv2 download response invalid'); + } + return `https://${domain}${path}${rKeyParam}`; +} + +async function buildForwardPushBody( + bridge: Bridge, + node: ForwardNodePayload, +): Promise> { + const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.qqInfo.uin); + if (fromUin <= 0) throw new Error('forward node user uin is invalid'); + + const nickname = node.nickname.trim() || String(fromUin); + const elems = await buildSendElems(node.elements); + const now = Math.floor(Date.now() / 1000); + const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; + const seq = Math.floor(Math.random() * 9000000) + 1000000; + + return { + responseHead: { + fromUin, + toUid: bridge.qqInfo.selfUid ?? '', + forward: { + friendName: nickname, + }, + }, + contentHead: { + msgType: 9, + subType: 4, + msgId: random, + sequence: seq, + timestamp: now, + divSeq: 0, + }, + body: { + richText: { + elems, + }, + }, + }; +} + +// --------------------------------------------------------------------------- +// Friend actions +// --------------------------------------------------------------------------- + +export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise { + const uid = await resolveUserUid(bridge, userId); + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2, + { targetUid: uid, remark }, OidbSetFriendRemarkSchema); +} + +// --------------------------------------------------------------------------- +// Group file count +// --------------------------------------------------------------------------- + +export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { + const resp = await sendOidbAndDecode(bridge, + 'OidbSvcTrpcTcp.0x6d8_3', 0x6D8, 3, + { count: { groupUin: groupId, appId: 7, busId: 0 } }, + OidbGroupFileCountViewReqSchema, + OidbGroupFileCountViewRespSchema); + return { + fileCount: toInt(resp?.count?.fileCount ?? 0), + maxCount: toInt(resp?.count?.maxCount ?? 10000), + }; +} + +// --------------------------------------------------------------------------- +// Group admin actions +// --------------------------------------------------------------------------- + +export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise { + const uid = await resolveUserUid(bridge, userId, groupId); + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1253_1', 0x1253, 1, + { groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, OidbMuteMemberSchema); +} + +export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise { + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, + { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema); +} + +export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise { + const uid = await resolveUserUid(bridge, userId, groupId); + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1, + { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema); +} + +export async function leaveGroup(bridge: Bridge, groupId: number): Promise { + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1, + { groupUin: groupId }, OidbLeaveGroupSchema); +} + +export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise { + const uid = await resolveUserUid(bridge, userId, groupId); + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1096_1', 0x1096, 1, + { groupUin: groupId, uid, isAdmin: enable }, OidbSetAdminSchema); +} + +export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise { + const uid = await resolveUserUid(bridge, userId, groupId); + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_3', 0x8FC, 3, + { groupUin: groupId, body: { targetUid: uid, targetName: card } }, OidbRenameMemberSchema); +} + +export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise { + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_15', 0x89A, 15, + { groupUin: groupId, body: { targetName: name } }, OidbRenameGroupSchema); +} + +export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise { + const uid = await resolveUserUid(bridge, userId, groupId); + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_2', 0x8FC, 2, + { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, OidbSpecialTitleSchema); +} + +// --------------------------------------------------------------------------- +// Friend / group add requests +// --------------------------------------------------------------------------- + +export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise { + let targetUid = uidOrFlag; + if (/^\d+$/.test(uidOrFlag)) { + targetUid = await resolveUserUid(bridge, parseInt(uidOrFlag, 10)); + } + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb5d_44', 0xB5D, 44, + { accept: approve ? 3 : 5, targetUid }, OidbFriendRequestActionSchema); +} + +export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise { + const targetUid = await resolveUserUid(bridge, userId); + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x126b_0', 0x126B, 0, + { + field1: { + targetUid, + field2: { + field1: 130, + field2: 109, + field3: { + field1: 8, + field2: 8, + field3: 50, + }, + }, + block, + field4: false, + }, + }, + OidbDeleteFriendSchema); + + // Refresh friend cache after deletion. + try { await bridge.fetchFriendList(); } catch { /* ignore */ } +} + +// --------------------------------------------------------------------------- +// Group / private file operations +// --------------------------------------------------------------------------- + +export async function uploadGroupFile( + bridge: Bridge, + groupId: number, + source: string, + name = '', + folderId = '/', + uploadFile = true, +): Promise { + const loaded = await loadBinarySource(source, 'file'); + if (!loaded.bytes.length) throw new Error('group file is empty'); + + const fileName = normalizeUploadFileName(name, loaded.fileName); + const hashes = computeHashes(loaded.bytes); + + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x6d6_0', + 0x6D6, + 0, + { + file: { + groupUin: groupId, + appId: 4, + busId: 102, + entrance: 6, + targetDirectory: normalizeDirectory(folderId), + fileName, + localDirectory: `/${fileName}`, + fileSize: BigInt(loaded.bytes.length), + fileSha1: hashes.sha1, + fileSha3: new Uint8Array(0), + fileMd5: hashes.md5, + field15: true, + }, + }, + OidbGroupFileReqSchema, + OidbGroupFileRespSchema, + true, + ); + + const upload = resp?.upload; + if (!upload) throw new Error('group file upload response missing'); + ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording); + + const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null; + if (!fileId) throw new Error('group file upload response missing file_id'); + + if (!upload.boolFileExist && uploadFile) { + const senderUin = toInt(bridge.qqInfo.uin); + if (senderUin <= 0) throw new Error('invalid self uin for group file upload'); + + const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) + || (typeof upload.serverDns === 'string' && upload.serverDns) + || ''; + const uploadPort = toInt(upload.uploadPort); + if (!uploadHost || uploadPort <= 0) { + throw new Error('group file upload host is invalid'); + } + + const ext = buildGroupFileUploadExt( + senderUin, + groupId, + fileName, + loaded.bytes.length, + hashes.md5, + fileId, + upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0), + upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0), + uploadHost, + uploadPort, + ); + + const session = await fetchHighwaySession(bridge); + await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext); + } + + return { fileId }; +} + +export async function uploadPrivateFile( + bridge: Bridge, + userId: number, + source: string, + name = '', + uploadFile = true, +): Promise { + const loaded = await loadBinarySource(source, 'file'); + if (!loaded.bytes.length) throw new Error('private file is empty'); + + const targetUid = await resolveUserUid(bridge, userId); + let selfUid = bridge.qqInfo.selfUid; + if (!selfUid) { + const selfUin = toInt(bridge.qqInfo.uin); + if (selfUin > 0) { + selfUid = await resolveUserUid(bridge, selfUin); + } + } + if (!selfUid) throw new Error('self uid is unavailable'); + + const senderUin = toInt(bridge.qqInfo.uin); + if (senderUin <= 0) throw new Error('invalid self uin for private file upload'); + + const fileName = normalizeUploadFileName(name, loaded.fileName); + const hashes = computeHashes(loaded.bytes); + + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0xe37_1700', + 0xE37, + 1700, + { + command: 1700, + seq: 0, + upload: { + senderUid: selfUid, + receiverUid: targetUid, + fileSize: loaded.bytes.length, + fileName, + md510MCheckSum: md5First10MB(loaded.bytes), + sha1CheckSum: hashes.sha1, + localPath: '/', + md5CheckSum: hashes.md5, + sha3CheckSum: new Uint8Array(0), + }, + businessId: 3, + clientType: 1, + flagSupportMediaPlatform: 1, + }, + OidbPrivateFileUploadReqSchema, + OidbPrivateFileUploadRespSchema, + ); + + const upload = resp?.upload; + if (!upload) throw new Error('private file upload response missing'); + ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined); + + const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null; + const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null; + if (!fileId) throw new Error('private file upload response missing file_id'); + + if (!upload.boolFileExist && uploadFile) { + const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) + || ''; + const uploadPort = toInt(upload.uploadPort); + if (!uploadHost || uploadPort <= 0) { + throw new Error('private file upload host is invalid'); + } + + const ext = buildPrivateFileUploadExt( + senderUin, + fileName, + loaded.bytes.length, + hashes.md5, + hashes.sha1, + fileId, + upload.mediaPlatformUploadKey instanceof Uint8Array + ? upload.mediaPlatformUploadKey + : (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)), + uploadHost, + uploadPort, + ); + + const session = await fetchHighwaySession(bridge); + await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext); + } + + return { fileId, fileHash }; +} + +export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId = '/'): Promise { + const targetDirectory = normalizeDirectory(folderId); + const files: GroupFileInfo[] = []; + const folders: GroupFolderInfo[] = []; + + const pageSize = 20; + let startIndex = 0; + for (let page = 0; page < 200; page++) { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x6d8_1', + 0x6D8, + 1, + { + list: { + groupUin: groupId, + appId: 7, + targetDirectory, + fileCount: pageSize, + sortBy: 1, + startIndex, + field17: 2, + field18: 0, + }, + }, + OidbGroupFileViewReqSchema, + OidbGroupFileViewRespSchema, + true, + ); + + const list = resp?.list; + if (!list) break; + ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording); + + for (const item of list.items ?? []) { + const type = toInt(item?.type); + if (type === 1 && item?.fileInfo) { + const file = item.fileInfo; + const uploader = toInt(file.uploaderUin); + const cached = bridge.qqInfo.findGroupMember(groupId, uploader); + files.push({ + fileId: typeof file.fileId === 'string' ? file.fileId : '', + fileName: typeof file.fileName === 'string' ? file.fileName : '', + busId: toInt(file.busId), + fileSize: toInt(file.fileSize), + uploadTime: toInt(file.uploadedTime), + deadTime: toInt(file.expireTime), + modifyTime: toInt(file.modifiedTime), + downloadTimes: toInt(file.downloadedTimes), + uploader, + uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName) + || cached?.card + || cached?.nickname + || '', + }); + } else if (type === 2 && item?.folderInfo) { + const folder = item.folderInfo; + const creator = toInt(folder.creatorUin); + const cached = bridge.qqInfo.findGroupMember(groupId, creator); + folders.push({ + folderId: typeof folder.folderId === 'string' ? folder.folderId : '', + folderName: typeof folder.folderName === 'string' ? folder.folderName : '', + createTime: toInt(folder.createTime), + creator, + creatorName: (typeof folder.creatorName === 'string' && folder.creatorName) + || cached?.card + || cached?.nickname + || '', + totalFileCount: toInt(folder.totalFileCount), + }); + } + } + + if (list.isEnd) break; + startIndex += pageSize; + } + + return { files, folders }; +} + +export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x6d6_2', + 0x6D6, + 2, + { + download: { + groupUin: groupId, + appId: 7, + busId, + fileId, + }, + }, + OidbGroupFileReqSchema, + OidbGroupFileRespSchema, + true, + ); + + const download = resp?.download; + if (!download) throw new Error('group file url response missing'); + ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording); + + const dns = (typeof download.downloadDns === 'string' && download.downloadDns) + || (typeof download.downloadIp === 'string' && download.downloadIp) + || ''; + const hexUrl = bytesToHexUpper(download.downloadUrl); + if (!dns || !hexUrl) { + throw new Error('group file url response invalid'); + } + + // Keep the same behavior as Lagrange: append file_id after ?fname= + return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`; +} + +export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x6d6_3', + 0x6D6, + 3, + { + delete: { + groupUin: groupId, + busId: 102, + fileId, + }, + }, + OidbGroupFileReqSchema, + OidbGroupFileRespSchema, + true, + ); + + const result = resp?.delete; + if (!result) throw new Error('group file delete response missing'); + ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording); +} + +export async function moveGroupFile( + bridge: Bridge, + groupId: number, + fileId: string, + parentDirectory: string, + targetDirectory: string, +): Promise { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x6d6_5', + 0x6D6, + 5, + { + move: { + groupUin: groupId, + appId: 7, + busId: 102, + fileId, + parentDirectory, + targetDirectory, + }, + }, + OidbGroupFileReqSchema, + OidbGroupFileRespSchema, + true, + ); + + const result = resp?.move; + if (!result) throw new Error('group file move response missing'); + ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording); +} + +export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x6d7_0', + 0x6D7, + 0, + { + create: { + groupUin: groupId, + rootDirectory: normalizeDirectory(parentId), + folderName: name, + }, + }, + OidbGroupFileFolderReqSchema, + OidbGroupFileFolderRespSchema, + true, + ); + + const result = resp?.create; + if (!result) throw new Error('group folder create response missing'); + ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording); +} + +export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x6d7_1', + 0x6D7, + 1, + { + delete: { + groupUin: groupId, + folderId, + }, + }, + OidbGroupFileFolderReqSchema, + OidbGroupFileFolderRespSchema, + true, + ); + + const result = resp?.delete; + if (!result) throw new Error('group folder delete response missing'); + ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording); +} + +export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x6d7_2', + 0x6D7, + 2, + { + rename: { + groupUin: groupId, + folderId, + newFolderName, + }, + }, + OidbGroupFileFolderReqSchema, + OidbGroupFileFolderRespSchema, + true, + ); + + const result = resp?.rename; + if (!result) throw new Error('group folder rename response missing'); + ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording); +} + +export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise { + const uid = await resolveUserUid(bridge, userId); + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0xe37_1200', + 0xE37, + 1200, + { + subCommand: 1200, + field2: 1, + body: { + receiverUid: uid, + fileUuid: fileId, + type: 2, + fileHash, + t2: 0, + }, + field101: 3, + field102: 103, + field200: 1, + field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), + }, + OidbPrivateFileDownloadReqSchema, + OidbPrivateFileDownloadRespSchema, + ); + + const result = resp?.body?.result; + const server = typeof result?.server === 'string' ? result.server : ''; + const port = toInt(result?.port); + const url = typeof result?.url === 'string' ? result.url : ''; + if (!server || !port || !url) { + throw new Error('private file url response invalid'); + } + return `http://${server}:${port}${url}&isthumb=0`; +} + +export async function fetchGroupPttUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise { + const normalizedNode = normalizeMediaNode(node); + return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, { + reqHead: { + common: { requestId: 4, command: 200 }, + scene: { + requestType: 1, + businessType: 3, + sceneType: 2, + group: { groupUin: groupId }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizedNode, + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); +} + +export async function fetchPrivatePttUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise { + const selfUid = await resolveSelfUid(bridge); + const normalizedNode = normalizeMediaNode(node); + return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, { + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 1, + businessType: 3, + sceneType: 1, + c2c: { + accountType: 2, + targetUid: selfUid, + }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizedNode, + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); +} + +export async function fetchGroupVideoUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise { + const normalizedNode = normalizeMediaNode(node); + return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, { + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 2, + businessType: 2, + sceneType: 2, + group: { groupUin: groupId }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizedNode, + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); +} + +export async function fetchPrivateVideoUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise { + const selfUid = await resolveSelfUid(bridge); + const normalizedNode = normalizeMediaNode(node); + return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, { + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 2, + businessType: 2, + sceneType: 1, + c2c: { + accountType: 2, + targetUid: selfUid, + }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizedNode, + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); +} + +export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise { + if (!Array.isArray(nodes) || nodes.length === 0) { + throw new Error('forward nodes are required'); + } + + const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node))); + const longMsgResult = protoEncode({ + action: [ + { + actionCommand: 'MultiMsg', + actionData: { msgBody: msgBody as any }, + }, + ], + }, LongMsgResultSchema); + + const selfUid = await resolveSelfUid(bridge); + const info: any = { + type: groupId ? 3 : 1, + uid: { uid: groupId ? String(groupId) : selfUid }, + payload: gzipSync(Buffer.from(longMsgResult)), + }; + if (groupId) info.groupUin = groupId; + + const request = protoEncode({ + info, + settings: { + field1: 4, + field2: 1, + field3: 7, + field4: 0, + }, + }, SendLongMsgReqSchema); + + const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'upload forward message failed'); + } + + const resp = protoDecode(result.responseData, SendLongMsgRespSchema); + const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : ''; + if (!resId) { + throw new Error('upload forward message response missing res_id'); + } + + forwardResCache.set(resId, nodes.map(node => ({ + userUin: node.userUin, + nickname: node.nickname, + elements: [...node.elements], + }))); + + return resId; +} + +export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise { + const cached = forwardResCache.get(resId); + if (cached) { + return cached.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements] })); + } + + const selfUid = await resolveSelfUid(bridge); + const request = protoEncode({ + info: { + uid: { uid: selfUid }, + resId, + acquire: true, + }, + settings: { + field1: 2, + field2: 0, + field3: 0, + field4: 0, + }, + }, RecvLongMsgReqSchema); + + const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'download forward message failed'); + } + + const resp = protoDecode(result.responseData, RecvLongMsgRespSchema); + const payload = resp?.result?.payload; + if (!(payload instanceof Uint8Array) || payload.length === 0) { + throw new Error('download forward message payload is empty'); + } + + const inflate = gunzipSync(Buffer.from(payload)); + const longMsg = protoDecode(inflate, LongMsgResultSchema); + const action = longMsg?.action?.find((item: any) => item?.actionCommand === 'MultiMsg'); + const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : []; + + const nodes: ForwardNodePayload[] = []; + for (const msgBody of msgBodyList) { + const wrapped = protoEncode({ message: msgBody }, PushMsgSchema); + const pkt: PacketInfo = { + pid: 0, + uin: bridge.qqInfo.uin, + serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', + seqId: 0, + retCode: 0, + fromClient: false, + body: wrapped, + }; + const events = parseMsgPush(pkt, bridge.qqInfo); + const event = events.find(e => + e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message'); + if (!event) continue; + + if (event.kind === 'group_message') { + nodes.push({ + userUin: event.senderUin, + nickname: event.senderCard || event.senderNick, + elements: event.elements, + }); + } else if (event.kind === 'friend_message') { + nodes.push({ + userUin: event.senderUin, + nickname: event.senderNick, + elements: event.elements, + }); + } else { + nodes.push({ + userUin: event.senderUin, + nickname: event.senderNick, + elements: event.elements, + }); + } + } + + if (nodes.length > 0) { + forwardResCache.set(resId, nodes.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements] }))); + } + return nodes; +} + +export async function setGroupAddRequest( + bridge: Bridge, groupId: number, sequence: number, eventType: number, + approve: boolean, reason = '', filtered = false, +): Promise { + const subCmd = filtered ? 2 : 1; + const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1'; + await sendOidbAndCheck(bridge, cmd, 0x10C8, subCmd, + { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, + OidbGroupRequestActionSchema, true); +} + +// --------------------------------------------------------------------------- +// Poke / Like +// --------------------------------------------------------------------------- + +export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise { + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xed3_1', 0xED3, 1, + { + uin: targetUin ?? peerUin, + groupUin: isGroup ? peerUin : 0, + friendUin: isGroup ? 0 : peerUin, + ext: 0, + }, OidbPokeSchema); +} + +export async function sendLike(bridge: Bridge, userId: number, count: number): Promise { + await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x7e5_104', 0x7E5, 104, + { targetUin: userId, count }, OidbLikeSchema); +} + +// --------------------------------------------------------------------------- +// Essence / Reaction +// --------------------------------------------------------------------------- + +export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise { + const subCmd = enable ? 1 : 2; + const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2'; + await sendOidbAndCheck(bridge, cmd, 0xEAC, subCmd, + { groupUin: groupId, sequence, random }, OidbEssenceSchema); +} + +export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise { + const subCmd = isSet ? 1 : 2; + const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2'; + await sendOidbAndCheck(bridge, cmd, 0x9082, subCmd, + { groupUin: groupId, sequence, code }, OidbGroupReactionSchema); +} + +// --------------------------------------------------------------------------- +// Recall messages +// --------------------------------------------------------------------------- + +export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise { + const request = protoEncode({ + type: 1, + groupUin: groupId, + info: { sequence, random: 0, field3: 0 }, + settings: { field1: 0 }, + }, GroupRecallRequestSchema); + const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request); + if (!result.success) throw new Error(result.errorMessage || 'recall group message failed'); +} + +export async function recallPrivateMessage( + bridge: Bridge, userUin: number, clientSeq: number, + msgSeq: number, random: number, timestamp: number, +): Promise { + const targetUid = await resolveUserUid(bridge, userUin); + const request = protoEncode({ + type: 1, + targetUid, + info: { + clientSequence: clientSeq, + random, + messageId: BigInt((0x01000000 * 0x100000000) + random), + timestamp, + field5: 0, + messageSequence: msgSeq, + }, + settings: { field1: false, field2: false }, + field6: false, + }, C2CRecallRequestSchema); + const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request); + if (!result.success) throw new Error(result.errorMessage || 'recall private message failed'); +} diff --git a/src/bridge/bridge-contacts.ts b/src/bridge/bridge-contacts.ts new file mode 100644 index 00000000..7c074a60 --- /dev/null +++ b/src/bridge/bridge-contacts.ts @@ -0,0 +1,335 @@ +// Contact / info-fetching operations extracted from Bridge. + +import type { Bridge } from './bridge'; +import type { DownloadRKeyInfo } from './bridge'; +import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; +import { protoDecode } from '../protobuf/decode'; +import { sendOidbAndDecode } from './bridge-oidb'; +import { + OidbSvcTrpcTcp0xFD4_1ResponseSchema, + OidbSvcTrpcTcp0xFE5_2ResponseSchema, + OidbSvcTrpcTcp0xFE7_3ResponseSchema, + OidbSvcTrpcTcp0x10C0ResponseSchema, +} from './proto/oidb'; +import { + OidbFriendListRequestSchema, + OidbGroupListRequestSchema, + OidbGroupMemberListRequestSchema, + OidbUserInfoRequestSchema, + OidbUserInfoResponseSchema, + AvatarInfoSchema, + OidbGroupRequestListSchema, + NTV2RichMediaReqSchema, + NTV2RichMediaRespSchema, +} from './proto/oidb-action'; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +export function buildFriendProperties(raw: any): Map { + const props = new Map(); + 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; +} + +export function permissionToRole(permission: number): string { + switch (permission) { + case 1: return 'owner'; + case 2: return 'admin'; + default: return 'member'; + } +} + +// --------------------------------------------------------------------------- +// Friend list +// --------------------------------------------------------------------------- + +export async function fetchFriendList(bridge: Bridge): Promise { + const friends: FriendInfo[] = []; + let nextUin: number | null = null; + + do { + const body: any = { + friendCount: 300, + field4: 0, + field6: 1, + field7: 0x7FFFFFFF, + body: [ + { type: 1, number: { numbers: [103, 102, 20002, 27394] } }, + { type: 4, number: { numbers: [100, 101, 102] } }, + ], + field10002: [13578, 13579, 13573, 13572, 13568], + field10003: 4051, + }; + if (nextUin !== null) { + body.nextUin = { uin: nextUin }; + } + + const resp = await sendOidbAndDecode( + bridge, 'OidbSvcTrpcTcp.0xfd4_1', 0xFD4, 1, body, + OidbFriendListRequestSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema); + + if (resp?.friends) { + 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) ?? '', + }); + } + } + + nextUin = resp?.next?.uin ?? null; + if (nextUin === 0) nextUin = null; + } while (nextUin !== null); + + bridge.qqInfo.setFriends(friends); + return friends; +} + +// --------------------------------------------------------------------------- +// Group list +// --------------------------------------------------------------------------- + +export async function fetchGroupList(bridge: Bridge): Promise { + const allTrue = true; + const body = { + config: { + config1: { + groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue, + groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue, + field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue, + field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue, + question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue, + field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue, + field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue, + field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue, + }, + config2: { + field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue, + field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue, + }, + config3: { field5: allTrue, field6: allTrue }, + }, + }; + + const resp = await sendOidbAndDecode( + bridge, 'OidbSvcTrpcTcp.0xfe5_2', 0xFE5, 2, body, + OidbGroupListRequestSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema, true); + + const groups: QQGroupInfo[] = []; + if (resp?.groups) { + 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(), + }); + } + } + bridge.qqInfo.setGroups(groups); + return groups; +} + +// --------------------------------------------------------------------------- +// Group member list +// --------------------------------------------------------------------------- + +export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Promise { + const members: GroupMemberInfo[] = []; + let token = ''; + + do { + const body: any = { + groupUin: groupId, + field2: 5, + field3: 2, + body: { + memberName: true, memberCard: true, level: true, field13: true, + field16: true, specialTitle: true, field18: true, field20: true, + field21: true, joinTimestamp: true, lastMsgTimestamp: true, + shutUpTimestamp: true, field103: true, field104: true, field105: true, + field106: true, permission: true, field200: true, field201: true, + }, + }; + if (token) body.token = token; + + const resp = await sendOidbAndDecode( + bridge, 'OidbSvcTrpcTcp.0xfe7_3', 0xFE7, 3, body, + OidbGroupMemberListRequestSchema, OidbSvcTrpcTcp0xFE7_3ResponseSchema); + + if (resp?.members) { + 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, + }); + } + } + + token = resp?.token ?? ''; + } while (token); + + bridge.qqInfo.setGroupMembers(groupId, members); + return members; +} + +// --------------------------------------------------------------------------- +// User profile +// --------------------------------------------------------------------------- + +export async function fetchUserProfile(bridge: Bridge, uin: number): Promise { + const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037]; + const body = { + uin, + field2: 0, + keys: keys.map(k => ({ key: k })), + }; + + const resp = await sendOidbAndDecode( + bridge, 'OidbSvcTrpcTcp.0xfe1_2', 0xFE1, 2, body, + OidbUserInfoRequestSchema, OidbUserInfoResponseSchema); + + if (!resp?.body) throw new Error('user info response body missing'); + + const info: UserProfileInfo = { + uin: resp.body.uin ?? uin, + uid: resp.body.uid ?? '', + nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', + }; + + if (resp.body.properties) { + const bytesMap = new Map(); + const numMap = new Map(); + for (const bp of resp.body.properties.bytesProperties ?? []) { + bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0)); + } + for (const np of resp.body.properties.numberProperties ?? []) { + numMap.set(np.number1 ?? 0, np.number2 ?? 0); + } + + const getString = (code: number) => { + const b = bytesMap.get(code); + return b ? Buffer.from(b).toString('utf8') : ''; + }; + + info.nickname = getString(20002); + info.remark = getString(103); + info.qid = getString(27394); + info.sign = getString(102); + + const avatarBytes = bytesMap.get(101); + if (avatarBytes) { + const av = protoDecode(avatarBytes, AvatarInfoSchema); + if (av?.url) info.avatar = av.url + '640'; + } + + const sexNum = numMap.get(20009) ?? 0; + info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown'; + info.age = numMap.get(20037) ?? 0; + } + + bridge.qqInfo.setUserProfile(info); + const selfUin = parseInt(bridge.qqInfo.uin, 10) || 0; + if (info.uin === selfUin) bridge.qqInfo.setSelfProfile(info); + return info; +} + +// --------------------------------------------------------------------------- +// Group requests +// --------------------------------------------------------------------------- + +export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise { + const subCmd = filtered ? 2 : 1; + const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1'; + const resp = await sendOidbAndDecode( + bridge, cmd, 0x10C0, subCmd, { count: 20, field2: 0 }, + OidbGroupRequestListSchema, OidbSvcTrpcTcp0x10C0ResponseSchema); + + 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, + }); + } + return requests; +} + +// --------------------------------------------------------------------------- +// Download RKeys +// --------------------------------------------------------------------------- + +export async function fetchDownloadRKeys(bridge: Bridge): Promise { + const PRIVATE_IMAGE = 10; + const GROUP_IMAGE = 20; + const FALLBACK_IMAGE = 2; + + const body = { + reqHead: { + common: { requestId: 1, command: 202 }, + scene: { requestType: 2, businessType: 1, sceneType: 0 }, + client: { agentType: 2 }, + }, + downloadRkey: { + types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE], + }, + }; + + const resp = await sendOidbAndDecode( + bridge, 'OidbSvcTrpcTcp.0x9067_202', 0x9067, 202, body, + NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, true); + + if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) { + throw new Error(resp.respHead.message ?? 'fetch download rkey failed'); + } + + 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; +} diff --git a/src/bridge/bridge-oidb.ts b/src/bridge/bridge-oidb.ts new file mode 100644 index 00000000..d43a0867 --- /dev/null +++ b/src/bridge/bridge-oidb.ts @@ -0,0 +1,91 @@ +// OIDB protocol helpers -- encode requests, send+check, send+decode, UID resolution. + +import type { Bridge } from './bridge'; +import type { ProtoSchema } from '../protobuf/decode'; +import { protoEncode, protoDecode } from '../protobuf/decode'; +import { makeOidbBaseSchema } from './proto/oidb'; + +/** + * Build a raw OIDB request buffer (base envelope wrapping a typed body). + */ +export function makeOidbRequest( + command: number, subCommand: number, + body: any, bodySchema: ProtoSchema, isUid = false, +): Uint8Array { + const baseSchema = makeOidbBaseSchema(bodySchema); + return protoEncode({ + command, + subCommand, + errorCode: 0, + body, + errorMsg: '', + reserved: isUid ? 1 : 0, + }, baseSchema); +} + +/** + * Send an OIDB packet and verify it succeeded (no decode of body). + */ +export async function sendOidbAndCheck( + bridge: Bridge, + serviceCmd: string, command: number, subCommand: number, + body: any, bodySchema: ProtoSchema, isUid = false, +): Promise { + const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid); + const result = await bridge.sendRawPacket(serviceCmd, request); + if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); + if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); + // Check OIDB error code if response present + if (result.responseData && result.responseData.length > 0) { + const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } }); + const resp = protoDecode(result.responseData, emptyBase); + if (resp && (resp as any).errorCode && (resp as any).errorCode !== 0) { + throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`); + } + } +} + +/** + * Send an OIDB packet and decode the response body with the given schema. + */ +export async function sendOidbAndDecode( + bridge: Bridge, + serviceCmd: string, command: number, subCommand: number, + body: any, bodySchema: ProtoSchema, responseSchema: ProtoSchema, isUid = false, +): Promise { + const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid); + const result = await bridge.sendRawPacket(serviceCmd, request); + if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); + if (!result.gotResponse || !result.responseData) throw new Error(result.errorMessage || 'no response'); + + const baseSchema = makeOidbBaseSchema(responseSchema); + const resp = protoDecode(result.responseData, baseSchema); + if (!resp) throw new Error('failed to decode OIDB response'); + if ((resp as any).errorCode && (resp as any).errorCode !== 0) { + throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`); + } + return (resp as any).body as T; +} + +/** + * Resolve a UIN to a UID string, using cache or fetching as needed. + * Mirrors C++ resolve_user_uid_for_action. + */ +export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise { + // Try group member first + if (groupId !== undefined) { + const uid = bridge.qqInfo.findUidByUinInGroup(groupId, uin); + if (uid) return uid; + // Try fetching member list + try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ } + const uid2 = bridge.qqInfo.findUidByUinInGroup(groupId, uin); + if (uid2) return uid2; + } + // Try cached + const uid = bridge.qqInfo.findUidByUin(uin); + if (uid) return uid; + // Fetch profile + const profile = await bridge.fetchUserProfile(uin); + if (profile.uid) return profile.uid; + throw new Error(`failed to resolve UID for UIN ${uin}`); +} diff --git a/src/bridge/bridge.ts b/src/bridge/bridge.ts new file mode 100644 index 00000000..54afc200 --- /dev/null +++ b/src/bridge/bridge.ts @@ -0,0 +1,495 @@ +// Bridge — per-UIN session: handler registration, packet dispatch, event routing. +// Supports packet sending via native addon. +// Heavy OIDB / contact / action logic is split into bridge-oidb, bridge-contacts, bridge-actions. + +import type { PacketInfo } from '../protocol/types'; +import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events'; +import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; +import { QQInfo } from './qq-info'; +import { MSG_PUSH_CMD, parseMsgPush } from './handlers/msg-push-handler'; +import type { PacketSender, SendPacketResult } from '../protocol/packet-sender'; +import { protoEncode, protoDecode } from '../protobuf/decode'; +import { buildSendElems } from './builders/element-builder'; +import { createLogger } from '../utils/logger'; +import { + SendMessageRequestSchema, + SendMessageResponseSchema, +} from './proto/action'; + +// Delegated modules +import { resolveUserUid as resolveUserUid_ } from './bridge-oidb'; +import { + fetchFriendList as fetchFriendList_, + fetchGroupList as fetchGroupList_, + fetchGroupMemberList as fetchGroupMemberList_, + fetchUserProfile as fetchUserProfile_, + fetchGroupRequests as fetchGroupRequests_, + fetchDownloadRKeys as fetchDownloadRKeys_, +} from './bridge-contacts'; +import { + muteGroupMember as muteGroupMember_, + muteGroupAll as muteGroupAll_, + kickGroupMember as kickGroupMember_, + leaveGroup as leaveGroup_, + setGroupAdmin as setGroupAdmin_, + setGroupCard as setGroupCard_, + setGroupName as setGroupName_, + setGroupSpecialTitle as setGroupSpecialTitle_, + setFriendAddRequest as setFriendAddRequest_, + deleteFriend as deleteFriend_, + uploadGroupFile as uploadGroupFile_, + uploadPrivateFile as uploadPrivateFile_, + fetchGroupFiles as fetchGroupFiles_, + fetchGroupFileUrl as fetchGroupFileUrl_, + fetchPrivateFileUrl as fetchPrivateFileUrl_, + fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_, + fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_, + fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_, + fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_, + uploadForwardNodes as uploadForwardNodes_, + fetchForwardNodes as fetchForwardNodes_, + deleteGroupFile as deleteGroupFile_, + moveGroupFile as moveGroupFile_, + createGroupFileFolder as createGroupFileFolder_, + deleteGroupFileFolder as deleteGroupFileFolder_, + renameGroupFileFolder as renameGroupFileFolder_, + setGroupAddRequest as setGroupAddRequest_, + sendPoke as sendPoke_, + sendLike as sendLike_, + setGroupEssence as setGroupEssence_, + setGroupReaction as setGroupReaction_, + recallGroupMessage as recallGroupMessage_, + recallPrivateMessage as recallPrivateMessage_, + setFriendRemark as setFriendRemark_, + fetchGroupFileCount as fetchGroupFileCount_, +} from './bridge-actions'; +import type { GroupFilesResult } from './bridge-actions'; +import type { MediaIndexNode } from './bridge-actions'; + +export type BridgeEventCallback = (event: QQEventVariant) => void; + +type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[]; + +export interface SendMessageReceipt { + messageId: number; + sequence: number; + clientSequence: number; + random: number; + timestamp: number; +} + +export interface DownloadRKeyInfo { + rkey: string; + ttlSeconds: number; + storeId: number; + createTime: number; + type: number; +} + +const log = createLogger('Bridge'); +const eventLog = createLogger('Event'); + +export class Bridge { + private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; + + private qqInfo_: QQInfo; + private pids_ = new Set(); + private eventCallback_: BridgeEventCallback | null = null; + private cmdHandlers_ = new Map(); + private packetClient_: PacketSender | null = null; + private memberRefreshTasks_ = new Map>(); + + // Sequence and random generators for outgoing messages + private clientSeq_ = 100000000 + (Date.now() % 1000000000); + private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; + + constructor(qqInfo: QQInfo) { + this.qqInfo_ = qqInfo; + this.registerDefaultHandlers(); + } + + get qqInfo(): QQInfo { return this.qqInfo_; } + + setPacketClient(client: PacketSender): void { + this.packetClient_ = client; + } + + private registerDefaultHandlers(): void { + this.registerCmd(MSG_PUSH_CMD, parseMsgPush); + } + + registerCmd(cmd: string, parser: CmdParser): void { + const arr = this.cmdHandlers_.get(cmd) ?? []; + arr.push(parser); + this.cmdHandlers_.set(cmd, arr); + } + + setEventCallback(cb: BridgeEventCallback): void { + this.eventCallback_ = cb; + } + + handlesCmd(cmd: string): boolean { + return this.cmdHandlers_.has(cmd); + } + + // --- PID management --- + + attachPid(pid: number): void { + this.pids_.add(pid); + } + detachPid(pid: number): void { + this.pids_.delete(pid); + } + hasPid(pid: number): boolean { return this.pids_.has(pid); } + get empty(): boolean { return this.pids_.size === 0; } + get activePid(): number | null { + for (const pid of this.pids_) return pid; + return null; + } + + // --- Packet dispatch --- + + onPacket(pkt: PacketInfo): void { + const handlers = this.cmdHandlers_.get(pkt.serviceCmd); + if (!handlers) return; + + for (const handler of handlers) { + try { + const events = handler(pkt, this.qqInfo_); + for (const event of events) { + this.triggerMemberCacheRefresh(event); + printEvent(event); + this.emitEvent(event); + } + } catch (e) { + log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e)); + } + } + } + + private emitEvent(event: QQEventVariant): void { + if (this.eventCallback_) { + try { this.eventCallback_(event); } catch (e) { + log.error('event callback error: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); + } + } + } + + private triggerMemberCacheRefresh(event: QQEventVariant): void { + let groupId = 0; + let reason = ''; + switch (event.kind) { + case 'group_member_join': + groupId = event.groupId; + reason = 'group_member_join'; + break; + case 'group_member_leave': + groupId = event.groupId; + reason = 'group_member_leave'; + break; + case 'group_admin': + groupId = event.groupId; + reason = 'group_admin'; + break; + default: + return; + } + + if (groupId <= 0) return; + if (this.memberRefreshTasks_.has(groupId)) return; + + const task = (async () => { + try { + if (!this.qqInfo_.findGroup(groupId)) { + try { await this.fetchGroupList(); } catch { /* ignore */ } + } + await this.fetchGroupMemberList(groupId); + log.debug('member cache refreshed: group=%d reason=%s', groupId, reason); + } catch (e) { + log.warn('failed to refresh member cache: group=%d reason=%s err=%s', + groupId, reason, e instanceof Error ? e.message : String(e)); + } finally { + this.memberRefreshTasks_.delete(groupId); + } + })(); + + this.memberRefreshTasks_.set(groupId, task); + } + + // --- Sequence / random generators --- + + private nextClientSequence(): number { + return ++this.clientSeq_; + } + + private nextMessageRandom(): number { + this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0; + return this.msgRandom_ & 0x7FFFFFFF; + } + + // --- Send packet (raw) --- + + async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise { + if (!this.packetClient_) { + return { + success: false, gotResponse: false, errorCode: -1, + errorMessage: 'no packet sender attached', responseData: null, + }; + } + return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs); + } + + // --- Send message (high-level) --- + + async sendGroupMessage(groupId: number, elements: MessageElement[]): Promise { + if (elements.length === 0) throw new Error('message is empty'); + + const protoElems = await buildSendElems(elements, { bridge: this, groupId }); + const random = this.nextMessageRandom(); + + const request = protoEncode({ + routingHead: { + grp: { groupCode: BigInt(groupId) }, + } as any, + contentHead: { + type: 1, + } as any, + messageBody: { + richText: { + elems: protoElems, + }, + } as any, + clientSequence: 0, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + multiSendSeq: 0, + }, SendMessageRequestSchema); + + const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protoDecode(result.responseData, SendMessageResponseSchema); + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + if (response.result !== undefined && response.result !== 0) { + throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`); + } + + const seq = response.groupSequence ?? 0; + const messageId = (random & 0x7FFFFFFF) || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + + return { + messageId, + sequence: seq, + clientSequence: 0, + random, + timestamp, + }; + } + + async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise { + if (elements.length === 0) throw new Error('message is empty'); + + // Resolve UID for image upload (C++ resolves UID before building elems) + let userUid = ''; + const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'); + if (hasMedia) { + userUid = await this.resolveUserUid(userUin); + } + + const protoElems = await buildSendElems(elements, { bridge: this, userUid }); + const random = this.nextMessageRandom(); + const clientSeq = this.nextClientSequence(); + + const request = protoEncode({ + routingHead: { + c2c: { + uin: userUin, + }, + } as any, + contentHead: { + type: 1, + subType: 0, + c2cCmd: 11, + } as any, + messageBody: { + richText: { + elems: protoElems, + }, + } as any, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { + msgFlag: Math.floor(Date.now() / 1000), + } as any, + multiSendSeq: 0, + }, SendMessageRequestSchema); + + const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protoDecode(result.responseData, SendMessageResponseSchema); + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + if (response.result !== undefined && response.result !== 0) { + throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`); + } + + const seq = response.privateSequence ?? 0; + const messageId = (random & 0x7FFFFFFF) || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + + return { + messageId, + sequence: seq, + clientSequence: clientSeq, + random, + timestamp, + }; + } + + // --- Delegated: OIDB helpers --- + + async resolveUserUid(uin: number, groupId?: number): Promise { + return resolveUserUid_(this, uin, groupId); + } + + // --- Delegated: Contact / info queries --- + + async fetchFriendList(): Promise { return fetchFriendList_(this); } + async fetchGroupList(): Promise { return fetchGroupList_(this); } + async fetchGroupMemberList(groupId: number): Promise { return fetchGroupMemberList_(this, groupId); } + async fetchUserProfile(uin: number): Promise { return fetchUserProfile_(this, uin); } + async fetchGroupRequests(filtered = false): Promise { return fetchGroupRequests_(this, filtered); } + async fetchDownloadRKeys(): Promise { return fetchDownloadRKeys_(this); } + + // --- Delegated: Admin / action methods --- + + async muteGroupMember(groupId: number, userId: number, duration: number): Promise { return muteGroupMember_(this, groupId, userId, duration); } + async muteGroupAll(groupId: number, enable: boolean): Promise { return muteGroupAll_(this, groupId, enable); } + async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise { return kickGroupMember_(this, groupId, userId, reject, reason); } + async leaveGroup(groupId: number): Promise { return leaveGroup_(this, groupId); } + async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise { return setGroupAdmin_(this, groupId, userId, enable); } + async setGroupCard(groupId: number, userId: number, card: string): Promise { return setGroupCard_(this, groupId, userId, card); } + async setGroupName(groupId: number, name: string): Promise { return setGroupName_(this, groupId, name); } + async setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise { return setGroupSpecialTitle_(this, groupId, userId, title); } + async setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise { return setFriendAddRequest_(this, uidOrFlag, approve); } + async deleteFriend(userId: number, block = false): Promise { return deleteFriend_(this, userId, block); } + async uploadGroupFile(groupId: number, file: string, name = '', folderId = '/', uploadFile = true): Promise<{ fileId: string | null }> { + return uploadGroupFile_(this, groupId, file, name, folderId, uploadFile); + } + async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> { + return uploadPrivateFile_(this, userId, file, name, uploadFile); + } + async fetchGroupFiles(groupId: number, folderId = '/'): Promise { return fetchGroupFiles_(this, groupId, folderId); } + async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise { return fetchGroupFileUrl_(this, groupId, fileId, busId); } + async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); } + async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise { return fetchGroupPttUrlByNode_(this, groupId, node); } + async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise { return fetchPrivatePttUrlByNode_(this, node); } + async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise { return fetchGroupVideoUrlByNode_(this, groupId, node); } + async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise { return fetchPrivateVideoUrlByNode_(this, node); } + async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise { return uploadForwardNodes_(this, nodes, groupId); } + async fetchForwardNodes(resId: string): Promise { return fetchForwardNodes_(this, resId); } + async deleteGroupFile(groupId: number, fileId: string): Promise { return deleteGroupFile_(this, groupId, fileId); } + async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); } + async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise { return createGroupFileFolder_(this, groupId, name, parentId); } + async deleteGroupFileFolder(groupId: number, folderId: string): Promise { return deleteGroupFileFolder_(this, groupId, folderId); } + async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); } + async setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason = '', filtered = false): Promise { return setGroupAddRequest_(this, groupId, sequence, eventType, approve, reason, filtered); } + async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { return sendPoke_(this, isGroup, peerUin, targetUin); } + async sendLike(userId: number, count: number): Promise { return sendLike_(this, userId, count); } + async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise { return setGroupEssence_(this, groupId, sequence, random, enable); } + async setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise { return setGroupReaction_(this, groupId, sequence, code, isSet); } + async recallGroupMessage(groupId: number, sequence: number): Promise { return recallGroupMessage_(this, groupId, sequence); } + async recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise { return recallPrivateMessage_(this, userUin, clientSeq, msgSeq, random, timestamp); } + async setFriendRemark(userId: number, remark: string): Promise { return setFriendRemark_(this, userId, remark); } + async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); } +} + +// --- Module-level helper functions --- + +function elementsToText(elements: MessageElement[]): string { + return elements.map(e => { + switch (e.type) { + case 'text': return e.text ?? ''; + case 'at': return `@${e.targetUin ?? 'all'}`; + case 'face': return `[表情:${e.faceId}]`; + case 'mface': return `[${e.summary ?? '表情'}]`; + case 'image': return '[图片]'; + case 'video': return '[视频]'; + case 'record': return '[语音]'; + case 'file': return `[文件:${e.fileName ?? ''}]`; + case 'json': return '[JSON卡片]'; + case 'xml': return '[XML卡片]'; + case 'reply': return `[回复:${e.replySeq}]`; + case 'poke': return '[戳一戳]'; + case 'forward': return '[合并转发]'; + case 'markdown': return '[Markdown]'; + default: return `[${e.type}]`; + } + }).join(''); +} + +function printEvent(event: QQEventVariant): void { + switch (event.kind) { + case 'group_message': { + const c = elementsToText(event.elements); + const s = event.senderCard || event.senderNick || String(event.senderUin); + eventLog.success('群 %d | %s(%d): %s', event.groupId, s, event.senderUin, c); + break; + } + case 'friend_message': + eventLog.info('私聊 %s(%d): %s', event.senderNick || String(event.senderUin), event.senderUin, elementsToText(event.elements)); + break; + case 'temp_message': + eventLog.info('临时 %d(群%d): %s', event.senderUin, event.groupId, elementsToText(event.elements)); + break; + case 'group_recall': + eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin); + break; + case 'friend_recall': + eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin); + break; + case 'group_member_join': + eventLog.info('入群 %d 加入 %d', event.userUin, event.groupId); + break; + case 'group_member_leave': + eventLog.warn('退群 %d %s %d', event.userUin, event.isKick ? '被踢出' : '退出', event.groupId); + break; + case 'group_mute': + eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration); + break; + case 'group_admin': + eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-'); + break; + case 'friend_poke': + eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin); + break; + case 'group_poke': + eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin); + break; + case 'friend_request': + eventLog.warn('好友请求 %d: %s', event.fromUin, event.message); + break; + case 'group_invite': + eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId); + break; + case 'group_essence': + eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-'); + break; + } +} diff --git a/src/bridge/builders/element-builder.ts b/src/bridge/builders/element-builder.ts new file mode 100644 index 00000000..d95db805 --- /dev/null +++ b/src/bridge/builders/element-builder.ts @@ -0,0 +1,206 @@ +// Element Builder — converts internal MessageElement[] into proto Elem objects +// for encoding with protoEncode(SendMessageRequestSchema). +// Port of src/bridge/src/bridge_messages.cpp build_send_elems() + +import type { Bridge } from '../bridge'; +import type { MessageElement } from '../events'; +import type { ProtoDecoded } from '../../protobuf/decode'; +import { protoEncode } from '../../protobuf/decode'; +import { + ElemSchema, +} from '../proto/element'; +import { + MentionExtraSendSchema, + MarkdownDataSchema, +} from '../proto/action'; +import { uploadImageMsgInfo } from '../highway/image-upload'; + +type ProtoElem = Partial>; + +export interface SendContext { + bridge: Bridge; + groupId?: number; + userUid?: string; +} + +function makeTextElem(text: string): ProtoElem { + return { + text: { str: text } as any, + }; +} + +function makeFaceElem(faceId: number): ProtoElem { + return { + face: { index: faceId } as any, + }; +} + +function makeMentionElem(element: MessageElement): ProtoElem { + const mentionAll = element.uid === 'all' || element.targetUin === 0; + + const extra = protoEncode({ + type: mentionAll ? 1 : 2, + uin: mentionAll ? 0 : (element.targetUin ?? 0), + field5: 0, + uid: mentionAll ? 'all' : (element.uid ?? ''), + }, MentionExtraSendSchema); + + return { + text: { + str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `), + pbReserve: extra, + } as any, + }; +} + +function makeReplyElem(element: MessageElement): ProtoElem { + return { + srcMsg: { + origSeqs: [element.replySeq! & 0xFFFFFFFF], + } as any, + }; +} + +function makeJsonElem(element: MessageElement): ProtoElem { + const content = element.text ?? ''; + const payload = new Uint8Array(content.length + 1); + payload[0] = 0x00; + const encoded = new TextEncoder().encode(content); + payload.set(encoded, 1); + + return { + richMsg: { + serviceId: 1, + template1: payload, + } as any, + }; +} + +function makeXmlElem(element: MessageElement): ProtoElem { + const content = element.text ?? ''; + const payload = new Uint8Array(content.length + 1); + payload[0] = 0x00; + const encoded = new TextEncoder().encode(content); + payload.set(encoded, 1); + + return { + richMsg: { + serviceId: element.subType === 0 ? 35 : (element.subType ?? 35), + template1: payload, + } as any, + }; +} + +function makeMarkdownElem(element: MessageElement): ProtoElem { + const data = protoEncode({ content: element.text ?? '' }, MarkdownDataSchema); + + return { + commonElem: { + serviceType: 45, + pbElem: data, + businessType: 1, + } as any, + }; +} + +function makeForwardElem(element: MessageElement): ProtoElem { + const resId = (element.resId ?? '').trim(); + if (!resId) { + throw new Error('forward resId is required'); + } + + const xml = `聊天记录查看转发消息查看转发消息`; + const encodedXml = new TextEncoder().encode(xml); + const payload = new Uint8Array(encodedXml.length + 1); + payload[0] = 0x00; + payload.set(encodedXml, 1); + + return { + richMsg: { + serviceId: 35, + template1: payload, + } as any, + }; +} + +async function makeImageElem(ctx: SendContext, element: MessageElement): Promise { + const isGroup = ctx.groupId !== undefined; + const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? ''); + if (!isGroup && !targetIdOrUid) { + throw new Error('private image target uid is missing'); + } + + const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element); + + return { + commonElem: { + serviceType: 48, + pbElem: msgInfo, + businessType: isGroup ? 20 : 10, + } as any, + }; +} + +/** + * Build proto Elem objects from an array of MessageElements. + * Supports: text, face, at, reply, json, xml, markdown, image. + * Image elements trigger highway upload via the SendContext. + */ +export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise { + const result: ProtoElem[] = []; + + for (const elem of elements) { + switch (elem.type) { + case 'text': + if (elem.text) result.push(makeTextElem(elem.text)); + break; + + case 'face': + if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId)); + break; + + case 'at': + result.push(makeMentionElem(elem)); + break; + + case 'reply': + if (elem.replySeq) result.push(makeReplyElem(elem)); + break; + + case 'json': + if (elem.text) result.push(makeJsonElem(elem)); + break; + + case 'xml': + if (elem.text) result.push(makeXmlElem(elem)); + break; + + case 'markdown': + if (elem.text) result.push(makeMarkdownElem(elem)); + break; + + case 'image': + if (ctx) { + result.push(await makeImageElem(ctx, elem)); + } else { + console.warn('[ElemBuilder] image send requires SendContext'); + } + break; + + case 'forward': + if (elem.resId) result.push(makeForwardElem(elem)); + break; + + case 'record': + case 'video': + console.warn(`[ElemBuilder] ${elem.type} send not yet implemented`); + break; + + default: + console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`); + break; + } + } + + return result; +} diff --git a/src/bridge/events.ts b/src/bridge/events.ts new file mode 100644 index 00000000..56db7656 --- /dev/null +++ b/src/bridge/events.ts @@ -0,0 +1,211 @@ +// Bridge event types and MessageElement. +// Port of src/bridge/include/bridge/events.h + +export interface MessageElement { + type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward' + text?: string; + faceId?: number; + targetUin?: number; + uid?: string; + imageUrl?: string; + fileId?: string; + thumbFileId?: string; + fileName?: string; + fileSize?: number; + replySeq?: number; + url?: string; + subType?: number; + duration?: number; + width?: number; + height?: number; + summary?: string; + flash?: boolean; + resId?: string; + fileHash?: string; + mediaNode?: { + fileUuid?: string; + storeId?: number; + uploadTime?: number; + ttl?: number; + subType?: number; + info?: { + fileSize?: number; + fileHash?: string; + fileSha1?: string; + fileName?: string; + width?: number; + height?: number; + time?: number; + original?: number; + type?: { + type?: number; + picFormat?: number; + videoFormat?: number; + voiceFormat?: number; + }; + }; + }; +} + +export interface ForwardNodePayload { + userUin: number; + nickname: string; + elements: MessageElement[]; +} + +export interface QQEvent { + time: number; + selfUin: number; +} + +export interface FriendMessage extends QQEvent { + kind: 'friend_message'; + senderUin: number; + senderNick: string; + msgSeq: number; + msgId: number; + elements: MessageElement[]; +} + +export interface GroupMessage extends QQEvent { + kind: 'group_message'; + groupId: number; + senderUin: number; + senderNick: string; + senderCard: string; + senderRole: string; + msgSeq: number; + msgId: number; + elements: MessageElement[]; +} + +export interface TempMessage extends QQEvent { + kind: 'temp_message'; + senderUin: number; + groupId: number; + senderNick: string; + msgSeq: number; + elements: MessageElement[]; +} + +export interface GroupMemberJoin extends QQEvent { + kind: 'group_member_join'; + groupId: number; + userUin: number; + operatorUin: number; +} + +export interface GroupMemberLeave extends QQEvent { + kind: 'group_member_leave'; + groupId: number; + userUin: number; + operatorUin: number; + isKick: boolean; +} + +export interface GroupMuteEvent extends QQEvent { + kind: 'group_mute'; + groupId: number; + userUin: number; + operatorUin: number; + duration: number; +} + +export interface GroupAdminEvent extends QQEvent { + kind: 'group_admin'; + groupId: number; + userUin: number; + set: boolean; +} + +export interface FriendRecall extends QQEvent { + kind: 'friend_recall'; + userUin: number; + msgSeq: number; +} + +export interface GroupRecallEvent extends QQEvent { + kind: 'group_recall'; + groupId: number; + operatorUin: number; + authorUin: number; + msgSeq: number; +} + +export interface FriendRequestEvent extends QQEvent { + kind: 'friend_request'; + fromUin: number; + message: string; + flag: string; +} + +export interface GroupInviteEvent extends QQEvent { + kind: 'group_invite'; + groupId: number; + fromUin: number; + subType: string; + message: string; + flag: string; +} + +export interface FriendPokeEvent extends QQEvent { + kind: 'friend_poke'; + userUin: number; + targetUin: number; + action: string; + suffix: string; + actionImgUrl: string; +} + +export interface GroupPokeEvent extends QQEvent { + kind: 'group_poke'; + groupId: number; + userUin: number; + targetUin: number; + action: string; + suffix: string; + actionImgUrl: string; +} + +export interface GroupEssenceEvent extends QQEvent { + kind: 'group_essence'; + groupId: number; + senderUin: number; + operatorUin: number; + msgSeq: number; + random: number; + set: boolean; +} + +export interface GroupFileUploadEvent extends QQEvent { + kind: 'group_file_upload'; + groupId: number; + userUin: number; + fileId: string; + fileName: string; + fileSize: number; + busId: number; +} + +export interface FriendAddEvent extends QQEvent { + kind: 'friend_add'; + userUin: number; +} + +export type QQEventVariant = + | FriendMessage + | GroupMessage + | TempMessage + | GroupMemberJoin + | GroupMemberLeave + | GroupMuteEvent + | GroupAdminEvent + | FriendRecall + | GroupRecallEvent + | FriendRequestEvent + | GroupInviteEvent + | FriendPokeEvent + | GroupPokeEvent + | GroupEssenceEvent + | GroupFileUploadEvent + | FriendAddEvent; diff --git a/src/bridge/handlers/msg-push-handler.ts b/src/bridge/handlers/msg-push-handler.ts new file mode 100644 index 00000000..49655e0d --- /dev/null +++ b/src/bridge/handlers/msg-push-handler.ts @@ -0,0 +1,857 @@ +// MsgPush packet handler — parses trpc.msg.olpush.OlPushService.MsgPush +// into bridge events. Port of src/bridge/src/handlers/msg_push_handler.h/.cpp + +import { inflateSync } from 'zlib'; +import { protoDecode } from '../../protobuf/decode'; +import { WireMessage } from '../../protobuf/wire'; +import { PushMsgSchema } from '../proto/message'; +import { + MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema, + MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema, +} from '../proto/element'; +import { FileExtraSchema } from '../proto/message'; +import { + GroupChangeSchema, GroupAdminSchema, GroupJoinSchema, + GroupInvitationSchema, GroupInviteSchema, + FriendRequestSchema, FriendRecallSchema, + GroupMuteSchema, NotifyMessageBodySchema, + GeneralGrayTipInfoSchema, OperatorInfoSchema, +} from '../proto/notify'; +import type { QQInfo } from '../qq-info'; +import type { PacketInfo } from '../../protocol/types'; +import type { + QQEventVariant, MessageElement, + FriendMessage, GroupMessage, TempMessage, + GroupMemberJoin, GroupMemberLeave, GroupMuteEvent, GroupAdminEvent, + FriendRecall, GroupRecallEvent, FriendRequestEvent, GroupInviteEvent, + FriendPokeEvent, GroupPokeEvent, GroupEssenceEvent, +} from '../events'; +import type { ProtoDecoded, ProtoSchema } from '../../protobuf/decode'; + +// --- PkgType enum --- +const enum PkgType { + ForwardFakePrivateMessage = 9, + PrivateMessage = 166, + GroupMessage = 82, + TempMessage = 141, + Event0x210 = 528, + Event0x2DC = 732, + PrivateRecordMessage = 208, + PrivateFileMessage = 529, + GroupRequestInvitationNotice = 525, + GroupRequestJoinNotice = 84, + GroupInviteNotice = 87, + GroupAdminChangedNotice = 44, + GroupMemberIncreaseNotice = 33, + GroupMemberDecreaseNotice = 34, +} + +const enum Event0x2DCSubType { + GroupMuteNotice = 12, + GroupRecallNotice = 17, + GroupGreyTipNotice = 20, + GroupEssenceNotice = 21, +} + +const enum Event0x210SubType { + FriendRequestNotice = 35, + FriendRecallNotice = 138, + FriendPokeNotice = 290, +} + +// --- Helpers --- + +function makeImageUrl(origUrl: string): string { + if (!origUrl) return ''; + if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl; + return 'http://gchat.qpic.cn' + origUrl; +} + +const HEX_CHARS = '0123456789ABCDEF'; +function bytesToHex(data: Uint8Array): string { + let r = ''; + for (const b of data) { r += HEX_CHARS[b >> 4]; r += HEX_CHARS[b & 0x0f]; } + return r; +} + +function decompressData(data: Uint8Array): string { + if (!data || data.length === 0) return ''; + if (data[0] === 0x01 && data.length > 1) { + try { + const inflated = inflateSync(Buffer.from(data.subarray(1))); + return inflated.toString('utf8'); + } catch { return ''; } + } + if (data[0] === 0x00 && data.length > 1) { + return Buffer.from(data.subarray(1)).toString('utf8'); + } + return Buffer.from(data).toString('utf8'); +} + +function isNumericUin(value: string): boolean { + return value.length > 0 && /^\d+$/.test(value); +} + +function parseU64OrZero(value: string): number { + if (!value) return 0; + const n = parseInt(value, 10); + return isNaN(n) ? 0 : n; +} + +function resolveUidToUin(qqInfo: QQInfo, groupId: number, uid: string, fallback = 0): number { + if (!uid) return fallback; + if (isNumericUin(uid)) { + const n = parseInt(uid, 10); + if (!isNaN(n)) return n; + } + if (groupId) { + const uin = qqInfo.resolveGroupMemberUid(groupId, uid); + if (uin !== null) return uin; + } + const uin = qqInfo.resolveUid(uid); + if (uin !== null) return uin; + return fallback; +} + +function decodeOperatorUid(bytes: Uint8Array): string { + if (!bytes || bytes.length === 0) return ''; + const info = protoDecode(bytes, OperatorInfoSchema); + if (info?.operatorField?.uid) return info.operatorField.uid; + return Buffer.from(bytes).toString('utf8'); +} + +function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map { + const map = new Map(); + for (const p of params) { + if (p.name !== undefined) map.set(p.name, p.value ?? ''); + } + return map; +} + +function findTemplateValue(map: Map, ...keys: string[]): string { + for (const k of keys) { + const v = map.get(k); + if (v) return v; + } + return ''; +} + +function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null { + if (content.length <= 7) return null; + const lenBe = (content[5] << 8) | content[6]; + const lenLe = content[5] | (content[6] << 8); + if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe); + if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe); + return content.subarray(7); +} + +// --- Element conversion --- + +type ElemDecoded = ProtoDecoded; + +function convertElements(elems: ElemDecoded[]): MessageElement[] { + const result: MessageElement[] = []; + let skipNext = false; + + for (const elem of elems) { + if (skipNext) { skipNext = false; continue; } + + // Reply / quote + if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) { + result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] }); + } + + // Text (with possible @ detection) + if (elem.text) { + const t = elem.text; + let mention: ProtoDecoded | null = null; + if (t.pbReserve && t.pbReserve.length > 0) { + mention = protoDecode(t.pbReserve, MentionExtraSchema); + } + const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11; + const hasMention = mention && (mention.type === 1 || mention.type === 2); + + if (hasAttr6 || hasMention) { + const me: MessageElement = { type: 'at', text: t.str ?? '' }; + if (hasAttr6) { + const buf = t.attr6Buf!; + me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0; + } + if (hasMention && mention) { + me.uid = mention.uid ?? ''; + if (!me.targetUin) me.targetUin = mention.uin ?? 0; + } + result.push(me); + } else { + const text = t.str ?? ''; + if (text) result.push({ type: 'text', text }); + } + } + + // Face + if (elem.face) { + result.push({ type: 'face', faceId: elem.face.index ?? 0 }); + } + + // MarketFace + if (elem.marketFace) { + result.push({ + type: 'mface', + text: elem.marketFace.faceName ?? '', + faceId: elem.marketFace.tabId ?? 0, + subType: elem.marketFace.subType ?? 0, + }); + } + + // NotOnlineImage (C2C image) + if (elem.notOnlineImage) { + const img = elem.notOnlineImage; + if (img.picMd5 && img.picMd5.length > 0) { + const urlPath = img.origUrl || img.bigUrl || ''; + result.push({ + type: 'image', + imageUrl: makeImageUrl(urlPath), + fileId: img.filePath ?? '', + fileSize: img.fileLen ?? 0, + width: img.picWidth ?? 0, + height: img.picHeight ?? 0, + subType: img.pbRes?.subType ?? 0, + summary: img.pbRes?.summary ?? '[image]', + }); + } + } + + // CustomFace (group image) + if (elem.customFace) { + const img = elem.customFace; + if (img.md5 && img.md5.length > 0) { + result.push({ + type: 'image', + imageUrl: makeImageUrl(img.origUrl ?? ''), + fileId: img.filePath ?? '', + fileSize: img.size ?? 0, + width: img.width ?? 0, + height: img.height ?? 0, + subType: img.pbRes?.subType ?? 0, + summary: img.pbRes?.summary ?? '[image]', + }); + } + } + + // VideoFile + if (elem.videoFile) { + const v = elem.videoFile; + result.push({ + type: 'video', + fileId: v.fileUuid ?? '', + fileName: v.fileName ?? '', + fileSize: v.fileSize ?? 0, + duration: v.fileTime ?? 0, + fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '', + mediaNode: { + fileUuid: v.fileUuid ?? '', + info: { + fileSize: v.fileSize ?? 0, + fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '', + fileName: v.fileName ?? '', + width: v.fileWidth ?? 0, + height: v.fileHeight ?? 0, + time: v.fileTime ?? 0, + type: { + type: 2, + videoFormat: v.fileFormat ?? 0, + }, + }, + }, + }); + } + + // GroupFile + if (elem.groupFile) { + const f = elem.groupFile; + result.push({ + type: 'file', + fileId: f.fileId ?? '', + fileName: f.filename ?? '', + fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0, + }); + } + + // TransElem type=24 (group file via transport) + if (elem.transElem) { + const te = elem.transElem; + if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) { + const val = te.elemValue; + const len = (val[1] << 8) | val[2]; + if (val.length >= 3 + len) { + const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema); + if (extra?.inner?.info) { + const info = extra.inner.info; + result.push({ + type: 'file', + fileName: info.fileName ?? '', + fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0, + fileId: info.fileId ?? '', + }); + } + } + } + } + + // RichMsg + if (elem.richMsg) { + const rm = elem.richMsg; + if (rm.template1 && rm.template1.length > 0) { + const content = decompressData(rm.template1); + if (content) { + const svcId = rm.serviceId ?? 0; + if (svcId === 35) { + const pos = content.indexOf('m_resid="'); + if (pos !== -1) { + const start = pos + 9; + const end = content.indexOf('"', start); + if (end !== -1) { + result.push({ type: 'forward', resId: content.substring(start, end) }); + continue; + } + } + result.push({ type: 'xml', text: content, subType: svcId }); + } else if (svcId === 1) { + result.push({ type: 'json', text: content }); + } else { + result.push({ type: 'xml', text: content, subType: svcId }); + } + } + } + } + + // LightApp + if (elem.lightApp) { + const la = elem.lightApp; + if (la.data && la.data.length > 0) { + const content = decompressData(la.data); + if (content) result.push({ type: 'json', text: content }); + } + } + + // CommonElem + if (elem.commonElem) { + const ce = elem.commonElem; + const svcType = ce.serviceType ?? 0; + const bizType = ce.businessType ?? 0; + + if (svcType === 2) { + // Poke + result.push({ type: 'poke', subType: bizType }); + } else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) { + // Flash image + const pb = ce.pbElem; + let pos = 1; + let length = 0, shift = 0; + while (pos < pb.length) { + const b = pb[pos++]; + length |= (b & 0x7f) << shift; + shift += 7; + if ((b & 0x80) === 0) break; + } + if (pos + length <= pb.length) { + const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema); + if (img) { + const me: MessageElement = { + type: 'image', fileId: img.filePath ?? '', + fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0, + height: img.picHeight ?? 0, flash: true, summary: '[flash image]', + }; + if (img.pbRes) me.subType = img.pbRes.subType ?? 0; + if (img.picMd5 && img.picMd5.length > 0) { + me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + bytesToHex(img.picMd5) + '/0'; + } + result.push(me); + } + } + skipNext = true; + } else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) { + // NTQQ new protocol image/record/video + const info = protoDecode(ce.pbElem, MsgInfoSchema); + if (info?.msgInfoBody && info.msgInfoBody.length > 0) { + const body = info.msgInfoBody[0]; + if (body.index?.info) { + const idx = body.index; + const fi = idx.info!; + + if (bizType === 10 || bizType === 20) { + // Image + let url = ''; + if (body.picture) { + const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn'; + const path = body.picture.urlPath ?? ''; + if (path) { + url = 'https://' + domain + path; + if (body.picture.ext?.originalParameter) { + url += body.picture.ext.originalParameter; + } + } + } + const me: MessageElement = { + type: 'image', fileId: fi.fileName ?? '', + fileSize: fi.fileSize ?? 0, width: fi.width ?? 0, + height: fi.height ?? 0, imageUrl: url, + }; + if (info.extBizInfo?.pic) { + me.subType = info.extBizInfo.pic.bizType ?? 0; + me.summary = info.extBizInfo.pic.textSummary || '[image]'; + } + result.push(me); + } else if (bizType === 12 || bizType === 22) { + // Record + result.push({ + type: 'record', fileName: fi.fileName ?? '', + fileId: idx.fileUuid ?? '', duration: fi.time ?? 0, + fileHash: fi.fileHash ?? '', + mediaNode: { + fileUuid: idx.fileUuid, + storeId: idx.storeId, + uploadTime: idx.uploadTime, + ttl: idx.ttl, + subType: idx.subType, + info: { + fileSize: fi.fileSize, + fileHash: fi.fileHash, + fileSha1: fi.fileSha1, + fileName: fi.fileName, + width: fi.width, + height: fi.height, + time: fi.time, + original: fi.original, + type: { + type: fi.type?.type, + picFormat: fi.type?.picFormat, + videoFormat: fi.type?.videoFormat, + voiceFormat: fi.type?.voiceFormat, + }, + }, + }, + }); + } else if (bizType === 11 || bizType === 21) { + // Video + result.push({ + type: 'video', fileName: fi.fileName ?? '', + fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0, + duration: fi.time ?? 0, + fileHash: fi.fileHash ?? '', + mediaNode: { + fileUuid: idx.fileUuid, + storeId: idx.storeId, + uploadTime: idx.uploadTime, + ttl: idx.ttl, + subType: idx.subType, + info: { + fileSize: fi.fileSize, + fileHash: fi.fileHash, + fileSha1: fi.fileSha1, + fileName: fi.fileName, + width: fi.width, + height: fi.height, + time: fi.time, + original: fi.original, + type: { + type: fi.type?.type, + picFormat: fi.type?.picFormat, + videoFormat: fi.type?.videoFormat, + voiceFormat: fi.type?.voiceFormat, + }, + }, + }, + }); + } + } + } + } else if (svcType === 33 && ce.pbElem) { + // Small face + const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema); + if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 }); + } else if (svcType === 37 && ce.pbElem) { + // Big face + const extra = protoDecode(ce.pbElem, QFaceExtraSchema); + if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid }); + skipNext = true; + } + } + } + + return result; +} + +function extractRichtextExtras( + rt: ProtoDecoded, + elements: MessageElement[], + isGroup = false +): void { + // Ptt (voice) + if (rt.ptt) { + const p = rt.ptt; + const me: MessageElement = { + type: 'record', fileName: p.fileName ?? '', + fileSize: p.fileSize ?? 0, duration: p.time ?? 0, + fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '', + }; + if (isGroup && (p.fileId ?? 0n) !== 0n) { + me.fileId = p.groupFileKey ?? ''; + } else { + if (p.fileUuid && p.fileUuid.length > 0) { + me.fileId = Buffer.from(p.fileUuid).toString('utf8'); + } + } + me.mediaNode = { + fileUuid: me.fileId ?? '', + info: { + fileSize: p.fileSize ?? 0, + fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '', + fileName: p.fileName ?? '', + time: p.time ?? 0, + type: { + type: 3, + voiceFormat: p.format ?? 0, + }, + }, + }; + elements.push(me); + } + + // NotOnlineFile (C2C file) + if (rt.notOnlineFile) { + const f = rt.notOnlineFile; + elements.push({ + type: 'file', fileId: f.fileUuid ?? '', + fileName: f.fileName ?? '', + fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0, + fileHash: f.fileHash ?? '', + }); + } +} + +function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void { + const extra = protoDecode(msgContent, FileExtraSchema); + if (!extra?.file) return; + const f = extra.file; + if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) { + elements.push({ + type: 'file', fileName: f.fileName, fileId: f.fileUuid, + fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0, + fileHash: f.fileHash, + }); + } +} + +// --- Main handler --- + +export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; + +export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[] { + if (pkt.body.length === 0) return []; + + const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema); + if (!push?.message) return []; + + const msg = push.message; + if (!msg.contentHead) return []; + + const head = msg.contentHead; + const msgType = head.msgType ?? 0; + const subType = head.subType ?? 0; + const sequence = head.sequence ?? 0; + const timestamp = head.timestamp ?? 0; + const msgId = head.msgId ?? 0; + + let fromUin = 0; + let fromUid = ''; + if (msg.responseHead) { + fromUin = msg.responseHead.fromUin ?? 0; + fromUid = msg.responseHead.fromUid ?? ''; + } + + let selfUin = 0; + if (pkt.uin) { + const n = parseInt(pkt.uin, 10); + if (!isNaN(n)) selfUin = n; + } + + const content = (msg.body?.msgContent) ? msg.body.msgContent : new Uint8Array(0); + + const buildElements = (isGroup: boolean): MessageElement[] => { + const elements: MessageElement[] = []; + if (msg.body?.richText) { + const rt = msg.body.richText; + if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[])); + extractRichtextExtras(rt, elements, isGroup); + } + if (msg.body?.msgContent && msg.body.msgContent.length > 0) { + extractMsgContent(msg.body.msgContent, elements); + } + return elements; + }; + + // --- Switch on msgType --- + + switch (msgType as PkgType) { + case PkgType.GroupMemberIncreaseNotice: { + const change = protoDecode(content, GroupChangeSchema); + if (!change) return []; + const ev: GroupMemberJoin = { + kind: 'group_member_join', time: timestamp, selfUin, + groupId: change.groupUin ?? 0, + userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin), + operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, + decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin), + }; + return [ev]; + } + + case PkgType.GroupMemberDecreaseNotice: { + const change = protoDecode(content, GroupChangeSchema); + if (!change) return []; + const dt = change.decreaseType ?? 0; + const ev: GroupMemberLeave = { + kind: 'group_member_leave', time: timestamp, selfUin, + groupId: change.groupUin ?? 0, + userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin), + operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, + decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin), + isKick: dt !== 0 && dt !== 130, + }; + return [ev]; + } + + case PkgType.GroupAdminChangedNotice: { + const admin = protoDecode(content, GroupAdminSchema); + if (!admin?.body) return []; + const extra = admin.body.extraEnable ?? admin.body.extraDisable; + if (!extra) return []; + const ev: GroupAdminEvent = { + kind: 'group_admin', time: timestamp, selfUin, + groupId: admin.groupUin ?? 0, + userUin: resolveUidToUin(qqInfo, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin), + set: admin.body.extraEnable !== undefined, + }; + return [ev]; + } + + case PkgType.GroupRequestJoinNotice: { + const join = protoDecode(content, GroupJoinSchema); + if (!join) return []; + const ev: GroupInviteEvent = { + kind: 'group_invite', time: timestamp, selfUin, + groupId: join.groupUin ?? 0, + fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin), + subType: 'add', message: '', + flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''), + }; + return [ev]; + } + + case PkgType.GroupRequestInvitationNotice: { + const invitation = protoDecode(content, GroupInvitationSchema); + if (!invitation?.info?.inner) return []; + const inner = invitation.info.inner; + const ev: GroupInviteEvent = { + kind: 'group_invite', time: timestamp, selfUin, + groupId: inner.groupUin ?? 0, + fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin), + subType: 'invite', message: '', + flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''), + }; + return [ev]; + } + + case PkgType.GroupInviteNotice: { + const invite = protoDecode(content, GroupInviteSchema); + if (!invite) return []; + const ev: GroupInviteEvent = { + kind: 'group_invite', time: timestamp, selfUin, + groupId: invite.groupUin ?? 0, + fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin), + subType: 'invite', message: '', + flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''), + }; + return [ev]; + } + + case PkgType.Event0x210: { + switch (subType as Event0x210SubType) { + case Event0x210SubType.FriendRequestNotice: { + const request = protoDecode(content, FriendRequestSchema); + if (!request?.info) return []; + const sourceUid = request.info.newSource || request.info.sourceUid || ''; + const ev: FriendRequestEvent = { + kind: 'friend_request', time: timestamp, selfUin, + fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin), + message: request.info.message ?? '', flag: sourceUid, + }; + return [ev]; + } + case Event0x210SubType.FriendRecallNotice: { + const recall = protoDecode(content, FriendRecallSchema); + if (!recall?.info) return []; + const ev: FriendRecall = { + kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin, + userUin: resolveUidToUin(qqInfo, 0, recall.info.fromUid ?? '', fromUin), + msgSeq: recall.info.clientSequence ?? 0, + }; + return [ev]; + } + case Event0x210SubType.FriendPokeNotice: { + const grayTip = protoDecode(content, GeneralGrayTipInfoSchema); + if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return []; + const templates = buildTemplateMap(grayTip.msgTemplParam ?? []); + const actor = findTemplateValue(templates, 'uin_str1'); + const target = findTemplateValue(templates, 'uin_str2'); + const ev: FriendPokeEvent = { + kind: 'friend_poke', time: timestamp, selfUin, + userUin: resolveUidToUin(qqInfo, 0, actor, parseU64OrZero(actor)), + targetUin: resolveUidToUin(qqInfo, 0, target, parseU64OrZero(target)), + action: findTemplateValue(templates, 'action_str', 'alt_str1'), + suffix: findTemplateValue(templates, 'suffix_str'), + actionImgUrl: findTemplateValue(templates, 'action_img_url'), + }; + return [ev]; + } + } + break; + } + + case PkgType.Event0x2DC: { + switch (subType as Event0x2DCSubType) { + case Event0x2DCSubType.GroupMuteNotice: { + const mute = protoDecode(content, GroupMuteSchema); + if (!mute?.data?.state) return []; + const duration = mute.data.state.duration ?? 0; + const ev: GroupMuteEvent = { + kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin, + groupId: mute.groupUin ?? 0, + operatorUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin), + userUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0), + duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration, + }; + return [ev]; + } + case Event0x2DCSubType.GroupRecallNotice: { + const payload = unwrapGroupNotifyPayload(content); + if (!payload) return []; + const notify = protoDecode(payload, NotifyMessageBodySchema); + if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return []; + const recalled = notify.recall.recallMessages[0]; + const ev: GroupRecallEvent = { + kind: 'group_recall', time: recalled.time ?? timestamp, selfUin, + groupId: notify.groupUin ?? 0, + operatorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, + notify.recall.operatorUid || notify.operatorUid || '', fromUin), + authorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin), + msgSeq: recalled.sequence ?? 0, + }; + return [ev]; + } + case Event0x2DCSubType.GroupGreyTipNotice: { + const payload = unwrapGroupNotifyPayload(content); + if (!payload) return []; + const notify = protoDecode(payload, NotifyMessageBodySchema); + if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return []; + const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []); + const actor = findTemplateValue(templates, 'uin_str1'); + const target = findTemplateValue(templates, 'uin_str2'); + const ev: GroupPokeEvent = { + kind: 'group_poke', time: timestamp, selfUin, + groupId: notify.groupUin ?? 0, + userUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, actor, parseU64OrZero(actor)), + targetUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, target, parseU64OrZero(target)), + action: findTemplateValue(templates, 'action_str', 'alt_str1'), + suffix: findTemplateValue(templates, 'suffix_str'), + actionImgUrl: findTemplateValue(templates, 'action_img_url'), + }; + return [ev]; + } + case Event0x2DCSubType.GroupEssenceNotice: { + const payload = unwrapGroupNotifyPayload(content); + if (!payload) return []; + const notify = protoDecode(payload, NotifyMessageBodySchema); + if (!notify?.essenceMessage) return []; + const essence = notify.essenceMessage; + const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0; + const ev: GroupEssenceEvent = { + kind: 'group_essence', time: essence.timestamp ?? timestamp, selfUin, + groupId: essence.groupUin ?? notify.groupUin ?? 0, + senderUin: essence.memberUin ?? 0, + operatorUin: essence.operatorUin ?? fromUin, + msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0, + random: essence.random ?? 0, + set: setFlag === 1, + }; + return [ev]; + } + } + break; + } + } + + // --- Message types --- + + if (msgType === PkgType.GroupMessage) { + const ev: GroupMessage = { + kind: 'group_message', time: timestamp, selfUin, + senderUin: fromUin, msgSeq: sequence, + msgId: msgId & 0x7FFFFFFF, + elements: buildElements(true), + groupId: 0, senderNick: '', senderCard: '', senderRole: '', + }; + if (msg.responseHead?.grp) { + ev.groupId = msg.responseHead.grp.groupUin ?? 0; + ev.senderNick = msg.responseHead.grp.memberName ?? ''; + } + const member = qqInfo.findGroupMember(ev.groupId, fromUin); + if (member) { + if (!ev.senderNick) ev.senderNick = member.nickname; + ev.senderCard = member.card; + ev.senderRole = member.role; + } + return [ev]; + } + + if (msgType === PkgType.TempMessage) { + const ev: TempMessage = { + kind: 'temp_message', time: timestamp, selfUin, + senderUin: fromUin, msgSeq: sequence, + elements: buildElements(false), + groupId: 0, senderNick: '', + }; + if (msg.responseHead?.grp) { + ev.groupId = msg.responseHead.grp.groupUin ?? 0; + ev.senderNick = msg.responseHead.grp.memberName ?? ''; + } + if (!ev.senderNick) { + const friend = qqInfo.findFriend(fromUin); + if (friend) ev.senderNick = friend.nickname; + } + return [ev]; + } + + if (msgType === PkgType.PrivateMessage || + msgType === PkgType.ForwardFakePrivateMessage || + msgType === PkgType.PrivateRecordMessage || + msgType === PkgType.PrivateFileMessage) { + const ev: FriendMessage = { + kind: 'friend_message', time: timestamp, selfUin, + senderUin: fromUin, msgSeq: sequence, + msgId: msgId & 0x7FFFFFFF, + elements: buildElements(false), + senderNick: '', + }; + if (msg.responseHead?.forward?.friendName) { + ev.senderNick = msg.responseHead.forward.friendName; + } + const friend = qqInfo.findFriend(fromUin); + if (friend && !ev.senderNick) ev.senderNick = friend.nickname; + return [ev]; + } + + // const preview = bytesToHex(content.subarray(0, Math.min(content.length, 48))); + return []; +} diff --git a/src/bridge/highway/highway-client.ts b/src/bridge/highway/highway-client.ts new file mode 100644 index 00000000..4d2ea5ef --- /dev/null +++ b/src/bridge/highway/highway-client.ts @@ -0,0 +1,216 @@ +// Highway HTTP client: session fetch and chunked binary upload. +// Port of src/bridge/src/highway_client.cpp + +import net from 'net'; +import type { Bridge } from '../bridge'; +import { protoEncode, protoDecode } from '../../protobuf/decode'; +import { + HttpConn0x6FF501RequestSchema, + HttpConn0x6FF501ResponseSchema, + ReqDataHighwayHeadSchema, + RespDataHighwayHeadSchema, + NTV2RichMediaHighwayExtSchema, + HighwayMsgInfoBodySchema, +} from '../proto/highway'; +import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils'; + +const HIGHWAY_APP_ID = 1600001604; +const HIGHWAY_BLOCK_SIZE = 1024 * 1024; + +export const PRIVATE_IMAGE_CMD_ID = 1003; +export const GROUP_IMAGE_CMD_ID = 1004; + +export interface HighwaySession { + sigSession: Uint8Array; + sessionKey: Uint8Array; + host: string; + port: number; +} + +function ipv4ToString(value: number): string { + return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`; +} + +export async function fetchHighwaySession(bridge: Bridge): Promise { + const request = protoEncode({ + httpConn: { + field1: 0, field2: 0, field3: 16, field4: 1, field6: 3, + serviceTypes: [1, 5, 10, 21], + field9: 2, field10: 9, field11: 8, ver: '1.0.1', + }, + }, HttpConn0x6FF501RequestSchema); + + const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'HttpConn request failed'); + } + + const resp = protoDecode(result.responseData, HttpConn0x6FF501ResponseSchema); + if (!resp?.httpConn) throw new Error('HttpConn response body missing'); + if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) { + throw new Error('HttpConn response missing sig_session'); + } + + const session: HighwaySession = { + sigSession: resp.httpConn.sigSession as Uint8Array, + sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0), + host: 'htdata3.qq.com', + port: 80, + }; + + for (const si of resp.httpConn.serverInfos ?? []) { + if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue; + for (const addr of si.serverAddrs) { + const ip = addr.ip ?? 0; + const port = addr.port ?? 0; + if (ip && port) { + session.host = ipv4ToString(ip); + session.port = port; + } + } + } + + console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`); + return session; +} + +function makeHighwayHead( + uin: string, commandId: number, fileSize: number, offset: number, length: number, + chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array, +): Uint8Array { + return protoEncode({ + msgBaseHead: { + version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0, + appId: HIGHWAY_APP_ID, dataFlag: 16, commandId, + }, + msgSegHead: { + serviceId: 0, filesize: BigInt(fileSize), dataOffset: BigInt(offset), dataLength: length, + retCode: 0, serviceTicket: sigSession, flag: 0, md5: chunkMd5, fileMd5, cacheAddr: 0, cachePort: 0, + }, + bytesReqExtendInfo: extend, + timestamp: 0n, + msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID }, + }, ReqDataHighwayHeadSchema); +} + +export function buildHighwayExtend( + uKey: string, msgInfo: any, ipv4s: any[], sha1: Uint8Array, +): Uint8Array { + const msgInfoBody = msgInfo?.msgInfoBody ?? []; + if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body'); + + const first = msgInfoBody[0]; + const networkIpv4s: any[] = []; + for (const ipv4 of ipv4s ?? []) { + const ip = ipv4.outIp ?? 0; + const port = ipv4.outPort ?? 0; + if (ip && port) { + networkIpv4s.push({ domain: { isEnable: true, ip: ipv4ToString(ip) }, port }); + } + } + + return protoEncode({ + fileUuid: first?.index?.fileUuid ?? '', + uKey, + network: { ipv4s: networkIpv4s }, + msgInfoBody: msgInfoBody.map((b: any) => ({ + index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum, + })), + blockSize: HIGHWAY_BLOCK_SIZE, + hash: { fileSha1: [sha1] }, + }, NTV2RichMediaHighwayExtSchema); +} + +// --- TCP-based HTTP highway upload --- + +function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise { + return new Promise((resolve, reject) => { + const socket = net.createConnection({ host, port }, () => resolve(socket)); + socket.setTimeout(timeoutMs); + socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); }); + socket.on('error', reject); + }); +} + +function socketWrite(socket: net.Socket, data: Uint8Array): Promise { + return new Promise((resolve, reject) => { + socket.write(data, (err) => err ? reject(err) : resolve()); + }); +} + +function readHttpResponseBody(socket: net.Socket): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let headerEnd = -1; + let contentLength = 0; + let totalNeeded = 0; + + const checkComplete = () => { + const buf = Buffer.concat(chunks); + if (headerEnd < 0) { + const idx = buf.indexOf('\r\n\r\n'); + if (idx >= 0) { + headerEnd = idx + 4; + const headerStr = buf.subarray(0, headerEnd).toString('ascii').toLowerCase(); + const clMatch = headerStr.match(/content-length:\s*(\d+)/); + contentLength = clMatch ? parseInt(clMatch[1], 10) : 0; + totalNeeded = headerEnd + contentLength; + } + } + if (headerEnd >= 0 && buf.length >= totalNeeded) { + socket.removeAllListeners('data'); + socket.removeAllListeners('error'); + resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))); + } + }; + + socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); }); + socket.on('error', reject); + socket.on('close', () => { + const buf = Buffer.concat(chunks); + if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd))); + else reject(new Error('connection closed before response')); + }); + }); +} + +async function httpPostFrame( + socket: net.Socket, host: string, path: string, body: Uint8Array, +): Promise { + const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`; + await socketWrite(socket, Buffer.from(header, 'ascii')); + if (body.length > 0) await socketWrite(socket, body); + return readHttpResponseBody(socket); +} + +export async function uploadHighwayHttp( + bridge: Bridge, session: HighwaySession, commandId: number, + bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array, +): Promise { + const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`; + const socket = await tcpConnect(session.host, session.port); + + try { + let offset = 0; + while (offset < bytes.length) { + const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset); + const chunk = bytes.subarray(offset, offset + chunkSize); + const chunkMd5 = computeMd5(chunk); + const head = makeHighwayHead( + bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize, + chunkMd5, fileMd5, session.sigSession, extend, + ); + const frame = packHighwayFrame(head, chunk); + const responseBody = await httpPostFrame(socket, session.host, pathStr, frame); + const { head: respHead } = unpackHighwayFrame(responseBody); + const resp = protoDecode(respHead, RespDataHighwayHeadSchema); + if (resp?.errorCode && resp.errorCode !== 0) { + throw new Error(`highway upload error_code=${resp.errorCode}`); + } + offset += chunkSize; + console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`); + } + } finally { + socket.destroy(); + } +} diff --git a/src/bridge/highway/image-upload.ts b/src/bridge/highway/image-upload.ts new file mode 100644 index 00000000..d32c7749 --- /dev/null +++ b/src/bridge/highway/image-upload.ts @@ -0,0 +1,195 @@ +// Image upload pipeline: load image, OIDB upload request, highway upload, build message element. +// Port of src/bridge/src/highway_upload_req.cpp + highway_client.cpp (image parts) + +import type { Bridge } from '../bridge'; +import type { MessageElement } from '../events'; +import { protoEncode, protoDecode } from '../../protobuf/decode'; +import { makeOidbBaseSchema } from '../proto/oidb'; +import { + NTV2UploadRichMediaReqSchema, + NTV2UploadRichMediaRespSchema, + EncodableMediaMsgInfoSchema, +} from '../proto/highway'; +import { + loadBinarySource, computeHashes, detectImageFormat, +} from './utils'; +import { + fetchHighwaySession, uploadHighwayHttp, buildHighwayExtend, + PRIVATE_IMAGE_CMD_ID, GROUP_IMAGE_CMD_ID, +} from './highway-client'; + +interface ImageData { + bytes: Uint8Array; + md5: Uint8Array; + sha1: Uint8Array; + md5Hex: string; + sha1Hex: string; + fileName: string; + summary: string; + subType: number; + width: number; + height: number; + picFormat: number; +} + +function loadImage(element: MessageElement): Promise { + return loadImageFromSource( + element.url || element.fileId || '', + element.fileName ?? '', + element.subType ?? 0, + element.summary ?? '', + ); +} + +async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise { + const loaded = await loadBinarySource(source, 'image'); + const hashes = computeHashes(loaded.bytes); + const fmt = detectImageFormat(loaded.bytes); + + const extMap: Record = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' }; + const ext = extMap[fmt.format] ?? '.jpg'; + + let finalName = fileName || loaded.fileName; + if (!finalName) finalName = hashes.md5Hex + ext; + + return { + bytes: loaded.bytes, + md5: hashes.md5, + sha1: hashes.sha1, + md5Hex: hashes.md5Hex, + sha1Hex: hashes.sha1Hex, + fileName: finalName, + summary: summary || (subType === 0 ? '[image]' : '[sticker]'), + subType, + width: fmt.width, + height: fmt.height, + picFormat: fmt.format, + }; +} + +async function startImageUpload(bridge: Bridge, isGroup: boolean, targetIdOrUid: string | number, image: ImageData): Promise { + const body: any = { + reqHead: { + common: { requestId: 1, command: 100 }, + scene: { + requestType: 2, + businessType: 1, + sceneType: isGroup ? 2 : 1, + ...(isGroup + ? { group: { groupUin: Number(targetIdOrUid) } } + : { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }), + }, + client: { agentType: 2 }, + }, + upload: { + uploadInfo: [{ + fileInfo: { + fileSize: image.bytes.length, + fileHash: image.md5Hex, + fileSha1: image.sha1Hex, + fileName: image.fileName, + type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 }, + width: image.width, + height: image.height, + time: 0, + original: 1, + }, + subFileType: 0, + }], + tryFastUploadCompleted: true, + srvSendMsg: false, + clientRandomId: BigInt(Math.floor(Math.random() * 0x7FFFFFFFFFFFFFFF)), + compatQmsgSceneType: isGroup ? 2 : 1, + extBizInfo: { + pic: { + bizType: image.subType, + textSummary: image.summary, + ...(isGroup + ? { reserveTroop: { subType: image.subType } } + : { reserveC2c: { subType: image.subType } }), + }, + video: { bytesPbReserve: new Uint8Array(0) }, + ptt: { + bytesReserve: new Uint8Array(0), + bytesPbReserve: new Uint8Array(0), + bytesGeneralFlags: new Uint8Array(0), + }, + }, + clientSeq: 0, + noNeedCompatMsg: false, + }, + }; + + const oidbCmd = isGroup ? 0x11C4 : 0x11C5; + const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100'; + + const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema); + const request = protoEncode({ + command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1, + }, baseSchema); + + const result = await bridge.sendRawPacket(serviceCmd, request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'image upload request failed'); + } + + const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema); + const resp: any = protoDecode(result.responseData, respBaseSchema); + if (!resp) throw new Error('failed to decode upload response'); + if (resp.errorCode && resp.errorCode !== 0) { + throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`); + } + + const uploadBody = resp.body; + if (!uploadBody) throw new Error('upload response body missing'); + if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) { + throw new Error(uploadBody.respHead.message ?? 'image upload failed'); + } + return uploadBody.upload; +} + +function finalizeImageMsgInfo(upload: any, image: ImageData): Uint8Array { + if (!upload?.msgInfo) throw new Error('upload response missing msgInfo'); + + const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({ + index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum, + })); + + const extBizInfo: any = {}; + if (upload.msgInfo.extBizInfo?.pic) { + extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic }; + extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? image.subType; + extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? image.summary; + } else { + extBizInfo.pic = { bizType: image.subType, textSummary: image.summary }; + } + if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video; + if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt; + if (upload.msgInfo.extBizInfo?.busiType !== undefined) extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType; + + return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema); +} + +/** + * Upload an image and return the encoded MsgInfo bytes to embed in a CommonElem. + */ +export async function uploadImageMsgInfo( + bridge: Bridge, + isGroup: boolean, + targetIdOrUid: string | number, + element: MessageElement, +): Promise { + const image = await loadImage(element); + const upload = await startImageUpload(bridge, isGroup, targetIdOrUid, image); + + // Upload binary if uKey is present (not fast-uploaded) + const uKey = upload?.uKey ?? ''; + if (uKey && upload?.msgInfo) { + const session = await fetchHighwaySession(bridge); + const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], image.sha1); + const commandId = isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID; + await uploadHighwayHttp(bridge, session, commandId, image.bytes, image.md5, extend); + } + + return finalizeImageMsgInfo(upload, image); +} diff --git a/src/bridge/highway/utils.ts b/src/bridge/highway/utils.ts new file mode 100644 index 00000000..f969ad7d --- /dev/null +++ b/src/bridge/highway/utils.ts @@ -0,0 +1,198 @@ +// Highway utilities: binary source loading, hashing, image format detection, frame packing. +// Port of src/bridge/src/highway_utils.h/.cpp + +import { createHash } from 'crypto'; +import fs from 'fs'; +import path from 'path'; + +export interface LoadedBinary { + bytes: Uint8Array; + fileName: string; +} + +export interface ImageHashes { + md5: Uint8Array; + sha1: Uint8Array; + md5Hex: string; + sha1Hex: string; +} + +export interface ImageFormat { + format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif + width: number; + height: number; +} + +// --- Binary source loading --- + +export async function loadBinarySource(source: string, resourceName: string): Promise { + if (!source) throw new Error(`${resourceName} source is empty`); + + if (source.startsWith('base64://')) { + return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' }; + } + + if (source.startsWith('http://') || source.startsWith('https://')) { + const resp = await fetch(source); + if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`); + const bytes = new Uint8Array(await resp.arrayBuffer()); + const fileName = guessFileNameFromUrl(source); + return { bytes, fileName }; + } + + // File path (strip file:// prefix) + let filePath = source; + if (filePath.startsWith('file://')) filePath = filePath.slice(7); + // Windows: strip leading / before drive letter + if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1); + + const bytes = fs.readFileSync(filePath); + const fileName = path.basename(filePath); + return { bytes, fileName }; +} + +function guessFileNameFromUrl(url: string): string { + const queryPos = url.search(/[?#]/); + const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url; + const lastSlash = pathPart.lastIndexOf('/'); + return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : ''; +} + +// --- Hashing --- + +export function computeHashes(data: Uint8Array): ImageHashes { + const md5 = createHash('md5').update(data).digest(); + const sha1 = createHash('sha1').update(data).digest(); + return { + md5: new Uint8Array(md5), + sha1: new Uint8Array(sha1), + md5Hex: md5.toString('hex'), + sha1Hex: sha1.toString('hex'), + }; +} + +export function computeMd5(data: Uint8Array): Uint8Array { + return new Uint8Array(createHash('md5').update(data).digest()); +} + +// --- Image format detection (port of C++ detect_image_format) --- + +function readBE16(data: Uint8Array, offset: number): number { + return (data[offset] << 8) | data[offset + 1]; +} + +function readBE32(data: Uint8Array, offset: number): number { + return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; +} + +function readLE16(data: Uint8Array, offset: number): number { + return data[offset] | (data[offset + 1] << 8); +} + +function readLE32(data: Uint8Array, offset: number): number { + return (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0; +} + +function readBE24(data: Uint8Array, offset: number): number { + return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2]; +} + +export function detectImageFormat(bytes: Uint8Array): ImageFormat { + let width = 0; + let height = 0; + + // PNG + if (bytes.length >= 24 && + bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) { + width = readBE32(bytes, 16); + height = readBE32(bytes, 20); + return { format: 1001, width, height }; + } + + // GIF + if (bytes.length >= 10 && + bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 && + (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) { + width = readLE16(bytes, 6); + height = readLE16(bytes, 8); + return { format: 2000, width, height }; + } + + // BMP + if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D) { + width = readLE32(bytes, 18); + height = readLE32(bytes, 22); + return { format: 1005, width, height }; + } + + // WebP + if (bytes.length >= 30 && + bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && + bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) { + if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) { + width = readLE16(bytes, 26); + height = readLE16(bytes, 28); + return { format: 1002, width, height }; + } + if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x4C) { + const bits = readLE32(bytes, 21); + width = (bits & 0x3FFF) + 1; + height = ((bits >> 14) & 0x3FFF) + 1; + return { format: 1002, width, height }; + } + if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x58) { + width = readBE24(bytes, 24) + 1; + height = readBE24(bytes, 27) + 1; + return { format: 1002, width, height }; + } + } + + // JPEG + if (bytes.length >= 4 && bytes[0] === 0xFF && bytes[1] === 0xD8) { + let offset = 2; + while (offset + 9 <= bytes.length) { + if (bytes[offset] !== 0xFF) { offset++; continue; } + const marker = bytes[offset + 1]; + if (marker === 0xD8 || marker === 0xD9) { offset += 2; continue; } + if (offset + 4 > bytes.length) break; + const segLen = readBE16(bytes, offset + 2); + if (segLen < 2 || offset + 2 + segLen > bytes.length) break; + if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) { + height = readBE16(bytes, offset + 5); + width = readBE16(bytes, offset + 7); + return { format: 1000, width, height }; + } + offset += 2 + segLen; + } + return { format: 1000, width: 0, height: 0 }; + } + + return { format: 1000, width: 0, height: 0 }; +} + +// --- Highway frame packing/unpacking --- + +export function packHighwayFrame(head: Uint8Array, body: Uint8Array): Uint8Array { + const frame = new Uint8Array(9 + head.length + body.length + 1); + frame[0] = 0x28; + const dv = new DataView(frame.buffer, frame.byteOffset); + dv.setUint32(1, head.length, false); + dv.setUint32(5, body.length, false); + frame.set(head, 9); + frame.set(body, 9 + head.length); + frame[frame.length - 1] = 0x29; + return frame; +} + +export function unpackHighwayFrame(frame: Uint8Array): { head: Uint8Array; body: Uint8Array } { + if (frame.length < 10 || frame[0] !== 0x28 || frame[frame.length - 1] !== 0x29) { + throw new Error('invalid highway response frame'); + } + const dv = new DataView(frame.buffer, frame.byteOffset); + const headLen = dv.getUint32(1, false); + const bodyLen = dv.getUint32(5, false); + return { + head: frame.subarray(9, 9 + headLen), + body: frame.subarray(9 + headLen, 9 + headLen + bodyLen), + }; +} diff --git a/src/bridge/manager.ts b/src/bridge/manager.ts new file mode 100644 index 00000000..5bfebf6a --- /dev/null +++ b/src/bridge/manager.ts @@ -0,0 +1,133 @@ +// BridgeManager — manages per-UIN Bridge sessions. +// Wires NtqqHandler packets to appropriate Bridge instances. +// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp + +import type { NtqqHandler } from '../protocol/ntqq-handler'; +import type { PacketInfo } from '../protocol/types'; +import type { QQEventVariant } from './events'; +import { Bridge } from './bridge'; +import { QQInfo } from './qq-info'; +import type { PacketSender } from '../protocol/packet-sender'; +import { createLogger } from '../utils/logger'; + +export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void; +export type SessionClosedCallback = (uin: string) => void; +export type BridgeEventCallback = (uin: string, event: QQEventVariant) => void; + +interface QQSession { + qqInfo: QQInfo; + bridge: Bridge; +} + +const log = createLogger('Bridge'); + +export class BridgeManager { + private sessions_ = new Map(); + private pidToUin_ = new Map(); + private pidPacketClients_ = new Map(); + + private onSessionStarted_: SessionStartedCallback | null = null; + private onSessionClosed_: SessionClosedCallback | null = null; + private onBridgeEvent_: BridgeEventCallback | null = null; + + setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; } + setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; } + setEventCallback(cb: BridgeEventCallback): void { this.onBridgeEvent_ = cb; } + + bind(ntqq: NtqqHandler): void { + ntqq.registerCmdAll((pkt: PacketInfo) => this.onPacket(pkt)); + } + + onPidDisconnected(pid: number): void { + this.pidPacketClients_.delete(pid); + const uin = this.pidToUin_.get(pid); + if (!uin) return; + + this.pidToUin_.delete(pid); + const session = this.sessions_.get(uin); + if (!session) return; + + session.bridge.detachPid(pid); + if (session.bridge.empty) { + this.sessions_.delete(uin); + log.debug('session closed: UIN=%s', uin); + if (this.onSessionClosed_) this.onSessionClosed_(uin); + } + } + + private static isRealUin(uin: string): boolean { + if (!uin || uin === '0') return false; + return /^\d+$/.test(uin) && uin.length >= 5; + } + + onHookLogin(pid: number, uin: string, packetClient: PacketSender): void { + if (!BridgeManager.isRealUin(uin)) return; + + this.pidPacketClients_.set(pid, packetClient); + + const { session, created } = this.ensureSession(uin); + session.bridge.attachPid(pid); + session.bridge.setPacketClient(packetClient); + this.pidToUin_.set(pid, uin); + + if (created) { + log.debug('session started: UIN=%s', uin); + if (this.onSessionStarted_) { + this.onSessionStarted_(uin, session.qqInfo, session.bridge); + } + } + } + + private onPacket(pkt: PacketInfo): void { + if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return; + const uin = pkt.uin; + + // Ensure session exists + const { session, created } = this.ensureSession(uin); + + // Attach PID if known + if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) { + session.bridge.attachPid(pkt.pid); + this.pidToUin_.set(pkt.pid, uin); + + const client = this.pidPacketClients_.get(pkt.pid); + if (client) session.bridge.setPacketClient(client); + } + + // Notify session started on first real packet + if (created) { + log.debug('session started: UIN=%s', uin); + if (this.onSessionStarted_) { + this.onSessionStarted_(uin, session.qqInfo, session.bridge); + } + } + + // Dispatch packet to bridge + session.bridge.onPacket(pkt); + } + + private ensureSession(uin: string): { session: QQSession; created: boolean } { + let session = this.sessions_.get(uin); + if (session) return { session, created: false }; + + const qqInfo = new QQInfo(uin); + const bridge = new Bridge(qqInfo); + session = { qqInfo, bridge }; + this.sessions_.set(uin, session); + + // Wire event callback + bridge.setEventCallback((event) => { + if (this.onBridgeEvent_) this.onBridgeEvent_(uin, event); + }); + + return { session, created: true }; + } + + getSession(uin: string): QQSession | null { + return this.sessions_.get(uin) ?? null; + } + + get sessions(): Map { + return this.sessions_; + } +} diff --git a/src/bridge/proto/action.ts b/src/bridge/proto/action.ts new file mode 100644 index 00000000..7974c008 --- /dev/null +++ b/src/bridge/proto/action.ts @@ -0,0 +1,89 @@ +// Proto schemas for outgoing message actions. +// Port of src/bridge/include/bridge/proto/action.h + +import type { ProtoSchema } from '../../protobuf/decode'; +import { ElemSchema } from './element'; + +// --- Routing --- + +export const RoutingC2CSchema = { + uin: { field: 1, type: 'uint32' as const }, + uid: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const RoutingGroupSchema = { + groupCode: { field: 1, type: 'uint64' as const }, +} satisfies ProtoSchema; + +export const RoutingHeadSchema = { + c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema }, + grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema }, +} satisfies ProtoSchema; + +// --- Content Head (for send) --- + +export const SendContentHeadSchema = { + type: { field: 1, type: 'uint32' as const }, + subType: { field: 2, type: 'uint32' as const }, + c2cCmd: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- Message Control --- + +export const MessageControlSchema = { + msgFlag: { field: 1, type: 'int32' as const }, +} satisfies ProtoSchema; + +// --- RichText (for send — only elems) --- + +export const SendRichTextSchema = { + elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema }, +} satisfies ProtoSchema; + +// --- MessageBody (for send) --- + +export const SendMessageBodySchema = { + richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema }, +} satisfies ProtoSchema; + +// --- SendMessageRequest --- + +export const SendMessageRequestSchema = { + routingHead: { field: 1, type: 'message' as const, schema: RoutingHeadSchema }, + contentHead: { field: 2, type: 'message' as const, schema: SendContentHeadSchema }, + messageBody: { field: 3, type: 'message' as const, schema: SendMessageBodySchema }, + clientSequence: { field: 4, type: 'uint32' as const }, + random: { field: 5, type: 'uint32' as const }, + syncCookie: { field: 6, type: 'bytes' as const }, + via: { field: 8, type: 'uint32' as const }, + dataStatist: { field: 9, type: 'uint32' as const }, + ctrl: { field: 12, type: 'message' as const, schema: MessageControlSchema }, + multiSendSeq: { field: 14, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- SendMessageResponse --- + +export const SendMessageResponseSchema = { + result: { field: 1, type: 'int32' as const }, + errMsg: { field: 2, type: 'string' as const }, + timestamp1: { field: 3, type: 'uint32' as const }, + field10: { field: 10, type: 'uint32' as const }, + groupSequence: { field: 11, type: 'uint32' as const }, + timestamp2: { field: 12, type: 'uint32' as const }, + privateSequence: { field: 14, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- MentionExtra (for building @mention text element) --- + +export const MentionExtraSendSchema = { + type: { field: 3, type: 'int32' as const }, + uin: { field: 4, type: 'uint32' as const }, + field5: { field: 5, type: 'int32' as const }, + uid: { field: 9, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- MarkdownData --- + +export const MarkdownDataSchema = { + content: { field: 1, type: 'string' as const }, +} satisfies ProtoSchema; diff --git a/src/bridge/proto/element.ts b/src/bridge/proto/element.ts new file mode 100644 index 00000000..7ce06cb8 --- /dev/null +++ b/src/bridge/proto/element.ts @@ -0,0 +1,418 @@ +// Proto schemas for QQ message elements. +// Port of src/bridge/include/bridge/proto/element.h + +import type { ProtoSchema } from '../../protobuf/decode'; + +// --- Nested / helper schemas --- + +export const CustomFacePbReserveSchema = { + subType: { field: 1, type: 'int32' as const }, + summary: { field: 9, type: 'string' as const }, +} satisfies ProtoSchema; + +export const NotOnlineImagePbReserve2Schema = { + field1: { field: 1, type: 'int32' as const }, + field2: { field: 2, type: 'string' as const }, + field3: { field: 3, type: 'int32' as const }, + field4: { field: 4, type: 'int32' as const }, + field5: { field: 5, type: 'int32' as const }, + field7: { field: 7, type: 'string' as const }, +} satisfies ProtoSchema; + +export const NotOnlineImagePbReserveSchema = { + subType: { field: 1, type: 'int32' as const }, + field3: { field: 3, type: 'int32' as const }, + field4: { field: 4, type: 'int32' as const }, + summary: { field: 8, type: 'string' as const }, + field10: { field: 10, type: 'int32' as const }, + field20: { field: 20, type: 'message' as const, schema: NotOnlineImagePbReserve2Schema }, + url: { field: 30, type: 'string' as const }, + md5Str: { field: 31, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- Core element schemas --- + +export const TextElemSchema = { + str: { field: 1, type: 'string' as const }, + link: { field: 2, type: 'string' as const }, + attr6Buf: { field: 3, type: 'bytes' as const }, + attr7Buf: { field: 4, type: 'bytes' as const }, + buf: { field: 11, type: 'bytes' as const }, + pbReserve: { field: 12, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const FaceElemSchema = { + index: { field: 1, type: 'int32' as const }, + oldData: { field: 2, type: 'bytes' as const }, + buf: { field: 11, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const OnlineImageSchema = { + guid: { field: 1, type: 'bytes' as const }, + filePath: { field: 2, type: 'bytes' as const }, + oldVerSendFile: { field: 3, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const NotOnlineImageSchema = { + filePath: { field: 1, type: 'string' as const }, + fileLen: { field: 2, type: 'uint32' as const }, + downloadPath: { field: 3, type: 'string' as const }, + oldVerSendFile: { field: 4, type: 'bytes' as const }, + imgType: { field: 5, type: 'int32' as const }, + previewsImage: { field: 6, type: 'bytes' as const }, + picMd5: { field: 7, type: 'bytes' as const }, + picHeight: { field: 8, type: 'uint32' as const }, + picWidth: { field: 9, type: 'uint32' as const }, + resId: { field: 10, type: 'string' as const }, + flag: { field: 11, type: 'bytes' as const }, + thumbUrl: { field: 12, type: 'string' as const }, + original: { field: 13, type: 'int32' as const }, + bigUrl: { field: 14, type: 'string' as const }, + origUrl: { field: 15, type: 'string' as const }, + bizType: { field: 16, type: 'int32' as const }, + result: { field: 17, type: 'int32' as const }, + index: { field: 18, type: 'int32' as const }, + opFaceBuf: { field: 19, type: 'bytes' as const }, + oldPicMd5: { field: 20, type: 'bool' as const }, + thumbWidth: { field: 21, type: 'int32' as const }, + thumbHeight: { field: 22, type: 'int32' as const }, + fileId: { field: 23, type: 'int32' as const }, + showLen: { field: 24, type: 'uint32' as const }, + downloadLen: { field: 25, type: 'uint32' as const }, + x400Url: { field: 26, type: 'string' as const }, + x400Width: { field: 27, type: 'int32' as const }, + x400Height: { field: 28, type: 'int32' as const }, + pbRes: { field: 29, type: 'message' as const, schema: NotOnlineImagePbReserveSchema }, +} satisfies ProtoSchema; + +export const TransElemSchema = { + elemType: { field: 1, type: 'int32' as const }, + elemValue: { field: 2, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const MarketFaceSchema = { + faceName: { field: 1, type: 'string' as const }, + itemType: { field: 2, type: 'uint32' as const }, + faceInfo: { field: 3, type: 'uint32' as const }, + faceId: { field: 4, type: 'bytes' as const }, + tabId: { field: 5, type: 'uint32' as const }, + subType: { field: 6, type: 'uint32' as const }, + key: { field: 7, type: 'bytes' as const }, + param: { field: 8, type: 'bytes' as const }, + mediaType: { field: 9, type: 'uint32' as const }, + imageWidth: { field: 10, type: 'uint32' as const }, + imageHeight: { field: 11, type: 'uint32' as const }, + mobileParam: { field: 12, type: 'bytes' as const }, + pbReserve: { field: 13, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const CustomFaceSchema = { + guid: { field: 1, type: 'bytes' as const }, + filePath: { field: 2, type: 'string' as const }, + shortcut: { field: 3, type: 'string' as const }, + buffer: { field: 4, type: 'bytes' as const }, + flag: { field: 5, type: 'bytes' as const }, + oldData: { field: 6, type: 'bytes' as const }, + fileId: { field: 7, type: 'uint32' as const }, + serverIp: { field: 8, type: 'int32' as const }, + serverPort: { field: 9, type: 'int32' as const }, + fileType: { field: 10, type: 'int32' as const }, + signature: { field: 11, type: 'bytes' as const }, + useful: { field: 12, type: 'int32' as const }, + md5: { field: 13, type: 'bytes' as const }, + thumbUrl: { field: 14, type: 'string' as const }, + bigUrl: { field: 15, type: 'string' as const }, + origUrl: { field: 16, type: 'string' as const }, + bizType: { field: 17, type: 'int32' as const }, + repeatIndex: { field: 18, type: 'int32' as const }, + repeatImage: { field: 19, type: 'int32' as const }, + imageType: { field: 20, type: 'int32' as const }, + index: { field: 21, type: 'int32' as const }, + width: { field: 22, type: 'int32' as const }, + height: { field: 23, type: 'int32' as const }, + source: { field: 24, type: 'int32' as const }, + size: { field: 25, type: 'uint32' as const }, + origin: { field: 26, type: 'int32' as const }, + thumbWidth: { field: 27, type: 'int32' as const }, + thumbHeight: { field: 28, type: 'int32' as const }, + showLen: { field: 29, type: 'int32' as const }, + downloadLen: { field: 30, type: 'int32' as const }, + x400Url: { field: 31, type: 'string' as const }, + x400Width: { field: 32, type: 'int32' as const }, + x400Height: { field: 33, type: 'int32' as const }, + pbRes: { field: 34, type: 'message' as const, schema: CustomFacePbReserveSchema }, +} satisfies ProtoSchema; + +export const RichMsgSchema = { + template1: { field: 1, type: 'bytes' as const }, + serviceId: { field: 2, type: 'int32' as const }, + msgResId: { field: 3, type: 'bytes' as const }, + rand: { field: 4, type: 'int32' as const }, + seq: { field: 5, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const GroupFileElemSchema = { + filename: { field: 1, type: 'string' as const }, + fileSize: { field: 2, type: 'uint64' as const }, + fileId: { field: 3, type: 'string' as const }, + batchId: { field: 4, type: 'string' as const }, + fileKey: { field: 5, type: 'string' as const }, + mark: { field: 6, type: 'bytes' as const }, + sequence: { field: 7, type: 'uint64' as const }, + batchItemId: { field: 8, type: 'bytes' as const }, + feedMsgTime: { field: 9, type: 'int32' as const }, + pbReserve: { field: 10, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const ExtraInfoSchema = { + nick: { field: 1, type: 'bytes' as const }, + groupCard: { field: 2, type: 'bytes' as const }, + level: { field: 3, type: 'int32' as const }, + flags: { field: 4, type: 'int32' as const }, + groupMask: { field: 5, type: 'int32' as const }, + msgTailId: { field: 6, type: 'int32' as const }, + senderTitle: { field: 7, type: 'bytes' as const }, + apnsTips: { field: 8, type: 'bytes' as const }, + uin: { field: 9, type: 'uint64' as const }, + msgStateFlag: { field: 10, type: 'int32' as const }, + apnsSoundType: { field: 11, type: 'int32' as const }, + newGroupFlag: { field: 12, type: 'int32' as const }, +} satisfies ProtoSchema; + +export const VideoFileSchema = { + fileUuid: { field: 1, type: 'string' as const }, + fileMd5: { field: 2, type: 'bytes' as const }, + fileName: { field: 3, type: 'string' as const }, + fileFormat: { field: 4, type: 'int32' as const }, + fileTime: { field: 5, type: 'int32' as const }, + fileSize: { field: 6, type: 'int32' as const }, + thumbWidth: { field: 7, type: 'int32' as const }, + thumbHeight: { field: 8, type: 'int32' as const }, + thumbFileMd5: { field: 9, type: 'bytes' as const }, + source: { field: 10, type: 'bytes' as const }, + thumbFileSize:{ field: 11, type: 'int32' as const }, + busiType: { field: 12, type: 'int32' as const }, + fromChatType: { field: 13, type: 'int32' as const }, + toChatType: { field: 14, type: 'int32' as const }, + supportProgressive: { field: 15, type: 'bool' as const }, + fileWidth: { field: 16, type: 'int32' as const }, + fileHeight: { field: 17, type: 'int32' as const }, + subBusiType: { field: 18, type: 'int32' as const }, + videoAttr: { field: 19, type: 'int32' as const }, + pbReserve: { field: 24, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const SrcMsgSchema = { + origSeqs: { field: 1, type: 'repeated_uint32' as const }, + senderUin: { field: 2, type: 'uint64' as const }, + time: { field: 3, type: 'int32' as const }, + flag: { field: 4, type: 'int32' as const }, + elemsRaw: { field: 5, type: 'repeated_bytes' as const }, + type: { field: 6, type: 'int32' as const }, + richMsg: { field: 7, type: 'bytes' as const }, + pbReserve: { field: 8, type: 'bytes' as const }, + sourceMsg: { field: 9, type: 'bytes' as const }, + toUin: { field: 10, type: 'uint64' as const }, + troopName: { field: 11, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const LightAppElemSchema = { + data: { field: 1, type: 'bytes' as const }, + msgResid: { field: 2, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const CommonElemSchema = { + serviceType: { field: 1, type: 'int32' as const }, + pbElem: { field: 2, type: 'bytes' as const }, + businessType: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const GeneralFlagsSchema = { + bubbleDiyTextId: { field: 1, type: 'int32' as const }, + groupFlagNew: { field: 2, type: 'int32' as const }, + uin: { field: 3, type: 'uint64' as const }, + longTextFlag: { field: 6, type: 'int32' as const }, + longTextResId: { field: 7, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- Elem (union of all element types) --- + +export const ElemSchema = { + text: { field: 1, type: 'message' as const, schema: TextElemSchema }, + face: { field: 2, type: 'message' as const, schema: FaceElemSchema }, + onlineImage: { field: 3, type: 'message' as const, schema: OnlineImageSchema }, + notOnlineImage: { field: 4, type: 'message' as const, schema: NotOnlineImageSchema }, + transElem: { field: 5, type: 'message' as const, schema: TransElemSchema }, + marketFace: { field: 6, type: 'message' as const, schema: MarketFaceSchema }, + customFace: { field: 8, type: 'message' as const, schema: CustomFaceSchema }, + richMsg: { field: 12, type: 'message' as const, schema: RichMsgSchema }, + groupFile: { field: 13, type: 'message' as const, schema: GroupFileElemSchema }, + extraInfo: { field: 16, type: 'message' as const, schema: ExtraInfoSchema }, + videoFile: { field: 19, type: 'message' as const, schema: VideoFileSchema }, + generalFlags: { field: 37, type: 'message' as const, schema: GeneralFlagsSchema }, + srcMsg: { field: 45, type: 'message' as const, schema: SrcMsgSchema }, + lightApp: { field: 51, type: 'message' as const, schema: LightAppElemSchema }, + commonElem: { field: 53, type: 'message' as const, schema: CommonElemSchema }, +} satisfies ProtoSchema; + +// --- Extra decode types (for CommonElem.pbElem sub-messages) --- + +export const MentionExtraSchema = { + type: { field: 3, type: 'int32' as const }, + uin: { field: 4, type: 'uint32' as const }, + field5: { field: 5, type: 'int32' as const }, + uid: { field: 9, type: 'string' as const }, +} satisfies ProtoSchema; + +export const QFaceExtraSchema = { + packId: { field: 1, type: 'string' as const }, + stickerId: { field: 2, type: 'string' as const }, + qsid: { field: 3, type: 'int32' as const }, + sourceType: { field: 4, type: 'int32' as const }, + stickerType: { field: 5, type: 'int32' as const }, + resultId: { field: 6, type: 'string' as const }, + text: { field: 7, type: 'string' as const }, + randomType: { field: 9, type: 'int32' as const }, +} satisfies ProtoSchema; + +export const QSmallFaceExtraSchema = { + faceId: { field: 1, type: 'uint32' as const }, + preview: { field: 2, type: 'string' as const }, + preview2: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- NTQQ MsgInfo types (CommonElem service_type 48) --- + +export const FileTypeSchema = { + type: { field: 1, type: 'uint32' as const }, + picFormat: { field: 2, type: 'uint32' as const }, + videoFormat: { field: 3, type: 'uint32' as const }, + voiceFormat: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const FileInfoSchema = { + fileSize: { field: 1, type: 'uint32' as const }, + fileHash: { field: 2, type: 'string' as const }, + fileSha1: { field: 3, type: 'string' as const }, + fileName: { field: 4, type: 'string' as const }, + type: { field: 5, type: 'message' as const, schema: FileTypeSchema }, + width: { field: 6, type: 'uint32' as const }, + height: { field: 7, type: 'uint32' as const }, + time: { field: 8, type: 'uint32' as const }, + original: { field: 9, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const IndexNodeSchema = { + info: { field: 1, type: 'message' as const, schema: FileInfoSchema }, + fileUuid: { field: 2, type: 'string' as const }, + storeId: { field: 3, type: 'uint32' as const }, + uploadTime: { field: 4, type: 'uint32' as const }, + ttl: { field: 5, type: 'uint32' as const }, + subType: { field: 6, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const PicUrlExtInfoSchema = { + originalParameter: { field: 1, type: 'string' as const }, + bigParameter: { field: 2, type: 'string' as const }, + thumbParameter: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const PictureInfoSchema = { + urlPath: { field: 1, type: 'string' as const }, + ext: { field: 2, type: 'message' as const, schema: PicUrlExtInfoSchema }, + domain: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const PicExtDataSchema = { + subType: { field: 1, type: 'uint32' as const }, + textSummary: { field: 9, type: 'string' as const }, +} satisfies ProtoSchema; + +export const PicExtBizInfoSchema = { + bizType: { field: 1, type: 'uint32' as const }, + textSummary: { field: 2, type: 'string' as const }, + bytesPbReserveC2c: { field: 11, type: 'bytes' as const }, + extData: { field: 12, type: 'message' as const, schema: PicExtDataSchema }, + fromScene: { field: 1001, type: 'uint32' as const }, + toScene: { field: 1002, type: 'uint32' as const }, + oldFileId: { field: 1003, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const VideoExtBizInfoSchema = { + fromScene: { field: 1, type: 'uint32' as const }, + toScene: { field: 2, type: 'uint32' as const }, + bytesPbReserve: { field: 3, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const PttExtBizInfoSchema = { + srcUin: { field: 1, type: 'uint64' as const }, + pttScene: { field: 2, type: 'uint32' as const }, + pttType: { field: 3, type: 'uint32' as const }, + changeVoice: { field: 4, type: 'uint32' as const }, + waveform: { field: 5, type: 'bytes' as const }, + autoConvertText: { field: 6, type: 'uint32' as const }, + bytesReserve: { field: 11, type: 'bytes' as const }, + bytesPbReserve: { field: 12, type: 'bytes' as const }, + bytesGeneralFlags: { field: 13, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const ExtBizInfoSchema = { + pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema }, + video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema }, + ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema }, + busiType: { field: 10, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const C2cSourceSchema = { + friendUid: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const TroopSourceSchema = { + groupUin: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const HashSumSchema = { + bytesPbReserveC2c: { field: 201, type: 'message' as const, schema: C2cSourceSchema }, + troopSource: { field: 202, type: 'message' as const, schema: TroopSourceSchema }, +} satisfies ProtoSchema; + +export const MsgInfoBodySchema = { + index: { field: 1, type: 'message' as const, schema: IndexNodeSchema }, + picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema }, + fileExist: { field: 5, type: 'bool' as const }, + hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema }, +} satisfies ProtoSchema; + +export const MsgInfoSchema = { + msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: MsgInfoBodySchema }, + extBizInfo: { field: 2, type: 'message' as const, schema: ExtBizInfoSchema }, +} satisfies ProtoSchema; + +// --- GroupFileExtra (TransElem type=24) --- + +export const GroupFileInfoSchema = { + busId: { field: 1, type: 'uint32' as const }, + fileId: { field: 2, type: 'string' as const }, + fileSize: { field: 3, type: 'uint64' as const }, + fileName: { field: 4, type: 'string' as const }, + fileSha: { field: 5, type: 'bytes' as const }, + extInfoString: { field: 6, type: 'string' as const }, + fileMd5: { field: 7, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const GroupFileExtraInnerSchema = { + info: { field: 2, type: 'message' as const, schema: GroupFileInfoSchema }, +} satisfies ProtoSchema; + +export const GroupFileExtraSchema = { + inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema }, +} satisfies ProtoSchema; + +// --- Preserve (for message receipt info) --- + +export const PreserveSchema = { + messageId: { field: 3, type: 'uint64' as const }, + senderUid: { field: 6, type: 'string' as const }, + receiverUid: { field: 7, type: 'string' as const }, + clientSequence: { field: 8, type: 'uint32' as const }, +} satisfies ProtoSchema; diff --git a/src/bridge/proto/highway.ts b/src/bridge/proto/highway.ts new file mode 100644 index 00000000..9f5a5d75 --- /dev/null +++ b/src/bridge/proto/highway.ts @@ -0,0 +1,354 @@ +// Proto schemas for highway upload protocol. +// Port of src/bridge/include/bridge/proto/highway.h + action.h (HttpConn) + +import type { ProtoSchema } from '../../protobuf/decode'; +import { + IndexNodeSchema, + PictureInfoSchema, + HashSumSchema, + PicExtBizInfoSchema, + VideoExtBizInfoSchema, + PttExtBizInfoSchema, +} from '../proto/element'; + +// --- DataHighwayHead --- + +export const DataHighwayHeadSchema = { + version: { field: 1, type: 'uint32' as const }, + uin: { field: 2, type: 'string' as const }, + command: { field: 3, type: 'string' as const }, + seq: { field: 4, type: 'uint32' as const }, + retryTimes:{ field: 5, type: 'uint32' as const }, + appId: { field: 6, type: 'uint32' as const }, + dataFlag: { field: 7, type: 'uint32' as const }, + commandId: { field: 8, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const SegHeadSchema = { + serviceId: { field: 1, type: 'uint32' as const }, + filesize: { field: 2, type: 'uint64' as const }, + dataOffset: { field: 3, type: 'uint64' as const }, + dataLength: { field: 4, type: 'uint32' as const }, + retCode: { field: 5, type: 'uint32' as const }, + serviceTicket: { field: 6, type: 'bytes' as const }, + flag: { field: 7, type: 'uint32' as const }, + md5: { field: 8, type: 'bytes' as const }, + fileMd5: { field: 9, type: 'bytes' as const }, + cacheAddr: { field: 10, type: 'uint32' as const }, + cachePort: { field: 13, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const LoginSigHeadSchema = { + loginSigType: { field: 1, type: 'uint32' as const }, + appId: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const ReqDataHighwayHeadSchema = { + msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema }, + msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema }, + bytesReqExtendInfo: { field: 3, type: 'bytes' as const }, + timestamp: { field: 4, type: 'uint64' as const }, + msgLoginSigHead: { field: 5, type: 'message' as const, schema: LoginSigHeadSchema }, +} satisfies ProtoSchema; + +export const RespDataHighwayHeadSchema = { + msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema }, + msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema }, + errorCode: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- Highway extend (NTV2RichMediaHighwayExt) --- + +export const HighwayDomainSchema = { + isEnable: { field: 1, type: 'bool' as const }, + ip: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const HighwayIPv4Schema = { + domain: { field: 1, type: 'message' as const, schema: HighwayDomainSchema }, + port: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const HighwayNetworkSchema = { + ipv4s: { field: 1, type: 'repeated_message' as const, schema: HighwayIPv4Schema }, +} satisfies ProtoSchema; + +export const HighwayHashSchema = { + fileSha1: { field: 1, type: 'repeated_bytes' as const }, +} satisfies ProtoSchema; + +export const HighwayMsgInfoBodySchema = { + index: { field: 1, type: 'message' as const, schema: IndexNodeSchema }, + picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema }, + fileExist: { field: 5, type: 'bool' as const }, + hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema }, +} satisfies ProtoSchema; + +export const NTV2RichMediaHighwayExtSchema = { + fileUuid: { field: 1, type: 'string' as const }, + uKey: { field: 2, type: 'string' as const }, + network: { field: 5, type: 'message' as const, schema: HighwayNetworkSchema }, + msgInfoBody: { field: 6, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema }, + blockSize: { field: 10, type: 'uint32' as const }, + hash: { field: 11, type: 'message' as const, schema: HighwayHashSchema }, +} satisfies ProtoSchema; + +// --- File upload extend (group/private file highway) --- + +export const FileUploadUrlSchema = { + unknown: { field: 1, type: 'int32' as const }, + host: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const FileUploadHostSchema = { + url: { field: 1, type: 'message' as const, schema: FileUploadUrlSchema }, + port: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const FileUploadHostConfigSchema = { + hosts: { field: 200, type: 'repeated_message' as const, schema: FileUploadHostSchema }, +} satisfies ProtoSchema; + +export const FileUploadNameInfoSchema = { + fileName: { field: 100, type: 'string' as const }, +} satisfies ProtoSchema; + +export const FileUploadClientInfoSchema = { + clientType: { field: 100, type: 'int32' as const }, + appId: { field: 200, type: 'string' as const }, + terminalType: { field: 300, type: 'int32' as const }, + clientVer: { field: 400, type: 'string' as const }, + unknown: { field: 600, type: 'int32' as const }, +} satisfies ProtoSchema; + +export const FileUploadFileEntrySchema = { + fileSize: { field: 100, type: 'uint64' as const }, + md5: { field: 200, type: 'bytes' as const }, + checkKey: { field: 300, type: 'bytes' as const }, + md5S2: { field: 400, type: 'bytes' as const }, + fileId: { field: 600, type: 'string' as const }, + uploadKey: { field: 700, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const FileUploadBusiInfoSchema = { + busId: { field: 1, type: 'int32' as const }, + senderUin: { field: 100, type: 'uint64' as const }, + receiverUin: { field: 200, type: 'uint64' as const }, + groupCode: { field: 400, type: 'uint64' as const }, +} satisfies ProtoSchema; + +export const FileUploadEntrySchema = { + busiBuff: { field: 100, type: 'message' as const, schema: FileUploadBusiInfoSchema }, + fileEntry: { field: 200, type: 'message' as const, schema: FileUploadFileEntrySchema }, + clientInfo: { field: 300, type: 'message' as const, schema: FileUploadClientInfoSchema }, + fileNameInfo: { field: 400, type: 'message' as const, schema: FileUploadNameInfoSchema }, + host: { field: 500, type: 'message' as const, schema: FileUploadHostConfigSchema }, +} satisfies ProtoSchema; + +export const FileUploadExtSchema = { + unknown1: { field: 1, type: 'int32' as const }, + unknown2: { field: 2, type: 'int32' as const }, + unknown3: { field: 3, type: 'int32' as const }, + entry: { field: 100, type: 'message' as const, schema: FileUploadEntrySchema }, + unknown200: { field: 200, type: 'int32' as const }, +} satisfies ProtoSchema; + +// --- Encodable MsgInfo (for embedding in message element) --- + +export const EncodableMediaExtBizInfoSchema = { + pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema }, + video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema }, + ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema }, + busiType: { field: 10, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const EncodableMediaMsgInfoSchema = { + msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema }, + extBizInfo: { field: 2, type: 'message' as const, schema: EncodableMediaExtBizInfoSchema }, +} satisfies ProtoSchema; + +// --- HttpConn.0x6ff_501 (highway session) --- + +export const HttpConnSchema = { + field1: { field: 1, type: 'int32' as const }, + field2: { field: 2, type: 'int32' as const }, + field3: { field: 3, type: 'int32' as const }, + field4: { field: 4, type: 'int32' as const }, + field6: { field: 6, type: 'int32' as const }, + serviceTypes: { field: 7, type: 'repeated_uint32' as const }, + field9: { field: 9, type: 'int32' as const }, + field10: { field: 10, type: 'int32' as const }, + field11: { field: 11, type: 'int32' as const }, + ver: { field: 15, type: 'string' as const }, +} satisfies ProtoSchema; + +export const HttpConn0x6FF501RequestSchema = { + httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnSchema }, +} satisfies ProtoSchema; + +export const ServerAddrSchema = { + type: { field: 1, type: 'uint32' as const }, + ip: { field: 2, type: 'uint32' as const }, // fixed32 as uint32 + port: { field: 3, type: 'uint32' as const }, + area: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const ServerInfoSchema = { + serviceType: { field: 1, type: 'uint32' as const }, + serverAddrs: { field: 2, type: 'repeated_message' as const, schema: ServerAddrSchema }, +} satisfies ProtoSchema; + +export const HttpConnResponseSchema = { + sigSession: { field: 1, type: 'bytes' as const }, + sessionKey: { field: 2, type: 'bytes' as const }, + serverInfos: { field: 3, type: 'repeated_message' as const, schema: ServerInfoSchema }, +} satisfies ProtoSchema; + +export const HttpConn0x6FF501ResponseSchema = { + httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnResponseSchema }, +} satisfies ProtoSchema; + +// --- NTV2 Upload Request (for OIDB 0x11C4/0x11C5) --- + +export const NTV2FileTypeSchema = { + type: { field: 1, type: 'uint32' as const }, + picFormat: { field: 2, type: 'uint32' as const }, + videoFormat: { field: 3, type: 'uint32' as const }, + voiceFormat: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2FileInfoSchema = { + fileSize: { field: 1, type: 'uint32' as const }, + fileHash: { field: 2, type: 'string' as const }, + fileSha1: { field: 3, type: 'string' as const }, + fileName: { field: 4, type: 'string' as const }, + type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema }, + width: { field: 6, type: 'uint32' as const }, + height: { field: 7, type: 'uint32' as const }, + time: { field: 8, type: 'uint32' as const }, + original: { field: 9, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2UploadInfoSchema = { + fileInfo: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema }, + subFileType: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2PicReserveC2CSchema = { + subType: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2PicReserveTroopSchema = { + subType: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2PicExtBizInfoSchema = { + bizType: { field: 1, type: 'uint32' as const }, + textSummary: { field: 2, type: 'string' as const }, + reserveC2c: { field: 11, type: 'message' as const, schema: NTV2PicReserveC2CSchema }, + reserveTroop: { field: 12, type: 'message' as const, schema: NTV2PicReserveTroopSchema }, +} satisfies ProtoSchema; + +export const NTV2VideoExtBizInfoSchema = { + bytesPbReserve: { field: 3, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const NTV2PttExtBizInfoSchema = { + bytesReserve: { field: 11, type: 'bytes' as const }, + bytesPbReserve: { field: 12, type: 'bytes' as const }, + bytesGeneralFlags: { field: 13, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const NTV2ExtBizInfoSchema = { + pic: { field: 1, type: 'message' as const, schema: NTV2PicExtBizInfoSchema }, + video: { field: 2, type: 'message' as const, schema: NTV2VideoExtBizInfoSchema }, + ptt: { field: 3, type: 'message' as const, schema: NTV2PttExtBizInfoSchema }, + busiType: { field: 10, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2UploadReqSchema = { + uploadInfo: { field: 1, type: 'repeated_message' as const, schema: NTV2UploadInfoSchema }, + tryFastUploadCompleted: { field: 2, type: 'bool' as const }, + srvSendMsg: { field: 3, type: 'bool' as const }, + clientRandomId: { field: 4, type: 'uint64' as const }, + compatQmsgSceneType: { field: 5, type: 'uint32' as const }, + extBizInfo: { field: 6, type: 'message' as const, schema: NTV2ExtBizInfoSchema }, + clientSeq: { field: 7, type: 'uint32' as const }, + noNeedCompatMsg: { field: 8, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const NTV2C2CUserInfoSchema = { + accountType: { field: 1, type: 'uint32' as const }, + targetUid: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const NTV2GroupInfoSchema = { + groupUin: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2UploadSceneInfoSchema = { + requestType: { field: 101, type: 'uint32' as const }, + businessType: { field: 102, type: 'uint32' as const }, + sceneType: { field: 200, type: 'uint32' as const }, + c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema }, + group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema }, +} satisfies ProtoSchema; + +export const NTV2CommonHeadSchema = { + requestId: { field: 1, type: 'uint32' as const }, + command: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2ClientMetaSchema = { + agentType: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2UploadReqHeadSchema = { + common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema }, + scene: { field: 2, type: 'message' as const, schema: NTV2UploadSceneInfoSchema }, + client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema }, +} satisfies ProtoSchema; + +export const NTV2UploadRichMediaReqSchema = { + reqHead: { field: 1, type: 'message' as const, schema: NTV2UploadReqHeadSchema }, + upload: { field: 2, type: 'message' as const, schema: NTV2UploadReqSchema }, +} satisfies ProtoSchema; + +// --- NTV2 Upload Response --- + +export const NTV2IPv4Schema = { + outIp: { field: 1, type: 'uint32' as const }, + outPort: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2SubFileInfoRespSchema = { + subType: { field: 1, type: 'uint32' as const }, + uKey: { field: 2, type: 'string' as const }, + uKeyTtl: { field: 3, type: 'uint32' as const }, + ipv4s: { field: 4, type: 'repeated_message' as const, schema: NTV2IPv4Schema }, +} satisfies ProtoSchema; + +export const NTV2UploadRespMsgInfoSchema = { + msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema }, + extBizInfo: { field: 2, type: 'message' as const, schema: NTV2ExtBizInfoSchema }, +} satisfies ProtoSchema; + +export const NTV2UploadRespBodySchema = { + uKey: { field: 1, type: 'string' as const }, + uKeyTtl: { field: 2, type: 'uint32' as const }, + ipv4s: { field: 3, type: 'repeated_message' as const, schema: NTV2IPv4Schema }, + msgSeq: { field: 5, type: 'uint64' as const }, + msgInfo: { field: 6, type: 'message' as const, schema: NTV2UploadRespMsgInfoSchema }, + subFileInfos: { field: 10, type: 'repeated_message' as const, schema: NTV2SubFileInfoRespSchema }, +} satisfies ProtoSchema; + +export const NTV2UploadRespHeadSchema = { + common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema }, + retCode: { field: 2, type: 'uint32' as const }, + message: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const NTV2UploadRichMediaRespSchema = { + respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema }, + upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema }, +} satisfies ProtoSchema; diff --git a/src/bridge/proto/longmsg.ts b/src/bridge/proto/longmsg.ts new file mode 100644 index 00000000..2ac29beb --- /dev/null +++ b/src/bridge/proto/longmsg.ts @@ -0,0 +1,68 @@ +import type { ProtoSchema } from '../../protobuf/decode'; +import { PushMsgBodySchema } from './message'; + +export const LongMsgUidSchema = { + uid: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const LongMsgSettingsSchema = { + field1: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'uint32' as const }, + field4: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const SendLongMsgInfoSchema = { + type: { field: 1, type: 'uint32' as const }, + uid: { field: 2, type: 'message' as const, schema: LongMsgUidSchema }, + groupUin: { field: 3, type: 'uint32' as const }, + payload: { field: 4, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const SendLongMsgReqSchema = { + info: { field: 2, type: 'message' as const, schema: SendLongMsgInfoSchema }, + settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema }, +} satisfies ProtoSchema; + +export const SendLongMsgRespResultSchema = { + resId: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const SendLongMsgRespSchema = { + result: { field: 2, type: 'message' as const, schema: SendLongMsgRespResultSchema }, + settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema }, +} satisfies ProtoSchema; + +export const RecvLongMsgInfoSchema = { + uid: { field: 1, type: 'message' as const, schema: LongMsgUidSchema }, + resId: { field: 2, type: 'string' as const }, + acquire: { field: 3, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const RecvLongMsgReqSchema = { + info: { field: 1, type: 'message' as const, schema: RecvLongMsgInfoSchema }, + settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema }, +} satisfies ProtoSchema; + +export const RecvLongMsgRespResultSchema = { + resId: { field: 3, type: 'string' as const }, + payload: { field: 4, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const RecvLongMsgRespSchema = { + result: { field: 1, type: 'message' as const, schema: RecvLongMsgRespResultSchema }, + settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema }, +} satisfies ProtoSchema; + +export const LongMsgContentSchema = { + msgBody: { field: 1, type: 'repeated_message' as const, schema: PushMsgBodySchema }, +} satisfies ProtoSchema; + +export const LongMsgActionSchema = { + actionCommand: { field: 1, type: 'string' as const }, + actionData: { field: 2, type: 'message' as const, schema: LongMsgContentSchema }, +} satisfies ProtoSchema; + +export const LongMsgResultSchema = { + action: { field: 2, type: 'repeated_message' as const, schema: LongMsgActionSchema }, +} satisfies ProtoSchema; diff --git a/src/bridge/proto/message.ts b/src/bridge/proto/message.ts new file mode 100644 index 00000000..e8f0f345 --- /dev/null +++ b/src/bridge/proto/message.ts @@ -0,0 +1,113 @@ +// Proto schemas for message envelopes (PushMsg). +// Port of src/bridge/include/bridge/proto/message.h + +import type { ProtoSchema } from '../../protobuf/decode'; +import { ElemSchema } from './element'; + +// --- ResponseHead.Grp --- + +export const ResponseGrpSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + memberName: { field: 2, type: 'string' as const }, + groupName: { field: 4, type: 'string' as const }, +} satisfies ProtoSchema; + +export const ResponseForwardSchema = { + friendName: { field: 6, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- ResponseHead --- + +export const ResponseHeadSchema = { + fromUin: { field: 1, type: 'uint32' as const }, + fromUid: { field: 2, type: 'string' as const }, + type: { field: 3, type: 'uint32' as const }, + sigMap: { field: 4, type: 'uint32' as const }, + toUin: { field: 5, type: 'uint32' as const }, + toUid: { field: 6, type: 'string' as const }, + forward: { field: 7, type: 'message' as const, schema: ResponseForwardSchema }, + grp: { field: 8, type: 'message' as const, schema: ResponseGrpSchema }, +} satisfies ProtoSchema; + +// --- ContentHead --- + +export const ContentHeadSchema = { + msgType: { field: 1, type: 'uint32' as const }, + subType: { field: 2, type: 'uint32' as const }, + divSeq: { field: 3, type: 'uint32' as const }, + msgId: { field: 4, type: 'uint32' as const }, + sequence: { field: 5, type: 'uint32' as const }, + timestamp: { field: 6, type: 'uint32' as const }, + field7: { field: 7, type: 'uint64' as const }, + newId: { field: 12, type: 'uint64' as const }, +} satisfies ProtoSchema; + +// --- Ptt (voice) --- + +export const PttSchema = { + fileType: { field: 1, type: 'uint32' as const }, + fileId: { field: 2, type: 'uint64' as const }, + fileUuid: { field: 3, type: 'bytes' as const }, + fileMd5: { field: 4, type: 'bytes' as const }, + fileName: { field: 5, type: 'string' as const }, + fileSize: { field: 6, type: 'uint32' as const }, + groupFileKey: { field: 10, type: 'string' as const }, + fileKey: { field: 14, type: 'bytes' as const }, + time: { field: 19, type: 'uint32' as const }, + format: { field: 29, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- NotOnlineFile (C2C file) --- + +export const NotOnlineFileSchema = { + fileType: { field: 1, type: 'uint32' as const }, + fileUuid: { field: 3, type: 'string' as const }, + fileMd5: { field: 4, type: 'bytes' as const }, + fileName: { field: 5, type: 'string' as const }, + fileSize: { field: 6, type: 'uint64' as const }, + fileHash: { field: 57, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- RichText --- + +export const RichTextSchema = { + elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema }, + notOnlineFile: { field: 3, type: 'message' as const, schema: NotOnlineFileSchema }, + ptt: { field: 4, type: 'message' as const, schema: PttSchema }, +} satisfies ProtoSchema; + +// --- MessageBody --- + +export const MessageBodySchema = { + richText: { field: 1, type: 'message' as const, schema: RichTextSchema }, + msgContent: { field: 2, type: 'bytes' as const }, +} satisfies ProtoSchema; + +// --- FileExtra (for C2C file in msg_content) --- + +export const FileExtraInfoSchema = { + fileSize: { field: 1, type: 'uint64' as const }, + fileName: { field: 2, type: 'string' as const }, + fileMd5: { field: 3, type: 'bytes' as const }, + fileUuid: { field: 4, type: 'string' as const }, + fileHash: { field: 5, type: 'string' as const }, +} satisfies ProtoSchema; + +export const FileExtraSchema = { + file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema }, +} satisfies ProtoSchema; + +// --- PushMsgBody --- + +export const PushMsgBodySchema = { + responseHead: { field: 1, type: 'message' as const, schema: ResponseHeadSchema }, + contentHead: { field: 2, type: 'message' as const, schema: ContentHeadSchema }, + body: { field: 3, type: 'message' as const, schema: MessageBodySchema }, +} satisfies ProtoSchema; + +// --- PushMsg (top-level) --- + +export const PushMsgSchema = { + message: { field: 1, type: 'message' as const, schema: PushMsgBodySchema }, + status: { field: 3, type: 'int32' as const }, +} satisfies ProtoSchema; diff --git a/src/bridge/proto/notify.ts b/src/bridge/proto/notify.ts new file mode 100644 index 00000000..36eb1163 --- /dev/null +++ b/src/bridge/proto/notify.ts @@ -0,0 +1,207 @@ +// Proto schemas for notification types. +// Port of src/bridge/include/bridge/proto/notify.h + +import type { ProtoSchema } from '../../protobuf/decode'; + +export const OperatorField1Schema = { + uid: { field: 1, type: 'string' as const }, + field2: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'bytes' as const }, + field4: { field: 4, type: 'uint32' as const }, + field5: { field: 5, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const OperatorInfoSchema = { + operatorField: { field: 1, type: 'message' as const, schema: OperatorField1Schema }, +} satisfies ProtoSchema; + +export const GroupChangeSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + flag: { field: 2, type: 'uint32' as const }, + memberUid: { field: 3, type: 'string' as const }, + decreaseType: { field: 4, type: 'uint32' as const }, + operatorBytes: { field: 5, type: 'bytes' as const }, + increaseType: { field: 6, type: 'uint32' as const }, + field7: { field: 7, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const GroupAdminExtraSchema = { + adminUid: { field: 1, type: 'string' as const }, + isPromote: { field: 2, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const GroupAdminBodySchema = { + extraDisable: { field: 1, type: 'message' as const, schema: GroupAdminExtraSchema }, + extraEnable: { field: 2, type: 'message' as const, schema: GroupAdminExtraSchema }, +} satisfies ProtoSchema; + +export const GroupAdminSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + flag: { field: 2, type: 'uint32' as const }, + isPromote: { field: 3, type: 'bool' as const }, + body: { field: 4, type: 'message' as const, schema: GroupAdminBodySchema }, +} satisfies ProtoSchema; + +export const InvitationInnerSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'uint32' as const }, + field4: { field: 4, type: 'uint32' as const }, + targetUid: { field: 5, type: 'string' as const }, + invitorUid: { field: 6, type: 'string' as const }, + field7: { field: 7, type: 'uint32' as const }, + field9: { field: 9, type: 'uint32' as const }, + field10: { field: 10, type: 'bytes' as const }, + field11: { field: 11, type: 'uint32' as const }, + field12: { field: 12, type: 'string' as const }, +} satisfies ProtoSchema; + +export const InvitationInfoSchema = { + inner: { field: 1, type: 'message' as const, schema: InvitationInnerSchema }, +} satisfies ProtoSchema; + +export const GroupInvitationSchema = { + cmd: { field: 1, type: 'int32' as const }, + info: { field: 2, type: 'message' as const, schema: InvitationInfoSchema }, +} satisfies ProtoSchema; + +export const GroupInviteSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'uint32' as const }, + field4: { field: 4, type: 'uint32' as const }, + invitorUid: { field: 5, type: 'string' as const }, + hashes: { field: 6, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const GroupJoinSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + targetUid: { field: 3, type: 'string' as const }, + field4: { field: 4, type: 'uint32' as const }, + field6: { field: 6, type: 'uint32' as const }, + field7: { field: 7, type: 'string' as const }, + field8: { field: 8, type: 'uint32' as const }, + field9: { field: 9, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const FriendRequestInfoSchema = { + targetUid: { field: 1, type: 'string' as const }, + sourceUid: { field: 2, type: 'string' as const }, + newSource: { field: 5, type: 'string' as const }, + message: { field: 10, type: 'string' as const }, + source: { field: 11, type: 'string' as const }, +} satisfies ProtoSchema; + +export const FriendRequestSchema = { + info: { field: 1, type: 'message' as const, schema: FriendRequestInfoSchema }, +} satisfies ProtoSchema; + +export const FriendRecallTipInfoSchema = { + tip: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const FriendRecallInfoSchema = { + fromUid: { field: 1, type: 'string' as const }, + toUid: { field: 2, type: 'string' as const }, + clientSequence: { field: 3, type: 'uint32' as const }, + newId: { field: 4, type: 'uint64' as const }, + time: { field: 5, type: 'uint32' as const }, + random: { field: 6, type: 'uint32' as const }, + pkgNum: { field: 7, type: 'uint32' as const }, + pkgIndex: { field: 8, type: 'uint32' as const }, + divSeq: { field: 9, type: 'uint32' as const }, + tipInfo: { field: 13, type: 'message' as const, schema: FriendRecallTipInfoSchema }, +} satisfies ProtoSchema; + +export const FriendRecallSchema = { + info: { field: 1, type: 'message' as const, schema: FriendRecallInfoSchema }, + instId: { field: 2, type: 'uint32' as const }, + appId: { field: 3, type: 'uint32' as const }, + longMessageFlag: { field: 4, type: 'uint32' as const }, + reserved: { field: 5, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const GroupMuteStateSchema = { + targetUid: { field: 1, type: 'string' as const }, + duration: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const GroupMuteDataSchema = { + timestamp: { field: 1, type: 'uint32' as const }, + type: { field: 2, type: 'uint32' as const }, + state: { field: 3, type: 'message' as const, schema: GroupMuteStateSchema }, +} satisfies ProtoSchema; + +export const GroupMuteSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + subType: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'uint32' as const }, + operatorUid: { field: 4, type: 'string' as const }, + data: { field: 5, type: 'message' as const, schema: GroupMuteDataSchema }, +} satisfies ProtoSchema; + +export const RecallMessageSchema = { + sequence: { field: 1, type: 'uint32' as const }, + time: { field: 2, type: 'uint32' as const }, + random: { field: 3, type: 'uint32' as const }, + type: { field: 4, type: 'uint32' as const }, + flag: { field: 5, type: 'uint32' as const }, + authorUid: { field: 6, type: 'string' as const }, +} satisfies ProtoSchema; + +export const GroupRecallTipInfoSchema = { + tip: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const GroupRecallSchema = { + operatorUid: { field: 1, type: 'string' as const }, + recallMessages: { field: 3, type: 'repeated_message' as const, schema: RecallMessageSchema }, + userDef: { field: 5, type: 'bytes' as const }, + groupType: { field: 6, type: 'int32' as const }, + opType: { field: 7, type: 'int32' as const }, + tipInfo: { field: 9, type: 'message' as const, schema: GroupRecallTipInfoSchema }, +} satisfies ProtoSchema; + +export const TemplParamSchema = { + name: { field: 1, type: 'string' as const }, + value: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const GeneralGrayTipInfoSchema = { + busiType: { field: 1, type: 'uint64' as const }, + busiId: { field: 2, type: 'uint64' as const }, + ctrlFlag: { field: 3, type: 'uint32' as const }, + c2cType: { field: 4, type: 'uint32' as const }, + serviceType: { field: 5, type: 'uint32' as const }, + templId: { field: 6, type: 'uint64' as const }, + msgTemplParam: { field: 7, type: 'repeated_message' as const, schema: TemplParamSchema }, + content: { field: 8, type: 'string' as const }, +} satisfies ProtoSchema; + +export const EssenceMessageSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + msgSequence: { field: 2, type: 'uint32' as const }, + random: { field: 3, type: 'uint32' as const }, + setFlag: { field: 4, type: 'uint32' as const }, + memberUin: { field: 5, type: 'uint32' as const }, + operatorUin: { field: 6, type: 'uint32' as const }, + timestamp: { field: 7, type: 'uint32' as const }, + msgSequence2: { field: 8, type: 'uint32' as const }, + operatorNickname: { field: 9, type: 'string' as const }, + memberNickname: { field: 10, type: 'string' as const }, + setFlag2: { field: 11, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NotifyMessageBodySchema = { + type: { field: 1, type: 'uint32' as const }, + groupUin: { field: 4, type: 'uint32' as const }, + eventParam: { field: 5, type: 'bytes' as const }, + recall: { field: 11, type: 'message' as const, schema: GroupRecallSchema }, + field13: { field: 13, type: 'uint32' as const }, + operatorUid: { field: 21, type: 'string' as const }, + generalGrayTip: { field: 26, type: 'message' as const, schema: GeneralGrayTipInfoSchema }, + essenceMessage: { field: 33, type: 'message' as const, schema: EssenceMessageSchema }, + msgSequence: { field: 37, type: 'uint32' as const }, + field39: { field: 39, type: 'uint32' as const }, +} satisfies ProtoSchema; diff --git a/src/bridge/proto/oidb-action.ts b/src/bridge/proto/oidb-action.ts new file mode 100644 index 00000000..970de8fe --- /dev/null +++ b/src/bridge/proto/oidb-action.ts @@ -0,0 +1,788 @@ +// Proto schemas for OIDB action requests. +// Port of src/bridge/include/bridge/proto/oidb.h (action-related structs) +// and src/bridge/src/bridge.cpp (recall message structs) + +import type { ProtoSchema } from '../../protobuf/decode'; + +// --- 0x1253_1: Mute group member --- + +export const OidbMuteMemberBodySchema = { + targetUid: { field: 1, type: 'string' as const }, + duration: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbMuteMemberSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + type: { field: 2, type: 'uint32' as const }, + body: { field: 3, type: 'message' as const, schema: OidbMuteMemberBodySchema }, +} satisfies ProtoSchema; + +// --- 0x89A_0: Mute group all --- + +export const OidbMuteAllStateSchema = { + state: { field: 17, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbMuteAllSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + muteState: { field: 2, type: 'message' as const, schema: OidbMuteAllStateSchema }, +} satisfies ProtoSchema; + +// --- 0x8A0_1: Kick group member --- + +export const OidbKickMemberSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + targetUid: { field: 3, type: 'string' as const }, + rejectAddRequest:{ field: 4, type: 'bool' as const }, + reason: { field: 5, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- 0x1097_1: Leave group --- + +export const OidbLeaveGroupSchema = { + groupUin: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- 0xB5D_44: Friend add request --- + +export const OidbFriendRequestActionSchema = { + accept: { field: 1, type: 'uint32' as const }, + targetUid: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- 0x126B_0: Delete friend --- + +export const OidbDeleteFriendField2Field3Schema = { + field1: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbDeleteFriendField2Schema = { + field1: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'message' as const, schema: OidbDeleteFriendField2Field3Schema }, +} satisfies ProtoSchema; + +export const OidbDeleteFriendField1Schema = { + targetUid: { field: 1, type: 'string' as const }, + field2: { field: 2, type: 'message' as const, schema: OidbDeleteFriendField2Schema }, + block: { field: 3, type: 'bool' as const }, + field4: { field: 4, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const OidbDeleteFriendSchema = { + field1: { field: 1, type: 'message' as const, schema: OidbDeleteFriendField1Schema }, +} satisfies ProtoSchema; + +// --- 0x10C8: Group request action --- + +export const OidbGroupRequestBodySchema = { + sequence: { field: 1, type: 'uint64' as const }, + eventType: { field: 2, type: 'uint32' as const }, + groupUin: { field: 3, type: 'uint32' as const }, + message: { field: 4, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupRequestActionSchema = { + accept: { field: 1, type: 'uint32' as const }, + body: { field: 2, type: 'message' as const, schema: OidbGroupRequestBodySchema }, +} satisfies ProtoSchema; + +// --- 0xED3_1: Poke --- + +export const OidbPokeSchema = { + uin: { field: 1, type: 'uint32' as const }, + groupUin: { field: 2, type: 'uint32' as const }, + friendUin: { field: 5, type: 'uint32' as const }, + ext: { field: 6, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- 0xEAC: Group essence --- + +export const OidbEssenceSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + sequence: { field: 2, type: 'uint32' as const }, + random: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- 0x1096_1: Set group admin --- + +export const OidbSetAdminSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + uid: { field: 2, type: 'string' as const }, + isAdmin: { field: 3, type: 'bool' as const }, +} satisfies ProtoSchema; + +// --- 0x8FC_3: Set group card (rename member) --- + +export const OidbRenameMemberBodySchema = { + targetUid: { field: 1, type: 'string' as const }, + targetName: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbRenameMemberSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + body: { field: 2, type: 'message' as const, schema: OidbRenameMemberBodySchema }, +} satisfies ProtoSchema; + +// --- 0x89A_15: Rename group --- + +export const OidbRenameGroupBodySchema = { + targetName: { field: 1, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbRenameGroupSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + body: { field: 2, type: 'message' as const, schema: OidbRenameGroupBodySchema }, +} satisfies ProtoSchema; + +// --- 0x8FC_2: Set group special title --- + +export const OidbSpecialTitleBodySchema = { + targetUid: { field: 1, type: 'string' as const }, + specialTitle:{ field: 5, type: 'string' as const }, + expireTime: { field: 6, type: 'int32' as const }, +} satisfies ProtoSchema; + +export const OidbSpecialTitleSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + body: { field: 2, type: 'message' as const, schema: OidbSpecialTitleBodySchema }, +} satisfies ProtoSchema; + +// --- 0x7E5_104: Send like --- + +export const OidbLikeSchema = { + targetUin: { field: 1, type: 'uint32' as const }, + count: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- 0x10C0_1 / 0x10C0_2: Group request list --- + +export const OidbGroupRequestListSchema = { + count: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- 0xFE1_2: User profile info --- + +export const OidbUserInfoKeySchema = { + key: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbUserInfoRequestSchema = { + uin: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema }, +} satisfies ProtoSchema; + +export const OidbTwoNumberSchema = { + number1: { field: 1, type: 'uint32' as const }, + number2: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbBytePropertySchema = { + code: { field: 1, type: 'uint32' as const }, + value: { field: 2, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const OidbUserInfoPropertySchema = { + numberProperties: { field: 1, type: 'repeated_message' as const, schema: OidbTwoNumberSchema }, + bytesProperties: { field: 2, type: 'repeated_message' as const, schema: OidbBytePropertySchema }, +} satisfies ProtoSchema; + +export const OidbUserInfoResponseBodySchema = { + uid: { field: 1, type: 'string' as const }, + properties: { field: 2, type: 'message' as const, schema: OidbUserInfoPropertySchema }, + uin: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbUserInfoResponseSchema = { + body: { field: 1, type: 'message' as const, schema: OidbUserInfoResponseBodySchema }, +} satisfies ProtoSchema; + +export const AvatarInfoSchema = { + url: { field: 5, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- FD4_1: Friend list request body fields --- + +export const OidbFriendListNumberSchema = { + numbers: { field: 1, type: 'repeated_uint32' as const }, +} satisfies ProtoSchema; + +export const OidbFriendListBodyItemSchema = { + type: { field: 1, type: 'uint32' as const }, + number: { field: 2, type: 'message' as const, schema: OidbFriendListNumberSchema }, +} satisfies ProtoSchema; + +export const OidbFriendListNextUinSchema = { + uin: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbFriendListRequestSchema = { + friendCount: { field: 2, type: 'uint32' as const }, + field4: { field: 4, type: 'uint32' as const }, + nextUin: { field: 5, type: 'message' as const, schema: OidbFriendListNextUinSchema }, + field6: { field: 6, type: 'uint32' as const }, + field7: { field: 7, type: 'uint32' as const }, + body: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendListBodyItemSchema }, + field10002: { field: 10002, type: 'repeated_uint32' as const }, + field10003: { field: 10003, type: 'uint32' as const }, +} satisfies ProtoSchema; + +// --- FE5_2: Group list request body (config fields) --- + +export const OidbGroupListConfig1Schema = { + groupOwner: { field: 1, type: 'bool' as const }, + field2: { field: 2, type: 'bool' as const }, + memberMax: { field: 3, type: 'bool' as const }, + memberCount: { field: 4, type: 'bool' as const }, + groupName: { field: 5, type: 'bool' as const }, + field8: { field: 8, type: 'bool' as const }, + field9: { field: 9, type: 'bool' as const }, + field10: { field: 10, type: 'bool' as const }, + field11: { field: 11, type: 'bool' as const }, + field12: { field: 12, type: 'bool' as const }, + field13: { field: 13, type: 'bool' as const }, + field14: { field: 14, type: 'bool' as const }, + field15: { field: 15, type: 'bool' as const }, + field16: { field: 16, type: 'bool' as const }, + field17: { field: 17, type: 'bool' as const }, + field18: { field: 18, type: 'bool' as const }, + question: { field: 19, type: 'bool' as const }, + field20: { field: 20, type: 'bool' as const }, + field22: { field: 22, type: 'bool' as const }, + field23: { field: 23, type: 'bool' as const }, + field24: { field: 24, type: 'bool' as const }, + field25: { field: 25, type: 'bool' as const }, + field26: { field: 26, type: 'bool' as const }, + field27: { field: 27, type: 'bool' as const }, + field28: { field: 28, type: 'bool' as const }, + field29: { field: 29, type: 'bool' as const }, + field30: { field: 30, type: 'bool' as const }, + field31: { field: 31, type: 'bool' as const }, + field32: { field: 32, type: 'bool' as const }, + field5001: { field: 5001, type: 'bool' as const }, + field5002: { field: 5002, type: 'bool' as const }, + field5003: { field: 5003, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const OidbGroupListConfig2Schema = { + field1: { field: 1, type: 'bool' as const }, + field2: { field: 2, type: 'bool' as const }, + field3: { field: 3, type: 'bool' as const }, + field4: { field: 4, type: 'bool' as const }, + field5: { field: 5, type: 'bool' as const }, + field6: { field: 6, type: 'bool' as const }, + field7: { field: 7, type: 'bool' as const }, + field8: { field: 8, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const OidbGroupListConfig3Schema = { + field5: { field: 5, type: 'bool' as const }, + field6: { field: 6, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const OidbGroupListConfigSchema = { + config1: { field: 1, type: 'message' as const, schema: OidbGroupListConfig1Schema }, + config2: { field: 2, type: 'message' as const, schema: OidbGroupListConfig2Schema }, + config3: { field: 3, type: 'message' as const, schema: OidbGroupListConfig3Schema }, +} satisfies ProtoSchema; + +export const OidbGroupListRequestSchema = { + config: { field: 1, type: 'message' as const, schema: OidbGroupListConfigSchema }, +} satisfies ProtoSchema; + +// --- FE7_3: Group member list request body --- + +export const OidbGroupMemberListBodySchema = { + memberName: { field: 10, type: 'bool' as const }, + memberCard: { field: 11, type: 'bool' as const }, + level: { field: 12, type: 'bool' as const }, + field13: { field: 13, type: 'bool' as const }, + field16: { field: 16, type: 'bool' as const }, + specialTitle: { field: 17, type: 'bool' as const }, + field18: { field: 18, type: 'bool' as const }, + field20: { field: 20, type: 'bool' as const }, + field21: { field: 21, type: 'bool' as const }, + joinTimestamp: { field: 100, type: 'bool' as const }, + lastMsgTimestamp: { field: 101, type: 'bool' as const }, + shutUpTimestamp: { field: 102, type: 'bool' as const }, + field103: { field: 103, type: 'bool' as const }, + field104: { field: 104, type: 'bool' as const }, + field105: { field: 105, type: 'bool' as const }, + field106: { field: 106, type: 'bool' as const }, + permission: { field: 107, type: 'bool' as const }, + field200: { field: 200, type: 'bool' as const }, + field201: { field: 201, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const OidbGroupMemberListRequestSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'uint32' as const }, + body: { field: 4, type: 'message' as const, schema: OidbGroupMemberListBodySchema }, + token: { field: 15, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- Group recall message (trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg) --- + +export const GroupRecallInfoSchema = { + sequence: { field: 1, type: 'uint32' as const }, + random: { field: 2, type: 'uint32' as const }, + field3: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const GroupRecallSettingsSchema = { + field1: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const GroupRecallRequestSchema = { + type: { field: 1, type: 'uint32' as const }, + groupUin: { field: 2, type: 'uint32' as const }, + info: { field: 3, type: 'message' as const, schema: GroupRecallInfoSchema }, + settings: { field: 4, type: 'message' as const, schema: GroupRecallSettingsSchema }, +} satisfies ProtoSchema; + +// --- C2C (private) recall message (trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg) --- + +export const C2CRecallInfoSchema = { + clientSequence: { field: 1, type: 'uint32' as const }, + random: { field: 2, type: 'uint32' as const }, + messageId: { field: 3, type: 'uint64' as const }, + timestamp: { field: 4, type: 'uint32' as const }, + field5: { field: 5, type: 'uint32' as const }, + messageSequence: { field: 6, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const C2CRecallSettingsSchema = { + field1: { field: 1, type: 'bool' as const }, + field2: { field: 2, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const C2CRecallRequestSchema = { + type: { field: 1, type: 'uint32' as const }, + targetUid:{ field: 3, type: 'string' as const }, + info: { field: 4, type: 'message' as const, schema: C2CRecallInfoSchema }, + settings: { field: 5, type: 'message' as const, schema: C2CRecallSettingsSchema }, + field6: { field: 6, type: 'bool' as const }, +} satisfies ProtoSchema; + +// --- 0x9082_1: Set group reaction --- + +export const OidbGroupReactionSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + sequence: { field: 2, type: 'uint32' as const }, + code: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- 0x6D8_1: Group file list --- + +export const OidbGroupFileListReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + appId: { field: 2, type: 'uint32' as const }, + targetDirectory: { field: 3, type: 'string' as const }, + fileCount: { field: 5, type: 'uint32' as const }, + sortBy: { field: 9, type: 'uint32' as const }, + startIndex: { field: 13, type: 'uint32' as const }, + field17: { field: 17, type: 'uint32' as const }, + field18: { field: 18, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileViewReqSchema = { + list: { field: 2, type: 'message' as const, schema: OidbGroupFileListReqSchema }, +} satisfies ProtoSchema; + +export const OidbGroupFileListFolderRespSchema = { + folderId: { field: 1, type: 'string' as const }, + parentDirectoryId: { field: 2, type: 'string' as const }, + folderName: { field: 3, type: 'string' as const }, + createTime: { field: 4, type: 'uint32' as const }, + modifiedTime: { field: 5, type: 'uint32' as const }, + creatorUin: { field: 6, type: 'uint32' as const }, + creatorName: { field: 7, type: 'string' as const }, + totalFileCount: { field: 8, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileListFileRespSchema = { + fileId: { field: 1, type: 'string' as const }, + fileName: { field: 2, type: 'string' as const }, + fileSize: { field: 3, type: 'uint64' as const }, + busId: { field: 4, type: 'uint32' as const }, + uploadedTime: { field: 6, type: 'uint32' as const }, + expireTime: { field: 7, type: 'uint32' as const }, + modifiedTime: { field: 8, type: 'uint32' as const }, + downloadedTimes: { field: 9, type: 'uint32' as const }, + uploaderName: { field: 14, type: 'string' as const }, + uploaderUin: { field: 15, type: 'uint32' as const }, + parentDirectory: { field: 16, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileListItemRespSchema = { + type: { field: 1, type: 'uint32' as const }, + folderInfo: { field: 2, type: 'message' as const, schema: OidbGroupFileListFolderRespSchema }, + fileInfo: { field: 3, type: 'message' as const, schema: OidbGroupFileListFileRespSchema }, +} satisfies ProtoSchema; + +export const OidbGroupFileListRespSchema = { + retCode: { field: 1, type: 'uint32' as const }, + retMsg: { field: 2, type: 'string' as const }, + clientWording: { field: 3, type: 'string' as const }, + isEnd: { field: 4, type: 'bool' as const }, + items: { field: 5, type: 'repeated_message' as const, schema: OidbGroupFileListItemRespSchema }, +} satisfies ProtoSchema; + +export const OidbGroupFileViewRespSchema = { + list: { field: 2, type: 'message' as const, schema: OidbGroupFileListRespSchema }, +} satisfies ProtoSchema; + +// --- 0x6D6_2 / 0x6D6_3: Group file url & delete --- + +export const OidbGroupFileUploadReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + appId: { field: 2, type: 'uint32' as const }, + busId: { field: 3, type: 'uint32' as const }, + entrance: { field: 4, type: 'uint32' as const }, + targetDirectory: { field: 5, type: 'string' as const }, + fileName: { field: 6, type: 'string' as const }, + localDirectory: { field: 7, type: 'string' as const }, + fileSize: { field: 8, type: 'uint64' as const }, + fileSha1: { field: 9, type: 'bytes' as const }, + fileSha3: { field: 10, type: 'bytes' as const }, + fileMd5: { field: 11, type: 'bytes' as const }, + field15: { field: 15, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileDownloadReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + appId: { field: 2, type: 'uint32' as const }, + busId: { field: 3, type: 'uint32' as const }, + fileId: { field: 4, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileDeleteReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + busId: { field: 3, type: 'uint32' as const }, + fileId: { field: 5, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileMoveReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + appId: { field: 2, type: 'uint32' as const }, + busId: { field: 3, type: 'uint32' as const }, + fileId: { field: 4, type: 'string' as const }, + parentDirectory: { field: 5, type: 'string' as const }, + targetDirectory: { field: 6, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileReqSchema = { + file: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadReqSchema }, + download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadReqSchema }, + delete: { field: 4, type: 'message' as const, schema: OidbGroupFileDeleteReqSchema }, + move: { field: 6, type: 'message' as const, schema: OidbGroupFileMoveReqSchema }, +} satisfies ProtoSchema; + +export const OidbGroupFileUploadRespSchema = { + retCode: { field: 1, type: 'int32' as const }, + retMsg: { field: 2, type: 'string' as const }, + clientWording: { field: 3, type: 'string' as const }, + uploadIp: { field: 4, type: 'string' as const }, + serverDns: { field: 5, type: 'string' as const }, + busId: { field: 6, type: 'int32' as const }, + fileId: { field: 7, type: 'string' as const }, + checkKey: { field: 8, type: 'bytes' as const }, + fileKey: { field: 9, type: 'bytes' as const }, + boolFileExist: { field: 10, type: 'bool' as const }, + uploadPort: { field: 14, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileDownloadRespSchema = { + retCode: { field: 1, type: 'uint32' as const }, + retMsg: { field: 2, type: 'string' as const }, + clientWording: { field: 3, type: 'string' as const }, + downloadIp: { field: 4, type: 'string' as const }, + downloadDns: { field: 5, type: 'string' as const }, + downloadUrl: { field: 6, type: 'bytes' as const }, + saveFileName: { field: 11, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileRetRespSchema = { + retCode: { field: 1, type: 'uint32' as const }, + retMsg: { field: 2, type: 'string' as const }, + clientWording: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileRespSchema = { + upload: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadRespSchema }, + download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadRespSchema }, + delete: { field: 4, type: 'message' as const, schema: OidbGroupFileRetRespSchema }, + move: { field: 6, type: 'message' as const, schema: OidbGroupFileRetRespSchema }, +} satisfies ProtoSchema; + +// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops --- + +export const OidbGroupFileCreateFolderReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + rootDirectory: { field: 3, type: 'string' as const }, + folderName: { field: 4, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileDeleteFolderReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + folderId: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileRenameFolderReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + folderId: { field: 3, type: 'string' as const }, + newFolderName: { field: 4, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileFolderReqSchema = { + create: { field: 1, type: 'message' as const, schema: OidbGroupFileCreateFolderReqSchema }, + delete: { field: 2, type: 'message' as const, schema: OidbGroupFileDeleteFolderReqSchema }, + rename: { field: 3, type: 'message' as const, schema: OidbGroupFileRenameFolderReqSchema }, +} satisfies ProtoSchema; + +export const OidbGroupFileFolderRetRespSchema = { + retcode: { field: 1, type: 'uint32' as const }, + retMsg: { field: 2, type: 'string' as const }, + clientWording: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileFolderRespSchema = { + create: { field: 1, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema }, + delete: { field: 2, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema }, + rename: { field: 3, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema }, +} satisfies ProtoSchema; + +// --- 0xE37_1200: Private file download url --- + +export const OidbPrivateFileDownloadReqBodySchema = { + receiverUid: { field: 10, type: 'string' as const }, + fileUuid: { field: 20, type: 'string' as const }, + type: { field: 30, type: 'uint32' as const }, + fileHash: { field: 60, type: 'string' as const }, + t2: { field: 601, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbPrivateFileDownloadReqSchema = { + subCommand: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'uint32' as const }, + body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadReqBodySchema }, + field101: { field: 101, type: 'uint32' as const }, + field102: { field: 102, type: 'uint32' as const }, + field200: { field: 200, type: 'uint32' as const }, + field99999: { field: 99999, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const OidbPrivateFileDownloadRespResultSchema = { + server: { field: 20, type: 'string' as const }, + port: { field: 40, type: 'uint32' as const }, + url: { field: 50, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbPrivateFileDownloadRespBodySchema = { + state: { field: 20, type: 'string' as const }, + result: { field: 30, type: 'message' as const, schema: OidbPrivateFileDownloadRespResultSchema }, +} satisfies ProtoSchema; + +export const OidbPrivateFileDownloadRespSchema = { + body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadRespBodySchema }, +} satisfies ProtoSchema; + +// --- 0xE37_1700: Private file upload --- + +export const OidbPrivateFileUploadReqBodySchema = { + senderUid: { field: 10, type: 'string' as const }, + receiverUid: { field: 20, type: 'string' as const }, + fileSize: { field: 30, type: 'uint32' as const }, + fileName: { field: 40, type: 'string' as const }, + md510MCheckSum:{ field: 50, type: 'bytes' as const }, + sha1CheckSum: { field: 60, type: 'bytes' as const }, + localPath: { field: 70, type: 'string' as const }, + md5CheckSum: { field: 110, type: 'bytes' as const }, + sha3CheckSum: { field: 120, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const OidbPrivateFileUploadReqSchema = { + command: { field: 1, type: 'uint32' as const }, + seq: { field: 2, type: 'int32' as const }, + upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadReqBodySchema }, + businessId: { field: 101, type: 'int32' as const }, + clientType: { field: 102, type: 'int32' as const }, + flagSupportMediaPlatform: { field: 200, type: 'int32' as const }, +} satisfies ProtoSchema; + +export const OidbPrivateFileUploadRespBodySchema = { + retCode: { field: 10, type: 'int32' as const }, + retMsg: { field: 20, type: 'string' as const }, + uploadIp: { field: 60, type: 'string' as const }, + uploadPort: { field: 80, type: 'uint32' as const }, + uuid: { field: 90, type: 'string' as const }, + uploadKey: { field: 100, type: 'bytes' as const }, + boolFileExist: { field: 110, type: 'bool' as const }, + fileAddon: { field: 200, type: 'string' as const }, + mediaPlatformUploadKey: { field: 220, type: 'bytes' as const }, +} satisfies ProtoSchema; + +export const OidbPrivateFileUploadRespSchema = { + upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadRespBodySchema }, +} satisfies ProtoSchema; + +// --- NTV2 Rich Media (0x9067_202): Download RKey --- + +export const NTV2CommonHeadSchema = { + requestId: { field: 1, type: 'uint32' as const }, + command: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2C2CUserInfoSchema = { + accountType: { field: 1, type: 'uint32' as const }, + targetUid: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const NTV2GroupInfoSchema = { + groupUin: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2SceneInfoSchema = { + requestType: { field: 101, type: 'uint32' as const }, + businessType: { field: 102, type: 'uint32' as const }, + sceneType: { field: 200, type: 'uint32' as const }, + c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema }, + group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema }, +} satisfies ProtoSchema; + +export const NTV2ClientMetaSchema = { + agentType: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2ReqHeadSchema = { + common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema }, + scene: { field: 2, type: 'message' as const, schema: NTV2SceneInfoSchema }, + client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema }, +} satisfies ProtoSchema; + +export const NTV2DownloadRKeyReqSchema = { + types: { field: 1, type: 'repeated_uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2FileTypeSchema = { + type: { field: 1, type: 'uint32' as const }, + picFormat: { field: 2, type: 'uint32' as const }, + videoFormat: { field: 3, type: 'uint32' as const }, + voiceFormat: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2FileInfoSchema = { + fileSize: { field: 1, type: 'uint32' as const }, + fileHash: { field: 2, type: 'string' as const }, + fileSha1: { field: 3, type: 'string' as const }, + fileName: { field: 4, type: 'string' as const }, + type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema }, + width: { field: 6, type: 'uint32' as const }, + height: { field: 7, type: 'uint32' as const }, + time: { field: 8, type: 'uint32' as const }, + original: { field: 9, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2IndexNodeSchema = { + info: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema }, + fileUuid: { field: 2, type: 'string' as const }, + storeId: { field: 3, type: 'uint32' as const }, + uploadTime: { field: 4, type: 'uint32' as const }, + ttl: { field: 5, type: 'uint32' as const }, + subType: { field: 6, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2VideoDownloadExtSchema = { + busiType: { field: 1, type: 'uint32' as const }, + sceneType: { field: 2, type: 'uint32' as const }, + subBusiType: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2DownloadExtSchema = { + video: { field: 2, type: 'message' as const, schema: NTV2VideoDownloadExtSchema }, +} satisfies ProtoSchema; + +export const NTV2DownloadReqSchema = { + node: { field: 1, type: 'message' as const, schema: NTV2IndexNodeSchema }, + download: { field: 2, type: 'message' as const, schema: NTV2DownloadExtSchema }, +} satisfies ProtoSchema; + +export const NTV2RichMediaReqSchema = { + reqHead: { field: 1, type: 'message' as const, schema: NTV2ReqHeadSchema }, + download: { field: 3, type: 'message' as const, schema: NTV2DownloadReqSchema }, + downloadRkey: { field: 4, type: 'message' as const, schema: NTV2DownloadRKeyReqSchema }, +} satisfies ProtoSchema; + +export const NTV2RespHeadSchema = { + common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema }, + retCode: { field: 2, type: 'uint32' as const }, + message: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const NTV2RKeyInfoSchema = { + rkey: { field: 1, type: 'string' as const }, + rkeyTtlSec: { field: 2, type: 'uint64' as const }, + storeId: { field: 3, type: 'uint32' as const }, + rkeyCreateTime:{ field: 4, type: 'uint32' as const }, + type: { field: 5, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2DownloadRKeyRespSchema = { + rkeys: { field: 1, type: 'repeated_message' as const, schema: NTV2RKeyInfoSchema }, +} satisfies ProtoSchema; + +export const NTV2MediaDownloadInfoSchema = { + domain: { field: 1, type: 'string' as const }, + urlPath: { field: 2, type: 'string' as const }, + httpsPort: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2MediaDownloadRespSchema = { + rKeyParam: { field: 1, type: 'string' as const }, + rKeyTtlSecond: { field: 2, type: 'uint32' as const }, + info: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadInfoSchema }, + rKeyCreateTime: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const NTV2RichMediaRespSchema = { + respHead: { field: 1, type: 'message' as const, schema: NTV2RespHeadSchema }, + download: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadRespSchema }, + downloadRkey:{ field: 4, type: 'message' as const, schema: NTV2DownloadRKeyRespSchema }, +} satisfies ProtoSchema; + +// --- 0xB6E_2: Set friend remark --- + +export const OidbSetFriendRemarkSchema = { + targetUid: { field: 1, type: 'string' as const }, + remark: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- 0x9082_2: Set group reaction (remove) — same schema as set --- +// (0x9082_1 for add, 0x9082_2 for remove — both use OidbGroupReactionSchema) + +// --- Group file count (0x6D8_3) --- + +export const OidbGroupFileCountReqSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + appId: { field: 2, type: 'uint32' as const }, + busId: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileCountRespSchema = { + fileCount: { field: 1, type: 'uint32' as const }, + maxCount: { field: 2, type: 'uint32' as const }, + isEnd: { field: 3, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const OidbGroupFileCountViewReqSchema = { + count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountReqSchema }, +} satisfies ProtoSchema; + +export const OidbGroupFileCountViewRespSchema = { + count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountRespSchema }, +} satisfies ProtoSchema; diff --git a/src/bridge/proto/oidb.ts b/src/bridge/proto/oidb.ts new file mode 100644 index 00000000..65fa1000 --- /dev/null +++ b/src/bridge/proto/oidb.ts @@ -0,0 +1,161 @@ +// Proto schemas for OidbSvc service types. +// Port of src/bridge/include/bridge/proto/oidb.h + +import type { ProtoSchema } from '../../protobuf/decode'; + +// --- OidbSvcTrpcTcpBase wrapper --- + +export const OidbPropertySchema = { + key: { field: 1, type: 'string' as const }, + value: { field: 2, type: 'bytes' as const }, +} satisfies ProtoSchema; + +// Factory for OidbSvcTrpcTcpBase +export function makeOidbBaseSchema(bodySchema: ProtoSchema): ProtoSchema { + return { + command: { field: 1, type: 'uint32' as const }, + subCommand: { field: 2, type: 'uint32' as const }, + errorCode: { field: 3, type: 'uint32' as const }, + body: { field: 4, type: 'message' as const, schema: bodySchema }, + errorMsg: { field: 5, type: 'string' as const }, + properties: { field: 11, type: 'repeated_message' as const, schema: OidbPropertySchema }, + reserved: { field: 12, type: 'int32' as const }, + }; +} + +// --- Friend list (0xFD4_1) --- + +export const OidbFriendPropertySchema = { + code: { field: 1, type: 'uint32' as const }, + value: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbFriendLayer1Schema = { + properties: { field: 2, type: 'repeated_message' as const, schema: OidbFriendPropertySchema }, +} satisfies ProtoSchema; + +export const OidbFriendAdditionalSchema = { + type: { field: 1, type: 'uint32' as const }, + layer1: { field: 2, type: 'message' as const, schema: OidbFriendLayer1Schema }, +} satisfies ProtoSchema; + +export const OidbFriendSchema = { + uid: { field: 1, type: 'string' as const }, + customGroup:{ field: 2, type: 'uint32' as const }, + uin: { field: 3, type: 'uint32' as const }, + additional: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendAdditionalSchema }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFD4_1ResponseUinSchema = { + uin: { field: 1, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFD4_1ResponseSchema = { + next: { field: 2, type: 'message' as const, schema: OidbSvcTrpcTcp0xFD4_1ResponseUinSchema }, + displayFriendCount: { field: 3, type: 'uint32' as const }, + timestamp: { field: 6, type: 'uint32' as const }, + selfUin: { field: 7, type: 'uint32' as const }, + friends: { field: 101, type: 'repeated_message' as const, schema: OidbFriendSchema }, + groups: { field: 102, type: 'repeated_message' as const, schema: OidbFriendPropertySchema }, +} satisfies ProtoSchema; + +// --- Group list (0xFE5_2) --- + +export const OidbSvcTrpcTcp0xFE5_2MemberSchema = { + uid: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFE5_2GroupInfoSchema = { + groupOwner: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2MemberSchema }, + createdTime: { field: 2, type: 'uint32' as const }, + memberMax: { field: 3, type: 'uint32' as const }, + memberCount: { field: 4, type: 'uint32' as const }, + groupName: { field: 5, type: 'string' as const }, + description: { field: 18, type: 'string' as const }, + question: { field: 19, type: 'string' as const }, + announcement: { field: 30, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFE5_2CustomInfoSchema = { + remark: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFE5_2GroupSchema = { + groupUin: { field: 3, type: 'uint32' as const }, + info: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupInfoSchema }, + customInfo: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2CustomInfoSchema }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFE5_2ResponseSchema = { + groups: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupSchema }, +} satisfies ProtoSchema; + +// --- Group member list (0xFE7_3) --- + +export const OidbSvcTrpcTcp0xFE7_3UinSchema = { + uid: { field: 2, type: 'string' as const }, + uin: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFE7_3CardSchema = { + memberCard: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFE7_3LevelSchema = { + infos: { field: 1, type: 'repeated_uint32' as const }, + level: { field: 2, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFE7_3MemberSchema = { + uin: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3UinSchema }, + memberName: { field: 10, type: 'string' as const }, + specialTitle: { field: 17, type: 'string' as const }, + memberCard: { field: 11, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3CardSchema }, + level: { field: 12, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3LevelSchema }, + joinTimestamp: { field: 100, type: 'uint32' as const }, + lastMsgTimestamp: { field: 101, type: 'uint32' as const }, + shutUpTimestamp: { field: 102, type: 'uint32' as const }, + permission: { field: 107, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0xFE7_3ResponseSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + members: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE7_3MemberSchema }, + field3: { field: 3, type: 'uint32' as const }, + memberChangeSeq: { field: 5, type: 'uint32' as const }, + memberCardChangeSeq:{ field: 6, type: 'uint32' as const }, + token: { field: 15, type: 'string' as const }, +} satisfies ProtoSchema; + +// --- Group request (0x10C0) --- + +export const OidbSvcTrpcTcp0x10C0ResponseUserSchema = { + uid: { field: 1, type: 'string' as const }, + name: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0x10C0ResponseGroupSchema = { + groupUin: { field: 1, type: 'uint32' as const }, + groupName: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0x10C0ResponseRequestSchema = { + sequence: { field: 1, type: 'uint64' as const }, + eventType: { field: 2, type: 'uint32' as const }, + state: { field: 3, type: 'uint32' as const }, + group: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseGroupSchema }, + target: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema }, + invitor: { field: 6, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema }, + operatorUser: { field: 7, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema }, + field9: { field: 9, type: 'string' as const }, + comment: { field: 10, type: 'string' as const }, +} satisfies ProtoSchema; + +export const OidbSvcTrpcTcp0x10C0ResponseSchema = { + requests: { field: 1, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseRequestSchema }, + field2: { field: 2, type: 'uint64' as const }, + newLatestSeq: { field: 3, type: 'uint64' as const }, + field4: { field: 4, type: 'uint32' as const }, + field5: { field: 5, type: 'uint64' as const }, + field6: { field: 6, type: 'uint32' as const }, +} satisfies ProtoSchema; diff --git a/src/bridge/qq-info.ts b/src/bridge/qq-info.ts new file mode 100644 index 00000000..0df7f7e5 --- /dev/null +++ b/src/bridge/qq-info.ts @@ -0,0 +1,205 @@ +// QQ info store — per-UIN state for friends, groups, member lookup. +// Port of src/bridge/include/bridge/qq_info.h + src/bridge/src/qq_info.cpp + +export interface UserProfileInfo { + uin: number; + uid: string; + nickname: string; + remark: string; + qid: string; + sex: string; + age: number; + sign: string; + avatar: string; +} + +export interface FriendInfo { + uin: number; + uid: string; + nickname: string; + remark: string; +} + +export interface GroupMemberInfo { + uin: number; + uid: string; + nickname: string; + card: string; + role: string; // 'owner' | 'admin' | 'member' + level: number; + title: string; + joinTime: number; + lastSentTime: number; + shutUpTime: number; +} + +export interface QQGroupInfo { + groupId: number; + groupName: string; + remark: string; + memberCount: number; + memberMax: number; + members: Map; +} + +export interface GroupRequestInfo { + groupId: number; + groupName: string; + targetUid: string; + targetUin: number; + targetName: string; + invitorUid: string; + invitorUin: number; + invitorName: string; + operatorUid: string; + operatorUin: number; + operatorName: string; + sequence: number; + state: number; + eventType: number; + comment: string; + filtered: boolean; +} + +export class QQInfo { + private uin_: string; + private nickname_ = ''; + private selfProfile_: UserProfileInfo | null = null; + private userProfiles_ = new Map(); + private friends_: FriendInfo[] = []; + private groups_ = new Map(); + + constructor(uin: string) { + this.uin_ = uin; + } + + get uin(): string { return this.uin_; } + + get nickname(): string { return this.nickname_; } + set nickname(v: string) { this.nickname_ = v; } + + // --- Self profile --- + + setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; } + get selfProfile(): UserProfileInfo | null { return this.selfProfile_; } + get selfUid(): string | null { return this.selfProfile_?.uid ?? null; } + + // --- User profiles --- + + setUserProfile(info: UserProfileInfo): void { + this.userProfiles_.set(info.uin, info); + } + + findUserProfile(uin: number): UserProfileInfo | null { + return this.userProfiles_.get(uin) ?? null; + } + + // --- Friends --- + + setFriends(friends: FriendInfo[]): void { this.friends_ = friends; } + get friends(): FriendInfo[] { return this.friends_; } + + findFriend(uin: number): FriendInfo | null { + return this.friends_.find(f => f.uin === uin) ?? null; + } + + // --- Groups --- + + setGroups(groups: QQGroupInfo[]): void { + this.groups_.clear(); + for (const g of groups) { + this.groups_.set(g.groupId, g); + } + } + + get groups(): QQGroupInfo[] { return [...this.groups_.values()]; } + + findGroup(groupId: number): QQGroupInfo | null { + return this.groups_.get(groupId) ?? null; + } + + findGroupMember(groupId: number, uin: number): GroupMemberInfo | null { + return this.groups_.get(groupId)?.members.get(uin) ?? null; + } + + setGroupMembers(groupId: number, members: GroupMemberInfo[]): void { + const g = this.groups_.get(groupId); + if (!g) return; + g.members.clear(); + for (const m of members) { + g.members.set(m.uin, m); + } + } + + updateGroupMember(groupId: number, member: GroupMemberInfo): void { + const g = this.groups_.get(groupId); + if (!g) return; + g.members.set(member.uin, member); + } + + // --- UID resolution --- + + resolveUid(uid: string): number | null { + // Check self + if (this.selfProfile_?.uid === uid) { + return this.selfProfile_.uin || parseInt(this.uin_, 10) || null; + } + // Check friends + for (const f of this.friends_) { + if (f.uid === uid) return f.uin; + } + // Check user profiles + for (const [, p] of this.userProfiles_) { + if (p.uid === uid) return p.uin; + } + // Check all group members + for (const [, g] of this.groups_) { + for (const [, m] of g.members) { + if (m.uid === uid) return m.uin; + } + } + return null; + } + + resolveGroupMemberUid(groupId: number, uid: string): number | null { + const g = this.groups_.get(groupId); + if (!g) return null; + for (const [, m] of g.members) { + if (m.uid === uid) return m.uin; + } + return null; + } + + // --- Reverse UID lookup (UIN → UID) --- + + findUidByUin(uin: number): string | null { + // Check self + if (this.selfProfile_ && this.selfProfile_.uin === uin && this.selfProfile_.uid) { + return this.selfProfile_.uid; + } + // Check friends + for (const f of this.friends_) { + if (f.uin === uin && f.uid) return f.uid; + } + // Check user profiles + for (const [, p] of this.userProfiles_) { + if (p.uin === uin && p.uid) return p.uid; + } + // Check all group members + for (const [, g] of this.groups_) { + for (const [, m] of g.members) { + if (m.uin === uin && m.uid) return m.uid; + } + } + return null; + } + + findUidByUinInGroup(groupId: number, uin: number): string | null { + const g = this.groups_.get(groupId); + if (!g) return null; + for (const [, m] of g.members) { + if (m.uin === uin && m.uid) return m.uid; + } + return null; + } +} diff --git a/src/common/runtime.ts b/src/common/runtime.ts new file mode 100644 index 00000000..333abea1 --- /dev/null +++ b/src/common/runtime.ts @@ -0,0 +1,75 @@ +import fs from 'fs'; +import path from 'path'; + +export interface RuntimeConfig { + webuiPort?: number; +} + +const CONFIG_DIR = 'config'; +const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json'); + +const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = { + webuiPort: 8080, +}; + +export function loadRuntimeConfig(): RuntimeConfig { + fs.mkdirSync(CONFIG_DIR, { recursive: true }); + + const loaded = tryLoadRuntimeConfig(); + if (!loaded) { + saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG); + return { ...DEFAULT_RUNTIME_CONFIG }; + } + + const normalized: RuntimeConfig = { + webuiPort: normalizePort(loaded.webuiPort ?? 8080, 8080), + }; + + if ( + normalized.webuiPort !== loaded.webuiPort + ) { + saveRuntimeConfig(normalized); + } + + return normalized; +} + +function tryLoadRuntimeConfig(): RuntimeConfig | null { + if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null; + + try { + const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8'); + const parsed = JSON.parse(raw) as unknown; + if (!isObject(parsed)) return null; + + return { + webuiPort: normalizePort(parsed.webuiPort ?? 8080, 8080), + }; + } catch { + return null; + } +} + +function saveRuntimeConfig(config: RuntimeConfig): void { + fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8'); +} + +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; + } + } + return fallback; +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/src/env.d.ts b/src/env.d.ts new file mode 100644 index 00000000..53e7e23f --- /dev/null +++ b/src/env.d.ts @@ -0,0 +1 @@ +declare const __BUILD_WEBUI__: boolean; diff --git a/src/hook/hook-manager.ts b/src/hook/hook-manager.ts new file mode 100644 index 00000000..f13e05ea --- /dev/null +++ b/src/hook/hook-manager.ts @@ -0,0 +1,291 @@ +import type { BridgeManager } from '../bridge/manager'; +import type { NtqqHandler } from '../protocol/ntqq-handler'; +import { createLogger } from '../utils/logger'; +import { HookPacketClient } from './hook-packet-client'; +import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjectResult, type HookProcessBaseInfo } from './injector'; +import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client'; + +const log = createLogger('Hook'); +const CONNECT_RETRY_COUNT = 30; +const CONNECT_RETRY_INTERVAL_MS = 1000; + +export type HookProcessStatus = 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected'; + +export interface HookProcessInfo extends HookProcessBaseInfo { + injected: boolean; + connected: boolean; + loggedIn: boolean; + uin: string; + status: HookProcessStatus; + error: string; + method: string; +} + +interface HookProcessState extends HookProcessInfo { + client: QqHookClient | null; + sender: HookPacketClient | null; + injectResult: HookInjectResult | null; + connectTask: Promise | null; + bound: boolean; +} + +export class HookManager { + private readonly states = new Map(); + private readonly loadTasks = new Map>(); + private readonly unloadTasks = new Map>(); + + constructor( + private readonly ntqq: NtqqHandler, + private readonly bridgeManager: BridgeManager, + ) {} + + async listProcesses(): Promise { + const processes = await listHookProcesses(); + for (const proc of processes) { + const state = this.ensureState(proc.pid); + state.name = proc.name; + state.path = proc.path; + } + + const seen = new Set(processes.map(proc => proc.pid)); + const result: HookProcessInfo[] = []; + for (const proc of processes) { + result.push(this.toPublicInfo(this.ensureState(proc.pid))); + } + for (const state of this.states.values()) { + if (!seen.has(state.pid) && state.injected) { + result.push(this.toPublicInfo(state)); + } + } + return result.sort((a, b) => a.pid - b.pid); + } + + async loadProcess(pid: number): Promise { + if (!Number.isInteger(pid) || pid <= 0) { + throw new Error('invalid pid'); + } + const runningTask = this.loadTasks.get(pid); + if (runningTask) return runningTask; + + const task = this.loadProcessInternal(pid); + this.loadTasks.set(pid, task); + try { + return await task; + } finally { + this.loadTasks.delete(pid); + } + } + + async unloadProcess(pid: number): Promise { + if (!Number.isInteger(pid) || pid <= 0) { + throw new Error('invalid pid'); + } + const runningTask = this.unloadTasks.get(pid); + if (runningTask) return runningTask; + + const task = this.unloadProcessInternal(pid); + this.unloadTasks.set(pid, task); + try { + return await task; + } finally { + this.unloadTasks.delete(pid); + } + } + + dispose(): void { + for (const state of this.states.values()) { + state.client?.close(); + state.client = null; + state.connected = false; + state.loggedIn = false; + state.status = state.injected ? 'disconnected' : 'available'; + } + } + + private async loadProcessInternal(pid: number): Promise { + const state = this.ensureState(pid); + state.status = 'loading'; + state.error = ''; + + try { + if (!state.injected) { + state.injectResult = injectHookProcess(pid); + state.injected = true; + state.method = state.injectResult.method; + log.info('SnowLuma loaded into PID=%d via %s', pid, state.method); + } + state.status = state.connected ? (state.loggedIn ? 'online' : 'loaded') : 'loaded'; + this.startClient(state); + } catch (error) { + state.status = 'error'; + state.error = error instanceof Error ? error.message : String(error); + log.error('load failed: PID=%d err=%s', pid, state.error); + } + + return this.toPublicInfo(state); + } + + private async unloadProcessInternal(pid: number): Promise { + const state = this.ensureState(pid); + state.error = ''; + + try { + state.client?.close(); + state.client = null; + state.sender = null; + state.connectTask = null; + state.bound = false; + state.connected = false; + state.loggedIn = false; + this.bridgeManager.onPidDisconnected(pid); + + const handle = state.injectResult?.handle; + if (state.injected && handle) { + unloadHookProcess(pid, handle); + log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid); + } + + state.injected = false; + state.injectResult = null; + state.method = ''; + state.uin = '0'; + state.status = 'available'; + } catch (error) { + state.status = 'error'; + state.error = error instanceof Error ? error.message : String(error); + log.error('unload failed: PID=%d err=%s', pid, state.error); + } + + return this.toPublicInfo(state); + } + + private ensureState(pid: number): HookProcessState { + let state = this.states.get(pid); + if (!state) { + state = { + pid, + name: 'QQ.exe', + path: '', + injected: false, + connected: false, + loggedIn: false, + uin: '0', + status: 'available', + error: '', + method: '', + client: null, + sender: null, + injectResult: null, + connectTask: null, + bound: false, + }; + this.states.set(pid, state); + } + return state; + } + + private startClient(state: HookProcessState): void { + if (!state.client) { + state.client = new QqHookClient(state.pid); + state.sender = new HookPacketClient(state.client); + } + if (!state.bound) { + this.bindClient(state, state.client); + state.bound = true; + } + if (!state.connectTask) { + state.connectTask = this.connectClient(state).finally(() => { + state.connectTask = null; + }); + void state.connectTask; + } + } + + private bindClient(state: HookProcessState, client: QqHookClient): void { + client.on('packet', packet => this.handlePacket(state, packet)); + client.on('loginState', loginState => this.handleLoginState(state, loginState)); + client.on('error', error => { + state.error = error instanceof Error ? error.message : String(error); + if (!state.connected) state.status = 'error'; + log.warn('pipe error: PID=%d err=%s', state.pid, state.error); + }); + client.on('close', () => { + state.connected = false; + if (state.loggedIn) { + state.loggedIn = false; + state.status = 'disconnected'; + this.bridgeManager.onPidDisconnected(state.pid); + } + }); + } + + private async connectClient(state: HookProcessState): Promise { + const client = state.client; + if (!client) return; + + for (let attempt = 1; attempt <= CONNECT_RETRY_COUNT; attempt++) { + try { + await client.connectAll({ recv: true }); + state.connected = true; + state.status = client.isLoggedIn ? 'online' : 'loaded'; + state.error = ''; + const loginState = client.getLoginState(); + if (loginState.loggedIn) { + this.handleLoginState(state, loginState); + } + log.info('pipe connected: PID=%d', state.pid); + return; + } catch (error) { + state.error = error instanceof Error ? error.message : String(error); + if (attempt >= CONNECT_RETRY_COUNT) { + state.status = 'error'; + log.error('pipe connect failed: PID=%d err=%s', state.pid, state.error); + return; + } + await delay(CONNECT_RETRY_INTERVAL_MS); + } + } + } + + private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void { + state.uin = loginState.uin || loginState.uinNumber.toString(); + state.loggedIn = loginState.loggedIn && isRealUin(state.uin); + state.status = state.loggedIn ? 'online' : (state.connected ? 'loaded' : state.status); + + if (!state.loggedIn || !state.sender) return; + + this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender); + log.success('login detected: PID=%d UIN=%s', state.pid, state.uin); + } + + private handlePacket(state: HookProcessState, packet: QqHookPacket): void { + if (!state.loggedIn) return; + const uin = packet.uin || state.uin; + if (!isRealUin(uin)) return; + this.ntqq.onHookPacket(state.pid, { ...packet, uin }); + } + + private toPublicInfo(state: HookProcessState): HookProcessInfo { + return { + pid: state.pid, + name: state.name, + path: state.path, + injected: state.injected, + connected: state.connected, + loggedIn: state.loggedIn, + uin: state.uin, + status: state.status, + error: state.error, + method: state.method, + }; + } +} + +function isRealUin(uin: string): boolean { + if (!uin || uin === '0') return false; + return /^\d+$/.test(uin) && uin.length >= 5; +} + +function delay(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); +} diff --git a/src/hook/hook-packet-client.ts b/src/hook/hook-packet-client.ts new file mode 100644 index 00000000..30505eac --- /dev/null +++ b/src/hook/hook-packet-client.ts @@ -0,0 +1,34 @@ +import type { PacketSender, SendPacketResult } from '../protocol/packet-sender'; +import { QqHookClient, type QqHookSendReply } from './qq-hook-client'; + +export class HookPacketClient implements PacketSender { + constructor(private readonly client: QqHookClient) {} + + async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise { + 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; + 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, + }; + } + } +} diff --git a/src/hook/injector.ts b/src/hook/injector.ts new file mode 100644 index 00000000..38ee80f1 --- /dev/null +++ b/src/hook/injector.ts @@ -0,0 +1,110 @@ +import { existsSync } from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export interface ManualMapHandle { + base: bigint; + entry: bigint; + size: number; +} + +interface NativeHookAddon { + getAllMainProcess(): number[]; + loadModuleManual(pid: number, dylibPath: string): ManualMapHandle; + unloadModuleManual(pid: number, handle: ManualMapHandle): void; +} + +export interface HookProcessBaseInfo { + pid: number; + name: string; + path: string; +} + +export interface HookInjectResult { + method: 'loadModuleManual'; + handle?: ManualMapHandle; +} + +let nativeAddon: NativeHookAddon | null = null; +let nativeLoadError: string | null = null; + +function loadNativeAddon(addonPath: string): NativeHookAddon { + const mod = { exports: {} as Record }; + process.dlopen(mod, addonPath); + return mod.exports as unknown as NativeHookAddon; +} + +function platformBinaryName(ext: 'node' | 'dll'): string { + if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`; + return `snowluma-${process.platform}-${process.arch}.${ext}`; +} + +function nativeSearchDirs(): string[] { + return [ + path.resolve(__dirname, '..', '..', 'native'), + path.resolve(__dirname, '..', 'native'), + path.resolve(process.cwd(), 'dist', 'native'), + path.resolve(process.cwd(), 'native'), + ]; +} + +export function resolveHookNativePath(ext: 'node' | 'dll'): string | 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; + } +} + +export function getNativeHookLoadError(): string | null { + return nativeLoadError; +} + +export function listHookProcesses(): HookProcessBaseInfo[] { + 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: 'QQ.exe', path: '' })); +} + +export function injectHookProcess(pid: number): HookInjectResult { + const addon = getNativeHookAddon(); + if (!addon) { + throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available'); + } + const dllPath = resolveHookNativePath('dll'); + if (!dllPath) { + throw new Error(`No hook DLL found for ${process.platform}-${process.arch}`); + } + return { method: 'loadModuleManual', handle: 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); +} diff --git a/src/hook/qq-hook-client.ts b/src/hook/qq-hook-client.ts new file mode 100644 index 00000000..34c6da8c --- /dev/null +++ b/src/hook/qq-hook-client.ts @@ -0,0 +1,652 @@ +import net from 'net'; +import { EventEmitter } from 'events'; + +export const PIPE_MAGIC = 0x31504851; +export const PIPE_VERSION = 1; +export const HEADER_SIZE = 40; +export const DEFAULT_ACK_TIMEOUT_MS = 5000; +export const DEFAULT_REPLY_TIMEOUT_MS = 30000; + +export enum PipeOp { + hello = 1, + sendRequest = 2, + sendAck = 3, + sendReply = 4, + error = 5, + recvPacket = 6, + loginState = 7, +} + +const PipeFlagWantReply = 1 << 0; +const PipeFlagLoggedIn = 1 << 2; + +export interface QqHookLoginState { + loggedIn: boolean; + uin: string; + uinNumber: bigint; +} + +export interface QqHookPacket { + seq: number; + error: number; + cmd: string; + uin: string; + body: Buffer; +} + +export interface QqHookHello { + pipeName: string; + pid: number; + recvPipe: boolean; +} + +export interface QqHookSendReply { + requestId: number; + error: number; + message: string; + body: Buffer; +} + +export interface QqHookClientOptions { + ackTimeoutMs?: number; + replyTimeoutMs?: number; +} + +export interface QqHookSendOptions { + wantReply?: boolean; + ackTimeoutMs?: number; + replyTimeoutMs?: number; +} + +interface PipeFrame { + op: number; + requestId: number; + status: number; + flags: number; + value0: bigint; + cmd: string; + msg: string; + body: Buffer; +} + +interface Deferred { + promise: Promise; + resolve: (value: T | PromiseLike) => void; + reject: (reason?: unknown) => void; +} + +interface PendingAck { + resolve: (value: { requestId: number; wantReply: boolean }) => void; + reject: (reason?: unknown) => void; + wantReply: boolean; +} + +function mojoPipeName(pid: number, suffix: string): string { + return `\\\\.\\pipe\\mojo.${pid}.${suffix}`; +} + +function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer { + if (Buffer.isBuffer(body)) return body; + if (body instanceof Uint8Array) return Buffer.from(body); + if (typeof body === 'string') return Buffer.from(body, 'utf8'); + if (body == null) return Buffer.alloc(0); + throw new TypeError('body must be Buffer, Uint8Array, string, or null'); +} + +function createDeferred(): Deferred { + let resolve!: (value: T | PromiseLike) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +function withTimeout(promise: Promise, timeoutMs: number, label: string): Promise { + if (!timeoutMs || timeoutMs <= 0) return promise; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new Error(`${label} timed out after ${timeoutMs} ms`)); + }, timeoutMs); + promise.then( + value => { + clearTimeout(timer); + resolve(value); + }, + error => { + clearTimeout(timer); + reject(error); + }); + }); +} + +function encodeFrame({ + op, + requestId = 0, + status = 0, + flags = 0, + value0 = 0n, + cmd = '', + msg = '', + body = Buffer.alloc(0), +}: { + op: number; + requestId?: number; + status?: number; + flags?: number; + value0?: bigint | number; + cmd?: string; + msg?: string; + body?: Buffer | Uint8Array | string | null; +}): Buffer { + const cmdBuf = Buffer.from(cmd, 'utf8'); + const msgBuf = Buffer.from(msg, 'utf8'); + const bodyBuf = toBuffer(body); + const header = Buffer.alloc(HEADER_SIZE); + header.writeUInt32LE(PIPE_MAGIC, 0); + header.writeUInt16LE(PIPE_VERSION, 4); + header.writeUInt16LE(op, 6); + header.writeUInt32LE(requestId >>> 0, 8); + header.writeInt32LE(status | 0, 12); + header.writeUInt32LE(flags >>> 0, 16); + header.writeUInt32LE(cmdBuf.length >>> 0, 20); + header.writeUInt32LE(msgBuf.length >>> 0, 24); + header.writeUInt32LE(bodyBuf.length >>> 0, 28); + header.writeBigUInt64LE(BigInt(value0), 32); + return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]); +} + +class FrameReader { + private buffer = Buffer.alloc(0); + + constructor(private readonly onFrame: (frame: PipeFrame) => void) {} + + push(chunk: Buffer): void { + this.buffer = Buffer.concat([this.buffer, chunk]); + while (this.buffer.length >= HEADER_SIZE) { + const magic = this.buffer.readUInt32LE(0); + const version = this.buffer.readUInt16LE(4); + if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) { + throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`); + } + + const cmdLen = this.buffer.readUInt32LE(20); + const msgLen = this.buffer.readUInt32LE(24); + const bodyLen = this.buffer.readUInt32LE(28); + const total = HEADER_SIZE + cmdLen + msgLen + bodyLen; + if (this.buffer.length < total) return; + + const frame: PipeFrame = { + op: this.buffer.readUInt16LE(6), + requestId: this.buffer.readUInt32LE(8), + status: this.buffer.readInt32LE(12), + flags: this.buffer.readUInt32LE(16), + value0: this.buffer.readBigUInt64LE(32), + cmd: '', + msg: '', + body: Buffer.alloc(0), + }; + + let offset = HEADER_SIZE; + frame.cmd = this.buffer.subarray(offset, offset + cmdLen).toString('utf8'); + offset += cmdLen; + frame.msg = this.buffer.subarray(offset, offset + msgLen).toString('utf8'); + offset += msgLen; + frame.body = Buffer.from(this.buffer.subarray(offset, offset + bodyLen)); + + this.buffer = this.buffer.subarray(total); + this.onFrame(frame); + } + } +} + +export class QqHookClient extends EventEmitter { + readonly pid: number; + readonly defaultAckTimeoutMs: number; + readonly defaultReplyTimeoutMs: number; + + private controlSocket: net.Socket | null = null; + private recvSocket: net.Socket | null = null; + private controlConnectPromise: Promise | null = null; + private recvConnectPromise: Promise | null = null; + private nextRequestId = 1; + private pendingAcks = new Map(); + private pendingReplies = new Map>(); + private controlHello: QqHookHello | null = null; + private recvHello: QqHookHello | null = null; + private controlHelloResolver: Deferred | null = null; + private recvHelloResolver: Deferred | null = null; + private controlWriteChain: Promise = Promise.resolve(); + private closed = false; + private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n }; + private loginWaiters: Deferred[] = []; + + constructor(pid: number, { + ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS, + replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS, + }: QqHookClientOptions = {}) { + super(); + this.pid = pid; + this.defaultAckTimeoutMs = ackTimeoutMs; + this.defaultReplyTimeoutMs = replyTimeoutMs; + } + + get isLoggedIn(): boolean { + return this.loginState.loggedIn; + } + + get currentUin(): string { + return this.loginState.uin; + } + + get currentUinNumber(): bigint { + return this.loginState.uinNumber; + } + + getLoginState(): QqHookLoginState { + return { ...this.loginState }; + } + + async waitForLogin({ timeoutMs = 0 } = {}): Promise { + await this.connect(); + if (this.loginState.loggedIn) { + return this.getLoginState(); + } + const deferred = createDeferred(); + this.loginWaiters.push(deferred); + return withTimeout(deferred.promise, timeoutMs, 'waitForLogin'); + } + + static controlPipeName(pid: number): string { + return mojoPipeName(pid, 'control'); + } + + static recvPipeName(pid: number): string { + return mojoPipeName(pid, 'recv'); + } + + async connect(): Promise { + if (this.closed) { + throw new Error('qq_hook client is closed'); + } + if (this.controlSocket && this.controlHello) { + return this.controlHello; + } + if (this.controlConnectPromise) { + return this.controlConnectPromise; + } + this.controlConnectPromise = (async () => { + this.controlSocket = await this.connectSocket( + QqHookClient.controlPipeName(this.pid), + 'control', + frame => this.handleControlFrame(frame)); + this.controlHello = await this.waitForHello(false); + return this.controlHello; + })(); + try { + return await this.controlConnectPromise; + } finally { + this.controlConnectPromise = null; + } + } + + async startRecv(onPacket?: (packet: QqHookPacket) => void): Promise { + if (this.closed) { + throw new Error('qq_hook client is closed'); + } + if (typeof onPacket === 'function') { + this.on('packet', onPacket); + } + if (this.recvSocket && this.recvHello) { + return this.recvHello; + } + if (this.recvConnectPromise) { + return this.recvConnectPromise; + } + this.recvConnectPromise = (async () => { + this.recvSocket = await this.connectSocket( + QqHookClient.recvPipeName(this.pid), + 'recv', + frame => this.handleRecvFrame(frame)); + this.recvHello = await this.waitForHello(true); + return this.recvHello; + })(); + try { + return await this.recvConnectPromise; + } finally { + this.recvConnectPromise = null; + } + } + + async connectAll({ recv = true } = {}): Promise<{ control: QqHookHello; recv: QqHookHello | null }> { + const control = await this.connect(); + const recvInfo = recv ? await this.startRecv() : null; + return { control, recv: recvInfo }; + } + + async send(cmd: string, body: Buffer | Uint8Array | string | null | undefined, { + wantReply = true, + ackTimeoutMs = this.defaultAckTimeoutMs, + replyTimeoutMs = this.defaultReplyTimeoutMs, + }: QqHookSendOptions = {}): Promise { + await this.connect(); + + const requestId = this.nextRequestId++ >>> 0; + const payload = encodeFrame({ + op: PipeOp.sendRequest, + requestId, + flags: wantReply ? PipeFlagWantReply : 0, + cmd, + body, + }); + + const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>(); + this.pendingAcks.set(requestId, { + resolve: ackDeferred.resolve, + reject: ackDeferred.reject, + wantReply, + }); + + let replyDeferred: Deferred | null = null; + if (wantReply) { + replyDeferred = createDeferred(); + this.pendingReplies.set(requestId, replyDeferred); + } + + try { + await this.writeControl(payload); + await withTimeout(ackDeferred.promise, ackTimeoutMs, `send ack ${requestId}`); + if (!wantReply) { + return { requestId }; + } + return await withTimeout( + replyDeferred!.promise, + replyTimeoutMs, + `send reply ${requestId}`); + } catch (error) { + this.pendingAcks.delete(requestId); + this.pendingReplies.delete(requestId); + throw error; + } + } + + async sendNoReply(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit = {}): Promise<{ requestId: number }> { + return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{ requestId: number }>; + } + + async sendAndWait(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit = {}): Promise { + return this.send(cmd, body, { ...options, wantReply: true }) as Promise; + } + + async sendMany(items: Array<{ cmd: string; body?: Buffer | Uint8Array | string | null; wantReply?: boolean; ackTimeoutMs?: number; replyTimeoutMs?: number }>, { + concurrency = 64, + wantReply = true, + ackTimeoutMs = this.defaultAckTimeoutMs, + replyTimeoutMs = this.defaultReplyTimeoutMs, + }: QqHookSendOptions & { concurrency?: number } = {}): Promise> { + const results = new Array(items.length); + let nextIndex = 0; + const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1)); + + const worker = async () => { + for (;;) { + const index = nextIndex; + nextIndex += 1; + if (index >= items.length) return; + const item = items[index]; + const itemWantReply = item.wantReply ?? wantReply; + results[index] = await this.send(item.cmd, item.body, { + wantReply: itemWantReply, + ackTimeoutMs: item.ackTimeoutMs ?? ackTimeoutMs, + replyTimeoutMs: item.replyTimeoutMs ?? replyTimeoutMs, + }); + } + }; + + await Promise.all(Array.from({ length: workerCount }, () => worker())); + return results; + } + + waitForPacket(predicate: (packet: QqHookPacket) => boolean = () => true, { timeoutMs = 0 } = {}): Promise { + return new Promise((resolve, reject) => { + let timer: NodeJS.Timeout | null = null; + const cleanup = () => { + this.off('packet', onPacket); + if (timer) { + clearTimeout(timer); + timer = null; + } + }; + const onPacket = (packet: QqHookPacket) => { + try { + if (!predicate(packet)) return; + cleanup(); + resolve(packet); + } catch (error) { + cleanup(); + reject(error); + } + }; + this.on('packet', onPacket); + if (timeoutMs > 0) { + timer = setTimeout(() => { + cleanup(); + reject(new Error(`recv packet timed out after ${timeoutMs} ms`)); + }, timeoutMs); + } + }); + } + + close(): void { + if (this.closed) return; + this.closed = true; + this.rejectControlPending(new Error('qq_hook client closed')); + this.rejectRecvPending(new Error('qq_hook client closed')); + this.rejectLoginWaiters(new Error('qq_hook client closed')); + + if (this.controlSocket) { + this.controlSocket.destroy(); + this.controlSocket = null; + } + if (this.recvSocket) { + this.recvSocket.destroy(); + this.recvSocket = null; + } + this.controlHello = null; + this.recvHello = null; + this.controlWriteChain = Promise.resolve(); + } + + private rejectLoginWaiters(error: Error): void { + const waiters = this.loginWaiters; + this.loginWaiters = []; + for (const waiter of waiters) waiter.reject(error); + } + + private rejectControlPending(error: Error): void { + for (const pending of this.pendingAcks.values()) { + pending.reject(error); + } + for (const pending of this.pendingReplies.values()) { + pending.reject(error); + } + this.pendingAcks.clear(); + this.pendingReplies.clear(); + if (this.controlHelloResolver) { + this.controlHelloResolver.reject(error); + this.controlHelloResolver = null; + } + } + + private rejectRecvPending(error: Error): void { + if (this.recvHelloResolver) { + this.recvHelloResolver.reject(error); + this.recvHelloResolver = null; + } + } + + private writeControl(payload: Buffer): Promise { + const socket = this.controlSocket; + if (!socket || socket.destroyed) { + return Promise.reject(new Error('control pipe is not connected')); + } + const writePromise = this.controlWriteChain.then(() => new Promise((resolve, reject) => { + if (!this.controlSocket || this.controlSocket.destroyed) { + reject(new Error('control pipe is not connected')); + return; + } + socket.write(payload, error => { + if (error) reject(error); + else resolve(); + }); + })); + this.controlWriteChain = writePromise.catch(() => {}); + return writePromise; + } + + private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise { + return new Promise((resolve, reject) => { + const socket = net.createConnection(pipeName); + const reader = new FrameReader(onFrame); + const onInitialError = (error: Error) => reject(error); + socket.once('error', onInitialError); + socket.once('connect', () => { + socket.off('error', onInitialError); + socket.on('data', chunk => { + try { + reader.push(chunk); + } catch (error) { + this.emit('error', error); + socket.destroy(error instanceof Error ? error : undefined); + } + }); + socket.on('error', error => { + this.emit('error', error); + }); + socket.on('close', () => { + this.handleSocketClose(kind); + this.emit('close', kind); + }); + resolve(socket); + }); + }); + } + + private waitForHello(recvPipe: boolean): Promise { + const deferred = createDeferred(); + if (recvPipe) { + this.recvHelloResolver = deferred; + } else { + this.controlHelloResolver = deferred; + } + return deferred.promise; + } + + private resolveHello(frame: PipeFrame, recvPipe: boolean): void { + const resolver = recvPipe ? this.recvHelloResolver : this.controlHelloResolver; + if (!resolver) return; + if (recvPipe) this.recvHelloResolver = null; + else this.controlHelloResolver = null; + resolver.resolve({ + pipeName: frame.msg, + pid: Number(frame.value0), + recvPipe, + }); + } + + private handleSocketClose(kind: 'control' | 'recv'): void { + if (kind === 'control') { + this.controlSocket = null; + this.controlHello = null; + this.rejectControlPending(new Error('control pipe closed')); + return; + } + this.recvSocket = null; + this.recvHello = null; + this.rejectRecvPending(new Error('recv pipe closed')); + } + + private applyLoginStateFrame(frame: PipeFrame): void { + const flaggedLoggedIn = (frame.flags & PipeFlagLoggedIn) !== 0; + const statusLoggedIn = frame.status !== 0; + const loggedIn = flaggedLoggedIn || statusLoggedIn; + const uinNumber = BigInt(frame.value0); + const uin = frame.msg || uinNumber.toString(); + const previous = this.loginState; + const next = { loggedIn, uin, uinNumber }; + this.loginState = next; + if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) { + this.emit('loginState', next); + if (next.loggedIn) { + const waiters = this.loginWaiters; + this.loginWaiters = []; + for (const waiter of waiters) waiter.resolve({ ...next }); + } + } + } + + private handleControlFrame(frame: PipeFrame): void { + if (frame.op === PipeOp.hello) { + this.resolveHello(frame, false); + return; + } + if (frame.op === PipeOp.loginState) { + this.applyLoginStateFrame(frame); + return; + } + if (frame.op === PipeOp.sendAck) { + const pending = this.pendingAcks.get(frame.requestId); + if (!pending) return; + this.pendingAcks.delete(frame.requestId); + pending.resolve({ requestId: frame.requestId, wantReply: pending.wantReply }); + return; + } + if (frame.op === PipeOp.sendReply) { + const pending = this.pendingReplies.get(frame.requestId); + if (!pending) return; + this.pendingReplies.delete(frame.requestId); + pending.resolve({ + requestId: frame.requestId, + error: frame.status, + message: frame.msg, + body: Buffer.from(frame.body), + }); + return; + } + if (frame.op === PipeOp.error) { + const error = new Error(frame.msg || `pipe error ${frame.status}`); + const ack = this.pendingAcks.get(frame.requestId); + if (ack) { + this.pendingAcks.delete(frame.requestId); + ack.reject(error); + } + const reply = this.pendingReplies.get(frame.requestId); + if (reply) { + this.pendingReplies.delete(frame.requestId); + reply.reject(error); + } + } + } + + private handleRecvFrame(frame: PipeFrame): void { + if (frame.op === PipeOp.hello) { + this.resolveHello(frame, true); + return; + } + if (frame.op === PipeOp.loginState) { + this.applyLoginStateFrame(frame); + return; + } + if (frame.op !== PipeOp.recvPacket) return; + this.emit('packet', { + seq: Number(frame.value0), + error: frame.status, + cmd: frame.cmd, + uin: frame.msg, + body: Buffer.from(frame.body), + } satisfies QqHookPacket); + } +} + +export { mojoPipeName }; diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 00000000..46348ce3 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,45 @@ +import { NtqqHandler } from './protocol/ntqq-handler'; +import { BridgeManager } from './bridge/manager'; +import { OneBotManager } from './onebot/manager'; +import { loadRuntimeConfig } from './common/runtime'; +import { createLogger } from './utils/logger'; +import { HookManager } from './hook/hook-manager'; + +const runtimeConfig = loadRuntimeConfig(); +const log = createLogger('App'); + +async function main() { + log.info('SnowLuma starting'); + + const ntqq = new NtqqHandler(); + const bridgeManager = new BridgeManager(); + const oneBotManager = new OneBotManager(); + const hookManager = new HookManager(ntqq, bridgeManager); + + // Bind bridge manager to NTQQ handler (receives all parsed packets) + bridgeManager.bind(ntqq); + oneBotManager.bind(bridgeManager); + + if (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) { + try { + log.info('WebUI is enabled, starting...'); + const { initWebUI } = await import('./webui/server'); + initWebUI(runtimeConfig.webuiPort || 8080, oneBotManager, hookManager); + } catch (err) { + log.error('Failed to start WebUI: ', err); + } + } + + // Graceful shutdown + process.on('SIGINT', () => { + log.warn('Shutting down...'); + oneBotManager.dispose(); + hookManager.dispose(); + process.exit(0); + }); +} + +main().catch((error) => { + log.error(error instanceof Error ? (error.stack ?? error.message) : String(error)); + process.exit(1); +}); diff --git a/src/onebot/actions/extended.ts b/src/onebot/actions/extended.ts new file mode 100644 index 00000000..82e944bc --- /dev/null +++ b/src/onebot/actions/extended.ts @@ -0,0 +1,601 @@ +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { asMessage, asNumber, asString, asBoolean } from '../api-handler'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + // --- Likes & Pokes --- + + h.registerAction('send_like', async (params) => { + const userId = asNumber(params.user_id); + const times = asNumber(params.times) || 1; + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + if (!ctx.sendLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.sendLike(userId, times); + return okResponse(); + }); + + h.registerAction('friend_poke', async (params) => { + const userId = asNumber(params.user_id); + const targetId = asNumber(params.target_id) || undefined; + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.sendFriendPoke(userId, targetId); + return okResponse(); + }); + + h.registerAction('group_poke', async (params) => { + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); + if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.sendGroupPoke(groupId, userId); + return okResponse(); + }); + + h.registerAction('send_poke', async (params) => { + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + if (groupId) { + if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.sendGroupPoke(groupId, userId); + } else { + if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.sendFriendPoke(userId); + } + return okResponse(); + }); + + // --- Essence --- + + h.registerAction('set_essence_msg', async (params) => { + const messageId = asNumber(params.message_id); + if (!Number.isInteger(messageId) || messageId === 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); + } + if (!ctx.setEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setEssenceMsg(messageId); + return okResponse(); + }); + + h.registerAction('delete_essence_msg', async (params) => { + const messageId = asNumber(params.message_id); + if (!Number.isInteger(messageId) || messageId === 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); + } + if (!ctx.deleteEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.deleteEssenceMsg(messageId); + return okResponse(); + }); + + h.registerAction('get_essence_msg_list', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + // Essence list fetch requires web ticket/cookie flow not wired yet. + // Keep API-compatible output shape for callers. + return okResponse([]); + }); + + // --- Reactions --- + + h.registerAction('set_group_reaction', async (params) => { + const groupId = asNumber(params.group_id); + const messageId = asNumber(params.message_id); + const code = asString(params.code); + const isSet = asBoolean(params.is_set, true); + + if (!Number.isInteger(messageId) || messageId === 0 || !code) { + return failedResponse(RETCODE.BAD_REQUEST, 'message_id and code are required'); + } + + const meta = ctx.getMessageMeta(messageId); + if (!meta || !meta.isGroup) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); + } + + if (groupId && groupId !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); + } + + if (!ctx.setGroupReaction) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupReaction(meta.targetId, meta.sequence, code, isSet); + return okResponse(); + }); + + // --- History --- + + h.registerAction('get_group_msg_history', async (params) => { + const groupId = asNumber(params.group_id); + const messageId = asNumber(params.message_id) || 0; + const count = asNumber(params.count) || 20; + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (!ctx.getGroupMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + const messages = await ctx.getGroupMsgHistory(groupId, messageId, count); + return okResponse({ messages }); + }); + + h.registerAction('get_friend_msg_history', async (params) => { + const userId = asNumber(params.user_id); + const messageId = asNumber(params.message_id) || 0; + const count = asNumber(params.count) || 20; + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + if (!ctx.getFriendMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + const messages = await ctx.getFriendMsgHistory(userId, messageId, count); + return okResponse({ messages }); + }); + + h.registerAction('mark_msg_as_read', async () => { + return okResponse(); + }); + + // --- RKey --- + + h.registerAction('get_rkey', async () => { + if (ctx.getDownloadRKeys) { + return okResponse(await ctx.getDownloadRKeys()); + } + return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + }); + + // --- OCR stubs --- + + h.registerAction('ocr_image', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('.ocr_image', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + // --- Group notice stubs --- + + h.registerAction('_send_group_notice', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('_get_group_notice', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('_del_group_notice', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + // --- Forward messages --- + + h.registerAction('upload_forward_msg', async (params) => { + const messages = asMessage(params.messages ?? params.message); + const groupId = asNumber(params.group_id); + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + + const result = await ctx.sendForwardMsg(messages); + const data: Record = { + res_id: result.forwardId, + forward_id: result.forwardId, + message_id: 0, + }; + if (groupId > 0) data.group_id = groupId; + return okResponse(data as any); + }); + + h.registerAction('upload_foward_msg', async (params) => { + const messages = asMessage(params.messages ?? params.message); + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + const result = await ctx.sendForwardMsg(messages); + return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 }); + }); + + h.registerAction('send_forward_msg', async (params) => { + const messageType = asString(params.message_type); + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + const messages = asMessage(params.messages ?? params.message); + + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + + if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) { + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + const result = await ctx.sendGroupForwardMsg(groupId, messages); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + } + + if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) { + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + const result = await ctx.sendPrivateForwardMsg(userId, messages); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + } + + if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + const result = await ctx.sendForwardMsg(messages); + return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId }); + }); + + h.registerAction('send_group_forward_msg', async (params) => { + const groupId = asNumber(params.group_id); + const messages = asMessage(params.messages ?? params.message); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + if (!ctx.sendGroupForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + + const result = await ctx.sendGroupForwardMsg(groupId, messages); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + }); + + h.registerAction('send_private_forward_msg', async (params) => { + const userId = asNumber(params.user_id); + const messages = asMessage(params.messages ?? params.message); + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + if (!ctx.sendPrivateForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + + const result = await ctx.sendPrivateForwardMsg(userId, messages); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + }); + + h.registerAction('get_forward_msg', async (params) => { + let id = asString(params.id); + if (!id) { + const rawMessageId = params.message_id; + const numericMessageId = asNumber(rawMessageId); + if (numericMessageId > 0) { + const event = ctx.getMessage(numericMessageId); + const segments = Array.isArray(event?.message) ? event.message : []; + for (const seg of segments) { + if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue; + const so = seg as Record; + if (String(so.type ?? '') !== 'forward') continue; + const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) + ? so.data as Record + : null; + const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id); + if (candidate) { + id = candidate; + break; + } + } + } + + if (!id) { + id = asString(rawMessageId); + } + } + + if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required'); + if (!ctx.getForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + + const messages = await ctx.getForwardMsg(id); + return okResponse({ messages }); + }); + + // --- Media --- + + h.registerAction('get_image', async (params) => { + const file = asString(params.file); + if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); + const imageInfo = findMediaInStore('image', file, ctx); + if (imageInfo) { + return okResponse(imageInfo as unknown as import('../types').JsonValue); + } + return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache'); + }); + + h.registerAction('get_record', async (params) => { + const file = asString(params.file); + if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); + const recordInfo = findMediaInStore('record', file, ctx); + if (recordInfo) { + return okResponse(recordInfo as unknown as import('../types').JsonValue); + } + return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache'); + }); + + // --- Credentials --- + + h.registerAction('get_cookies', async () => { + return okResponse({ cookies: '' }); + }); + + h.registerAction('get_csrf_token', async () => { + return okResponse({ token: 0 }); + }); + + h.registerAction('get_credentials', async () => { + return okResponse({ cookies: '', csrf_token: 0 }); + }); + + // --- Utility --- + + h.registerAction('set_restart', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not supported'); + }); + + h.registerAction('clean_cache', async () => { + return okResponse(); + }); + + h.registerAction('.handle_quick_operation', async (params) => { + const context = params.context as import('../types').JsonObject | undefined; + const operation = params.operation as Record | undefined; + if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required'); + const { executeQuickOperation } = await import('../http-post-transport'); + await executeQuickOperation(context, operation, h); + return okResponse(); + }); + + // --- NapCat-compatible extended APIs --- + + h.registerAction('set_friend_remark', async (params) => { + const userId = asNumber(params.user_id); + const remark = asString(params.remark) ?? ''; + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + if (!ctx.setFriendRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setFriendRemark(userId, remark); + return okResponse(); + }); + + h.registerAction('set_msg_emoji_like', async (params) => { + const messageId = asNumber(params.message_id); + const emojiId = asString(params.emoji_id); + const set = asBoolean(params.set, true); + if (!Number.isInteger(messageId) || messageId === 0 || !emojiId) { + return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required'); + } + if (!ctx.setMsgEmojiLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setMsgEmojiLike(messageId, emojiId, set); + return okResponse(); + }); + + h.registerAction('mark_private_msg_as_read', async () => { + return okResponse(); + }); + + h.registerAction('mark_group_msg_as_read', async () => { + return okResponse(); + }); + + h.registerAction('_mark_all_as_read', async () => { + return okResponse(); + }); + + h.registerAction('get_group_file_system_info', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (ctx.getGroupFileCount) { + const info = await ctx.getGroupFileCount(groupId); + return okResponse({ + file_count: info.fileCount, + limit_count: info.maxCount, + used_space: 0, + total_space: 10737418240, + }); + } + return okResponse({ + file_count: 0, + limit_count: 10000, + used_space: 0, + total_space: 10737418240, + }); + }); + + h.registerAction('check_url_safely', async () => { + return okResponse({ level: 1 }); + }); + + h.registerAction('download_file', async (params) => { + const url = asString(params.url); + const base64 = asString(params.base64); + const name = asString(params.name); + if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required'); + + const fs = await import('fs'); + const pathMod = await import('path'); + const cryptoMod = await import('crypto'); + const tempDir = pathMod.join('data', 'downloads'); + if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); + + let filePath: string; + if (base64) { + const buf = Buffer.from(base64, 'base64'); + const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex'); + filePath = pathMod.join(tempDir, fileName); + fs.writeFileSync(filePath, buf); + } else { + const response = await fetch(url!, { + headers: parseDownloadHeaders(params.headers), + }); + if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`); + const buf = Buffer.from(await response.arrayBuffer()); + const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex'); + filePath = pathMod.join(tempDir, fileName); + fs.writeFileSync(filePath, buf); + } + return okResponse({ file: pathMod.resolve(filePath) }); + }); + + h.registerAction('set_qq_profile', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('set_online_status', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('get_group_ignored_notifies', async () => { + return okResponse([]); + }); + + h.registerAction('get_group_shut_list', async () => { + return okResponse([]); + }); + + h.registerAction('forward_friend_single_msg', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('forward_group_single_msg', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('get_recent_contact', async () => { + return okResponse([]); + }); + + h.registerAction('get_profile_like', async () => { + return okResponse({}); + }); + + h.registerAction('get_friends_with_category', async () => { + if (ctx.getFriendList) { + return okResponse(await ctx.getFriendList()); + } + return okResponse([]); + }); + + // --- Additional NapCat-compatible stubs --- + + h.registerAction('get_online_clients', async () => { + return okResponse({ clients: [] }); + }); + + h.registerAction('_get_model_show', async () => { + return okResponse({ variants: [] }); + }); + + h.registerAction('_set_model_show', async () => { + return okResponse(); + }); + + h.registerAction('.get_word_slices', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('get_group_at_all_remain', async () => { + return okResponse({ can_at_all: false, remain_at_all_count_for_group: 0, remain_at_all_count_for_uin: 0 }); + }); + + h.registerAction('get_unidirectional_friend_list', async () => { + return okResponse([]); + }); + + h.registerAction('set_self_longnick', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('get_collection_list', async () => { + return okResponse([]); + }); + + h.registerAction('create_collection', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('set_qq_avatar', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('set_input_status', async () => { + return okResponse(); + }); + + h.registerAction('translate_en2zh', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('get_clientkey', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('get_mini_app_ark', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('click_inline_keyboard_button', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('set_group_sign', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('send_group_sign', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('get_group_info_ex', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (ctx.getGroupInfo) { + return okResponse(await ctx.getGroupInfo(groupId)); + } + return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + }); + + h.registerAction('get_group_detail_info', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (ctx.getGroupInfo) { + return okResponse(await ctx.getGroupInfo(groupId)); + } + return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + }); + + h.registerAction('trans_group_file', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('rename_group_file', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('get_file', async (params) => { + const fileId = asString(params.file_id) || asString(params.file); + if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required'); + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); + + h.registerAction('.send_packet', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); +} + +/** + * Search through cached message segments to find a media element (image/record) + * that matches the given file identifier. + */ +function findMediaInStore( + mediaType: 'image' | 'record', + file: string, + ctx: ApiActionContext, +): Record | null { + // The file param can match a file id, a URL, or a filename stored in segments. + // We don't have a reverse index, so this is best-effort from stored events. + // Most callers will pass the `file` field from a received message segment. + // Just return the info if we can look it up from any recent cached message. + // This is a known limitation — full implementation would require a media cache. + return null; +} + +/** + * Parse download_file headers parameter into a Record. + */ +function parseDownloadHeaders(headers: unknown): Record { + const result: Record = {}; + if (!headers) return result; + const headerList: string[] = []; + if (typeof headers === 'string') { + headerList.push(...headers.split(/\r?\n/).filter(Boolean)); + } else if (Array.isArray(headers)) { + for (const h of headers) { + if (typeof h === 'string') headerList.push(h); + } + } + for (const line of headerList) { + const idx = line.indexOf('='); + if (idx > 0) { + result[line.substring(0, idx).trim()] = line.substring(idx + 1).trim(); + } + } + return result; +} diff --git a/src/onebot/actions/friend.ts b/src/onebot/actions/friend.ts new file mode 100644 index 00000000..1a001191 --- /dev/null +++ b/src/onebot/actions/friend.ts @@ -0,0 +1,31 @@ +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { asNumber, asBoolean } from '../api-handler'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + h.registerAction('get_friend_list', async () => { + if (ctx.getFriendList) { + return okResponse(await ctx.getFriendList()); + } + return okResponse([]); + }); + + h.registerAction('get_stranger_info', async (params) => { + const userId = asNumber(params.user_id); + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + if (ctx.getStrangerInfo) { + const info = await ctx.getStrangerInfo(userId); + return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 }); + } + return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 }); + }); + + h.registerAction('delete_friend', async (params) => { + const userId = asNumber(params.user_id); + const block = asBoolean(params.block, false); + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + if (!ctx.handleDeleteFriend) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.handleDeleteFriend(userId, block); + return okResponse(); + }); +} diff --git a/src/onebot/actions/group-admin.ts b/src/onebot/actions/group-admin.ts new file mode 100644 index 00000000..590829b7 --- /dev/null +++ b/src/onebot/actions/group-admin.ts @@ -0,0 +1,93 @@ +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { asNumber, asString, asBoolean } from '../api-handler'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + h.registerAction('set_group_kick', async (params) => { + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + const reject = asBoolean(params.reject_add_request, false); + if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); + if (!ctx.setGroupKick) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupKick(groupId, userId, reject); + return okResponse(); + }); + + h.registerAction('set_group_ban', async (params) => { + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + const duration = asNumber(params.duration) || 1800; + if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); + if (!ctx.setGroupBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupBan(groupId, userId, duration); + return okResponse(); + }); + + h.registerAction('set_group_whole_ban', async (params) => { + const groupId = asNumber(params.group_id); + const enable = asBoolean(params.enable, true); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (!ctx.setGroupWholeBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupWholeBan(groupId, enable); + return okResponse(); + }); + + h.registerAction('set_group_admin', async (params) => { + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + const enable = asBoolean(params.enable, true); + if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); + if (!ctx.setGroupAdmin) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupAdmin(groupId, userId, enable); + return okResponse(); + }); + + h.registerAction('set_group_card', async (params) => { + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + const card = asString(params.card); + if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); + if (!ctx.setGroupCard) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupCard(groupId, userId, card); + return okResponse(); + }); + + h.registerAction('set_group_name', async (params) => { + const groupId = asNumber(params.group_id); + const name = asString(params.group_name); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (!ctx.setGroupName) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupName(groupId, name); + return okResponse(); + }); + + h.registerAction('set_group_leave', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (!ctx.setGroupLeave) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupLeave(groupId); + return okResponse(); + }); + + h.registerAction('set_group_special_title', async (params) => { + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + const title = asString(params.special_title); + if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); + if (!ctx.setGroupSpecialTitle) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.setGroupSpecialTitle(groupId, userId, title); + return okResponse(); + }); + + h.registerAction('set_group_anonymous', async () => { + return okResponse(); + }); + + h.registerAction('set_group_anonymous_ban', async () => { + return okResponse(); + }); + + h.registerAction('set_group_portrait', async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }); +} diff --git a/src/onebot/actions/group-file.ts b/src/onebot/actions/group-file.ts new file mode 100644 index 00000000..2e1369d8 --- /dev/null +++ b/src/onebot/actions/group-file.ts @@ -0,0 +1,129 @@ +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { asBoolean, asNumber, asString } from '../api-handler'; +import { RETCODE, failedResponse } from '../types'; +import { okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + h.registerAction('upload_group_file', async (params) => { + const groupId = asNumber(params.group_id); + const file = asString(params.file); + const name = asString(params.name); + const folderId = asString(params.folder) || asString(params.folder_id) || '/'; + const uploadFile = asBoolean(params.upload_file, true); + if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required'); + if (!ctx.uploadGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + const fileId = await ctx.uploadGroupFile(groupId, file, name, folderId, uploadFile); + return okResponse({ file_id: fileId }); + }); + + h.registerAction('upload_private_file', async (params) => { + const userId = asNumber(params.user_id); + const file = asString(params.file); + const name = asString(params.name); + const uploadFile = asBoolean(params.upload_file, true); + if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required'); + if (!ctx.uploadPrivateFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + const fileId = await ctx.uploadPrivateFile(userId, file, name, uploadFile); + return okResponse({ file_id: fileId }); + }); + + h.registerAction('get_group_file_url', async (params) => { + const groupId = asNumber(params.group_id); + const fileId = asString(params.file_id); + const busId = asNumber(params.busid) || 102; + if (!groupId || !fileId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required'); + } + if (!ctx.getGroupFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + return okResponse({ url: await ctx.getGroupFileUrl(groupId, fileId, busId) }); + }); + + h.registerAction('get_group_root_files', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + } + if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + return okResponse(await ctx.getGroupFiles(groupId, '/')); + }); + + h.registerAction('get_group_files_by_folder', async (params) => { + const groupId = asNumber(params.group_id); + const folderId = asString(params.folder_id) || asString(params.folder) || '/'; + if (!groupId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + } + if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + return okResponse(await ctx.getGroupFiles(groupId, folderId)); + }); + + h.registerAction('delete_group_file', async (params) => { + const groupId = asNumber(params.group_id); + const fileId = asString(params.file_id); + if (!groupId || !fileId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required'); + } + if (!ctx.deleteGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.deleteGroupFile(groupId, fileId); + return okResponse(); + }); + + h.registerAction('move_group_file', async (params) => { + const groupId = asNumber(params.group_id); + const fileId = asString(params.file_id); + const parentDirectory = asString(params.parent_directory); + const targetDirectory = asString(params.target_directory); + if (!groupId || !fileId || !parentDirectory || !targetDirectory) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required'); + } + if (!ctx.moveGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory); + return okResponse(); + }); + + h.registerAction('create_group_file_folder', async (params) => { + const groupId = asNumber(params.group_id); + const name = asString(params.name); + const parentId = asString(params.parent_id) || '/'; + if (!groupId || !name) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required'); + } + if (!ctx.createGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.createGroupFileFolder(groupId, name, parentId); + return okResponse(); + }); + + h.registerAction('delete_group_file_folder', async (params) => { + const groupId = asNumber(params.group_id); + const folderId = asString(params.folder_id); + if (!groupId || !folderId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required'); + } + if (!ctx.deleteGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.deleteGroupFileFolder(groupId, folderId); + return okResponse(); + }); + + h.registerAction('rename_group_file_folder', async (params) => { + const groupId = asNumber(params.group_id); + const folderId = asString(params.folder_id); + const newName = asString(params.new_folder_name) || asString(params.name); + if (!groupId || !folderId || !newName) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required'); + } + if (!ctx.renameGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.renameGroupFileFolder(groupId, folderId, newName); + return okResponse(); + }); + + h.registerAction('get_private_file_url', async (params) => { + const userId = asNumber(params.user_id); + const fileId = asString(params.file_id); + const fileHash = asString(params.file_hash); + if (!userId || !fileId || !fileHash) { + return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required'); + } + if (!ctx.getPrivateFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) }); + }); +} diff --git a/src/onebot/actions/group-info.ts b/src/onebot/actions/group-info.ts new file mode 100644 index 00000000..3f5efd9e --- /dev/null +++ b/src/onebot/actions/group-info.ts @@ -0,0 +1,70 @@ +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { asNumber, asBoolean } from '../api-handler'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + h.registerAction('get_group_list', async (params) => { + const noCache = asBoolean(params.no_cache, false); + if (ctx.getGroupList) { + return okResponse(await ctx.getGroupList(noCache)); + } + return okResponse([]); + }); + + h.registerAction('get_group_info', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + const noCache = asBoolean(params.no_cache, false); + if (ctx.getGroupInfo) { + const info = await ctx.getGroupInfo(groupId, noCache); + return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 }); + } + return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 }); + }); + + h.registerAction('get_group_member_list', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + const noCache = asBoolean(params.no_cache, false); + if (ctx.getGroupMemberList) { + return okResponse(await ctx.getGroupMemberList(groupId, noCache)); + } + return okResponse([]); + }); + + h.registerAction('get_group_member_info', async (params) => { + const groupId = asNumber(params.group_id); + const userId = asNumber(params.user_id); + if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required'); + const noCache = asBoolean(params.no_cache, false); + if (ctx.getGroupMemberInfo) { + const info = await ctx.getGroupMemberInfo(groupId, userId, noCache); + return okResponse(info ?? { + group_id: groupId, user_id: userId, nickname: '', card: '', + sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0, + level: '0', role: 'member', title: '', + }); + } + return okResponse({ + group_id: groupId, user_id: userId, nickname: '', card: '', + sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0, + level: '0', role: 'member', title: '', + }); + }); + + h.registerAction('get_group_honor_info', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + return okResponse({ + group_id: groupId, current_talkative: null, talkative_list: [], + performer_list: [], legend_list: [], strong_newbie_list: [], emotion_list: [], + }); + }); + + h.registerAction('get_group_system_msg', async () => { + if (ctx.handleGetGroupSystemMsg) { + return okResponse(await ctx.handleGetGroupSystemMsg()); + } + return okResponse([]); + }); +} diff --git a/src/onebot/actions/info.ts b/src/onebot/actions/info.ts new file mode 100644 index 00000000..527067e4 --- /dev/null +++ b/src/onebot/actions/info.ts @@ -0,0 +1,30 @@ +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + h.registerAction('get_login_info', async () => { + const login = ctx.getLoginInfo(); + return okResponse({ user_id: login.userId, nickname: login.nickname }); + }); + + h.registerAction('get_status', async () => { + const online = ctx.isOnline(); + return okResponse({ online, good: online }); + }); + + h.registerAction('get_version_info', async () => { + return okResponse({ + app_name: 'SnowLuma', + app_version: '0.1.0-node', + protocol_version: 'v11', + }); + }); + + h.registerAction('can_send_image', async () => { + return okResponse({ yes: ctx.canSendImage?.() ?? false }); + }); + + h.registerAction('can_send_record', async () => { + return okResponse({ yes: ctx.canSendRecord?.() ?? false }); + }); +} diff --git a/src/onebot/actions/message.ts b/src/onebot/actions/message.ts new file mode 100644 index 00000000..5ddcad61 --- /dev/null +++ b/src/onebot/actions/message.ts @@ -0,0 +1,112 @@ +import type { JsonObject, JsonValue } from '../types'; +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { asNumber, asString, asBoolean, asMessage } from '../api-handler'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + h.registerAction('send_msg', async (params) => { + const messageType = asString(params.message_type); + const message = asMessage(params.message); + const autoEscape = asBoolean(params.auto_escape, false); + + if (message === undefined) { + return failedResponse(RETCODE.BAD_REQUEST, 'message is required'); + } + + if (messageType === 'group' || params.group_id !== undefined) { + const groupId = asNumber(params.group_id); + if (!Number.isInteger(groupId) || groupId <= 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + } + if (!ctx.sendGroupMessage) { + return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented'); + } + const result = await ctx.sendGroupMessage(groupId, message, autoEscape); + return okResponse({ message_id: result.messageId }); + } + + const userId = asNumber(params.user_id); + if (!Number.isInteger(userId) || userId <= 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + } + if (!ctx.sendPrivateMessage) { + return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented'); + } + const result = await ctx.sendPrivateMessage(userId, message, autoEscape); + return okResponse({ message_id: result.messageId }); + }); + + h.registerAction('send_private_msg', async (params) => { + const userId = asNumber(params.user_id); + const message = asMessage(params.message); + const autoEscape = asBoolean(params.auto_escape, false); + + if (!Number.isInteger(userId) || userId <= 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + } + if (message === undefined) { + return failedResponse(RETCODE.BAD_REQUEST, 'message is required'); + } + if (!ctx.sendPrivateMessage) { + return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented'); + } + + const result = await ctx.sendPrivateMessage(userId, message, autoEscape); + return okResponse({ message_id: result.messageId }); + }); + + h.registerAction('send_group_msg', async (params) => { + const groupId = asNumber(params.group_id); + const message = asMessage(params.message); + const autoEscape = asBoolean(params.auto_escape, false); + + if (!Number.isInteger(groupId) || groupId <= 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + } + if (message === undefined) { + return failedResponse(RETCODE.BAD_REQUEST, 'message is required'); + } + if (!ctx.sendGroupMessage) { + return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented'); + } + + const result = await ctx.sendGroupMessage(groupId, message, autoEscape); + return okResponse({ message_id: result.messageId }); + }); + + h.registerAction('get_msg', async (params) => { + const messageId = asNumber(params.message_id); + if (!Number.isInteger(messageId) || messageId === 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); + } + + const data = ctx.getMessage(messageId); + if (!data) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); + } + + const result: JsonObject = { ...data }; + delete result.post_type; + delete result.self_id; + result.real_id = (result.message_id ?? messageId) as JsonValue; + return okResponse(result); + }); + + h.registerAction('delete_msg', async (params) => { + const messageId = asNumber(params.message_id); + if (!Number.isInteger(messageId) || messageId === 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); + } + if (!ctx.deleteMessage) { + return failedResponse(RETCODE.ACTION_FAILED, 'delete_msg is not implemented'); + } + + const meta = ctx.getMessageMeta(messageId); + if (!meta) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable'); + } + + await ctx.deleteMessage(messageId, meta); + return okResponse(); + }); +} diff --git a/src/onebot/actions/request.ts b/src/onebot/actions/request.ts new file mode 100644 index 00000000..05c73550 --- /dev/null +++ b/src/onebot/actions/request.ts @@ -0,0 +1,25 @@ +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { asString, asBoolean } from '../api-handler'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + h.registerAction('set_friend_add_request', async (params) => { + const flag = asString(params.flag); + const approve = asBoolean(params.approve, true); + if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required'); + if (!ctx.handleFriendRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.handleFriendRequest(flag, approve); + return okResponse(); + }); + + h.registerAction('set_group_add_request', async (params) => { + const flag = asString(params.flag); + const subType = asString(params.sub_type, asString(params.type, 'add')); + const approve = asBoolean(params.approve, true); + const reason = asString(params.reason); + if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required'); + if (!ctx.handleGroupRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + await ctx.handleGroupRequest(flag, subType, approve, reason); + return okResponse(); + }); +} diff --git a/src/onebot/api-handler.ts b/src/onebot/api-handler.ts new file mode 100644 index 00000000..2ea3f563 --- /dev/null +++ b/src/onebot/api-handler.ts @@ -0,0 +1,207 @@ +import type { JsonObject, JsonValue, MessageMeta } from './types'; +import { RETCODE, failedResponse } from './types'; + +import { register as registerInfo } from './actions/info'; +import { register as registerMessage } from './actions/message'; +import { register as registerFriend } from './actions/friend'; +import { register as registerGroupInfo } from './actions/group-info'; +import { register as registerGroupAdmin } from './actions/group-admin'; +import { register as registerGroupFile } from './actions/group-file'; +import { register as registerRequest } from './actions/request'; +import { register as registerExtended } from './actions/extended'; + +export interface MessageSendResult { + messageId: number; + meta?: MessageMeta; + echoEvent?: JsonObject; +} + +export interface ApiActionContext { + getLoginInfo: () => { userId: number; nickname: string }; + isOnline: () => boolean; + getMessage: (messageId: number) => JsonObject | null; + getMessageMeta: (messageId: number) => MessageMeta | null; + sendPrivateMessage?: (userId: number, message: JsonValue, autoEscape: boolean) => Promise; + sendGroupMessage?: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise; + deleteMessage?: (messageId: number, meta: MessageMeta) => Promise; + canSendImage?: () => boolean; + canSendRecord?: () => boolean; + // Info retrieval (async — triggers OIDB fetch) + getFriendList?: () => Promise; + getGroupList?: (noCache?: boolean) => Promise; + getGroupInfo?: (groupId: number, noCache?: boolean) => Promise; + getGroupMemberList?: (groupId: number, noCache?: boolean) => Promise; + getGroupMemberInfo?: (groupId: number, userId: number, noCache?: boolean) => Promise; + getStrangerInfo?: (userId: number) => Promise; + // Group admin + setGroupKick?: (groupId: number, userId: number, rejectAdd: boolean) => Promise; + setGroupBan?: (groupId: number, userId: number, duration: number) => Promise; + setGroupWholeBan?: (groupId: number, enable: boolean) => Promise; + setGroupAdmin?: (groupId: number, userId: number, enable: boolean) => Promise; + setGroupCard?: (groupId: number, userId: number, card: string) => Promise; + setGroupName?: (groupId: number, name: string) => Promise; + setGroupLeave?: (groupId: number) => Promise; + setGroupSpecialTitle?: (groupId: number, userId: number, title: string) => Promise; + // Group file + uploadGroupFile?: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise; + uploadPrivateFile?: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise; + getGroupFileUrl?: (groupId: number, fileId: string, busId?: number) => Promise; + getGroupFiles?: (groupId: number, folderId?: string) => Promise; + deleteGroupFile?: (groupId: number, fileId: string) => Promise; + moveGroupFile?: (groupId: number, fileId: string, parentDirectory: string, targetDirectory: string) => Promise; + createGroupFileFolder?: (groupId: number, name: string, parentId?: string) => Promise; + deleteGroupFileFolder?: (groupId: number, folderId: string) => Promise; + renameGroupFileFolder?: (groupId: number, folderId: string, newName: string) => Promise; + getPrivateFileUrl?: (userId: number, fileId: string, fileHash: string) => Promise; + // Requests + handleFriendRequest?: (flag: string, approve: boolean) => Promise; + handleGroupRequest?: (flag: string, subType: string, approve: boolean, reason: string) => Promise; + // Extended + sendLike?: (userId: number, times: number) => Promise; + sendFriendPoke?: (userId: number, targetId?: number) => Promise; + sendGroupPoke?: (groupId: number, userId: number) => Promise; + setEssenceMsg?: (messageId: number) => Promise; + deleteEssenceMsg?: (messageId: number) => Promise; + // New context methods + setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise; + handleDeleteFriend?: (userId: number, block?: boolean) => Promise; + getGroupMsgHistory?: (groupId: number, messageId?: number, count?: number) => Promise; + getFriendMsgHistory?: (userId: number, messageId?: number, count?: number) => Promise; + handleGetGroupSystemMsg?: () => Promise; + getDownloadRKeys?: () => Promise; + // Forward message + sendGroupForwardMsg?: (groupId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>; + sendPrivateForwardMsg?: (userId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>; + sendForwardMsg?: (messages: JsonValue) => Promise<{ forwardId: string }>; + getForwardMsg?: (resId: string) => Promise; + // Extended NapCat-compatible + setFriendRemark?: (userId: number, remark: string) => Promise; + getGroupFileCount?: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>; + setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise; +} + +type ActionHandler = (params: JsonObject) => Promise; + +export class ApiHandler { + private readonly handlers = new Map(); + + constructor(context: ApiActionContext) { + registerInfo(this, context); + registerMessage(this, context); + registerFriend(this, context); + registerGroupInfo(this, context); + registerGroupAdmin(this, context); + registerGroupFile(this, context); + registerRequest(this, context); + registerExtended(this, context); + } + + registerAction(action: string, handler: ActionHandler): void { + this.handlers.set(action, handler); + } + + async handle(action: string, params: JsonObject): Promise { + const handler = this.handlers.get(action); + if (!handler) { + return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action'); + } + + try { + return await handler(params); + } catch (error) { + const message = error instanceof Error ? error.message : 'internal error'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + } + + async processRequest(rawRequest: string): Promise { + if (!rawRequest.trim()) { + return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request')); + } + + try { + const parsed = JSON.parse(rawRequest) as unknown; + if (!isJsonObject(parsed)) { + return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request')); + } + + const action = asString(parsed.action); + if (!action) { + return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request')); + } + + const params = isJsonObject(parsed.params) ? parsed.params : {}; + const echo = parsed.echo; + const response = await this.handle(action, params); + if (echo !== undefined) { + response.echo = toJsonValue(echo); + } + + return JSON.stringify(response); + } catch { + return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request')); + } + } +} + +function isJsonObject(value: unknown): value is JsonObject { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +export function asString(value: unknown, fallback = ''): string { + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'boolean') return String(value); + return fallback; +} + +export function asNumber(value: unknown): number { + if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); + if (typeof value === 'string' && value.trim()) { + const n = Number(value); + if (Number.isFinite(n)) return Math.trunc(n); + } + return 0; +} + +export function asBoolean(value: unknown, fallback: boolean): boolean { + if (typeof value === 'boolean') return value; + if (typeof value === 'number') return value !== 0; + if (typeof value === 'string') { + const text = value.trim().toLowerCase(); + if (text === 'true' || text === '1' || text === 'yes' || text === 'on') return true; + if (text === 'false' || text === '0' || text === 'no' || text === 'off') return false; + } + return fallback; +} + +export function toJsonValue(value: unknown): JsonValue { + if (value === null) return null; + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value; + if (Array.isArray(value)) return value.map(toJsonValue); + if (isJsonObject(value)) { + const obj: JsonObject = {}; + for (const [key, item] of Object.entries(value)) { + obj[key] = toJsonValue(item); + } + return obj; + } + return String(value); +} + +export function asMessage(value: unknown): import('./types').JsonValue | undefined { + if (value === undefined) return undefined; + if (typeof value === 'string') { + const trimmed = value.trim(); + if (trimmed.startsWith('[') && trimmed.endsWith(']')) { + try { + const parsed = JSON.parse(trimmed); + if (Array.isArray(parsed)) { + return toJsonValue(parsed); + } + } catch { + // Fallback to literal text if it just looks like an array but is invalid JSON + } + } + } + return toJsonValue(value); +} diff --git a/src/onebot/config.ts b/src/onebot/config.ts new file mode 100644 index 00000000..99f06fc9 --- /dev/null +++ b/src/onebot/config.ts @@ -0,0 +1,315 @@ +import fs from 'fs'; +import path from 'path'; +import { randomBytes } from 'crypto'; +import type { + HttpPostEndpoint, + HttpServerEndpoint, + JsonObject, + OneBotConfig, + WsClientEndpoint, + WsRole, + WsServerEndpoint, +} from './types'; + +const CONFIG_DIR = 'config'; +const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json'); + +export function makeDefaultOneBotConfig(): OneBotConfig { + return { + httpServers: [{ host: '0.0.0.0', port: 3000, path: '/' }], + httpPostEndpoints: [], + wsServers: [{ host: '0.0.0.0', port: 3001 }], + wsClients: [], + musicSignUrl: '', + }; +} + +export function loadOneBotConfig(uin: string): OneBotConfig { + ensureConfigDir(); + + const merged = deepClone(toJsonObject(makeDefaultOneBotConfig())); + const globalConfig = tryLoadJson(DEFAULT_CONFIG_PATH); + if (globalConfig) { + deepMerge(merged, globalConfig); + } + + const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`); + const perUinConfig = tryLoadJson(perUinPath); + if (perUinConfig) { + deepMerge(merged, perUinConfig); + } + + const config = fromJson(merged); + let shouldSave = !perUinConfig; + + // Auto-generate per-endpoint accessToken if not set. + for (const s of config.httpServers) { + if (!s.accessToken) { + s.accessToken = generateRandomKey(); + shouldSave = true; + } + } + for (const s of config.wsServers) { + if (!s.accessToken) { + s.accessToken = generateRandomKey(); + shouldSave = true; + } + } + for (const c of config.wsClients) { + if (!c.accessToken) { + c.accessToken = generateRandomKey(); + shouldSave = true; + } + } + + // Persist normalized endpoints and generated keys. + merged.httpServers = config.httpServers.map((s) => { + const out: JsonObject = { + host: s.host, + port: s.port, + path: s.path ?? '/', + accessToken: s.accessToken ?? '', + }; + if (s.name) out.name = s.name; + return out; + }); + merged.httpPostEndpoints = config.httpPostEndpoints.map((e) => { + const out: JsonObject = { url: e.url }; + if (e.name) out.name = e.name; + if (e.accessToken) out.accessToken = e.accessToken; + if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs; + return out; + }); + merged.wsServers = config.wsServers.map((s) => { + const out: JsonObject = { + host: s.host, + port: s.port, + path: s.path ?? '/', + role: s.role ?? 'universal', + accessToken: s.accessToken ?? '', + }; + if (s.name) out.name = s.name; + return out; + }); + merged.wsClients = config.wsClients.map((c) => { + const out: JsonObject = { + url: c.url, + role: c.role ?? 'universal', + accessToken: c.accessToken ?? '', + }; + if (c.name) out.name = c.name; + if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) { + out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs)); + } + return out; + }); + merged.musicSignUrl = config.musicSignUrl ?? ''; + + if (shouldSave) { + saveJson(perUinPath, merged); + } + + return config; +} + +export function saveOneBotConfig(uin: string, config: OneBotConfig): void { + ensureConfigDir(); + const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`); + const jsonObj = toJsonObject(config); + saveJson(perUinPath, jsonObj); +} + +function ensureConfigDir(): void { + fs.mkdirSync(CONFIG_DIR, { recursive: true }); +} + +function toJsonObject(config: OneBotConfig): JsonObject { + return { + httpServers: config.httpServers.map((s) => { + const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', accessToken: s.accessToken ?? '' }; + if (s.name) out.name = s.name; + return out; + }), + httpPostEndpoints: config.httpPostEndpoints.map((e) => { + const out: JsonObject = { url: e.url }; + if (e.name) out.name = e.name; + if (e.accessToken) out.accessToken = e.accessToken; + if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs; + return out; + }), + wsServers: config.wsServers.map((s) => { + const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', role: s.role ?? 'universal', accessToken: s.accessToken ?? '' }; + if (s.name) out.name = s.name; + return out; + }), + wsClients: config.wsClients.map((c) => { + const out: JsonObject = { + url: c.url, + role: c.role ?? 'universal', + accessToken: c.accessToken ?? '', + }; + if (c.name) out.name = c.name; + if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) { + out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs)); + } + return out; + }), + musicSignUrl: config.musicSignUrl ?? '', + }; +} + +function fromJson(json: JsonObject): OneBotConfig { + const httpServers = toHttpServers(json.httpServers); + const httpPostEndpoints = toHttpPostEndpoints(json.httpPostEndpoints); + const wsServers = toWsServers(json.wsServers); + const wsClients = toWsClients(json.wsClients); + + return { + httpServers: httpServers.length > 0 ? httpServers : [{ host: '0.0.0.0', port: 3000, path: '/' }], + httpPostEndpoints, + wsServers: wsServers.length > 0 ? wsServers : [{ host: '0.0.0.0', port: 3001 }], + wsClients, + musicSignUrl: typeof json.musicSignUrl === 'string' ? json.musicSignUrl : '', + }; +} + +function toHttpServers(value: unknown): HttpServerEndpoint[] { + if (!Array.isArray(value)) return []; + const result: HttpServerEndpoint[] = []; + + for (const item of value) { + if (!isObject(item)) continue; + const host = asString(item.host, '0.0.0.0'); + const port = asNumber(item.port, 3000); + const pathValue = asString(item.path, '/'); + const endpoint: HttpServerEndpoint = { host, port, path: pathValue }; + const name = asString(item.name); + if (name) endpoint.name = name; + const token = asString(item.accessToken); + if (token) endpoint.accessToken = token; + result.push(endpoint); + } + + return result; +} + +function toHttpPostEndpoints(value: unknown): HttpPostEndpoint[] { + if (!Array.isArray(value)) return []; + const result: HttpPostEndpoint[] = []; + + for (const item of value) { + if (!isObject(item)) continue; + const url = asString(item.url); + if (!url) continue; + const endpoint: HttpPostEndpoint = { url }; + const name = asString(item.name); + if (name) endpoint.name = name; + const token = asString(item.accessToken); + if (token) endpoint.accessToken = token; + const timeout = asNumber(item.timeoutMs, 0); + if (timeout > 0) endpoint.timeoutMs = timeout; + result.push(endpoint); + } + + return result; +} + +function toWsServers(value: unknown): WsServerEndpoint[] { + if (!Array.isArray(value)) return []; + const result: WsServerEndpoint[] = []; + + for (const item of value) { + if (!isObject(item)) continue; + const host = asString(item.host, '0.0.0.0'); + const port = asNumber(item.port, 3001); + const pathValue = asString(item.path, '/'); + const role = asRole(item.role, 'universal'); + const endpoint: WsServerEndpoint = { host, port, path: pathValue, role }; + const name = asString(item.name); + if (name) endpoint.name = name; + const token = asString(item.accessToken); + if (token) endpoint.accessToken = token; + result.push(endpoint); + } + + return result; +} + +function toWsClients(value: unknown): WsClientEndpoint[] { + if (!Array.isArray(value)) return []; + const result: WsClientEndpoint[] = []; + + for (const item of value) { + if (!isObject(item)) continue; + const url = asString(item.url); + if (!url) continue; + const role = asRole(item.role, 'universal'); + const reconnectIntervalMs = asNumber(item.reconnectIntervalMs, 5000); + const endpoint: WsClientEndpoint = { url, role, reconnectIntervalMs }; + const name = asString(item.name); + if (name) endpoint.name = name; + const token = asString(item.accessToken); + if (token) endpoint.accessToken = token; + result.push(endpoint); + } + + return result; +} + +function asRole(value: unknown, fallback: WsRole): WsRole { + const text = asString(value, fallback); + return text === 'api' || text === 'event' || text === 'universal' ? text : fallback; +} + +function asString(value: unknown, fallback = ''): string { + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'boolean') return String(value); + return fallback; +} + +function asNumber(value: unknown, fallback = 0): number { + if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value)); + if (typeof value === 'string' && value.trim()) { + const n = Number(value); + if (Number.isFinite(n)) return Math.max(0, Math.trunc(n)); + } + return fallback; +} + +function generateRandomKey(byteLength = 18): string { + return randomBytes(byteLength).toString('hex'); +} + +function tryLoadJson(filePath: string): JsonObject | null { + if (!fs.existsSync(filePath)) return null; + try { + const raw = fs.readFileSync(filePath, 'utf8'); + const parsed = JSON.parse(raw) as unknown; + return isObject(parsed) ? parsed : null; + } catch { + return null; + } +} + +function saveJson(filePath: string, json: JsonObject): void { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8'); +} + +function deepClone(obj: JsonObject): JsonObject { + return JSON.parse(JSON.stringify(obj)) as JsonObject; +} + +function deepMerge(base: JsonObject, override: JsonObject): void { + for (const [key, value] of Object.entries(override)) { + if (isObject(base[key]) && isObject(value)) { + deepMerge(base[key] as JsonObject, value); + } else { + base[key] = value as never; + } + } +} + +function isObject(value: unknown): value is JsonObject { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/src/onebot/event-converter.ts b/src/onebot/event-converter.ts new file mode 100644 index 00000000..15d4e5c6 --- /dev/null +++ b/src/onebot/event-converter.ts @@ -0,0 +1,513 @@ +import type { MessageElement, QQEventVariant } from '../bridge/events'; +import type { JsonArray, JsonObject } from './types'; +import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from './message-id'; + +export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string; +export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise; +export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number; + +export class EventConverter { + private imageUrlResolver_: ImageUrlResolver | null = null; + private mediaUrlResolver_: MediaUrlResolver | null = null; + private messageIdResolver_: MessageIdResolver | null = null; + + setImageUrlResolver(resolver: ImageUrlResolver): void { + this.imageUrlResolver_ = resolver; + } + + setMediaUrlResolver(resolver: MediaUrlResolver): void { + this.mediaUrlResolver_ = resolver; + } + + setMessageIdResolver(resolver: MessageIdResolver): void { + this.messageIdResolver_ = resolver; + } + + async convert(instanceUin: string, event: QQEventVariant): Promise { + const selfId = parseSelfId(instanceUin); + + switch (event.kind) { + case 'friend_message': + { + const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT); + const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_); + return { + time: event.time, + self_id: selfId, + post_type: 'message', + message_type: 'private', + sub_type: 'friend', + message_id: messageId, + message_seq: event.msgSeq, + user_id: event.senderUin, + message: segments, + raw_message: segmentsToRawMessage(segments), + font: 0, + sender: { + user_id: event.senderUin, + nickname: event.senderNick, + sex: 'unknown', + age: 0, + }, + }; + } + + case 'group_message': + { + const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT); + const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_); + return { + time: event.time, + self_id: selfId, + post_type: 'message', + message_type: 'group', + sub_type: 'normal', + message_id: messageId, + message_seq: event.msgSeq, + group_id: event.groupId, + user_id: event.senderUin, + message: segments, + raw_message: segmentsToRawMessage(segments), + font: 0, + sender: { + user_id: event.senderUin, + nickname: event.senderNick, + card: event.senderCard, + role: event.senderRole || 'member', + sex: 'unknown', + age: 0, + }, + anonymous: null, + }; + } + + case 'temp_message': + { + const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT); + const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_); + return { + time: event.time, + self_id: selfId, + post_type: 'message', + message_type: 'private', + sub_type: 'group', + message_id: messageId, + message_seq: event.msgSeq, + user_id: event.senderUin, + message: segments, + raw_message: segmentsToRawMessage(segments), + font: 0, + sender: { + user_id: event.senderUin, + nickname: event.senderNick, + sex: 'unknown', + age: 0, + }, + }; + } + + case 'group_member_join': + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'group_increase', + sub_type: event.operatorUin === event.userUin ? 'approve' : 'invite', + group_id: event.groupId, + operator_id: event.operatorUin, + user_id: event.userUin, + }; + + case 'group_member_leave': + { + let subType: string; + if (event.isKick) { + subType = event.userUin === parseSelfId(instanceUin) ? 'kick_me' : 'kick'; + } else { + subType = 'leave'; + } + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'group_decrease', + sub_type: subType, + group_id: event.groupId, + operator_id: event.operatorUin, + user_id: event.userUin, + }; + } + + case 'group_mute': + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'group_ban', + sub_type: event.duration > 0 ? 'ban' : 'lift_ban', + group_id: event.groupId, + operator_id: event.operatorUin, + user_id: event.userUin, + duration: event.duration, + }; + + case 'group_admin': + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'group_admin', + sub_type: event.set ? 'set' : 'unset', + group_id: event.groupId, + user_id: event.userUin, + }; + + case 'friend_recall': + { + const messageId = this.resolveMessageId(false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT); + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'friend_recall', + user_id: event.userUin, + message_id: messageId, + }; + } + + case 'group_recall': + { + const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT); + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'group_recall', + group_id: event.groupId, + operator_id: event.operatorUin, + user_id: event.authorUin, + message_id: messageId, + }; + } + + case 'friend_request': + return { + time: event.time, + self_id: selfId, + post_type: 'request', + request_type: 'friend', + user_id: event.fromUin, + comment: event.message, + flag: event.flag, + }; + + case 'group_invite': + return { + time: event.time, + self_id: selfId, + post_type: 'request', + request_type: 'group', + sub_type: event.subType || 'invite', + group_id: event.groupId, + user_id: event.fromUin, + comment: event.message, + flag: event.flag, + }; + + case 'friend_poke': + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'notify', + sub_type: 'poke', + user_id: event.userUin, + target_id: event.targetUin, + action: event.action, + suffix: event.suffix, + action_img_url: event.actionImgUrl, + }; + + case 'group_poke': + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'notify', + sub_type: 'poke', + group_id: event.groupId, + user_id: event.userUin, + target_id: event.targetUin, + action: event.action, + suffix: event.suffix, + action_img_url: event.actionImgUrl, + }; + + case 'group_essence': + { + const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT); + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'essence', + sub_type: event.set ? 'add' : 'delete', + group_id: event.groupId, + user_id: event.senderUin, + sender_id: event.senderUin, + operator_id: event.operatorUin, + message_id: messageId, + message_seq: event.msgSeq, + random: event.random, + }; + } + + case 'group_file_upload': + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'group_upload', + group_id: event.groupId, + user_id: event.userUin, + file: { + id: event.fileId, + name: event.fileName, + size: event.fileSize, + busid: event.busId, + }, + }; + + case 'friend_add': + return { + time: event.time, + self_id: selfId, + post_type: 'notice', + notice_type: 'friend_add', + user_id: event.userUin, + }; + + default: + return null; + } + } + + private resolveMessageId(isGroup: boolean, sessionId: number, sequence: number, eventName: string): number { + if (this.messageIdResolver_) { + const resolved = this.messageIdResolver_(isGroup, sessionId, sequence, eventName); + if (Number.isInteger(resolved) && resolved !== 0) return resolved; + } + const seq = Math.trunc(sequence); + return seq === 0 ? 0 : seq; + } +} + +function parseSelfId(instanceUin: string): number { + const parsed = Number.parseInt(instanceUin, 10); + return Number.isNaN(parsed) ? 0 : parsed; +} + +async function elementsToJson( + elements: MessageElement[], + isGroup: boolean, + sessionId: number, + resolver?: ImageUrlResolver | null, + mediaResolver?: MediaUrlResolver | null, + messageIdResolver?: MessageIdResolver | null, +): Promise { + const result: JsonArray = []; + for (const element of elements) { + result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver)); + } + return result; +} + +export async function elementsToOneBotSegments( + elements: MessageElement[], + isGroup: boolean, + sessionId: number, + resolver?: ImageUrlResolver | null, + mediaResolver?: MediaUrlResolver | null, + messageIdResolver?: MessageIdResolver | null, +): Promise { + return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver); +} + +async function elementToSegment( + element: MessageElement, + isGroup: boolean, + sessionId: number, + resolver?: ImageUrlResolver | null, + mediaResolver?: MediaUrlResolver | null, + messageIdResolver?: MessageIdResolver | null, +): Promise { + if (element.type === 'text') { + return { type: 'text', data: { text: element.text ?? '' } }; + } + + if (element.type === 'face') { + return { type: 'face', data: { id: String(element.faceId ?? 0) } }; + } + + if (element.type === 'image') { + const url = resolver ? resolver(element, isGroup) : (element.imageUrl ?? ''); + return { + type: 'image', + data: { + url, + file: element.fileId ?? '', + }, + }; + } + + if (element.type === 'at') { + const qq = (element.uid === 'all' || element.targetUin === 0) + ? 'all' + : String(element.targetUin ?? 0); + return { type: 'at', data: { qq } }; + } + + if (element.type === 'reply') { + const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver); + return { type: 'reply', data: { id: String(id) } }; + } + + if (element.type === 'record') { + const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? ''); + return { + type: 'record', + data: { + file: element.fileName ?? element.fileId ?? '', + url, + }, + }; + } + + if (element.type === 'video') { + const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? ''); + return { + type: 'video', + data: { + file: element.fileName ?? element.fileId ?? '', + url, + }, + }; + } + + if (element.type === 'json') { + return { type: 'json', data: { data: element.text ?? '' } }; + } + + if (element.type === 'xml') { + return { + type: 'xml', + data: { + data: element.text ?? '', + resid: element.subType ?? 35, + }, + }; + } + + if (element.type === 'file') { + const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? ''); + return { + type: 'file', + data: { + name: element.fileName ?? '', + size: element.fileSize ?? 0, + id: element.fileId ?? '', + url, + file_hash: element.fileHash ?? '', + }, + }; + } + + if (element.type === 'mface') { + return { + type: 'mface', + data: { + name: element.text ?? '', + tab_id: element.faceId ?? 0, + sub_type: element.subType ?? 0, + }, + }; + } + + if (element.type === 'poke') { + return { + type: 'poke', + data: { + type: element.subType ?? 0, + }, + }; + } + + if (!isGroup && element.type === 'at') { + return { type: 'text', data: { text: element.text ?? '' } }; + } + + return { type: element.type, data: {} }; +} + +// --- CQ code raw_message generation (from already-resolved JSON segments) --- + +function cqEscape(text: string): string { + return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ','); +} + +function segmentsToRawMessage(segments: JsonArray): string { + return segments.map(seg => segmentToCQ(seg as JsonObject)).join(''); +} + +function segmentToCQ(seg: JsonObject): string { + const type = String(seg.type ?? ''); + const data = (seg.data ?? {}) as Record; + switch (type) { + case 'text': + return cqEscape(String(data.text ?? '')); + case 'face': + return `[CQ:face,id=${data.id ?? 0}]`; + case 'image': + return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'at': + return `[CQ:at,qq=${data.qq ?? ''}]`; + case 'reply': + return `[CQ:reply,id=${data.id ?? 0}]`; + case 'record': + return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'video': + return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'json': + return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`; + case 'xml': + return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`; + case 'forward': + return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`; + case 'mface': + return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`; + case 'poke': + return `[CQ:poke,type=${data.type ?? 0}]`; + case 'file': + return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + default: + return `[CQ:${type}]`; + } +} + +function resolveReplyId( + isGroup: boolean, + sessionId: number, + sequence: number, + resolver?: MessageIdResolver | null, +): number { + const seq = Math.trunc(sequence); + if (seq === 0) return 0; + + if (resolver) { + const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT; + const resolved = resolver(isGroup, sessionId, seq, eventName); + if (Number.isInteger(resolved) && resolved !== 0) return resolved; + } + + return seq; +} diff --git a/src/onebot/http-post-transport.ts b/src/onebot/http-post-transport.ts new file mode 100644 index 00000000..d4df26a7 --- /dev/null +++ b/src/onebot/http-post-transport.ts @@ -0,0 +1,199 @@ +import type { JsonObject, OneBotConfig } from './types'; +import { createLogger } from '../utils/logger'; + +export interface HttpPostEndpoint { + name?: string; + url: string; + accessToken?: string; + timeoutMs?: number; +} + +export interface HttpPostTransportContext { + uin: string; + api: import('./api-handler').ApiHandler; +} + +const log = createLogger('OneBot.POST'); +const DEFAULT_TIMEOUT_MS = 5000; + +export class HttpPostTransport { + private readonly config: OneBotConfig; + private readonly context: HttpPostTransportContext; + private stopped = false; + + constructor(config: OneBotConfig, context: HttpPostTransportContext) { + this.config = config; + this.context = context; + } + + start(): void { + this.stopped = false; + const count = this.config.httpPostEndpoints?.length ?? 0; + if (count > 0) { + log.info('configured %d HTTP POST endpoint(s)', count); + } + } + + stop(): void { + this.stopped = true; + } + + publishEvent(event: JsonObject): void { + const endpoints = this.config.httpPostEndpoints; + if (!endpoints || endpoints.length === 0) return; + + const payload = JSON.stringify(event); + for (const endpoint of endpoints) { + void this.postEvent(endpoint, payload, event); + } + } + + private async postEvent(endpoint: HttpPostEndpoint, payload: string, event: JsonObject): Promise { + if (this.stopped) return; + + const headers: Record = { + 'Content-Type': 'application/json', + 'User-Agent': 'OneBot', + 'X-Self-ID': this.context.uin, + }; + + if (endpoint.accessToken) { + headers['X-Signature'] = await computeHmacSha1(endpoint.accessToken, payload); + } + + const timeoutMs = endpoint.timeoutMs ?? DEFAULT_TIMEOUT_MS; + + try { + const response = await fetch(endpoint.url, { + method: 'POST', + headers, + body: payload, + signal: AbortSignal.timeout(timeoutMs), + }); + + // OneBot v11: if the response has a JSON body, it's a quick operation + if (response.ok) { + const contentType = response.headers.get('content-type') ?? ''; + if (contentType.includes('application/json')) { + const body = await response.text(); + if (body.trim()) { + await this.handleQuickOperation(event, body); + } + } + } else { + log.warn('POST %s returned %d', endpoint.url, response.status); + } + } catch (error) { + if (!this.stopped) { + log.warn('POST %s failed: %s', endpoint.url, error instanceof Error ? error.message : String(error)); + } + } + } + + private async handleQuickOperation(event: JsonObject, responseBody: string): Promise { + try { + const operation = JSON.parse(responseBody) as Record; + if (!operation || typeof operation !== 'object') return; + + await executeQuickOperation(event, operation, this.context.api); + } catch (error) { + log.warn('quick operation failed: %s', error instanceof Error ? error.message : String(error)); + } + } +} + +async function computeHmacSha1(secret: string, payload: string): Promise { + const { createHmac } = await import('crypto'); + return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex'); +} + +/** + * Execute a quick operation based on the event type and the response body. + * This implements the .handle_quick_operation hidden API behavior. + * See: https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md + */ +export async function executeQuickOperation( + event: JsonObject, + operation: Record, + api: import('./api-handler').ApiHandler, +): Promise { + const postType = event.post_type as string; + + if (postType === 'message') { + // Quick reply + if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') { + const messageType = event.message_type as string; + const autoEscape = !!operation.auto_escape; + + if (messageType === 'group') { + const params: JsonObject = { + group_id: event.group_id as number, + message: operation.reply as import('./types').JsonValue, + auto_escape: autoEscape, + }; + // at_sender defaults to true for group messages + if (operation.at_sender !== false && event.user_id) { + // Prepend an @ segment + const atSegment = { type: 'at', data: { qq: String(event.user_id) } }; + if (typeof operation.reply === 'string') { + params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as import('./types').JsonValue; + params.auto_escape = false; + } else if (Array.isArray(operation.reply)) { + params.message = [atSegment, ...(operation.reply as unknown[])] as import('./types').JsonValue; + } + } + await api.handle('send_group_msg', params); + } else if (messageType === 'private') { + await api.handle('send_private_msg', { + user_id: event.user_id as number, + message: operation.reply as import('./types').JsonValue, + auto_escape: autoEscape, + }); + } + } + + // Quick delete + if (operation.delete) { + await api.handle('delete_msg', { message_id: event.message_id as number }); + } + + // Quick ban (group only) + if (operation.ban && event.message_type === 'group') { + const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800; + await api.handle('set_group_ban', { + group_id: event.group_id as number, + user_id: event.user_id as number, + duration: duration as import('./types').JsonValue, + }); + } + + // Quick kick (group only) + if (operation.kick && event.message_type === 'group') { + await api.handle('set_group_kick', { + group_id: event.group_id as number, + user_id: event.user_id as number, + reject_add_request: !!operation.reject_add_request as unknown as import('./types').JsonValue, + }); + } + } + + if (postType === 'request') { + if (operation.approve !== undefined) { + const requestType = event.request_type as string; + if (requestType === 'friend') { + await api.handle('set_friend_add_request', { + flag: event.flag as string, + approve: operation.approve as import('./types').JsonValue, + remark: (operation.remark ?? '') as import('./types').JsonValue, + }); + } else if (requestType === 'group') { + await api.handle('set_group_add_request', { + flag: event.flag as string, + sub_type: event.sub_type as string, + approve: operation.approve as import('./types').JsonValue, + reason: (operation.reason ?? '') as import('./types').JsonValue, + }); + } + } + } +} diff --git a/src/onebot/http-transport.ts b/src/onebot/http-transport.ts new file mode 100644 index 00000000..ad10ec2e --- /dev/null +++ b/src/onebot/http-transport.ts @@ -0,0 +1,202 @@ +import { + createServer, + type IncomingHttpHeaders, + type IncomingMessage, + type Server, + type ServerResponse, +} from 'http'; +import type { ApiHandler } from './api-handler'; +import type { OneBotConfig } from './types'; +import { createLogger } from '../utils/logger'; + +export interface HttpTransportContext { + api: ApiHandler; +} + +const log = createLogger('OneBot.HTTP'); + +export class HttpTransport { + private readonly config: OneBotConfig; + private readonly context: HttpTransportContext; + private readonly servers: Server[] = []; + + constructor(config: OneBotConfig, context: HttpTransportContext) { + this.config = config; + this.context = context; + } + + start(): void { + for (const endpoint of this.config.httpServers) { + const expectedPath = normalizePath(endpoint.path ?? '/'); + const endpointToken = endpoint.accessToken ?? ''; + const server = createServer((req, res) => { + void this.handleRequest(expectedPath, endpointToken, req, res); + }); + + server.on('listening', () => { + const label = endpoint.name ? `[${endpoint.name}] ` : ''; + log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath); + }); + + server.on('error', (error) => { + log.warn('server error: %s', error instanceof Error ? error.message : String(error)); + }); + + server.listen(endpoint.port, endpoint.host); + this.servers.push(server); + } + } + + stop(): void { + for (const server of this.servers) { + server.close(); + } + this.servers.length = 0; + } + + private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise { + const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1'); + const incomingPath = parsedUrl.pathname; + + // Determine the expected prefix (e.g., "/" or "/api/") + const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/'; + let action = ''; + + if (incomingPath === expectedPath || incomingPath === expectedPath + '/') { + action = ''; // No action in URL (legacy body mode) + } else if (incomingPath.startsWith(ep)) { + action = incomingPath.substring(ep.length); // Extract action from URL + } else { + writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' }); + return; + } + + if (!isAuthorized(req, accessToken)) { + writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' }); + return; + } + + if (req.method === 'GET' && !action) { + writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } }); + return; + } + + try { + let params: Record = {}; + let echo: unknown; + + if (req.method === 'GET') { + parsedUrl.searchParams.forEach((value, key) => { + try { + params[key] = JSON.parse(value); + } catch { + params[key] = value; + } + }); + } else if (req.method === 'POST') { + const bodyContent = await readRequestBody(req); + if (bodyContent.trim()) { + try { + const parsedBody = JSON.parse(bodyContent); + if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) { + // Legacy format: { action: "...", params: {...} } vs standard raw params + if (parsedBody.action && !action) { + action = String(parsedBody.action); + } + if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) { + params = parsedBody.params as Record; + } else { + params = parsedBody as Record; + } + echo = parsedBody.echo; + } + } catch { + writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' }); + return; + } + } + } else { + writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' }); + return; + } + + if (!action) { + writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' }); + return; + } + + // Handle the API call + const response = await this.context.api.handle(action, params as import('./types').JsonObject); + + if (echo !== undefined) { + response.echo = echo as import('./types').JsonValue; + } + + writeJson(res, 200, response); + } catch (error) { + const wording = error instanceof Error ? error.message : 'internal error'; + writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording }); + } + } +} + +function parseRequestPath(urlValue: string): string { + try { + return new URL(urlValue, 'http://127.0.0.1').pathname; + } catch { + return '/'; + } +} + +function normalizePath(pathValue: string): string { + const path = pathValue.trim() || '/'; + if (path === '/') return '/'; + return path.endsWith('/') ? path.slice(0, -1) : path; +} + +function isAuthorized(request: IncomingMessage, token: string): boolean { + if (!token) return true; + // 1. Header auth + const rawAuth = request.headers.authorization; + const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? ''; + if (auth === `Bearer ${token}`) return true; + + // 2. Query string auth + try { + const url = new URL(request.url ?? '/', 'http://127.0.0.1'); + if (url.searchParams.get('access_token') === token) { + return true; + } + } catch {} + + return false; +} + +function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let total = 0; + + req.on('data', (chunk: Buffer) => { + total += chunk.length; + if (total > maxBytes) { + reject(new Error('request body too large')); + req.destroy(); + return; + } + chunks.push(chunk); + }); + + req.on('end', () => { + resolve(Buffer.concat(chunks).toString('utf8')); + }); + + req.on('error', reject); + }); +} + +function writeJson(res: ServerResponse, statusCode: number, data: unknown): void { + res.statusCode = statusCode; + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.end(JSON.stringify(data)); +} diff --git a/src/onebot/instance-context.ts b/src/onebot/instance-context.ts new file mode 100644 index 00000000..d667bd56 --- /dev/null +++ b/src/onebot/instance-context.ts @@ -0,0 +1,614 @@ +import type { Bridge } from '../bridge/bridge'; +import type { ForwardNodePayload } from '../bridge/events'; +import type { QQInfo } from '../bridge/qq-info'; +import type { ApiActionContext, MessageSendResult } from './api-handler'; +import { elementsToOneBotSegments } from './event-converter'; +import { MessageStore } from './message-store'; +import { parseMessage } from './message-parser'; +import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; +import type { JsonObject, JsonValue, MessageMeta } from './types'; + +export interface InstanceRef { + uin: string; + qqInfo: QQInfo; + bridge: Bridge; + messageStore: MessageStore; + musicSignUrl?: string; + cacheMessageMeta(messageId: number, meta: MessageMeta): void; +} + +export function buildApiContext(ref: InstanceRef): ApiActionContext { + const { bridge, qqInfo, messageStore } = ref; + + return { + getLoginInfo: () => getLoginInfo(ref), + isOnline: () => true, + getMessage: (messageId) => messageStore.findEvent(messageId), + getMessageMeta: (messageId) => messageStore.findMeta(messageId), + canSendImage: () => true, + canSendRecord: () => false, + sendPrivateMessage: (userId, message, autoEscape) => handleSendPrivate(ref, userId, message, autoEscape), + sendGroupMessage: (groupId, message, autoEscape) => handleSendGroup(ref, groupId, message, autoEscape), + deleteMessage: (messageId, meta) => handleDeleteMessage(bridge, meta), + // Info retrieval (async, triggers OIDB fetch) + getFriendList: () => handleGetFriendList(bridge, qqInfo), + getGroupList: (noCache) => handleGetGroupList(bridge, qqInfo, noCache), + getGroupInfo: (groupId, noCache) => handleGetGroupInfo(bridge, qqInfo, groupId, noCache), + getGroupMemberList: (groupId, noCache) => handleGetGroupMemberList(bridge, qqInfo, groupId, noCache), + getGroupMemberInfo: (groupId, userId, noCache) => handleGetGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache), + getStrangerInfo: (userId) => handleGetStrangerInfo(bridge, qqInfo, userId), + // Group admin + setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject), + setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration), + setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable), + setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable), + setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card), + setGroupName: (groupId, name) => bridge.setGroupName(groupId, name), + setGroupLeave: (groupId) => bridge.leaveGroup(groupId), + setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title), + // Group file + uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => { + const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true); + return result.fileId; + }, + uploadPrivateFile: async (userId, file, name, uploadFile) => { + const result = await bridge.uploadPrivateFile(userId, file, name ?? '', uploadFile ?? true); + return result.fileId; + }, + getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102), + getGroupFiles: (groupId, folderId) => handleGetGroupFiles(bridge, groupId, folderId), + deleteGroupFile: (groupId, fileId) => bridge.deleteGroupFile(groupId, fileId), + moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory), + createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'), + deleteGroupFileFolder: (groupId, folderId) => bridge.deleteGroupFileFolder(groupId, folderId), + renameGroupFileFolder: (groupId, folderId, newName) => bridge.renameGroupFileFolder(groupId, folderId, newName), + getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash), + // Requests + handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve), + handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason), + // Extended + sendLike: (userId, times) => bridge.sendLike(userId, times), + sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId), + sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId), + setEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, true), + deleteEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, false), + // New extended + setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet), + handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block), + getGroupMsgHistory: (groupId, messageId, count) => handleGetGroupMsgHistory(messageStore, groupId, messageId, count), + getFriendMsgHistory: (userId, messageId, count) => handleGetFriendMsgHistory(messageStore, userId, messageId, count), + handleGetGroupSystemMsg: async () => { + try { + const reqs = await bridge.fetchGroupRequests(); + return reqs.map(r => ({ + group_id: r.groupId, group_name: r.groupName, + request_id: r.sequence, requester_uin: r.targetUin, + requester_nick: r.targetName, message: r.comment, + flag: `${r.eventType}:${r.groupId}:${r.targetUid}`, + } as JsonObject)); + } catch { return []; } + }, + getDownloadRKeys: async () => { + try { + const rkeys = await bridge.fetchDownloadRKeys(); + return rkeys.map(r => ({ + rkey: r.rkey, type: r.type, ttl: r.ttlSeconds, create_time: r.createTime, + } as JsonObject)); + } catch { return []; } + }, + sendGroupForwardMsg: async (groupId, messages) => { + return handleSendGroupForward(ref, groupId, messages); + }, + sendPrivateForwardMsg: async (userId, messages) => { + return handleSendPrivateForward(ref, userId, messages); + }, + sendForwardMsg: async (messages) => { + return handleUploadForward(ref, messages); + }, + getForwardMsg: async (resId) => { + return handleGetForward(ref, resId); + }, + // Extended NapCat-compatible + setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark), + getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId), + setMsgEmojiLike: async (messageId, emojiId, set) => { + const meta = messageStore.findMeta(messageId); + if (!meta || !meta.isGroup) throw new Error('message not found or not a group message'); + await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set); + }, + }; +} + +// --- Login info --- + +function getLoginInfo(ref: InstanceRef): { userId: number; nickname: string } { + const userId = parseInt(ref.uin, 10) || 0; + const nickname = ref.qqInfo.nickname || ref.uin; + return { userId, nickname }; +} + +async function refreshAllGroupMembersCache(bridge: Bridge, qqInfo: QQInfo): Promise { + let groups = qqInfo.groups; + try { + groups = await bridge.fetchGroupList(); + } catch { /* use cached groups */ } + + for (const g of groups) { + try { + await bridge.fetchGroupMemberList(g.groupId); + } catch { /* best effort */ } + } +} + +function normalizeHistoryCount(count?: number): number { + if (!Number.isFinite(count)) return 20; + const n = Math.trunc(count as number); + if (n <= 0) return 20; + if (n > 200) return 200; + return n; +} + +function sanitizeMessageEventForApi(event: JsonObject): JsonObject { + const result: JsonObject = { ...event }; + delete result.post_type; + delete result.self_id; + result.real_id = (result.message_id ?? 0) as JsonValue; + return result; +} + +// --- Info retrieval --- + +async function handleGetFriendList(bridge: Bridge, qqInfo: QQInfo): Promise { + try { + const friends = await bridge.fetchFriendList(); + return friends.map(f => ({ + user_id: f.uin as any, + nickname: f.nickname as any, + remark: f.remark as any, + })); + } catch { + return qqInfo.friends.map(f => ({ + user_id: f.uin as any, + nickname: f.nickname as any, + remark: f.remark as any, + })); + } +} + +async function handleGetGroupList(bridge: Bridge, qqInfo: QQInfo, noCache?: boolean): Promise { + try { + if (noCache) { + await refreshAllGroupMembersCache(bridge, qqInfo); + } else if (qqInfo.groups.length === 0) { + await bridge.fetchGroupList(); + } + } catch { /* use cached */ } + return qqInfo.groups.map(g => ({ + group_id: g.groupId as any, + group_name: g.groupName as any, + member_count: g.memberCount as any, + max_member_count: g.memberMax as any, + })); +} + +async function handleGetGroupInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise { + if (noCache) { + try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ } + } else if (!qqInfo.findGroup(groupId)) { + try { await bridge.fetchGroupList(); } catch { /* use cached */ } + } + const g = qqInfo.findGroup(groupId); + if (!g) return null; + return { + group_id: g.groupId as any, + group_name: g.groupName as any, + member_count: g.memberCount as any, + max_member_count: g.memberMax as any, + }; +} + +async function handleGetGroupMemberList(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise { + if (noCache) { + try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ } + + const g = qqInfo.findGroup(groupId); + if (!g) return []; + const result: JsonObject[] = []; + for (const [, m] of g.members) { + result.push({ + group_id: groupId as any, user_id: m.uin as any, + nickname: m.nickname as any, card: m.card as any, + sex: 'unknown' as any, age: 0 as any, + join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any, + level: String(m.level) as any, role: m.role as any, title: m.title as any, + }); + } + return result; + } + + try { + const members = await bridge.fetchGroupMemberList(groupId); + return members.map(m => ({ + group_id: groupId as any, + user_id: m.uin as any, + nickname: m.nickname as any, + card: m.card as any, + sex: 'unknown' as any, + age: 0 as any, + join_time: m.joinTime as any, + last_sent_time: m.lastSentTime as any, + level: String(m.level) as any, + role: m.role as any, + title: m.title as any, + })); + } catch { + const g = qqInfo.findGroup(groupId); + if (!g) return []; + const result: JsonObject[] = []; + for (const [, m] of g.members) { + result.push({ + group_id: groupId as any, user_id: m.uin as any, + nickname: m.nickname as any, card: m.card as any, + sex: 'unknown' as any, age: 0 as any, + join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any, + level: String(m.level) as any, role: m.role as any, title: m.title as any, + }); + } + return result; + } +} + +async function handleGetGroupMemberInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, userId: number, noCache?: boolean): Promise { + if (noCache) { + try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ } + } else if (!qqInfo.findGroupMember(groupId, userId)) { + try { await bridge.fetchGroupMemberList(groupId); } catch { /* use cached */ } + } + const m = qqInfo.findGroupMember(groupId, userId); + if (!m) return null; + return { + group_id: groupId as any, user_id: m.uin as any, + nickname: m.nickname as any, card: m.card as any, + sex: 'unknown' as any, age: 0 as any, + join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any, + level: String(m.level) as any, role: m.role as any, title: m.title as any, + }; +} + +async function handleGetGroupFiles(bridge: Bridge, groupId: number, folderId?: string): Promise { + const result = await bridge.fetchGroupFiles(groupId, folderId ?? '/'); + return { + files: result.files.map((file) => ({ + group_id: groupId as any, + file_id: file.fileId as any, + file_name: file.fileName as any, + busid: file.busId as any, + file_size: file.fileSize as any, + upload_time: file.uploadTime as any, + dead_time: file.deadTime as any, + modify_time: file.modifyTime as any, + download_times: file.downloadTimes as any, + uploader: file.uploader as any, + uploader_name: file.uploaderName as any, + } as JsonObject)) as any, + folders: result.folders.map((folder) => ({ + group_id: groupId as any, + folder_id: folder.folderId as any, + folder_name: folder.folderName as any, + create_time: folder.createTime as any, + creator: folder.creator as any, + create_name: folder.creatorName as any, + total_file_count: folder.totalFileCount as any, + } as JsonObject)) as any, + }; +} + +async function handleGetStrangerInfo(bridge: Bridge, qqInfo: QQInfo, userId: number): Promise { + try { + const p = await bridge.fetchUserProfile(userId); + return { + user_id: p.uin as any, + nickname: p.nickname as any, + sex: p.sex as any, + age: p.age as any, + }; + } catch { + const p = qqInfo.findUserProfile(userId); + if (!p) return null; + return { user_id: p.uin as any, nickname: p.nickname as any, sex: p.sex as any, age: p.age as any }; + } +} + +// --- Message history --- + +async function handleGetGroupMsgHistory( + messageStore: MessageStore, + groupId: number, + messageId?: number, + count?: number, +): Promise { + if (!Number.isInteger(groupId) || groupId <= 0) return []; + const limit = normalizeHistoryCount(count); + + let anchorSequence: number | undefined; + if (Number.isInteger(messageId) && messageId !== 0) { + const meta = messageStore.findMeta(messageId as number); + if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) return []; + anchorSequence = meta.sequence; + } + + const events = messageStore.listSessionEvents(true, groupId, limit, anchorSequence); + return events + .filter((event) => { + if (event.message_type !== 'group') return false; + const gid = Number(event.group_id ?? 0); + return Number.isFinite(gid) && Math.trunc(gid) === groupId; + }) + .map(sanitizeMessageEventForApi); +} + +async function handleGetFriendMsgHistory( + messageStore: MessageStore, + userId: number, + messageId?: number, + count?: number, +): Promise { + if (!Number.isInteger(userId) || userId <= 0) return []; + const limit = normalizeHistoryCount(count); + + let anchorSequence: number | undefined; + if (Number.isInteger(messageId) && messageId !== 0) { + const meta = messageStore.findMeta(messageId as number); + if (!meta || meta.isGroup || meta.targetId !== userId || meta.sequence <= 0) return []; + anchorSequence = meta.sequence; + } + + const events = messageStore.listSessionEvents(false, userId, limit, anchorSequence); + return events + .filter((event) => { + if (event.message_type !== 'private') return false; + const uid = Number(event.user_id ?? 0); + return Number.isFinite(uid) && Math.trunc(uid) === userId; + }) + .map(sanitizeMessageEventForApi); +} + +// --- Delete message --- + +async function handleDeleteMessage(bridge: Bridge, meta: MessageMeta): Promise { + if (meta.isGroup) { + await bridge.recallGroupMessage(meta.targetId, meta.sequence); + } else { + await bridge.recallPrivateMessage( + meta.targetId, meta.clientSequence, meta.sequence, meta.random, meta.timestamp); + } +} + +// --- Group request --- + +async function handleGroupAddRequest(bridge: Bridge, flag: string, approve: boolean, reason: string): Promise { + // flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter) + const parts = flag.split(':'); + if (parts.length < 3) throw new Error('invalid group request flag'); + const groupId = parseInt(parts[1], 10); + if (!groupId) throw new Error('invalid group_id in flag'); + // We need sequence and eventType -- fetch from group requests + const requests = await bridge.fetchGroupRequests(); + const matching = requests.find(r => r.groupId === groupId); + if (matching) { + await bridge.setGroupAddRequest(groupId, matching.sequence, matching.eventType, approve, reason, matching.filtered); + } else { + throw new Error('matching group request not found'); + } +} + +// --- Essence --- + +async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, messageId: number, enable: boolean): Promise { + const meta = messageStore.findMeta(messageId); + if (!meta || !meta.isGroup) throw new Error('message not found or not a group message'); + await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable); +} + +// --- Send message --- + +async function handleSendPrivate( + ref: InstanceRef, + userId: number, + message: JsonValue, + autoEscape: boolean, +): Promise { + const elements = await parseMessage(message, autoEscape, { + resolveReplySequence: (replyMessageId) => + ref.messageStore.resolveReplySequence(false, userId, replyMessageId), + musicSignUrl: ref.musicSignUrl, + }); + if (elements.length === 0) throw new Error('message is empty'); + + const receipt = await ref.bridge.sendPrivateMessage(userId, elements); + const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT); + + // Cache the sent message meta + ref.cacheMessageMeta(messageId, { + isGroup: false, + targetId: userId, + sequence: receipt.sequence, + eventName: PRIVATE_MESSAGE_EVENT, + clientSequence: receipt.clientSequence, + random: receipt.random, + timestamp: receipt.timestamp, + }); + + return { messageId }; +} + +async function handleSendGroup( + ref: InstanceRef, + groupId: number, + message: JsonValue, + autoEscape: boolean, +): Promise { + const elements = await parseMessage(message, autoEscape, { + resolveReplySequence: (replyMessageId) => + ref.messageStore.resolveReplySequence(true, groupId, replyMessageId), + musicSignUrl: ref.musicSignUrl, + }); + if (elements.length === 0) throw new Error('message is empty'); + + const receipt = await ref.bridge.sendGroupMessage(groupId, elements); + const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT); + + // Cache the sent message meta + ref.cacheMessageMeta(messageId, { + isGroup: true, + targetId: groupId, + sequence: receipt.sequence, + eventName: GROUP_MESSAGE_EVENT, + clientSequence: receipt.clientSequence, + random: receipt.random, + timestamp: receipt.timestamp, + }); + + return { messageId }; +} + +async function handleSendGroupForward( + ref: InstanceRef, + groupId: number, + messages: JsonValue, +): Promise<{ messageId: number; forwardId: string }> { + const nodes = await parseForwardNodes(ref, messages); + const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId); + const receipt = await ref.bridge.sendGroupMessage(groupId, [{ type: 'forward', resId: forwardId }]); + const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT); + + ref.cacheMessageMeta(messageId, { + isGroup: true, + targetId: groupId, + sequence: receipt.sequence, + eventName: GROUP_MESSAGE_EVENT, + clientSequence: receipt.clientSequence, + random: receipt.random, + timestamp: receipt.timestamp, + }); + + return { messageId, forwardId }; +} + +async function handleSendPrivateForward( + ref: InstanceRef, + userId: number, + messages: JsonValue, +): Promise<{ messageId: number; forwardId: string }> { + const nodes = await parseForwardNodes(ref, messages); + const forwardId = await ref.bridge.uploadForwardNodes(nodes); + const receipt = await ref.bridge.sendPrivateMessage(userId, [{ type: 'forward', resId: forwardId }]); + const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT); + + ref.cacheMessageMeta(messageId, { + isGroup: false, + targetId: userId, + sequence: receipt.sequence, + eventName: PRIVATE_MESSAGE_EVENT, + clientSequence: receipt.clientSequence, + random: receipt.random, + timestamp: receipt.timestamp, + }); + + return { messageId, forwardId }; +} + +async function handleUploadForward( + ref: InstanceRef, + messages: JsonValue, +): Promise<{ forwardId: string }> { + const nodes = await parseForwardNodes(ref, messages); + const forwardId = await ref.bridge.uploadForwardNodes(nodes); + return { forwardId }; +} + +async function handleGetForward( + ref: InstanceRef, + resId: string, +): Promise { + const nodes = await ref.bridge.fetchForwardNodes(resId); + const results: JsonObject[] = []; + for (const node of nodes) { + results.push({ + type: 'node' as any, + data: { + user_id: node.userUin as any, + nickname: node.nickname as any, + uin: String(node.userUin) as any, + name: node.nickname as any, + content: await elementsToOneBotSegments(node.elements, false, node.userUin) as any, + } as any, + } as JsonObject); + } + return results; +} + +async function parseForwardNodes(ref: InstanceRef, messages: JsonValue): Promise { + if (!Array.isArray(messages)) { + throw new Error('forward messages must be an array'); + } + + const nodes: ForwardNodePayload[] = []; + for (const item of messages) { + const segment = asJsonObject(item); + if (!segment) continue; + + let nodeData: JsonObject | null = null; + if (String(segment.type ?? '') === 'node') { + nodeData = asJsonObject(segment.data); + } else if (segment.content !== undefined || segment.message !== undefined) { + nodeData = segment; + } + if (!nodeData) continue; + + const messageId = toPositiveInt(nodeData.id ?? nodeData.message_id); + if (messageId > 0) { + const event = ref.messageStore.findEvent(messageId); + if (!event) throw new Error(`forward node message_id not found: ${messageId}`); + + const eventSender = asJsonObject(event.sender) ?? {}; + const nickname = String(eventSender.card ?? eventSender.nickname ?? nodeData.nickname ?? nodeData.name ?? ''); + const userUin = toPositiveInt(event.user_id); + const content = (event.message ?? event.raw_message ?? '') as JsonValue; + const elements = await parseMessage(content, false); + if (userUin > 0 && elements.length > 0) { + nodes.push({ userUin, nickname: nickname || String(userUin), elements }); + } + continue; + } + + const userUin = toPositiveInt(nodeData.user_id ?? nodeData.uin); + if (userUin <= 0) throw new Error('forward node user_id/uin is required'); + + const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin); + const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue; + const elements = await parseMessage(content, false); + if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`); + + nodes.push({ userUin, nickname, elements }); + } + + if (nodes.length === 0) { + throw new Error('forward node list is empty'); + } + return nodes; +} + +function asJsonObject(value: JsonValue | undefined): JsonObject | null { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return null; + return value as JsonObject; +} + +function toPositiveInt(value: JsonValue | undefined): number { + if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value)); + if (typeof value === 'string' && value.trim()) { + const parsed = Number(value); + if (Number.isFinite(parsed)) return Math.max(0, Math.trunc(parsed)); + } + return 0; +} diff --git a/src/onebot/instance-rkey.ts b/src/onebot/instance-rkey.ts new file mode 100644 index 00000000..ba931065 --- /dev/null +++ b/src/onebot/instance-rkey.ts @@ -0,0 +1,143 @@ +import type { MessageElement } from '../bridge/events'; +import type { Bridge, DownloadRKeyInfo } from '../bridge/bridge'; +import { createLogger } from '../utils/logger'; + +const log = createLogger('OneBot'); + +interface CachedRKey { + value: string; + type: number; + createTime: number; + ttlSeconds: number; + expiresAt: number; +} + +const RKEY_REFRESH_SKEW = 60; +const RKEY_REFRESH_COOLDOWN = 30; +const PRIVATE_IMAGE_RKEY_TYPE = 10; +const GROUP_IMAGE_RKEY_TYPE = 20; +const PRIVATE_VIDEO_RKEY_TYPE = 12; +const GROUP_VIDEO_RKEY_TYPE = 22; +const PRIVATE_PTT_RKEY_TYPE = 14; +const GROUP_PTT_RKEY_TYPE = 24; +const FALLBACK_IMAGE_RKEY_TYPE = 2; + +export class RKeyCache { + private cache = new Map(); + private lastRefreshAttempt = 0; + + warmUp(bridge: Bridge, uin: string): void { + bridge.fetchDownloadRKeys().then( + (rkeys) => { + this.updateCache(rkeys); + log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length); + }, + (err) => { + log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err)); + }, + ); + } + + resolveImageUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string { + const url = element.imageUrl ?? ''; + if (!urlNeedsRKey(url)) return url; + + const rkey = this.findRKey(bridge, isGroup); + if (!rkey) return url; + + const cleanRKey = stripRKeyPrefix(rkey); + const separator = url.includes('?') ? '&rkey=' : '?rkey='; + return url + separator + encodeURIComponent(cleanRKey); + } + + /** + * Resolve a URL for video/record/file media elements. + * Appends the correct RKey type based on media kind and group/private context. + */ + resolveMediaUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string { + const url = element.url ?? ''; + if (!url || !urlNeedsRKey(url)) return url; + + const mediaType = element.type; + let primaryType: number; + if (mediaType === 'video') { + primaryType = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE; + } else if (mediaType === 'record') { + primaryType = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE; + } else { + // For file types, try image rkeys as a fallback (file URLs typically use image rkeys) + primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE; + } + + const rkey = this.findRKeyForType(bridge, primaryType); + if (!rkey) return url; + + const cleanRKey = stripRKeyPrefix(rkey); + const separator = url.includes('?') ? '&rkey=' : '?rkey='; + return url + separator + encodeURIComponent(cleanRKey); + } + + private updateCache(rkeys: DownloadRKeyInfo[]): void { + const now = Math.floor(Date.now() / 1000); + for (const rk of rkeys) { + if (!rk.rkey || !rk.type) continue; + const baseTime = rk.createTime || now; + const ttl = rk.ttlSeconds || 3600; + this.cache.set(rk.type, { + value: rk.rkey, + type: rk.type, + createTime: rk.createTime, + ttlSeconds: rk.ttlSeconds, + expiresAt: baseTime + ttl, + }); + } + } + + private findRKey(bridge: Bridge, isGroup: boolean): string | null { + const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE; + return this.findRKeyForType(bridge, primaryType); + } + + private findRKeyForType(bridge: Bridge, primaryType: number): string | null { + const now = Math.floor(Date.now() / 1000); + + const tryFind = (type: number): string | null => { + const cached = this.cache.get(type); + if (!cached || !cached.value) return null; + if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null; + return cached.value; + }; + + let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); + if (result) return result; + + // Refresh check cooldown + if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null; + this.lastRefreshAttempt = now; + + // Schedule async refresh + bridge.fetchDownloadRKeys().then( + (rkeys) => this.updateCache(rkeys), + () => { /* ignore */ }, + ); + + // Try again (won't be ready yet for this call, but future calls will benefit) + result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); + return result; + } +} + +function urlNeedsRKey(url: string): boolean { + if (!url || url.includes('rkey=')) return false; + if (url.includes('gchat.qpic.cn')) return false; + return url.includes('multimedia.nt.qq.com.cn') || + url.includes('.nt.qq.com.cn') || + url.includes('/download'); +} + +function stripRKeyPrefix(rkey: string): string { + for (const prefix of ['&rkey=', '?rkey=']) { + if (rkey.startsWith(prefix)) return rkey.slice(prefix.length); + } + return rkey; +} diff --git a/src/onebot/instance.ts b/src/onebot/instance.ts new file mode 100644 index 00000000..52fd1df6 --- /dev/null +++ b/src/onebot/instance.ts @@ -0,0 +1,266 @@ +import path from 'path'; +import type { QQEventVariant } from '../bridge/events'; +import type { Bridge } from '../bridge/bridge'; +import type { QQInfo } from '../bridge/qq-info'; +import { ApiHandler } from './api-handler'; +import { EventConverter } from './event-converter'; +import { MessageStore } from './message-store'; +import { RKeyCache } from './instance-rkey'; +import { buildApiContext } from './instance-context'; +import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; +import type { JsonObject, MessageMeta, OneBotConfig } from './types'; +import { HttpTransport } from './http-transport'; +import { HttpPostTransport } from './http-post-transport'; +import { WsTransport } from './ws-transport'; + +export class OneBotInstance { + readonly uin: string; + + readonly qqInfo: QQInfo; + private readonly bridge: Bridge; + private readonly apiHandler: ApiHandler; + private readonly eventConverter: EventConverter; + private readonly messageStore: MessageStore; + private readonly httpTransport: HttpTransport; + private readonly httpPostTransport: HttpPostTransport; + private readonly wsTransport: WsTransport; + private readonly rkeyCache: RKeyCache; + + private readonly pids = new Set(); + private online = true; + private heartbeatTimer: NodeJS.Timeout | null = null; + private static readonly HEARTBEAT_INTERVAL = 30000; + + constructor(uin: string, qqInfo: QQInfo, bridge: Bridge, config: OneBotConfig) { + this.uin = uin; + this.qqInfo = qqInfo; + this.bridge = bridge; + + this.eventConverter = new EventConverter(); + this.rkeyCache = new RKeyCache(); + this.eventConverter.setImageUrlResolver((element, isGroup) => + this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup)); + this.eventConverter.setMediaUrlResolver(async (element, isGroup, sessionId) => { + // Fetch URL from bridge if not already present + if (!element.url) { + try { + if (element.type === 'file' && element.fileId) { + element.url = isGroup + ? await this.bridge.fetchGroupFileUrl(sessionId, element.fileId) + : element.fileHash + ? await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash) + : ''; + } else if ((element.type === 'record' || element.type === 'video') && element.mediaNode) { + if (isGroup) { + element.url = element.type === 'record' + ? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode) + : await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode); + } else { + element.url = element.type === 'record' + ? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode) + : await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode); + } + } + } catch { /* best-effort */ } + } + // Then apply RKey if needed + return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup); + }); + this.eventConverter.setMessageIdResolver((isGroup, sessionId, sequence, eventName) => + hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT))); + this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json')); + + const context = buildApiContext({ + uin: this.uin, + qqInfo: this.qqInfo, + bridge: this.bridge, + messageStore: this.messageStore, + musicSignUrl: config.musicSignUrl, + cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta), + }); + this.apiHandler = new ApiHandler(context); + + this.httpTransport = new HttpTransport(config, { + api: this.apiHandler, + }); + + this.httpPostTransport = new HttpPostTransport(config, { + uin: this.uin, + api: this.apiHandler, + }); + + this.wsTransport = new WsTransport(config, { + uin: this.uin, + api: this.apiHandler, + buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType), + buildHeartbeatEvent: () => this.makeHeartbeatEvent(), + }); + + this.httpTransport.start(); + this.httpPostTransport.start(); + this.wsTransport.start(); + this.startHeartbeat(); + this.rkeyCache.warmUp(this.bridge, this.uin); + } + + dispose(): void { + this.online = false; + this.stopHeartbeat(); + this.httpTransport.stop(); + this.httpPostTransport.stop(); + this.wsTransport.stop(); + this.messageStore.close(); + } + + onBridgeEvent(event: QQEventVariant): void { + this.cacheMessageMetaFromBridgeEvent(event); + + void this.dispatchBridgeEventAsync(event); + } + + private async dispatchBridgeEventAsync(event: QQEventVariant): Promise { + const converted = await this.eventConverter.convert(this.uin, event); + if (!converted) return; + + this.dispatchEvent(converted); + } + + addPid(pid: number): void { + this.pids.add(pid); + } + + removePid(pid: number): void { + this.pids.delete(pid); + } + + hasPid(pid: number): boolean { + return this.pids.has(pid); + } + + get empty(): boolean { + return this.pids.size === 0; + } + + private dispatchEvent(event: JsonObject): void { + this.cacheMessageEvent(event); + this.wsTransport.publishEvent(event); + this.httpPostTransport.publishEvent(event); + } + + private cacheMessageEvent(event: JsonObject): void { + if (event.post_type !== 'message') return; + + const messageId = toInt(event.message_id); + if (messageId === 0) return; + + const isGroup = event.message_type === 'group'; + const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id); + const sequence = toInt(event.message_seq); + const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT; + + if (sessionId === 0) return; + this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event); + } + + private cacheMessageMetaFromBridgeEvent(event: QQEventVariant): void { + if (event.kind === 'group_message') { + const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT); + this.cacheMessageMeta(messageId, { + isGroup: true, + targetId: event.groupId, + sequence: event.msgSeq, + eventName: GROUP_MESSAGE_EVENT, + clientSequence: 0, + random: event.msgId, + timestamp: event.time, + }); + return; + } + + if (event.kind === 'friend_message') { + const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT); + this.cacheMessageMeta(messageId, { + isGroup: false, + targetId: event.senderUin, + sequence: event.msgSeq, + eventName: PRIVATE_MESSAGE_EVENT, + clientSequence: 0, + random: event.msgId, + timestamp: event.time, + }); + return; + } + + if (event.kind === 'temp_message') { + const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT); + this.cacheMessageMeta(messageId, { + isGroup: false, + targetId: event.senderUin, + sequence: event.msgSeq, + eventName: PRIVATE_MESSAGE_EVENT, + clientSequence: 0, + random: 0, + timestamp: event.time, + }); + } + } + + private cacheMessageMeta(messageId: number, meta: MessageMeta): void { + if (!Number.isInteger(messageId) || messageId === 0) return; + this.messageStore.storeMeta(messageId, meta); + } + + private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject { + const selfId = parseInt(this.uin, 10) || 0; + const time = Math.floor(Date.now() / 1000); + return { + time, + self_id: selfId, + post_type: 'meta_event', + meta_event_type: 'lifecycle', + sub_type: subType, + status: { + online: this.online, + good: this.online, + }, + }; + } + + // --- Heartbeat --- + + private startHeartbeat(): void { + this.heartbeatTimer = setInterval(() => { + this.dispatchEvent(this.makeHeartbeatEvent()); + }, OneBotInstance.HEARTBEAT_INTERVAL); + this.heartbeatTimer.unref?.(); + } + + private makeHeartbeatEvent(): JsonObject { + const selfId = parseInt(this.uin, 10) || 0; + const time = Math.floor(Date.now() / 1000); + return { + time, + self_id: selfId, + post_type: 'meta_event', + meta_event_type: 'heartbeat', + status: { online: this.online, good: this.online }, + interval: OneBotInstance.HEARTBEAT_INTERVAL, + }; + } + + private stopHeartbeat(): void { + if (this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = null; + } + } +} + +function toInt(value: unknown): number { + if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); + if (typeof value === 'string' && value.trim()) { + const parsed = Number(value); + if (Number.isFinite(parsed)) return Math.trunc(parsed); + } + return 0; +} diff --git a/src/onebot/manager.ts b/src/onebot/manager.ts new file mode 100644 index 00000000..98cb98a8 --- /dev/null +++ b/src/onebot/manager.ts @@ -0,0 +1,139 @@ +import type { QQEventVariant } from '../bridge/events'; +import type { Bridge } from '../bridge/bridge'; +import type { QQInfo } from '../bridge/qq-info'; +import type { BridgeManager } from '../bridge/manager'; +import { loadOneBotConfig } from './config'; +import { OneBotInstance } from './instance'; +import { createLogger } from '../utils/logger'; + +const log = createLogger('OneBot'); +const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1'; + +export class OneBotManager { + private readonly instances = new Map(); + + bind(bridgeManager: BridgeManager): void { + bridgeManager.setSessionStartedCallback((uin, qqInfo, bridge) => { + this.onSessionStarted(uin, qqInfo, bridge); + }); + + bridgeManager.setSessionClosedCallback((uin) => { + this.onSessionClosed(uin); + }); + + bridgeManager.setEventCallback((uin, event) => { + this.onBridgeEvent(uin, event); + }); + } + + getInstance(uin: string): OneBotInstance | null { + return this.instances.get(uin) ?? null; + } + + getInstances(): OneBotInstance[] { + return [...this.instances.values()]; + } + + dispose(): void { + for (const instance of this.instances.values()) { + instance.dispose(); + } + this.instances.clear(); + } + + private onSessionStarted(uin: string, qqInfo: QQInfo, bridge: Bridge): void { + if (this.instances.has(uin)) return; + + const config = loadOneBotConfig(uin); + const instance = new OneBotInstance(uin, qqInfo, bridge, config); + + const activePid = bridge.activePid; + if (activePid !== null) { + instance.addPid(activePid); + } + + this.instances.set(uin, instance); + log.info('session started: UIN=%s', uin); + + // Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state) + warmUpBridgeState(uin, qqInfo, bridge).catch((err) => { + log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); + } + + private onSessionClosed(uin: string): void { + const instance = this.instances.get(uin); + if (!instance) return; + + instance.dispose(); + this.instances.delete(uin); + log.info('session closed: UIN=%s', uin); + } + + private onBridgeEvent(uin: string, event: QQEventVariant): void { + const instance = this.instances.get(uin); + if (!instance) return; + + instance.onBridgeEvent(event); + } +} + +async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise { + // Step 1: Fetch friend list + derive self profile + try { + const friends = await bridge.fetchFriendList(); + log.info('friends loaded: UIN=%s count=%d', uin, friends.length); + + const selfUin = parseInt(uin, 10) || 0; + for (const f of friends) { + if (f.uin === selfUin) { + qqInfo.setSelfProfile({ + uin: f.uin, uid: f.uid, + nickname: f.nickname || uin, + remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', + }); + qqInfo.nickname = f.nickname || uin; + log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? ''); + break; + } + } + } catch (e) { + log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e)); + } + + // Step 2: Fetch group list + let groups: { groupId: number }[] = []; + try { + groups = await bridge.fetchGroupList(); + log.info('groups loaded: UIN=%s count=%d', uin, groups.length); + } catch (e) { + log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e)); + } + + // Step 3: Fetch members for each group + let loadedGroupCount = 0; + let loadedMemberCount = 0; + let failedGroupCount = 0; + for (const g of groups) { + try { + const members = await bridge.fetchGroupMemberList(g.groupId); + loadedGroupCount += 1; + loadedMemberCount += members.length; + if (VERBOSE_WARMUP) { + log.debug('members loaded: group=%d count=%d', g.groupId, members.length); + } + } catch (e) { + failedGroupCount += 1; + log.warn('failed to load members for group %d: %s', g.groupId, e instanceof Error ? e.message : String(e)); + } + } + + log.info( + 'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d', + uin, + loadedGroupCount, + groups.length, + loadedMemberCount, + failedGroupCount, + ); +} diff --git a/src/onebot/message-id.ts b/src/onebot/message-id.ts new file mode 100644 index 00000000..fbc2470a --- /dev/null +++ b/src/onebot/message-id.ts @@ -0,0 +1,15 @@ +import { createHash } from 'node:crypto'; + +export const GROUP_MESSAGE_EVENT = 'group_message'; +export const PRIVATE_MESSAGE_EVENT = 'private_message'; + +export function hashMessageIdInt32(sequence: number, sessionId: number, eventName: string): number { + const seq = Number.isFinite(sequence) ? Math.trunc(sequence) : 0; + const session = Number.isFinite(sessionId) ? Math.trunc(sessionId) : 0; + const key = `${seq}:${session}:${eventName}`; + const digest = createHash('sha1').update(key).digest(); + + let id = digest.readInt32BE(0); + if (id === 0) id = 1; + return id; +} diff --git a/src/onebot/message-parser.ts b/src/onebot/message-parser.ts new file mode 100644 index 00000000..2ef83715 --- /dev/null +++ b/src/onebot/message-parser.ts @@ -0,0 +1,326 @@ +// OneBot11 message segment parser. +// Converts OneBot message format (string with CQ codes or JSON segment arrays) +// into internal MessageElement arrays for sending. + +import type { MessageElement } from '../bridge/events'; +import type { JsonValue, JsonObject } from './types'; + +export interface ParseMessageOptions { + resolveReplySequence?: (replyMessageId: number) => number | null; + musicSignUrl?: string; +} + +// --- CQ Code parsing --- + +const CQ_REGEX = /\[CQ:([a-z]+)(?:,([^\]]*))?\]/g; + +function parseCQParams(raw: string): Record { + const params: Record = {}; + if (!raw) return params; + for (const pair of raw.split(',')) { + const eq = pair.indexOf('='); + if (eq > 0) { + params[pair.substring(0, eq)] = pair.substring(eq + 1) + .replace(/[/g, '[') + .replace(/]/g, ']') + .replace(/,/g, ',') + .replace(/&/g, '&'); + } + } + return params; +} + +function cqUnescape(text: string): string { + return text + .replace(/[/g, '[') + .replace(/]/g, ']') + .replace(/&/g, '&'); +} + +async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise { + const elements: MessageElement[] = []; + let lastIndex = 0; + + for (const match of message.matchAll(CQ_REGEX)) { + // Text before this CQ code + if (match.index! > lastIndex) { + const text = cqUnescape(message.substring(lastIndex, match.index!)); + if (text) elements.push({ type: 'text', text }); + } + lastIndex = match.index! + match[0].length; + + const cqType = match[1]; + const params = parseCQParams(match[2] || ''); + const elem = await segmentToElement(cqType, params, options); + if (elem) elements.push(elem); + } + + // Trailing text + if (lastIndex < message.length) { + const text = cqUnescape(message.substring(lastIndex)); + if (text) elements.push({ type: 'text', text }); + } + + return elements; +} + +// --- JSON segment parsing --- + +interface MessageSegment { + type: string; + data?: Record; +} + +function isSegmentArray(val: unknown): val is MessageSegment[] { + return Array.isArray(val) && val.every( + (item) => typeof item === 'object' && item !== null && 'type' in item + ); +} + +async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { + switch (type) { + case 'text': { + const text = String(data.text ?? ''); + return text ? { type: 'text', text } : null; + } + case 'face': { + const id = parseInt(String(data.id ?? '0'), 10); + return { type: 'face', faceId: id }; + } + case 'at': { + const qq = String(data.qq ?? ''); + if (qq === 'all') { + return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' }; + } + const uin = parseInt(qq, 10); + return uin > 0 ? { type: 'at', targetUin: uin, text: `@${uin} ` } : null; + } + case 'reply': { + const id = parseInt(String(data.id ?? '0'), 10); + if (!Number.isInteger(id) || id === 0) return null; + + if (options?.resolveReplySequence) { + const resolved = options.resolveReplySequence(id); + if (typeof resolved === 'number' && resolved > 0) { + return { type: 'reply', replySeq: resolved }; + } + } + + // Backward-compatible path: allow direct seq reply IDs. + return id > 0 ? { type: 'reply', replySeq: id } : null; + } + case 'image': { + return { + type: 'image', + url: String(data.file ?? data.url ?? ''), + flash: data.type === 'flash', + subType: parseInt(String(data.subType ?? '0'), 10), + summary: data.summary ? String(data.summary) : undefined, + }; + } + case 'record': { + return { + type: 'record', + url: String(data.file ?? data.url ?? ''), + }; + } + case 'video': { + return { + type: 'video', + url: String(data.file ?? data.url ?? ''), + }; + } + case 'json': { + return { + type: 'json', + text: String(data.data ?? ''), + }; + } + case 'xml': { + return { + type: 'xml', + text: String(data.data ?? ''), + subType: parseInt(String(data.id ?? '0'), 10), + }; + } + case 'poke': { + return { + type: 'poke', + faceId: parseInt(String(data.type ?? data.id ?? '0'), 10), + }; + } + case 'forward': { + return { + type: 'forward', + resId: String(data.id ?? ''), + }; + } + case 'node': { + // Fake forward node segment — store the raw data for later processing + // The content field may be a segment array, a single segment, or a CQ string + const uin = String(data.user_id ?? data.uin ?? '0'); + const name = String(data.nickname ?? data.name ?? ''); + return { + type: 'node', + targetUin: parseInt(uin, 10) || 0, + text: name, + // Raw content is stored as JSON string in resId for later processing + resId: JSON.stringify(data.content ?? ''), + }; + } + case 'markdown': { + return { + type: 'markdown', + text: String(data.content ?? ''), + }; + } + case 'share': { + // Link share — map to json card message + const url = String(data.url ?? ''); + const title = String(data.title ?? ''); + const content = String(data.content ?? ''); + const image = String(data.image ?? ''); + const jsonData = JSON.stringify({ + app: 'com.tencent.structmsg', + view: 'news', + prompt: title, + meta: { news: { title, desc: content, jumpUrl: url, preview: image } }, + }); + return { type: 'json', text: jsonData }; + } + case 'music': { + // Music share — uses external signing service (NapCat-compatible) + const musicType = String(data.type ?? ''); + const signUrl = options?.musicSignUrl || 'https://ss.xingzhige.com/music_card/card'; + try { + let postData: Record; + if (musicType === 'custom') { + postData = { + type: 'custom', + id: undefined, + url: String(data.url ?? ''), + audio: String(data.audio ?? ''), + title: String(data.title ?? ''), + image: String(data.image ?? ''), + singer: String(data.content ?? ''), + }; + } else { + postData = { type: musicType, id: String(data.id ?? '') }; + } + const resp = await fetch(signUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(postData), + }); + if (!resp.ok) throw new Error(`music sign HTTP ${resp.status}`); + const musicJson = await resp.text(); + return { type: 'json', text: musicJson }; + } catch (e) { + console.warn(`[MsgParser] music sign failed: ${e}, falling back to local card`); + // Fallback: build a basic card locally + const title = String(data.title ?? 'Music'); + const jsonData = JSON.stringify({ + app: 'com.tencent.structmsg', + view: 'music', + prompt: `[音乐]${title}`, + meta: { + music: { + title, + desc: String(data.content ?? ''), + jumpUrl: String(data.url ?? ''), + musicUrl: String(data.audio ?? ''), + preview: String(data.image ?? ''), + }, + }, + }); + return { type: 'json', text: jsonData }; + } + } + case 'location': { + // Location — map to json card + const lat = String(data.lat ?? ''); + const lon = String(data.lon ?? ''); + const title = String(data.title ?? '位置'); + const content = String(data.content ?? `${lat},${lon}`); + const jsonData = JSON.stringify({ + app: 'com.tencent.map', + view: 'LocationShare', + prompt: `[位置]${title}`, + meta: { Location: { lat, lng: lon, title, address: content } }, + }); + return { type: 'json', text: jsonData }; + } + case 'contact': { + // Contact card — map to json card + const contactType = String(data.type ?? 'qq'); + const contactId = String(data.id ?? ''); + const jsonData = JSON.stringify({ + app: 'com.tencent.contact.lua', + view: 'contact', + prompt: `[推荐${contactType === 'group' ? '群' : '好友'}]`, + meta: { contact: { type: contactType, id: contactId } }, + }); + return { type: 'json', text: jsonData }; + } + case 'rps': { + // Rock-paper-scissors — map to dice-like face + return { type: 'face', faceId: 359 }; + } + case 'dice': { + // Dice — map to dice face + return { type: 'face', faceId: 358 }; + } + case 'shake': { + // Window shake — map to poke + return { type: 'poke', faceId: 1 }; + } + case 'anonymous': { + // Anonymous flag — ignored during send, the protocol handles anonymity + return null; + } + default: + console.warn(`[MsgParser] unsupported segment type: ${type}`); + return null; + } +} + +// --- Public API --- + +/** + * Parse an OneBot11 message value into internal MessageElement array. + * Supports: + * - string (plain text or CQ code string) + * - array of { type, data } segments (JSON segment format) + * + * If autoEscape is true, the string is treated as plain text (no CQ parsing). + */ +export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise { + if (typeof message === 'string') { + if (autoEscape) { + return message ? [{ type: 'text', text: message }] : []; + } + return parseFromCQString(message, options); + } + + if (isSegmentArray(message)) { + const elements: MessageElement[] = []; + for (const seg of message) { + const data = (seg.data ?? {}) as Record; + const elem = await segmentToElement(seg.type, data, options); + if (elem) elements.push(elem); + } + return elements; + } + + // Single segment object + if (typeof message === 'object' && message !== null && !Array.isArray(message)) { + const seg = message as unknown as MessageSegment; + if (seg.type) { + const data = (seg.data ?? {}) as Record; + const elem = await segmentToElement(seg.type, data, options); + return elem ? [elem] : []; + } + } + + return []; +} diff --git a/src/onebot/message-store.ts b/src/onebot/message-store.ts new file mode 100644 index 00000000..b836c89a --- /dev/null +++ b/src/onebot/message-store.ts @@ -0,0 +1,218 @@ +// SQLite-backed message store using node:sqlite (DatabaseSync). +// Refactored to use a single unified `messages` table for all message types. + +import fs from 'fs'; +import path from 'path'; +import { DatabaseSync } from 'node:sqlite'; +import type { JsonObject, MessageMeta } from './types'; + +export class MessageStore { + private readonly db: DatabaseSync; + + constructor(dbPath: string) { + const dir = path.dirname(dbPath); + fs.mkdirSync(dir, { recursive: true }); + + // Replace .json extension with .db if present + const finalPath = dbPath.replace(/\.json$/, '.db'); + this.db = new DatabaseSync(finalPath); + this.db.exec('PRAGMA journal_mode = WAL'); + this.db.exec('PRAGMA synchronous = NORMAL'); + this.initSchema(); + } + + close(): void { + this.db.close(); + } + + storeEvent( + messageId: number, + isGroup: boolean, + sessionId: number, + sequence: number, + eventName: string, + event: JsonObject + ): void { + if (!isValidMessageId(messageId)) return; + const json = JSON.stringify(event); + const timestamp = toInt(event.time); + + this.db.prepare( + `INSERT INTO messages + (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data) + VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?) + ON CONFLICT(message_hash) DO UPDATE SET + is_group = excluded.is_group, + session_id = excluded.session_id, + sequence = excluded.sequence, + event_name = excluded.event_name, + timestamp = excluded.timestamp, + data = excluded.data` + ).run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json); + } + + storeMeta(messageId: number, meta: MessageMeta): void { + if (!isValidMessageId(messageId)) return; + this.db.prepare( + `INSERT INTO messages + (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(message_hash) DO UPDATE SET + is_group = excluded.is_group, + session_id = excluded.session_id, + sequence = excluded.sequence, + event_name = excluded.event_name, + client_sequence = excluded.client_sequence, + random = excluded.random, + timestamp = excluded.timestamp` + ).run( + messageId, + meta.isGroup ? 1 : 0, + meta.targetId, + meta.sequence, + meta.eventName, + meta.clientSequence, + meta.random, + meta.timestamp + ); + } + + findEvent(messageId: number): JsonObject | null { + if (!isValidMessageId(messageId)) return null; + const row = this.db.prepare( + 'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL', + ).get(messageId) as { data: string } | undefined; + + if (!row?.data) return null; + try { + return JSON.parse(row.data) as JsonObject; + } catch { + return null; + } + } + + findMeta(messageId: number): MessageMeta | null { + if (!isValidMessageId(messageId)) return null; + + const row = this.db.prepare( + 'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?', + ).get(messageId) as { + is_group: number; + session_id: number; + sequence: number; + event_name: string; + client_sequence: number; + random: number; + timestamp: number; + } | undefined; + + if (!row) return null; + + return { + isGroup: row.is_group === 1, + targetId: row.session_id, + sequence: row.sequence, + eventName: row.event_name, + clientSequence: row.client_sequence, + random: row.random, + timestamp: row.timestamp, + }; + } + + resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null { + if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) return null; + const row = this.db.prepare( + `SELECT sequence + FROM messages + WHERE is_group = ? AND session_id = ? AND message_hash = ? + LIMIT 1` + ).get(isGroup ? 1 : 0, sessionId, messageId) as { sequence: number } | undefined; + + if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null; + return row.sequence; + } + + listSessionEvents( + isGroup: boolean, + sessionId: number, + count = 20, + anchorSequence?: number, + ): JsonObject[] { + if (!Number.isInteger(sessionId) || sessionId <= 0) return []; + + const limit = normalizePositiveInt(count, 20, 200); + const hasAnchor = Number.isInteger(anchorSequence) && (anchorSequence as number) > 0; + const anchor = hasAnchor ? (anchorSequence as number) : 0; + + const rows = hasAnchor + ? this.db.prepare( + `SELECT data + FROM messages + WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ? + ORDER BY sequence DESC + LIMIT ?` + ).all(isGroup ? 1 : 0, sessionId, anchor, limit) + : this.db.prepare( + `SELECT data + FROM messages + WHERE is_group = ? AND session_id = ? AND data IS NOT NULL + ORDER BY sequence DESC + LIMIT ?` + ).all(isGroup ? 1 : 0, sessionId, limit); + + const result: JsonObject[] = []; + for (const row of rows as Array<{ data: string }>) { + if (!row?.data) continue; + try { + const parsed = JSON.parse(row.data) as JsonObject; + result.push(parsed); + } catch { + // Ignore malformed rows to avoid breaking history APIs. + } + } + + // Keep chronological order (oldest -> newest) for API consumers. + result.reverse(); + return result; + } + + + + private initSchema(): void { + this.db.exec(` + CREATE TABLE IF NOT EXISTS messages ( + message_hash INTEGER PRIMARY KEY, + is_group INTEGER NOT NULL, + session_id INTEGER NOT NULL, + sequence INTEGER NOT NULL, + event_name TEXT NOT NULL, + client_sequence INTEGER NOT NULL DEFAULT 0, + random INTEGER NOT NULL DEFAULT 0, + timestamp INTEGER NOT NULL DEFAULT 0, + data TEXT + ) + `); + this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)'); + } +} + +function isValidMessageId(messageId: number): boolean { + return Number.isInteger(messageId) && messageId !== 0; +} + +function toInt(value: unknown): number { + if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); + if (typeof value === 'string' && value.trim()) { + const parsed = Number(value); + if (Number.isFinite(parsed)) return Math.trunc(parsed); + } + return 0; +} + +function normalizePositiveInt(value: number, fallback: number, max: number): number { + if (!Number.isFinite(value)) return fallback; + const n = Math.trunc(value); + if (n <= 0) return fallback; + if (n > max) return max; + return n; +} diff --git a/src/onebot/types.ts b/src/onebot/types.ts new file mode 100644 index 00000000..8de9185e --- /dev/null +++ b/src/onebot/types.ts @@ -0,0 +1,96 @@ +export type JsonPrimitive = string | number | boolean | null; +export type JsonValue = JsonPrimitive | JsonObject | JsonArray; +export interface JsonObject { + [key: string]: JsonValue; +} +export type JsonArray = JsonValue[]; + +export interface ApiResponse { + status: 'ok' | 'failed'; + retcode: number; + data: JsonValue; + echo?: JsonValue; + wording?: string; +} + +export interface OneBotRequest { + action: string; + params?: JsonObject; + echo?: JsonValue; +} + +export interface WsServerEndpoint { + name?: string; + host: string; + port: number; + path?: string; + role?: WsRole; + accessToken?: string; +} + +export interface HttpServerEndpoint { + name?: string; + host: string; + port: number; + path?: string; + accessToken?: string; +} + +export interface WsClientEndpoint { + name?: string; + url: string; + role?: WsRole; + reconnectIntervalMs?: number; + accessToken?: string; +} + +export interface HttpPostEndpoint { + name?: string; + url: string; + accessToken?: string; + timeoutMs?: number; +} + +export interface OneBotConfig { + httpServers: HttpServerEndpoint[]; + httpPostEndpoints: HttpPostEndpoint[]; + wsServers: WsServerEndpoint[]; + wsClients: WsClientEndpoint[]; + musicSignUrl?: string; +} + +export type WsRole = 'api' | 'event' | 'universal'; + +export interface MessageMeta { + isGroup: boolean; + targetId: number; + sequence: number; + eventName: string; + clientSequence: number; + random: number; + timestamp: number; +} + +export const RETCODE = { + ACTION_FAILED: 100, + INTERNAL_ERROR: 1200, + BAD_REQUEST: 1400, + UNKNOWN_ACTION: 1404, +} as const; + +export function okResponse(data: JsonValue = null): ApiResponse { + return { + status: 'ok', + retcode: 0, + data, + }; +} + +export function failedResponse(retcode: number, wording: string): ApiResponse { + return { + status: 'failed', + retcode, + data: null, + wording, + }; +} diff --git a/src/onebot/ws-transport.ts b/src/onebot/ws-transport.ts new file mode 100644 index 00000000..58b1b2f7 --- /dev/null +++ b/src/onebot/ws-transport.ts @@ -0,0 +1,267 @@ +import WebSocket, { WebSocketServer } from 'ws'; +import type { IncomingHttpHeaders, IncomingMessage } from 'http'; +import type { ApiHandler } from './api-handler'; +import type { JsonObject, OneBotConfig, WsRole } from './types'; +import { createLogger } from '../utils/logger'; + +interface ForwardConnection { + socket: WebSocket; + role: WsRole; +} + +interface ReverseConnection { + socket: WebSocket; + role: WsRole; + endpointUrl: string; + reconnectIntervalMs: number; +} + +export interface WsTransportContext { + uin: string; + api: ApiHandler; + buildLifecycleEvent: (subType: 'connect' | 'enable' | 'disable') => JsonObject; + buildHeartbeatEvent: () => JsonObject; +} + +const log = createLogger('OneBot.WS'); + +export class WsTransport { + private readonly config: OneBotConfig; + private readonly context: WsTransportContext; + + private readonly servers: WebSocketServer[] = []; + private readonly forwardConnections = new Map(); + private readonly reverseConnections = new Set(); + private readonly reconnectTimers = new Set(); + private stopped = false; + + constructor(config: OneBotConfig, context: WsTransportContext) { + this.config = config; + this.context = context; + } + + start(): void { + this.stopped = false; + this.startServers(); + this.startReverseClients(); + } + + stop(): void { + this.stopped = true; + this.publishEvent(this.context.buildLifecycleEvent('disable')); + + for (const timer of this.reconnectTimers) { + clearTimeout(timer); + } + this.reconnectTimers.clear(); + + for (const [socket] of this.forwardConnections) { + safeClose(socket); + } + this.forwardConnections.clear(); + + for (const conn of this.reverseConnections) { + safeClose(conn.socket); + } + this.reverseConnections.clear(); + + for (const server of this.servers) { + server.close(); + } + this.servers.length = 0; + } + + publishEvent(event: JsonObject): void { + const payload = JSON.stringify(event); + + for (const { socket, role } of this.forwardConnections.values()) { + if (role === 'event' || role === 'universal') { + safeSend(socket, payload); + } + } + + for (const { socket, role } of this.reverseConnections.values()) { + if (role === 'event' || role === 'universal') { + safeSend(socket, payload); + } + } + } + + private startServers(): void { + for (const endpoint of this.config.wsServers) { + const wss = new WebSocketServer({ + host: endpoint.host, + port: endpoint.port, + path: endpoint.path ?? '/', + }); + + wss.on('listening', () => { + const label = endpoint.name ? `[${endpoint.name}] ` : ''; + log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, endpoint.path ?? '/'); + }); + + wss.on('connection', (socket, request) => { + if (!isAuthorized(request, endpoint.accessToken ?? '')) { + safeClose(socket, 1008, 'invalid access token'); + return; + } + + const role = endpoint.role ?? classifyForwardRole(request); + const conn: ForwardConnection = { socket, role }; + this.forwardConnections.set(socket, conn); + + socket.on('message', (raw) => { + void this.handleApiMessage(socket, role, raw); + }); + + socket.on('close', () => { + this.forwardConnections.delete(socket); + }); + + socket.on('error', (error) => { + log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error)); + }); + + this.sendBootstrapMetaEvents(socket, role); + }); + + wss.on('error', (error) => { + log.warn('server error: %s', error instanceof Error ? error.message : String(error)); + }); + + this.servers.push(wss); + } + } + + private startReverseClients(): void { + for (const endpoint of this.config.wsClients) { + const role = endpoint.role ?? 'universal'; + const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000); + this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name); + } + } + + private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string): void { + if (this.stopped) return; + + const headers: Record = { + 'User-Agent': 'OneBot', + 'X-Self-ID': this.context.uin, + 'X-Client-Role': role, + }; + + if (accessToken) { + headers.Authorization = `Bearer ${accessToken}`; + } + + const socket = new WebSocket(endpointUrl, { headers }); + const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs }; + this.reverseConnections.add(conn); + + socket.on('open', () => { + const label = name ? `[${name}] ` : ''; + log.info('%sreverse connected %s', label, endpointUrl); + this.sendBootstrapMetaEvents(socket, role); + }); + + socket.on('message', (raw) => { + void this.handleApiMessage(socket, role, raw); + }); + + socket.on('close', () => { + this.reverseConnections.delete(conn); + if (this.stopped) return; + + const timer = setTimeout(() => { + this.reconnectTimers.delete(timer); + this.connectReverseClient(endpointUrl, role, reconnectIntervalMs, accessToken, name); + }, reconnectIntervalMs); + timer.unref?.(); + this.reconnectTimers.add(timer); + }); + + socket.on('error', (error) => { + log.warn('reverse error %s: %s', endpointUrl, error instanceof Error ? error.message : String(error)); + }); + } + + private async handleApiMessage(socket: WebSocket, role: WsRole, raw: WebSocket.RawData): Promise { + if (role !== 'api' && role !== 'universal') return; + + const text = rawDataToString(raw); + if (!text) return; + + const response = await this.context.api.processRequest(text); + safeSend(socket, response); + } + + private sendBootstrapMetaEvents(socket: WebSocket, role: WsRole): void { + if (role !== 'event' && role !== 'universal') return; + + const connectEvent = this.context.buildLifecycleEvent('connect'); + const enableEvent = this.context.buildLifecycleEvent('enable'); + const heartbeatEvent = this.context.buildHeartbeatEvent(); + + safeSend(socket, JSON.stringify(connectEvent)); + safeSend(socket, JSON.stringify(enableEvent)); + safeSend(socket, JSON.stringify(heartbeatEvent)); + } +} + +function classifyForwardRole(request: IncomingMessage): WsRole { + const path = parseRequestPath(request.url ?? '/'); + if (path.endsWith('/api')) return 'api'; + if (path.endsWith('/event')) return 'event'; + return 'universal'; +} + +function parseRequestPath(urlValue: string): string { + try { + return new URL(urlValue, 'ws://127.0.0.1').pathname; + } catch { + return '/'; + } +} + +function isAuthorized(request: IncomingMessage, token: string): boolean { + if (!token) return true; + // 1. Header auth + const rawAuth = request.headers.authorization; + const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? ''; + if (auth === `Bearer ${token}`) return true; + + // 2. Query string auth + try { + const url = new URL(request.url ?? '/', 'ws://127.0.0.1'); + if (url.searchParams.get('access_token') === token) { + return true; + } + } catch {} + + return false; +} + +function rawDataToString(raw: WebSocket.RawData): string { + if (typeof raw === 'string') return raw; + if (raw instanceof Buffer) return raw.toString('utf8'); + if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8'); + if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8'); + if (ArrayBuffer.isView(raw)) { + return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8'); + } + return ''; +} + +function safeSend(socket: WebSocket, payload: string): void { + if (socket.readyState !== WebSocket.OPEN) return; + socket.send(payload, (error) => { + if (error) { + log.warn('send error: %s', error instanceof Error ? error.message : String(error)); + } + }); +} + +function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void { + if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return; + socket.close(code, reason); +} diff --git a/src/protobuf/decode.ts b/src/protobuf/decode.ts new file mode 100644 index 00000000..24a11f74 --- /dev/null +++ b/src/protobuf/decode.ts @@ -0,0 +1,241 @@ +// Runtime schema-based protobuf decode/encode. +// TypeScript equivalent of the C++ proto_field DSL using plain schema objects. +// +// Usage: +// const MyMessageSchema = { +// fromUin: { field: 1, type: 'uint32' as const }, +// fromUid: { field: 2, type: 'string' as const }, +// grp: { field: 8, type: 'message' as const, schema: GrpSchema }, +// elements: { field: 2, type: 'repeated_message' as const, schema: ElemSchema }, +// }; +// type MyMessage = ProtoDecoded; +// const msg = protoDecode(rawBytes, MyMessageSchema); + +import { WireMessage, WireType, encodeVarint, encodeKey, decodeVarint } from './wire'; + +// --- Schema types --- + +export type FieldType = + | 'bool' | 'int32' | 'uint32' | 'int64' | 'uint64' + | 'string' | 'bytes' | 'message' + | 'repeated_varint' | 'repeated_uint32' | 'repeated_string' + | 'repeated_bytes' | 'repeated_message'; + +export interface FieldDef { + field: number; + type: FieldType; + schema?: ProtoSchema; // required for 'message' / 'repeated_message' +} + +export type ProtoSchema = { [key: string]: FieldDef }; + +// --- Decoded type inference --- + +type FieldTypeToTS = + T extends 'bool' ? boolean : + T extends 'int32' | 'uint32' ? number : + T extends 'int64' | 'uint64' ? bigint : + T extends 'string' ? string : + T extends 'bytes' ? Uint8Array : + T extends 'message' ? (S extends ProtoSchema ? ProtoDecoded : Record) : + T extends 'repeated_varint' | 'repeated_uint32' ? number[] : + T extends 'repeated_string' ? string[] : + T extends 'repeated_bytes' ? Uint8Array[] : + T extends 'repeated_message' ? (S extends ProtoSchema ? ProtoDecoded[] : Record[]) : + never; + +type IsRepeated = T extends `repeated_${string}` ? true : false; + +type FieldValue = + IsRepeated extends true + ? FieldTypeToTS + : FieldTypeToTS | undefined; + +export type ProtoDecoded = { + [K in keyof S]: FieldValue; +}; + +// --- Decode --- + +export function protoDecode( + data: Uint8Array | WireMessage, + schema: S +): ProtoDecoded | null { + const wire = data instanceof WireMessage ? data : WireMessage.decode(data); + if (!wire) return null; + + const result: Record = {}; + + for (const [key, def] of Object.entries(schema)) { + switch (def.type) { + case 'bool': { + const v = wire.getVarint(def.field); + if (v !== null) result[key] = v !== 0n; + break; + } + case 'int32': { + const v = wire.getInt32(def.field); + if (v !== null) result[key] = v; + break; + } + case 'uint32': { + const v = wire.getUint32(def.field); + if (v !== null) result[key] = v; + break; + } + case 'int64': { + const v = wire.getInt64(def.field); + if (v !== null) result[key] = v; + break; + } + case 'uint64': { + const v = wire.getUint64(def.field); + if (v !== null) result[key] = v; + break; + } + case 'string': { + const v = wire.getString(def.field); + if (v !== null) result[key] = v; + break; + } + case 'bytes': { + const v = wire.getBytes(def.field); + if (v !== null) result[key] = v; + break; + } + case 'message': { + const sub = wire.getMessage(def.field); + if (sub && def.schema) { + result[key] = protoDecode(sub, def.schema); + } + break; + } + case 'repeated_varint': { + const vals = wire.getRepeatedVarint(def.field); + result[key] = vals.map(v => Number(BigInt.asIntN(32, v))); + break; + } + case 'repeated_uint32': { + const vals = wire.getRepeatedVarint(def.field); + result[key] = vals.map(v => Number(BigInt.asUintN(32, v))); + break; + } + case 'repeated_string': { + result[key] = wire.getRepeatedString(def.field); + break; + } + case 'repeated_bytes': { + const flds = wire.fields(def.field); + result[key] = flds + .filter(f => f.wireType === WireType.LengthDelimited) + .map(f => f.bytes); + break; + } + case 'repeated_message': { + if (!def.schema) { result[key] = []; break; } + const msgs = wire.getRepeatedMessage(def.field); + result[key] = msgs + .map(m => protoDecode(m, def.schema!)) + .filter((m): m is NonNullable => m !== null); + break; + } + } + } + + return result as ProtoDecoded; +} + +// --- Encode --- + +export function protoEncode( + obj: Partial>, + schema: S +): Uint8Array { + const out: number[] = []; + const record = obj as Record; + + for (const [key, def] of Object.entries(schema)) { + const val = record[key]; + if (val === undefined || val === null) continue; + + switch (def.type) { + case 'bool': { + encodeKey(def.field, WireType.Varint, out); + encodeVarint(val ? 1 : 0, out); + break; + } + case 'int32': + case 'uint32': { + encodeKey(def.field, WireType.Varint, out); + encodeVarint(val as number, out); + break; + } + case 'int64': + case 'uint64': { + encodeKey(def.field, WireType.Varint, out); + encodeVarint(val as bigint, out); + break; + } + case 'string': { + const encoded = new TextEncoder().encode(val as string); + encodeKey(def.field, WireType.LengthDelimited, out); + encodeVarint(encoded.length, out); + for (const b of encoded) out.push(b); + break; + } + case 'bytes': { + const buf = val as Uint8Array; + encodeKey(def.field, WireType.LengthDelimited, out); + encodeVarint(buf.length, out); + for (const b of buf) out.push(b); + break; + } + case 'message': { + if (!def.schema) break; + const nested = protoEncode(val as any, def.schema); + encodeKey(def.field, WireType.LengthDelimited, out); + encodeVarint(nested.length, out); + for (const b of nested) out.push(b); + break; + } + case 'repeated_varint': + case 'repeated_uint32': { + for (const v of val as number[]) { + encodeKey(def.field, WireType.Varint, out); + encodeVarint(v, out); + } + break; + } + case 'repeated_string': { + const encoder = new TextEncoder(); + for (const s of val as string[]) { + const encoded = encoder.encode(s); + encodeKey(def.field, WireType.LengthDelimited, out); + encodeVarint(encoded.length, out); + for (const b of encoded) out.push(b); + } + break; + } + case 'repeated_bytes': { + for (const buf of val as Uint8Array[]) { + encodeKey(def.field, WireType.LengthDelimited, out); + encodeVarint(buf.length, out); + for (const b of buf) out.push(b); + } + break; + } + case 'repeated_message': { + if (!def.schema) break; + for (const item of val as any[]) { + const nested = protoEncode(item, def.schema); + encodeKey(def.field, WireType.LengthDelimited, out); + encodeVarint(nested.length, out); + for (const b of nested) out.push(b); + } + break; + } + } + } + + return new Uint8Array(out); +} diff --git a/src/protobuf/wire.ts b/src/protobuf/wire.ts new file mode 100644 index 00000000..b708febe --- /dev/null +++ b/src/protobuf/wire.ts @@ -0,0 +1,242 @@ +// Protobuf wire-format decoder/encoder. +// Generic decoder that works without .proto schemas — decodes any protobuf +// binary into a field_number → value tree structure. +// Port of src/protobuf/wire.h + wire.cpp + +export enum WireType { + Varint = 0, + Fixed64 = 1, + LengthDelimited = 2, + Fixed32 = 5, +} + +export interface WireField { + fieldNumber: number; + wireType: WireType; + varint: bigint; // Varint, Fixed64, Fixed32 + bytes: Uint8Array; // LengthDelimited +} + +// --- Varint decode --- +export function decodeVarint(data: Uint8Array, offset: number): [bigint, number] | null { + let result = 0n; + for (let i = 0; i < 10 && offset + i < data.length; i++) { + result |= BigInt(data[offset + i] & 0x7f) << BigInt(7 * i); + if ((data[offset + i] & 0x80) === 0) { + return [result, i + 1]; + } + } + return null; +} + +// --- Varint encode --- +export function encodeVarint(value: bigint | number, out: number[]): void { + let v = typeof value === 'number' ? BigInt(value >>> 0) : value; + if (v < 0n) v = v + (1n << 64n); // treat as unsigned 64-bit + while (v >= 0x80n) { + out.push(Number(v & 0x7Fn) | 0x80); + v >>= 7n; + } + out.push(Number(v)); +} + +// --- Key encode --- +export function encodeKey(fieldNumber: number, wireType: WireType, out: number[]): void { + encodeVarint(BigInt(fieldNumber) << 3n | BigInt(wireType), out); +} + +// --- Field value helpers --- +export function fieldAsInt32(f: WireField): number { return Number(BigInt.asIntN(32, f.varint)); } +export function fieldAsUint32(f: WireField): number { return Number(BigInt.asUintN(32, f.varint)); } +export function fieldAsInt64(f: WireField): bigint { return BigInt.asIntN(64, f.varint); } +export function fieldAsUint64(f: WireField): bigint { return f.varint; } +export function fieldAsBool(f: WireField): boolean { return f.varint !== 0n; } +export function fieldAsString(f: WireField): string { + return new TextDecoder().decode(f.bytes); +} +export function fieldAsBytes(f: WireField): Uint8Array { + return f.bytes; +} + +export class WireMessage { + private fields_: WireField[]; + + private constructor(fields: WireField[]) { + this.fields_ = fields; + } + + static decode(data: Uint8Array): WireMessage | null { + if (!data || data.length === 0) return null; + + const fields: WireField[] = []; + let pos = 0; + + while (pos < data.length) { + const tagResult = decodeVarint(data, pos); + if (!tagResult) break; + const [tag, tagLen] = tagResult; + pos += tagLen; + + const fieldNum = Number(tag >> 3n); + const wireType = Number(tag & 0x07n) as WireType; + + if (fieldNum === 0) break; + + const field: WireField = { + fieldNumber: fieldNum, + wireType, + varint: 0n, + bytes: new Uint8Array(0), + }; + + switch (wireType) { + case WireType.Varint: { + const valResult = decodeVarint(data, pos); + if (!valResult) return null; + field.varint = valResult[0]; + pos += valResult[1]; + break; + } + case WireType.Fixed64: { + if (pos + 8 > data.length) return null; + const dv = new DataView(data.buffer, data.byteOffset + pos, 8); + field.varint = dv.getBigUint64(0, true); + pos += 8; + break; + } + case WireType.Fixed32: { + if (pos + 4 > data.length) return null; + const dv = new DataView(data.buffer, data.byteOffset + pos, 4); + field.varint = BigInt(dv.getUint32(0, true)); + pos += 4; + break; + } + case WireType.LengthDelimited: { + const lenResult = decodeVarint(data, pos); + if (!lenResult) return null; + const fieldLen = Number(lenResult[0]); + pos += lenResult[1]; + if (pos + fieldLen > data.length) return null; + field.bytes = data.subarray(pos, pos + fieldLen); + pos += fieldLen; + break; + } + default: + return null; + } + + fields.push(field); + } + + return new WireMessage(fields); + } + + // --- Single field access --- + + field(num: number): WireField | null { + for (const f of this.fields_) { + if (f.fieldNumber === num) return f; + } + return null; + } + + has(num: number): boolean { + return this.field(num) !== null; + } + + getVarint(num: number): bigint | null { + const f = this.field(num); + if (!f || f.wireType !== WireType.Varint) return null; + return f.varint; + } + + getInt32(num: number): number | null { + const v = this.getVarint(num); + return v !== null ? Number(BigInt.asIntN(32, v)) : null; + } + + getUint32(num: number): number | null { + const v = this.getVarint(num); + return v !== null ? Number(BigInt.asUintN(32, v)) : null; + } + + getInt64(num: number): bigint | null { + const v = this.getVarint(num); + return v !== null ? BigInt.asIntN(64, v) : null; + } + + getUint64(num: number): bigint | null { + return this.getVarint(num); + } + + getString(num: number): string | null { + const f = this.field(num); + if (!f || f.wireType !== WireType.LengthDelimited) return null; + return fieldAsString(f); + } + + getBytes(num: number): Uint8Array | null { + const f = this.field(num); + if (!f || f.wireType !== WireType.LengthDelimited) return null; + return f.bytes; + } + + getMessage(num: number): WireMessage | null { + const f = this.field(num); + if (!f || f.wireType !== WireType.LengthDelimited) return null; + return WireMessage.decode(f.bytes); + } + + // --- Repeated field access --- + + fields(num: number): WireField[] { + return this.fields_.filter(f => f.fieldNumber === num); + } + + getRepeatedVarint(num: number): bigint[] { + const result: bigint[] = []; + for (const f of this.fields_) { + if (f.fieldNumber !== num) continue; + if (f.wireType === WireType.Varint) { + result.push(f.varint); + } else if (f.wireType === WireType.LengthDelimited) { + // Packed repeated varint + let pos = 0; + while (pos < f.bytes.length) { + const r = decodeVarint(f.bytes, pos); + if (!r) break; + result.push(r[0]); + pos += r[1]; + } + } + } + return result; + } + + getRepeatedString(num: number): string[] { + const result: string[] = []; + const decoder = new TextDecoder(); + for (const f of this.fields_) { + if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) { + result.push(decoder.decode(f.bytes)); + } + } + return result; + } + + getRepeatedMessage(num: number): WireMessage[] { + const result: WireMessage[] = []; + for (const f of this.fields_) { + if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) { + const sub = WireMessage.decode(f.bytes); + if (sub) result.push(sub); + } + } + return result; + } + + // --- Raw iteration --- + + get allFields(): WireField[] { return this.fields_; } + get empty(): boolean { return this.fields_.length === 0; } +} diff --git a/src/protocol/ntqq-handler.ts b/src/protocol/ntqq-handler.ts new file mode 100644 index 00000000..2d450245 --- /dev/null +++ b/src/protocol/ntqq-handler.ts @@ -0,0 +1,54 @@ +import { createLogger } from '../utils/logger'; +import type { PacketInfo } from './types'; + +const log = createLogger('NTQQ'); + +export type CmdCallback = (pkt: PacketInfo) => void; + +export interface HookPacketInput { + seq: number; + error: number; + cmd: string; + uin: string; + body: Uint8Array; +} + +export class NtqqHandler { + private cmdHandlers = new Map(); + private cmdAllHandlers: CmdCallback[] = []; + + registerCmd(cmd: string, cb: CmdCallback): void { + const arr = this.cmdHandlers.get(cmd) ?? []; + arr.push(cb); + this.cmdHandlers.set(cmd, arr); + } + registerCmdAll(cb: CmdCallback): void { this.cmdAllHandlers.push(cb); } + + onHookPacket(pid: number, packet: HookPacketInput): void { + this.dispatchPacket({ + pid, + uin: packet.uin, + serviceCmd: packet.cmd, + seqId: packet.seq, + retCode: packet.error, + fromClient: false, + body: Buffer.from(packet.body), + }); + } + + private dispatchPacket(pkt: PacketInfo): void { + const specific = this.cmdHandlers.get(pkt.serviceCmd); + if (specific) { + for (const cb of specific) { + try { cb(pkt); } catch (e) { + log.error('dispatch error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e)); + } + } + } + for (const cb of this.cmdAllHandlers) { + try { cb(pkt); } catch (e) { + log.error('dispatch error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e)); + } + } + } +} diff --git a/src/protocol/packet-sender.ts b/src/protocol/packet-sender.ts new file mode 100644 index 00000000..ad2b5a19 --- /dev/null +++ b/src/protocol/packet-sender.ts @@ -0,0 +1,11 @@ +export interface SendPacketResult { + success: boolean; + gotResponse: boolean; + errorCode: number; + errorMessage: string; + responseData: Buffer | null; +} + +export interface PacketSender { + sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise; +} diff --git a/src/protocol/types.ts b/src/protocol/types.ts new file mode 100644 index 00000000..c49059ad --- /dev/null +++ b/src/protocol/types.ts @@ -0,0 +1,10 @@ +export interface PacketInfo { + pid: number; + uin: string; + packetType?: number; + serviceCmd: string; + seqId: number; + retCode: number; + fromClient: boolean; + body: Uint8Array; +} diff --git a/src/tests/config.test.ts b/src/tests/config.test.ts new file mode 100644 index 00000000..de1472ca --- /dev/null +++ b/src/tests/config.test.ts @@ -0,0 +1,16 @@ +import { describe, it, expect } from 'vitest'; +import { loadOneBotConfig, makeDefaultOneBotConfig } from '../onebot/config'; + +describe('makeDefaultOneBotConfig', () => { + it('returns default config structure', () => { + const config = makeDefaultOneBotConfig(); + expect(config.httpServers).toHaveLength(1); + expect(config.httpServers[0].host).toBe('0.0.0.0'); + expect(config.httpServers[0].port).toBe(3000); + expect(config.httpPostEndpoints).toEqual([]); + expect(config.wsServers).toHaveLength(1); + expect(config.wsServers[0].port).toBe(3001); + expect(config.wsClients).toEqual([]); + expect(config.musicSignUrl).toBe(''); + }); +}); diff --git a/src/tests/decode.test.ts b/src/tests/decode.test.ts new file mode 100644 index 00000000..5a3bd17f --- /dev/null +++ b/src/tests/decode.test.ts @@ -0,0 +1,173 @@ +import { describe, it, expect } from 'vitest'; +import { protoDecode, protoEncode, type ProtoSchema } from '../protobuf/decode'; +import { WireMessage, encodeKey, encodeVarint, WireType } from '../protobuf/wire'; + +describe('protoDecode', () => { + const SimpleSchema = { + name: { field: 1, type: 'string' as const }, + age: { field: 2, type: 'uint32' as const }, + active: { field: 3, type: 'bool' as const }, + }; + + function buildProto(): Uint8Array { + const out: number[] = []; + // field 1 string "Alice" + encodeKey(1, WireType.LengthDelimited, out); + const str = new TextEncoder().encode('Alice'); + encodeVarint(str.length, out); + out.push(...str); + // field 2 uint32 = 30 + encodeKey(2, WireType.Varint, out); + encodeVarint(30, out); + // field 3 bool = true + encodeKey(3, WireType.Varint, out); + encodeVarint(1, out); + return new Uint8Array(out); + } + + it('decodes all fields', () => { + const result = protoDecode(buildProto(), SimpleSchema); + expect(result).not.toBeNull(); + expect(result!.name).toBe('Alice'); + expect(result!.age).toBe(30); + expect(result!.active).toBe(true); + }); + + it('handles missing fields', () => { + // Only field 1 + const out: number[] = []; + encodeKey(1, WireType.LengthDelimited, out); + const str = new TextEncoder().encode('Bob'); + encodeVarint(str.length, out); + out.push(...str); + + const result = protoDecode(new Uint8Array(out), SimpleSchema); + expect(result).not.toBeNull(); + expect(result!.name).toBe('Bob'); + expect(result!.age).toBeUndefined(); + expect(result!.active).toBeUndefined(); + }); + + it('returns null for empty data', () => { + expect(protoDecode(new Uint8Array(0), SimpleSchema)).toBeNull(); + }); + + it('decodes nested messages', () => { + const InnerSchema = { + value: { field: 1, type: 'uint32' as const }, + }; + const OuterSchema = { + inner: { field: 1, type: 'message' as const, schema: InnerSchema }, + }; + + // Build inner + const innerOut: number[] = []; + encodeKey(1, WireType.Varint, innerOut); + encodeVarint(99, innerOut); + + // Build outer + const outerOut: number[] = []; + encodeKey(1, WireType.LengthDelimited, outerOut); + encodeVarint(innerOut.length, outerOut); + outerOut.push(...innerOut); + + const result = protoDecode(new Uint8Array(outerOut), OuterSchema); + expect(result).not.toBeNull(); + expect(result!.inner).not.toBeUndefined(); + expect(result!.inner!.value).toBe(99); + }); + + it('decodes repeated messages', () => { + const ItemSchema = { + id: { field: 1, type: 'uint32' as const }, + }; + const ListSchema = { + items: { field: 1, type: 'repeated_message' as const, schema: ItemSchema }, + }; + + const out: number[] = []; + for (const id of [1, 2, 3]) { + const itemOut: number[] = []; + encodeKey(1, WireType.Varint, itemOut); + encodeVarint(id, itemOut); + + encodeKey(1, WireType.LengthDelimited, out); + encodeVarint(itemOut.length, out); + out.push(...itemOut); + } + + const result = protoDecode(new Uint8Array(out), ListSchema); + expect(result).not.toBeNull(); + expect(result!.items).toHaveLength(3); + expect(result!.items.map((i) => i.id)).toEqual([1, 2, 3]); + }); + + it('accepts WireMessage directly', () => { + const wire = WireMessage.decode(buildProto()); + const result = protoDecode(wire!, SimpleSchema); + expect(result!.name).toBe('Alice'); + }); +}); + +describe('protoEncode', () => { + const SimpleSchema = { + name: { field: 1, type: 'string' as const }, + age: { field: 2, type: 'uint32' as const }, + active: { field: 3, type: 'bool' as const }, + }; + + it('encodes and decodes roundtrip', () => { + const data = { name: 'Charlie', age: 25, active: true }; + const encoded = protoEncode(data, SimpleSchema); + const decoded = protoDecode(encoded, SimpleSchema); + expect(decoded).not.toBeNull(); + expect(decoded!.name).toBe('Charlie'); + expect(decoded!.age).toBe(25); + expect(decoded!.active).toBe(true); + }); + + it('skips undefined fields', () => { + const data = { name: 'Dave', age: undefined, active: undefined }; + const encoded = protoEncode(data as any, SimpleSchema); + const decoded = protoDecode(encoded, SimpleSchema); + expect(decoded!.name).toBe('Dave'); + expect(decoded!.age).toBeUndefined(); + expect(decoded!.active).toBeUndefined(); + }); + + it('encodes bytes', () => { + const ByteSchema = { + payload: { field: 1, type: 'bytes' as const }, + }; + const data = { payload: new Uint8Array([0xDE, 0xAD]) }; + const encoded = protoEncode(data, ByteSchema); + const decoded = protoDecode(encoded, ByteSchema); + expect(decoded!.payload).toEqual(new Uint8Array([0xDE, 0xAD])); + }); + + it('encodes nested messages', () => { + const InnerSchema = { + value: { field: 1, type: 'uint32' as const }, + }; + const OuterSchema = { + inner: { field: 1, type: 'message' as const, schema: InnerSchema }, + }; + + const data = { inner: { value: 42 } }; + const encoded = protoEncode(data, OuterSchema); + const decoded = protoDecode(encoded, OuterSchema); + expect(decoded!.inner!.value).toBe(42); + }); + + it('encodes int64/uint64', () => { + const BigSchema = { + signed: { field: 1, type: 'int64' as const }, + unsigned: { field: 2, type: 'uint64' as const }, + }; + const data = { signed: -1n, unsigned: 0xFFFFFFFFFFFFFFFFn }; + const encoded = protoEncode(data, BigSchema); + const decoded = protoDecode(encoded, BigSchema); + expect(decoded!.signed).toBe(-1n); + expect(decoded!.unsigned).toBe(0xFFFFFFFFFFFFFFFFn); + }); +}); diff --git a/src/tests/hex.test.ts b/src/tests/hex.test.ts new file mode 100644 index 00000000..471b10f4 --- /dev/null +++ b/src/tests/hex.test.ts @@ -0,0 +1,65 @@ +import { describe, it, expect } from 'vitest'; +import { toHex, fromHex, hexPreview } from '../utils/hex'; + +describe('toHex', () => { + it('converts empty buffer', () => { + expect(toHex(new Uint8Array(0))).toBe(''); + }); + + it('converts single byte', () => { + expect(toHex(new Uint8Array([0xff]))).toBe('ff'); + expect(toHex(new Uint8Array([0x00]))).toBe('00'); + expect(toHex(new Uint8Array([0x0a]))).toBe('0a'); + }); + + it('converts multiple bytes', () => { + expect(toHex(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))).toBe('deadbeef'); + }); + + it('works with Buffer', () => { + expect(toHex(Buffer.from([0x01, 0x23, 0x45]))).toBe('012345'); + }); +}); + +describe('fromHex', () => { + it('converts empty string', () => { + expect(fromHex('')).toEqual(Buffer.alloc(0)); + }); + + it('converts hex string', () => { + const buf = fromHex('deadbeef'); + expect(buf).toEqual(Buffer.from([0xde, 0xad, 0xbe, 0xef])); + }); + + it('handles uppercase', () => { + const buf = fromHex('DEADBEEF'); + expect(buf).toEqual(Buffer.from([0xde, 0xad, 0xbe, 0xef])); + }); + + it('throws on odd-length string', () => { + expect(() => fromHex('abc')).toThrow('Invalid hex string length'); + }); + + it('roundtrips with toHex', () => { + const original = Buffer.from([0x00, 0x7f, 0x80, 0xff]); + expect(fromHex(toHex(original))).toEqual(original); + }); +}); + +describe('hexPreview', () => { + it('shows full hex for small data', () => { + const data = new Uint8Array([0xab, 0xcd]); + expect(hexPreview(data)).toBe('abcd'); + }); + + it('truncates with ellipsis', () => { + const data = new Uint8Array(128).fill(0xaa); + const preview = hexPreview(data, 4); + expect(preview).toBe('aaaaaaaa...'); + }); + + it('no ellipsis when exactly at limit', () => { + const data = new Uint8Array(4).fill(0xbb); + expect(hexPreview(data, 4)).toBe('bbbbbbbb'); + }); +}); diff --git a/src/tests/message-id.test.ts b/src/tests/message-id.test.ts new file mode 100644 index 00000000..33ff9736 --- /dev/null +++ b/src/tests/message-id.test.ts @@ -0,0 +1,49 @@ +import { describe, it, expect } from 'vitest'; +import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../onebot/message-id'; + +describe('hashMessageIdInt32', () => { + it('returns consistent hash for same inputs', () => { + const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT); + const id2 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT); + expect(id1).toBe(id2); + }); + + it('returns non-zero', () => { + // The function ensures id !== 0 by setting it to 1 + const id = hashMessageIdInt32(0, 0, ''); + expect(id).not.toBe(0); + }); + + it('returns different values for different sequences', () => { + const id1 = hashMessageIdInt32(1, 12345, GROUP_MESSAGE_EVENT); + const id2 = hashMessageIdInt32(2, 12345, GROUP_MESSAGE_EVENT); + expect(id1).not.toBe(id2); + }); + + it('returns different values for different sessions', () => { + const id1 = hashMessageIdInt32(100, 11111, GROUP_MESSAGE_EVENT); + const id2 = hashMessageIdInt32(100, 22222, GROUP_MESSAGE_EVENT); + expect(id1).not.toBe(id2); + }); + + it('returns different values for different event names', () => { + const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT); + const id2 = hashMessageIdInt32(100, 12345, PRIVATE_MESSAGE_EVENT); + expect(id1).not.toBe(id2); + }); + + it('returns 32-bit integer', () => { + const id = hashMessageIdInt32(999999, 123456789, GROUP_MESSAGE_EVENT); + expect(id).toBeGreaterThanOrEqual(-2147483648); + expect(id).toBeLessThanOrEqual(2147483647); + }); + + it('handles non-finite inputs gracefully', () => { + const id1 = hashMessageIdInt32(NaN, 0, 'test'); + const id2 = hashMessageIdInt32(Infinity, 0, 'test'); + expect(typeof id1).toBe('number'); + expect(typeof id2).toBe('number'); + // Both should map to sequence=0 + expect(id1).toBe(id2); + }); +}); diff --git a/src/tests/message-parser.test.ts b/src/tests/message-parser.test.ts new file mode 100644 index 00000000..e283b38b --- /dev/null +++ b/src/tests/message-parser.test.ts @@ -0,0 +1,245 @@ +import { describe, it, expect } from 'vitest'; +import { parseMessage } from '../onebot/message-parser'; + +describe('parseMessage', () => { + describe('plain text', () => { + it('parses simple text', async () => { + const result = await parseMessage('hello world', false); + expect(result).toEqual([{ type: 'text', text: 'hello world' }]); + }); + + it('returns empty for empty string', async () => { + const result = await parseMessage('', false); + expect(result).toEqual([]); + }); + + it('autoEscape treats CQ codes as text', async () => { + const result = await parseMessage('[CQ:face,id=123]', true); + expect(result).toEqual([{ type: 'text', text: '[CQ:face,id=123]' }]); + }); + }); + + describe('CQ code parsing', () => { + it('parses face CQ code', async () => { + const result = await parseMessage('[CQ:face,id=123]', false); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('face'); + expect(result[0].faceId).toBe(123); + }); + + it('parses at CQ code', async () => { + const result = await parseMessage('[CQ:at,qq=12345]', false); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('at'); + expect(result[0].targetUin).toBe(12345); + }); + + it('parses at all', async () => { + const result = await parseMessage('[CQ:at,qq=all]', false); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('at'); + expect(result[0].targetUin).toBe(0); + }); + + it('parses mixed text and CQ codes', async () => { + const result = await parseMessage('Hello [CQ:face,id=1] World', false); + expect(result).toHaveLength(3); + expect(result[0]).toEqual({ type: 'text', text: 'Hello ' }); + expect(result[1].type).toBe('face'); + expect(result[2]).toEqual({ type: 'text', text: ' World' }); + }); + + it('unescapes CQ special chars', async () => { + const result = await parseMessage('a&b[c]d', false); + expect(result).toEqual([{ type: 'text', text: 'a&b[c]d' }]); + }); + }); + + describe('JSON segment array', () => { + it('parses text segment', async () => { + const result = await parseMessage( + [{ type: 'text', data: { text: 'hello' } }] as any, + false, + ); + expect(result).toEqual([{ type: 'text', text: 'hello' }]); + }); + + it('parses face segment', async () => { + const result = await parseMessage( + [{ type: 'face', data: { id: 123 } }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('face'); + expect(result[0].faceId).toBe(123); + }); + + it('parses image segment', async () => { + const result = await parseMessage( + [{ type: 'image', data: { file: 'https://example.com/img.png' } }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('image'); + expect(result[0].url).toBe('https://example.com/img.png'); + }); + + it('parses at segment', async () => { + const result = await parseMessage( + [{ type: 'at', data: { qq: 12345 } }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('at'); + expect(result[0].targetUin).toBe(12345); + }); + + it('parses multiple segments', async () => { + const result = await parseMessage( + [ + { type: 'text', data: { text: 'hi ' } }, + { type: 'at', data: { qq: 999 } }, + { type: 'text', data: { text: ' there' } }, + ] as any, + false, + ); + expect(result).toHaveLength(3); + expect(result[0].type).toBe('text'); + expect(result[1].type).toBe('at'); + expect(result[2].type).toBe('text'); + }); + + it('skips unknown segment types', async () => { + const result = await parseMessage( + [ + { type: 'text', data: { text: 'ok' } }, + { type: 'unknown_type_xyz', data: {} }, + ] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('text'); + }); + }); + + describe('special segments', () => { + it('parses json segment', async () => { + const result = await parseMessage( + [{ type: 'json', data: { data: '{"app":"test"}' } }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('json'); + expect(result[0].text).toBe('{"app":"test"}'); + }); + + it('parses reply segment with resolveReplySequence', async () => { + const result = await parseMessage( + [{ type: 'reply', data: { id: 42 } }] as any, + false, + { resolveReplySequence: (id) => id === 42 ? 100 : null }, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('reply'); + expect(result[0].replySeq).toBe(100); + }); + + it('parses share as json card', async () => { + const result = await parseMessage( + [{ type: 'share', data: { url: 'https://example.com', title: 'Test' } }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('json'); + const parsed = JSON.parse(result[0].text); + expect(parsed.app).toBe('com.tencent.structmsg'); + expect(parsed.meta.news.title).toBe('Test'); + }); + + it('parses rps as face', async () => { + const result = await parseMessage( + [{ type: 'rps', data: {} }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('face'); + expect(result[0].faceId).toBe(359); + }); + + it('parses dice as face', async () => { + const result = await parseMessage( + [{ type: 'dice', data: {} }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('face'); + expect(result[0].faceId).toBe(358); + }); + + it('parses shake as poke', async () => { + const result = await parseMessage( + [{ type: 'shake', data: {} }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('poke'); + }); + + it('ignores anonymous segment', async () => { + const result = await parseMessage( + [ + { type: 'anonymous', data: {} }, + { type: 'text', data: { text: 'hi' } }, + ] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('text'); + }); + + it('parses location as json card', async () => { + const result = await parseMessage( + [{ type: 'location', data: { lat: '39.9', lon: '116.3', title: 'Beijing' } }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('json'); + const parsed = JSON.parse(result[0].text); + expect(parsed.app).toBe('com.tencent.map'); + expect(parsed.meta.Location.lat).toBe('39.9'); + }); + + it('parses contact as json card', async () => { + const result = await parseMessage( + [{ type: 'contact', data: { type: 'group', id: '12345' } }] as any, + false, + ); + expect(result).toHaveLength(1); + expect(result[0].type).toBe('json'); + const parsed = JSON.parse(result[0].text); + expect(parsed.meta.contact.type).toBe('group'); + }); + }); + + describe('single segment object', () => { + it('parses single segment object', async () => { + const result = await parseMessage( + { type: 'text', data: { text: 'single' } } as any, + false, + ); + expect(result).toEqual([{ type: 'text', text: 'single' }]); + }); + }); + + describe('edge cases', () => { + it('returns empty for null', async () => { + const result = await parseMessage(null as any, false); + expect(result).toEqual([]); + }); + + it('returns empty for number', async () => { + const result = await parseMessage(42 as any, false); + expect(result).toEqual([]); + }); + }); +}); diff --git a/src/tests/wire.test.ts b/src/tests/wire.test.ts new file mode 100644 index 00000000..0aae88a8 --- /dev/null +++ b/src/tests/wire.test.ts @@ -0,0 +1,175 @@ +import { describe, it, expect } from 'vitest'; +import { + WireType, + WireMessage, + decodeVarint, + encodeVarint, + encodeKey, + fieldAsInt32, + fieldAsUint32, + fieldAsString, + fieldAsBool, +} from '../protobuf/wire'; + +// Helper to build bytes from number array +function bytes(...vals: number[]): Uint8Array { + return new Uint8Array(vals); +} + +describe('decodeVarint', () => { + it('decodes single-byte varint', () => { + const result = decodeVarint(bytes(0x05), 0); + expect(result).toEqual([5n, 1]); + }); + + it('decodes zero', () => { + const result = decodeVarint(bytes(0x00), 0); + expect(result).toEqual([0n, 1]); + }); + + it('decodes multi-byte varint (300)', () => { + // 300 = 0b100101100 => 0xAC 0x02 + const result = decodeVarint(bytes(0xac, 0x02), 0); + expect(result).toEqual([300n, 2]); + }); + + it('decodes with offset', () => { + const result = decodeVarint(bytes(0xff, 0x01), 1); + expect(result).toEqual([1n, 1]); + }); + + it('returns null on empty data', () => { + const result = decodeVarint(bytes(), 0); + expect(result).toBeNull(); + }); +}); + +describe('encodeVarint', () => { + it('encodes small number', () => { + const out: number[] = []; + encodeVarint(5, out); + expect(out).toEqual([5]); + }); + + it('encodes 300', () => { + const out: number[] = []; + encodeVarint(300, out); + expect(out).toEqual([0xac, 0x02]); + }); + + it('encodes bigint', () => { + const out: number[] = []; + encodeVarint(300n, out); + expect(out).toEqual([0xac, 0x02]); + }); + + it('roundtrips', () => { + for (const val of [0, 1, 127, 128, 300, 65535, 2147483647]) { + const out: number[] = []; + encodeVarint(val, out); + const [decoded] = decodeVarint(new Uint8Array(out), 0)!; + expect(Number(decoded)).toBe(val); + } + }); +}); + +describe('encodeKey', () => { + it('encodes field 1 varint', () => { + const out: number[] = []; + encodeKey(1, WireType.Varint, out); + expect(out).toEqual([0x08]); // (1 << 3) | 0 = 8 + }); + + it('encodes field 2 length-delimited', () => { + const out: number[] = []; + encodeKey(2, WireType.LengthDelimited, out); + expect(out).toEqual([0x12]); // (2 << 3) | 2 = 18 + }); +}); + +describe('WireMessage', () => { + // Build a simple protobuf: field 1 = varint 150, field 2 = string "testing" + function buildSimpleMessage(): Uint8Array { + const out: number[] = []; + // field 1, varint = 150 + encodeKey(1, WireType.Varint, out); + encodeVarint(150, out); + // field 2, string = "testing" + encodeKey(2, WireType.LengthDelimited, out); + const str = new TextEncoder().encode('testing'); + encodeVarint(str.length, out); + out.push(...str); + return new Uint8Array(out); + } + + it('decodes empty data returns null', () => { + expect(WireMessage.decode(new Uint8Array(0))).toBeNull(); + }); + + it('decodes varint field', () => { + const msg = WireMessage.decode(buildSimpleMessage()); + expect(msg).not.toBeNull(); + expect(msg!.getUint32(1)).toBe(150); + }); + + it('decodes string field', () => { + const msg = WireMessage.decode(buildSimpleMessage()); + expect(msg).not.toBeNull(); + expect(msg!.getString(2)).toBe('testing'); + }); + + it('returns null for missing fields', () => { + const msg = WireMessage.decode(buildSimpleMessage()); + expect(msg!.getUint32(99)).toBeNull(); + expect(msg!.getString(99)).toBeNull(); + }); + + it('has() works', () => { + const msg = WireMessage.decode(buildSimpleMessage()); + expect(msg!.has(1)).toBe(true); + expect(msg!.has(2)).toBe(true); + expect(msg!.has(3)).toBe(false); + }); + + it('decodes nested message', () => { + const inner: number[] = []; + encodeKey(1, WireType.Varint, inner); + encodeVarint(42, inner); + + const outer: number[] = []; + encodeKey(3, WireType.LengthDelimited, outer); + encodeVarint(inner.length, outer); + outer.push(...inner); + + const msg = WireMessage.decode(new Uint8Array(outer)); + const nested = msg!.getMessage(3); + expect(nested).not.toBeNull(); + expect(nested!.getUint32(1)).toBe(42); + }); + + it('handles repeated fields', () => { + const out: number[] = []; + for (const v of [10, 20, 30]) { + encodeKey(1, WireType.Varint, out); + encodeVarint(v, out); + } + const msg = WireMessage.decode(new Uint8Array(out)); + const vals = msg!.getRepeatedVarint(1); + expect(vals.map(Number)).toEqual([10, 20, 30]); + }); + + it('field helpers work correctly', () => { + const out: number[] = []; + encodeKey(1, WireType.Varint, out); + encodeVarint(1, out); // bool true + encodeKey(2, WireType.Varint, out); + encodeVarint(0xFFFFFFFF, out); // uint32 max + + const msg = WireMessage.decode(new Uint8Array(out))!; + const f1 = msg.field(1)!; + const f2 = msg.field(2)!; + + expect(fieldAsBool(f1)).toBe(true); + expect(fieldAsUint32(f2)).toBe(0xFFFFFFFF); + }); +}); diff --git a/src/utils/hex.ts b/src/utils/hex.ts new file mode 100644 index 00000000..79852e5f --- /dev/null +++ b/src/utils/hex.ts @@ -0,0 +1,25 @@ +const HEX_CHARS = '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; +} + +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; +} + +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; +} diff --git a/src/utils/logger.ts b/src/utils/logger.ts new file mode 100644 index 00000000..2283f3f0 --- /dev/null +++ b/src/utils/logger.ts @@ -0,0 +1,107 @@ +import { format } from 'util'; + +type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error'; + +interface LogOptions { + scope: string; +} + +const LEVEL_WEIGHT: Record = { + debug: 10, + info: 20, + success: 25, + warn: 30, + error: 40, +}; + +const LEVEL_LABEL: Record = { + debug: 'DEBUG', + info: 'INFO', + success: 'OK', + warn: 'WARN', + error: 'ERROR', +}; + +const COLOR_CODE: Record = { + debug: 90, + info: 36, + success: 32, + warn: 33, + error: 31, +}; + +const COLOR_SCOPE = 35; +const COLOR_DIM = 2; +const COLOR_RESET = '\x1b[0m'; + +function resolveMinLevel(): LogLevel { + const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase(); + if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') { + return raw; + } + return 'info'; +} + +const MIN_LEVEL = resolveMinLevel(); + +function shouldLog(level: LogLevel): boolean { + return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[MIN_LEVEL]; +} + +function useColor(): boolean { + 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}`; +} + +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}`; +} + +function render(level: LogLevel, scope: string, args: unknown[]): string { + const message = format(...args); + const ts = currentTime(); + const label = LEVEL_LABEL[level].padEnd(5, ' '); + + if (!useColor()) { + return `${ts} ${label} [${scope}] ${message}`; + } + + const cTs = ansi(COLOR_DIM, ts); + const cLabel = ansi(COLOR_CODE[level], label); + const cScope = ansi(COLOR_SCOPE, `[${scope}]`); + return `${cTs} ${cLabel} ${cScope} ${message}`; +} + +function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { + if (!shouldLog(level)) return; + const line = render(level, options.scope, args); + const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout; + stream.write(line + '\n'); +} + +export interface Logger { + debug: (...args: unknown[]) => void; + info: (...args: unknown[]) => void; + success: (...args: unknown[]) => void; + warn: (...args: unknown[]) => void; + error: (...args: unknown[]) => void; +} + +export function createLogger(scope: string): Logger { + const options: LogOptions = { scope }; + return { + debug: (...args: unknown[]) => emit('debug', options, args), + info: (...args: unknown[]) => emit('info', options, args), + success: (...args: unknown[]) => emit('success', options, args), + warn: (...args: unknown[]) => emit('warn', options, args), + error: (...args: unknown[]) => emit('error', options, args), + }; +} diff --git a/src/webui/server.ts b/src/webui/server.ts new file mode 100644 index 00000000..67f61dd8 --- /dev/null +++ b/src/webui/server.ts @@ -0,0 +1,180 @@ +import { serve } from '@hono/node-server'; +import { serveStatic } from '@hono/node-server/serve-static'; +import { Hono } from 'hono'; +import { createLogger } from '../utils/logger'; +import { randomBytes } from 'crypto'; +import type { OneBotManager } from '../onebot/manager'; +import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config'; +import type { OneBotConfig } from '../onebot/types'; +import type { HookManager } from '../hook/hook-manager'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const log = createLogger('WebUI'); +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +// Session token store: token -> expiry timestamp (24h) +const sessionTokens = new Map(); + +// Login attempt tracker: ip -> { count, resetAt } +const loginAttempts = new Map(); + +const LOGIN_MAX_ATTEMPTS = 5; +const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; // 15 minutes +const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours + +function purgeExpiredTokens() { + const now = Date.now(); + for (const [token, expiry] of sessionTokens) { + if (now > expiry) sessionTokens.delete(token); + } +} + +function getClientIp(req: Request): string { + return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1'; +} + +export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hookManager?: HookManager) { + const app = new Hono(); + + // Generate random password (printed once at startup) + const randomPassword = randomBytes(8).toString('hex'); + log.info(`=========================================`); + log.info(`WebUI 安全认证`); + log.info(`默认用户: admin`); + log.info(`临时密码: ${randomPassword}`); + log.info(`=========================================`); + + // API Auth middleware + app.use('/api/*', async (c, next) => { + if (c.req.path === '/api/login') { + return next(); + } + + const authHeader = c.req.header('Authorization'); + if (!authHeader || !authHeader.startsWith('Bearer ')) { + return c.json({ status: 'failed', message: 'Unauthorized' }, 401); + } + + purgeExpiredTokens(); + const token = authHeader.slice(7); + const expiry = sessionTokens.get(token); + if (!expiry || Date.now() > expiry) { + return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401); + } + + await next(); + }); + + // Login Endpoint with rate limiting + app.post('/api/login', async (c) => { + const ip = getClientIp(c.req.raw); + const now = Date.now(); + const attempt = loginAttempts.get(ip); + + if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) { + const waitSec = Math.ceil((attempt.resetAt - now) / 1000); + return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429); + } + + try { + const { password } = await c.req.json(); + if (password === randomPassword) { + loginAttempts.delete(ip); + purgeExpiredTokens(); + const token = randomBytes(32).toString('hex'); + sessionTokens.set(token, now + TOKEN_TTL_MS); + return c.json({ success: true, token }); + } + + const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS }; + current.count += 1; + if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS; + loginAttempts.set(ip, current); + + return c.json({ success: false, message: '密码错误' }, 401); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + }); + + // API Routes + app.get('/api/status', (c) => { + return c.json({ status: 'running' }); + }); + + app.get('/api/qq-list', (c) => { + const instances = oneBotManager.getInstances(); + const list = instances.map(inst => ({ + uin: inst.uin, + nickname: inst.qqInfo.nickname + })); + return c.json({ list }); + }); + + app.get('/api/processes', async (c) => { + if (!hookManager) return c.json({ list: [] }); + try { + return c.json({ list: await hookManager.listProcesses() }); + } catch (err) { + return c.json({ list: [], message: err instanceof Error ? err.message : String(err) }, 500); + } + }); + + app.post('/api/processes/:pid/load', async (c) => { + if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); + const pid = Number(c.req.param('pid')); + if (!Number.isInteger(pid) || pid <= 0) { + return c.json({ success: false, message: 'invalid pid' }, 400); + } + try { + const processInfo = await hookManager.loadProcess(pid); + return c.json({ success: processInfo.status !== 'error', process: processInfo }); + } catch (err) { + return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500); + } + }); + + app.post('/api/processes/:pid/unload', async (c) => { + if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); + const pid = Number(c.req.param('pid')); + if (!Number.isInteger(pid) || pid <= 0) { + return c.json({ success: false, message: 'invalid pid' }, 400); + } + try { + const processInfo = await hookManager.unloadProcess(pid); + return c.json({ success: processInfo.status !== 'error', process: processInfo }); + } catch (err) { + return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500); + } + }); + + app.get('/api/config/:uin', (c) => { + const uin = c.req.param('uin'); + const config = loadOneBotConfig(uin); + return c.json({ config }); + }); + + app.post('/api/config/:uin', async (c) => { + try { + const uin = c.req.param('uin'); + const body = await c.req.json() as OneBotConfig; + saveOneBotConfig(uin, body); + log.info(`Updated OneBot config for UIN: ${uin}`); + return c.json({ success: true, message: '配置保存成功,将在下次会话重连时生效。' }); + } catch (err) { + return c.json({ success: false, message: String(err) }, 400); + } + }); + + // Serve static files generated by the React frontend + const staticRoot = path.join(__dirname, 'client'); + app.use('/*', serveStatic({ root: staticRoot })); + + serve({ + fetch: app.fetch, + port + }, (info) => { + log.info(`WebUI server is listening on http://localhost:${info.port}`); + }); +} diff --git a/tools/test_onebot_ws.py b/tools/test_onebot_ws.py new file mode 100644 index 00000000..3655fcc0 --- /dev/null +++ b/tools/test_onebot_ws.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +import argparse +import asyncio +import json +import sys +import uuid +from typing import Any, Dict + +try: + import websockets +except ImportError: + print("Missing dependency: websockets") + print("Install with: pip install websockets") + sys.exit(2) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="OneBot WS API smoke test") + parser.add_argument("--url", default="ws://127.0.0.1:3001/", help="OneBot WebSocket URL") + parser.add_argument("--token", default="", help="Bearer token if OneBot accessToken is set") + parser.add_argument("--group-id", type=int, default=1081372778, help="Target group_id for send_group_msg") + parser.add_argument("--message", default="hello from snowluma from refactor", help="Message text to send") + parser.add_argument("--timeout", type=float, default=20.0, help="Per-request timeout seconds") + return parser.parse_args() + + +async def recv_json(ws: Any, timeout: float) -> Dict[str, Any]: + raw = await asyncio.wait_for(ws.recv(), timeout) + if isinstance(raw, bytes): + raw = raw.decode("utf-8", errors="replace") + return json.loads(raw) + + +async def call_api(ws: Any, action: str, params: Dict[str, Any], timeout: float) -> Dict[str, Any]: + echo = f"py-{action}-{uuid.uuid4().hex[:8]}" + payload = { + "action": action, + "params": params, + "echo": echo, + } + await ws.send(json.dumps(payload, ensure_ascii=False)) + + while True: + resp = await recv_json(ws, timeout) + if resp.get("echo") == echo: + return resp + + +def short_json(data: Dict[str, Any], max_len: int = 240) -> str: + text = json.dumps(data, ensure_ascii=False) + if len(text) <= max_len: + return text + return text[:max_len] + "..." + + +async def main() -> int: + args = parse_args() + + headers = {} + if args.token: + headers["Authorization"] = f"Bearer {args.token}" + + try: + async with websockets.connect(args.url, additional_headers=headers, max_size=20 * 1024 * 1024) as ws: + try: + first = await recv_json(ws, 1.0) + print("[WS] first event:", short_json(first)) + except Exception: + pass + + status = await call_api(ws, "get_status", {}, args.timeout) + print("[API] get_status:", short_json(status)) + + groups = await call_api(ws, "get_group_list", {}, args.timeout) + group_count = len(groups.get("data", [])) if isinstance(groups.get("data"), list) else -1 + print(f"[API] get_group_list: group_count={group_count}") + + send_resp = await call_api( + ws, + "send_group_msg", + { + "group_id": args.group_id, + "message": args.message, + }, + args.timeout, + ) + print("[API] send_group_msg:", short_json(send_resp)) + + ok = ( + status.get("status") == "ok" + and groups.get("status") == "ok" + and send_resp.get("status") == "ok" + ) + return 0 if ok else 1 + except Exception as e: + print("[ERROR]", str(e)) + return 1 + + +if __name__ == "__main__": + raise SystemExit(asyncio.run(main())) diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..b9bcb696 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2022"], + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": false, + "declarationMap": false, + "sourceMap": false, + "resolveJsonModule": true, + "types": ["node"] + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "native", "src/tests"] +} diff --git a/vite.config.ts b/vite.config.ts new file mode 100644 index 00000000..c0176187 --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,64 @@ +import { defineConfig, PluginOption, UserConfig } from 'vite'; +import { fileURLToPath } from 'url'; +import path from 'path'; +import { builtinModules } from 'module'; +import cp from 'vite-plugin-cp'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +const external = [ + 'ws' +]; + +const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat(); + +const BaseConfigPlugin: PluginOption[] = [ + cp({ + targets: [ + { src: './launcher/*', dest: 'dist', flatten: true }, + { src: './native/*', dest: 'dist/native/', flatten: true }, + ] + }) +]; + +const BaseConfig = (source_map: boolean = false) => defineConfig({ + resolve: { + conditions: ['node', 'default'], + alias: { + '@': path.resolve(__dirname, 'src') + } + }, + build: { + sourcemap: source_map, + target: 'esnext', + minify: false, + lib: { + entry: { + index: path.resolve(__dirname, 'src/index.ts') + }, + formats: ['es'], + fileName: (_, entryName) => `${entryName}.mjs` + }, + rollupOptions: { + external: [...nodeModules, ...external] + }, + outDir: 'dist', + emptyOutDir: true + }, + define: { + __BUILD_WEBUI__: process.env.BUILD_WEBUI === 'true' + } +}); + +export default defineConfig(({ mode }): UserConfig => { + if (mode === 'development') { + return { + ...BaseConfig(true), + plugins: [...BaseConfigPlugin] + }; + } + return { + ...BaseConfig(), + plugins: [...BaseConfigPlugin] + }; +}); diff --git a/webui/.gitignore b/webui/.gitignore new file mode 100644 index 00000000..a547bf36 --- /dev/null +++ b/webui/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/webui/README.md b/webui/README.md new file mode 100644 index 00000000..7dbf7ebf --- /dev/null +++ b/webui/README.md @@ -0,0 +1,73 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs) +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) + +## React Compiler + +The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: + +```js +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + + // Remove tseslint.configs.recommended and replace with this + tseslint.configs.recommendedTypeChecked, + // Alternatively, use this for stricter rules + tseslint.configs.strictTypeChecked, + // Optionally, add this for stylistic rules + tseslint.configs.stylisticTypeChecked, + + // Other configs... + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` + +You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: + +```js +// eslint.config.js +import reactX from 'eslint-plugin-react-x' +import reactDom from 'eslint-plugin-react-dom' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + // Enable lint rules for React + reactX.configs['recommended-typescript'], + // Enable lint rules for React DOM + reactDom.configs.recommended, + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` diff --git a/webui/eslint.config.js b/webui/eslint.config.js new file mode 100644 index 00000000..5e6b472f --- /dev/null +++ b/webui/eslint.config.js @@ -0,0 +1,23 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]) diff --git a/webui/index.html b/webui/index.html new file mode 100644 index 00000000..8494216e --- /dev/null +++ b/webui/index.html @@ -0,0 +1,16 @@ + + + + + + + SnowLuma + + + + + +
+ + + diff --git a/webui/package.json b/webui/package.json new file mode 100644 index 00000000..3905bbc7 --- /dev/null +++ b/webui/package.json @@ -0,0 +1,39 @@ +{ + "name": "webui", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "@heroui/react": "^3.0.2", + "@heroui/styles": "^3.0.2", + "clsx": "^2.1.1", + "framer-motion": "^12.38.0", + "lucide-react": "^1.8.0", + "react": "^19.2.5", + "react-dom": "^19.2.5", + "tailwind-merge": "^3.5.0" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@tailwindcss/vite": "^4.2.2", + "@types/node": "^25.6.0", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "eslint": "^10.2.0", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.5.0", + "sass": "^1.99.0", + "tailwindcss": "^4.2.2", + "typescript": "catalog:", + "typescript-eslint": "^8.58.2", + "vite": "catalog:" + } +} diff --git a/webui/public/favicon.svg b/webui/public/favicon.svg new file mode 100644 index 00000000..6893eb13 --- /dev/null +++ b/webui/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/webui/public/icons.svg b/webui/public/icons.svg new file mode 100644 index 00000000..e9522193 --- /dev/null +++ b/webui/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/webui/public/logo.png b/webui/public/logo.png new file mode 100644 index 00000000..ea437bbb Binary files /dev/null and b/webui/public/logo.png differ diff --git a/webui/src/App.css b/webui/src/App.css new file mode 100644 index 00000000..6bfc5fb2 --- /dev/null +++ b/webui/src/App.css @@ -0,0 +1,469 @@ +.layout { + display: flex; + height: 100vh; + width: 100%; +} + +.sidebar { + width: 240px; + background: var(--bg-sidebar); + border-right: 1px solid var(--border-subtle); + display: flex; + flex-direction: column; + padding: 24px 0 0 0; + transition: background-color 0.3s; +} + +.brand { + padding: 0 24px; + margin-bottom: 32px; +} + +.brand h1 { + font-size: 1.3rem; + font-weight: 600; + color: var(--text-main); + background: linear-gradient(90deg, var(--color-primary), #818cf8); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; + display: inline-block; +} + +.nav-menu { + flex: 1; + padding: 0 16px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.nav-item { + padding: 10px 16px; + border-radius: var(--radius-md); + cursor: pointer; + color: var(--text-muted); + font-size: 0.9rem; + transition: all 0.2s; +} + +.nav-item:hover { + background: var(--bg-hover); + color: var(--text-main); +} + +.nav-item.active { + background: var(--color-primary); + color: #fff; + font-weight: 500; +} + +.sidebar-footer { + padding: 16px; + border-top: 1px solid var(--border-subtle); + display: flex; + flex-direction: column; + gap: 8px; +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 8px 16px; + border-radius: var(--radius-md); + font-size: 0.85rem; + font-weight: 500; + cursor: pointer; + border: 1px solid transparent; + transition: all 0.2s; + outline: none; + font-family: inherit; +} + +.btn-primary { + background: var(--color-primary); + color: #fff; +} + +.btn-primary:hover { + background: var(--color-primary-hover); +} + +.btn-ghost { + background: transparent; + color: var(--text-muted); +} + +.btn-ghost:hover { + background: var(--bg-hover); + color: var(--text-main); +} + +.btn-outline { + background: transparent; + border-color: var(--border-subtle); + color: var(--text-muted); +} + +.btn-outline:hover { + background: var(--bg-hover); + color: var(--text-main); +} + +.btn-danger { + background: transparent; + border-color: var(--border-subtle); + color: var(--color-danger); +} + +.btn-danger:hover { + background: var(--color-danger); + border-color: var(--color-danger); + color: #fff; +} + +.btn-icon { + padding: 4px; + width: 28px; + height: 28px; +} + +.content { + flex: 1; + display: flex; + flex-direction: column; + overflow: hidden; + background: var(--bg-body); +} + +.header { + height: 60px; + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 32px; + background: var(--bg-card); + border-bottom: 1px solid var(--border-subtle); +} + +.search-input { + background: var(--bg-input); + border: 1px solid var(--border-subtle); + padding: 8px 14px; + border-radius: var(--radius-sm); + color: var(--text-main); + width: 260px; + font-size: 0.85rem; + transition: border-color 0.2s; +} + +.search-input:focus { + border-color: var(--color-primary); +} + +.header-right { + display: flex; + align-items: center; + gap: 8px; + font-size: 0.85rem; + color: var(--text-muted); +} + +.status-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--text-muted); +} +.status-dot.on { background: #10b981; } +.status-dot.off { background: var(--color-danger); } + +.main-scroll { + flex: 1; + overflow-y: auto; + padding: 32px; +} + +.card { + background: var(--bg-card); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); + padding: 24px; +} + +.overview-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + gap: 20px; +} + +.overview-card { + display: flex; + flex-direction: column; + gap: 12px; +} + +.card-label { + font-size: 0.85rem; + color: var(--text-muted); +} + +.card-value { + font-size: 2rem; + font-weight: 600; + color: var(--text-main); +} +.status-ok { + color: #10b981; +} + +/* Config Layout */ +.config-layout { + display: flex; + gap: 24px; + align-items: flex-start; +} + +.list-pane { + width: 280px; + padding: 16px; +} + +.pane-title { + font-size: 0.95rem; + color: var(--text-main); + margin-bottom: 16px; + font-weight: 600; +} + +.qq-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.qq-item { + display: flex; + align-items: center; + gap: 12px; + padding: 10px; + border-radius: var(--radius-md); + cursor: pointer; + transition: background 0.2s; + border: 1px solid transparent; +} + +.qq-item:hover { + background: var(--bg-hover); +} + +.qq-item.active { + background: var(--bg-hover); + border-color: var(--border-active); +} + +.qq-avatar { + width: 36px; + height: 36px; + border-radius: 50%; + background: linear-gradient(135deg, var(--color-primary), #818cf8); +} + +.qq-info { + display: flex; + flex-direction: column; +} + +.qq-nik { + font-size: 0.9rem; + font-weight: 500; + color: var(--text-main); +} + +.qq-uin { + font-size: 0.75rem; + color: var(--text-muted); +} + +.editor-pane { + flex: 1; + min-height: 500px; + padding: 32px; +} + +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100%; + color: var(--text-muted); + font-size: 0.9rem; + opacity: 0.7; +} + +.empty-icon { + font-size: 2rem; + margin-bottom: 12px; +} + +.editor-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 32px; + border-bottom: 1px solid var(--border-subtle); + padding-bottom: 16px; +} + +.editor-title h2 { + font-size: 1.25rem; + color: var(--text-main); + margin-bottom: 4px; +} + +.editor-subtitle { + font-size: 0.85rem; + color: var(--text-muted); + font-family: monospace; +} + +.editor-actions { + display: flex; + align-items: center; + gap: 16px; +} + +.save-status { + font-size: 0.85rem; + color: var(--text-muted); +} +.save-status.ok { color: #10b981; } + +.cfg-section { + margin-bottom: 32px; +} + +.cfg-section-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 16px; +} + +.cfg-section-header h4 { + font-size: 1rem; + color: var(--text-main); + font-weight: 600; +} + +.cfg-section-body { + display: flex; + flex-direction: column; + gap: 16px; +} + +.endpoint-row { + display: flex; + align-items: center; + gap: 16px; + background: var(--bg-input); + border: 1px solid var(--border-subtle); + padding: 16px; + border-radius: var(--radius-md); +} + +.input-group { + display: flex; + flex-direction: column; + gap: 8px; + flex: 1; +} + +.input-group label { + font-size: 0.8rem; + color: var(--text-muted); +} + +.input-group input { + background: var(--bg-card); + border: 1px solid var(--border-subtle); + padding: 8px 12px; + border-radius: var(--radius-sm); + color: var(--text-main); + font-family: monospace; + font-size: 0.85rem; + transition: border-color 0.2s; + outline: none; +} + +.input-group input:focus { + border-color: var(--border-focus); +} + +.endpoint-actions { + display: flex; + align-items: center; + margin-top: 24px; +} + +.text-muted { + color: var(--text-muted); + font-size: 0.85rem; +} + +/* Login Screen Override */ +.login-screen { + position: fixed; + inset: 0; + z-index: 1000; + background: var(--bg-body); + display: flex; + justify-content: center; + align-items: center; +} + +.login-card { + width: 380px; + display: flex; + flex-direction: column; + align-items: center; + padding: 40px; +} + +.login-title { + font-size: 1.5rem; + color: var(--text-main); + margin-bottom: 12px; + background: linear-gradient(90deg, var(--color-primary), #818cf8); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; +} + +.login-desc { + font-size: 0.85rem; + color: var(--text-muted); + text-align: center; + margin-bottom: 32px; +} + +.login-form { + width: 100%; + display: flex; + flex-direction: column; + gap: 20px; +} + +.login-submit-btn { + width: 100%; + padding: 10px; +} + +.login-error { + color: var(--color-danger); + font-size: 0.8rem; + text-align: center; +} diff --git a/webui/src/App.scss b/webui/src/App.scss new file mode 100644 index 00000000..1acdf2d7 --- /dev/null +++ b/webui/src/App.scss @@ -0,0 +1,2 @@ +// Token layer only — component styles live in Tailwind classes inside TSX +@use './styles/variables'; diff --git a/webui/src/App.tsx b/webui/src/App.tsx new file mode 100644 index 00000000..185d855b --- /dev/null +++ b/webui/src/App.tsx @@ -0,0 +1,227 @@ +import { useState, useEffect } from 'react'; +import { ThemeProvider } from './contexts/ThemeContext'; +import { MainLayout } from './components/layout/MainLayout'; +import { LoginPage } from './components/pages/LoginPage'; +import { OverviewPage } from './components/pages/OverviewPage'; +import { ConfigPage } from './components/pages/ConfigPage'; +import type { QQInfo, OneBotConfig, HookProcessInfo } from './types'; + +const fetchApi = async (url: string, options: RequestInit = {}) => { + const token = localStorage.getItem('snowluma_token'); + const headers = new Headers(options.headers || {}); + if (token) headers.set('Authorization', `Bearer ${token}`); + return fetch(url, { ...options, headers }); +}; + +function App() { + const [status, setStatus] = useState('连接中'); + const [isAuthenticated, setIsAuthenticated] = useState( + import.meta.env.VITE_SKIP_AUTH === 'true' ? true : null + ); + const [activePage, setActivePage] = useState<'总览' | '配置'>('总览'); + const [qqList, setQqList] = useState([]); + const [processList, setProcessList] = useState([]); + const [processLoadingPid, setProcessLoadingPid] = useState(null); + const [processUnloadingPid, setProcessUnloadingPid] = useState(null); + const [processActionStatus, setProcessActionStatus] = useState(''); + const [selectedUin, setSelectedUin] = useState(null); + const [config, setConfig] = useState(null); + const [saveStatus, setSaveStatus] = useState(''); + + function checkStatus() { + fetchApi('/api/status') + .then(async (res) => { + if (res.status === 401) { setIsAuthenticated(false); setStatus('需要认证'); return; } + if (res.ok) { + setIsAuthenticated(true); + const data = await res.json(); + setStatus(data.status === 'running' ? '已连接' : '已断开'); + fetchQqList(); + fetchProcesses(); + return; + } + // Any other non-ok status (502, 500, etc.) + setIsAuthenticated(false); + setStatus('已断开'); + }) + .catch(() => { setStatus('已断开'); setIsAuthenticated(false); }); + } + + useEffect(() => { + if (import.meta.env.VITE_SKIP_AUTH !== 'true') checkStatus(); + }, []); + + useEffect(() => { + if (isAuthenticated !== true) return; + fetchQqList(); + fetchProcesses(); + const timer = window.setInterval(() => { + fetchQqList(); + fetchProcesses(); + }, 3000); + return () => window.clearInterval(timer); + }, [isAuthenticated]); + + const handleLogin = async (password: string) => { + try { + const res = await fetch('/api/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ password }), + }); + const data = await res.json(); + if (res.ok && data.success) { + localStorage.setItem('snowluma_token', data.token); + setIsAuthenticated(true); + checkStatus(); + return { success: true }; + } + return { success: false, error: '认证失败,请检查控制台日志' }; + } catch { + return { success: false, error: '内部错误,请检查后端运行状态' }; + } + }; + + const handleLogout = () => { + localStorage.removeItem('snowluma_token'); + setIsAuthenticated(false); + setStatus('需要认证'); + setQqList([]); + setProcessList([]); + setConfig(null); + }; + + async function fetchQqList() { + try { + const res = await fetchApi('/api/qq-list'); + if (res.ok) { const data = await res.json(); setQqList(data.list || []); } + } catch (err) { console.error(err); } + } + + async function fetchProcesses() { + try { + const res = await fetchApi('/api/processes'); + if (res.ok) { const data = await res.json(); setProcessList(data.list || []); } + } catch (err) { console.error(err); } + } + + const loadProcess = async (pid: number) => { + setProcessLoadingPid(pid); + setProcessActionStatus('正在手动映射加载 SnowLuma...'); + try { + const res = await fetchApi(`/api/processes/${pid}/load`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + const data = await res.json().catch(() => ({})); + setProcessActionStatus(res.ok && data.success ? '已开始监听登录状态' : data.message || '加载失败'); + await fetchProcesses(); + await fetchQqList(); + } catch { + setProcessActionStatus('网络错误,加载失败'); + } finally { + setProcessLoadingPid(null); + setTimeout(() => setProcessActionStatus(''), 3000); + } + }; + + const unloadProcess = async (pid: number) => { + setProcessUnloadingPid(pid); + setProcessActionStatus('正在卸载 SnowLuma...'); + try { + const res = await fetchApi(`/api/processes/${pid}/unload`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + const data = await res.json().catch(() => ({})); + setProcessActionStatus(res.ok && data.success ? '已卸载 SnowLuma' : data.message || '卸载失败'); + await fetchProcesses(); + await fetchQqList(); + } catch { + setProcessActionStatus('网络错误,卸载失败'); + } finally { + setProcessUnloadingPid(null); + setTimeout(() => setProcessActionStatus(''), 3000); + } + }; + + const loadConfig = async (uin: string) => { + setSelectedUin(uin); + setSaveStatus(''); + setConfig(null); + try { + const res = await fetchApi(`/api/config/${uin}`); + if (res.ok) { const data = await res.json(); setConfig(data.config); } + } catch (err) { console.error(err); } + }; + + const saveConfig = async () => { + if (!selectedUin || !config) return; + setSaveStatus('保存中...'); + try { + const res = await fetchApi(`/api/config/${selectedUin}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(config), + }); + setSaveStatus(res.ok ? '保存成功' : '保存出错'); + setTimeout(() => setSaveStatus(''), 3000); + } catch { + setSaveStatus('网络错误'); + } + }; + + // Loading state + if (isAuthenticated === null) { + return ( +
+
+
+ ); + } + + // Login + if (isAuthenticated === false) { + return ( + + + + ); + } + + // Main app + return ( + + + {activePage === '总览' && ( + + )} + {activePage === '配置' && ( + + )} + + + ); +} + +export default App; diff --git a/webui/src/assets/hero.png b/webui/src/assets/hero.png new file mode 100644 index 00000000..cc51a3d2 Binary files /dev/null and b/webui/src/assets/hero.png differ diff --git a/webui/src/assets/react.svg b/webui/src/assets/react.svg new file mode 100644 index 00000000..6c87de9b --- /dev/null +++ b/webui/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/webui/src/assets/vite.svg b/webui/src/assets/vite.svg new file mode 100644 index 00000000..5101b674 --- /dev/null +++ b/webui/src/assets/vite.svg @@ -0,0 +1 @@ +Vite diff --git a/webui/src/components/layout/MainLayout.tsx b/webui/src/components/layout/MainLayout.tsx new file mode 100644 index 00000000..dfe080f6 --- /dev/null +++ b/webui/src/components/layout/MainLayout.tsx @@ -0,0 +1,250 @@ +import type { ReactNode } from 'react'; +import { motion, AnimatePresence } from 'framer-motion'; +import { Activity, LayoutDashboard, Settings, Sparkles } from 'lucide-react'; +import { Sidebar } from './Sidebar'; +import { useTheme } from '../../contexts/ThemeContext'; + +type Page = '总览' | '配置'; + +interface MainLayoutProps { + activePage: Page; + onNavigate: (page: Page) => void; + status: string; + onLogout: () => void; + children: ReactNode; +} + +const pageMeta: Record = { + '总览': { title: '总览', subtitle: '查看当前接入的 QQ 账号及服务运行状态', badge: '控制台视图', icon: LayoutDashboard }, + '配置': { title: '节点配置', subtitle: '管理 OneBot 协议端点与通信参数', badge: '协议编排', icon: Settings }, +}; + +export function MainLayout({ activePage, onNavigate, status, onLogout, children }: MainLayoutProps) { + const meta = pageMeta[activePage]; + const { resolved } = useTheme(); + const dark = resolved === 'dark'; + const PageIcon = meta.icon; + const runtimeLabel = status === '已连接' ? '运行中' : status; + + return ( +
+ {/* Full-screen ambient gradient — matches login page */} +
+ + {/* Animated orbs */} +
+ + +
+ + {/* Sidebar */} + + + {/* Main content */} +
+
+ {/* Top highlight */} +
+ + {/* Grid texture overlay */} +
+ + {/* Accent glow in corner */} + + +
+ {/* Page header */} + + +
+
+ + + +
+
+ {/* Icon */} +
+ +
+ + {/* Title block */} +
+
+

+ {meta.title} +

+ + + {meta.badge} + +
+

+ {meta.subtitle} +

+
+
+ + + +
+
运行状态
+
{runtimeLabel}
+
+
+
+
+ + + + {/* Page content */} +
+ + + {children} + + + + + © {new Date().getFullYear()} SnowLuma. All rights reserved. + +
+
+
+
+
+ ); +} diff --git a/webui/src/components/layout/Sidebar.tsx b/webui/src/components/layout/Sidebar.tsx new file mode 100644 index 00000000..afcecb82 --- /dev/null +++ b/webui/src/components/layout/Sidebar.tsx @@ -0,0 +1,192 @@ +import { LayoutDashboard, Settings, LogOut, Sun, Moon, Monitor } from 'lucide-react'; +import { Avatar } from '@heroui/react'; +import { StatusBadge } from '../ui/StatusBadge'; +import { motion } from 'framer-motion'; +import { useTheme, type ThemeMode } from '../../contexts/ThemeContext'; + +type Page = '总览' | '配置'; + +interface SidebarProps { + activePage: Page; + onNavigate: (page: Page) => void; + status: string; + onLogout: () => void; +} + +const navItems: { page: Page; label: string; icon: typeof LayoutDashboard }[] = [ + { page: '总览', label: '总览', icon: LayoutDashboard }, + { page: '配置', label: '配置', icon: Settings }, +]; + +const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [ + { mode: 'system', icon: Monitor, label: '跟随系统' }, + { mode: 'light', icon: Sun, label: '浅色' }, + { mode: 'dark', icon: Moon, label: '深色' }, +]; + +export function Sidebar({ activePage, onNavigate, status, onLogout }: SidebarProps) { + const { resolved, mode, setMode } = useTheme(); + const dark = resolved === 'dark'; + + return ( + + ); +} diff --git a/webui/src/components/layout/TopBar.tsx b/webui/src/components/layout/TopBar.tsx new file mode 100644 index 00000000..ad0ff943 --- /dev/null +++ b/webui/src/components/layout/TopBar.tsx @@ -0,0 +1,27 @@ +import { Moon, Sun } from 'lucide-react'; +import { useTheme } from '../../contexts/ThemeContext'; + +interface TopBarProps { + title: string; + subtitle?: string; +} + +export function TopBar({ title, subtitle }: TopBarProps) { + const { resolved, mode, setMode } = useTheme(); + const cycleTheme = () => setMode(mode === 'system' ? 'light' : mode === 'light' ? 'dark' : 'system'); + + return ( +
+
+

{title}

+ {subtitle &&

{subtitle}

} +
+ +
+ ); +} diff --git a/webui/src/components/pages/ConfigPage.tsx b/webui/src/components/pages/ConfigPage.tsx new file mode 100644 index 00000000..eabde66b --- /dev/null +++ b/webui/src/components/pages/ConfigPage.tsx @@ -0,0 +1,205 @@ +import { MousePointerClick } from 'lucide-react'; +import { motion } from 'framer-motion'; +import { SectionCard } from '../ui/SectionCard'; +import { EndpointRow } from '../ui/EndpointRow'; +import { FieldInput } from '../ui/FieldInput'; +import { useTheme } from '../../contexts/ThemeContext'; +import type { QQInfo, OneBotConfig } from '../../types'; + +interface ConfigPageProps { + qqList: QQInfo[]; + selectedUin: string | null; + config: OneBotConfig | null; + saveStatus: string; + onSelectAccount: (uin: string) => void; + onSave: () => void; + onConfigChange: (config: OneBotConfig) => void; +} + +export function ConfigPage({ + qqList, selectedUin, config, saveStatus, + onSelectAccount, onSave, onConfigChange, +}: ConfigPageProps) { + const { resolved } = useTheme(); + const dark = resolved === 'dark'; + + return ( +
+ {/* Account list panel */} +
+
+
+ + 在线连接 + +
+
+ {qqList.length === 0 ? ( +

暂无在线会话

+ ) : qqList.map(q => { + const isActive = selectedUin === q.uin; + return ( + onSelectAccount(q.uin)} + className="w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-left cursor-pointer" + style={{ + background: isActive ? 'var(--accent-subtle)' : 'transparent', + transition: 'var(--transition-fast)', + }} + > +
+ {q.nickname[0]?.toUpperCase() || '?'} +
+
+
+ {q.nickname} +
+
+ {q.uin} +
+
+
+ ); + })} +
+
+
+ + {/* Editor panel */} +
+ {!selectedUin ? ( +
+ +

在左栏选择会话以配置通信节点

+
+ ) : !config ? ( +
+
+
+
+
+ ) : ( +
+ {/* Header */} +
+
+

+ OneBot 协议端点 +

+ + UIN {selectedUin} + +
+
+ {saveStatus && ( + + {saveStatus} + + )} + + 保存设定 + +
+
+ + {/* HTTP Servers */} + { const c = { ...config }; c.httpServers = [...c.httpServers, { port: 3000, host: '0.0.0.0', path: '/' }]; onConfigChange(c); }}> + {config.httpServers.length === 0 ? null : config.httpServers.map((s, idx) => ( + { const c = { ...config }; c.httpServers = c.httpServers.filter((_, i) => i !== idx); onConfigChange(c); }}> + { const c = { ...config }; c.httpServers = c.httpServers.map((item, i) => i === idx ? { ...item, port: v as number } : item); onConfigChange(c); }} /> + { const c = { ...config }; c.httpServers = c.httpServers.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} /> + + ))} + + + {/* HTTP Post */} + { const c = { ...config }; c.httpPostEndpoints = [...c.httpPostEndpoints, { url: 'http://127.0.0.1:5700' }]; onConfigChange(c); }}> + {config.httpPostEndpoints.length === 0 ? null : config.httpPostEndpoints.map((s, idx) => ( + { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.filter((_, i) => i !== idx); onConfigChange(c); }}> + { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.map((item, i) => i === idx ? { ...item, url: v as string } : item); onConfigChange(c); }} /> + { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} /> + + ))} + + + {/* WS Servers */} + { const c = { ...config }; c.wsServers = [...c.wsServers, { port: 3001, host: '0.0.0.0', path: '/' }]; onConfigChange(c); }}> + {config.wsServers.length === 0 ? null : config.wsServers.map((s, idx) => ( + { const c = { ...config }; c.wsServers = c.wsServers.filter((_, i) => i !== idx); onConfigChange(c); }}> + { const c = { ...config }; c.wsServers = c.wsServers.map((item, i) => i === idx ? { ...item, port: v as number } : item); onConfigChange(c); }} /> + { const c = { ...config }; c.wsServers = c.wsServers.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} /> + + ))} + + + {/* WS Clients */} + { const c = { ...config }; c.wsClients = [...c.wsClients, { url: 'ws://127.0.0.1:8080/ws', reconnectIntervalMs: 5000 }]; onConfigChange(c); }}> + {config.wsClients.length === 0 ? null : config.wsClients.map((c2, idx) => ( + { const c = { ...config }; c.wsClients = c.wsClients.filter((_, i) => i !== idx); onConfigChange(c); }}> + { const c = { ...config }; c.wsClients = c.wsClients.map((item, i) => i === idx ? { ...item, url: v as string } : item); onConfigChange(c); }} /> + { const c = { ...config }; c.wsClients = c.wsClients.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} /> + + ))} + + + {/* Music Sign URL */} + {}}> +
+ onConfigChange({ ...config, musicSignUrl: (v as string) || undefined })} /> +
+
+
+ )} +
+
+ ); +} diff --git a/webui/src/components/pages/LoginPage.tsx b/webui/src/components/pages/LoginPage.tsx new file mode 100644 index 00000000..af4717a3 --- /dev/null +++ b/webui/src/components/pages/LoginPage.tsx @@ -0,0 +1,473 @@ +import { useState, useMemo, useRef, useCallback } from 'react'; +import { Avatar } from '@heroui/react'; +import { Sun, Moon, Monitor, Eye, EyeOff, ArrowRight, KeyRound } from 'lucide-react'; +import { motion, AnimatePresence, useMotionValue, useSpring, useTransform } from 'framer-motion'; +import { useTheme, type ThemeMode } from '../../contexts/ThemeContext'; + +interface LoginPageProps { + onLogin: (password: string) => Promise<{ success: boolean; error?: string }>; +} + +const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [ + { mode: 'system', icon: Monitor, label: '跟随系统' }, + { mode: 'light', icon: Sun, label: '浅色' }, + { mode: 'dark', icon: Moon, label: '深色' }, +]; + +const SPARKLES = Array.from({ length: 12 }, (_, i) => ({ + id: i, + x: (i * 31 + 9) % 100, + y: (i * 47 + 13) % 100, + size: 2 + (i % 2), + delay: (i * 0.35) % 4, + duration: 3.5 + (i % 3), +})); + +const BRAND_TAGS = ['OneBot v11', '多账号', '实时面板']; + +export function LoginPage({ onLogin }: LoginPageProps) { + const [password, setPassword] = useState(''); + const [showPwd, setShowPwd] = useState(false); + const [error, setError] = useState(''); + const [loading, setLoading] = useState(false); + const [shakeKey, setShakeKey] = useState(0); + const { mode, resolved, setMode } = useTheme(); + const containerRef = useRef(null); + + const logoSrc = useMemo(() => '/logo.png', []); + + const mouseX = useMotionValue(0); + const mouseY = useMotionValue(0); + const smoothX = useSpring(mouseX, { stiffness: 60, damping: 20 }); + const smoothY = useSpring(mouseY, { stiffness: 60, damping: 20 }); + + const shellRotateX = useTransform(smoothY, [-0.5, 0.5], [4, -4]); + const shellRotateY = useTransform(smoothX, [-0.5, 0.5], [-5, 5]); + + const orb1X = useTransform(smoothX, [-0.5, 0.5], [-45, 45]); + const orb1Y = useTransform(smoothY, [-0.5, 0.5], [-28, 28]); + const orb2X = useTransform(smoothX, [-0.5, 0.5], [35, -35]); + const orb2Y = useTransform(smoothY, [-0.5, 0.5], [30, -30]); + const accentX = useTransform(smoothX, [-0.5, 0.5], [-16, 16]); + const accentY = useTransform(smoothY, [-0.5, 0.5], [-12, 12]); + + const handleMouseMove = useCallback((e: React.MouseEvent) => { + const rect = containerRef.current?.getBoundingClientRect(); + if (!rect) return; + mouseX.set((e.clientX - rect.left) / rect.width - 0.5); + mouseY.set((e.clientY - rect.top) / rect.height - 0.5); + }, [mouseX, mouseY]); + + const handleMouseLeave = useCallback(() => { + mouseX.set(0); + mouseY.set(0); + }, [mouseX, mouseY]); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setError(''); + setLoading(true); + const result = await onLogin(password); + setLoading(false); + if (!result.success && result.error) { + setError(result.error); + setShakeKey(k => k + 1); + } + }; + + const darkMode = resolved === 'dark'; + + return ( +
+
+ +
+ {SPARKLES.map(s => ( + + ))} + + + +
+ + + +
+ +
+ +
+
+ + + +
+
+
+ + +
+
+ + + SL + +
+ + +
+
+ SnowLuma 控制台 +
+

+ SnowLuma +

+
+ + + + 基于 OneBot v11 标准实现的高性能 QQ 协议网关。 + + + + {BRAND_TAGS.map(tag => ( + + {tag} + + ))} + +
+ +
+ + © {new Date().getFullYear()} SnowLuma. All rights reserved. + +
+
+ +
+ + {/* Subtle animated background glow for the card */} + +
+
+
+ 安全登录 +
+ {/*

+ 验证访问令牌 +

*/} +
+
+ {THEME_OPTIONS.map(({ mode: m, icon: Icon, label }) => { + const active = mode === m; + return ( + + ); + })} +
+
+ + + 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}} + transition={{ duration: 0.45, ease: 'easeInOut' }} + > +
+
+ +
+ setPassword(e.target.value)} + autoFocus + className="h-full w-full bg-transparent text-sm font-medium outline-none placeholder:font-normal" + style={{ + color: 'var(--text-primary)', + }} + onFocus={e => { + const icon = e.target.previousElementSibling as HTMLElement; + if (icon) icon.style.color = 'var(--accent)'; + }} + onBlur={e => { + const icon = e.target.previousElementSibling as HTMLElement; + if (icon) icon.style.color = 'var(--text-tertiary)'; + }} + /> +
+ +
+ + + {error && ( + + {error} + + )} + + + + + {loading ? ( + <> + + 验证中… + + ) : ( + <> + 进入控制台 + + + )} + + +
+
+
+
+
+
+
+
+ ); +} + diff --git a/webui/src/components/pages/OverviewPage.tsx b/webui/src/components/pages/OverviewPage.tsx new file mode 100644 index 00000000..8830ed6d --- /dev/null +++ b/webui/src/components/pages/OverviewPage.tsx @@ -0,0 +1,298 @@ +import { Users, Activity, Cpu, RefreshCw, Loader2, CheckCircle2, AlertCircle, Unplug } from 'lucide-react'; +import { motion } from 'framer-motion'; +import { StatCard } from '../ui/StatCard'; +import { useTheme } from '../../contexts/ThemeContext'; +import type { QQInfo, HookProcessInfo } from '../../types'; + +interface OverviewPageProps { + qqList: QQInfo[]; + status: string; + processList: HookProcessInfo[]; + processLoadingPid: number | null; + processUnloadingPid: number | null; + processActionStatus: string; + onRefreshProcesses: () => void; + onLoadProcess: (pid: number) => void; + onUnloadProcess: (pid: number) => void; +} + +const processStatusLabel: Record = { + available: '可加载', + loading: '加载中', + loaded: '等待登录', + online: '已在线', + error: '错误', + disconnected: '已断开', +}; + +function processStatusColor(status: HookProcessInfo['status']): string { + if (status === 'online') return 'var(--color-success)'; + if (status === 'error' || status === 'disconnected') return 'var(--color-danger)'; + if (status === 'loading' || status === 'loaded') return 'var(--accent)'; + return 'var(--text-secondary)'; +} + +export function OverviewPage({ + qqList, + status, + processList, + processLoadingPid, + processUnloadingPid, + processActionStatus, + onRefreshProcesses, + onLoadProcess, + onUnloadProcess, +}: OverviewPageProps) { + const { resolved } = useTheme(); + const dark = resolved === 'dark'; + + return ( +
+ {/* Stat cards */} +
+ } + /> + } + accent={status === '已连接' ? 'success' : 'danger'} + /> +
+ + +
+
+
+ +
+
+

+ 选择 QQ 进程 +

+

+ 加载 SnowLuma 后会监听登录状态,登录成功后自动接入原有 OneBot 流程 +

+
+
+ +
+ + {processActionStatus && ( +
+ {processActionStatus} +
+ )} + + {processList.length > 0 ? ( +
+ {processList.map((proc, idx) => { + const loading = processLoadingPid === proc.pid || proc.status === 'loading'; + const unloading = processUnloadingPid === proc.pid; + const busy = loading || unloading; + const online = proc.status === 'online'; + const canUnload = proc.injected || proc.status === 'loaded' || online || proc.status === 'disconnected'; + const disabled = busy; + const actionLabel = canUnload + ? unloading ? '卸载中' : '卸载' + : loading ? '加载中' : '加载'; + const action = canUnload ? () => onUnloadProcess(proc.pid) : () => onLoadProcess(proc.pid); + return ( + +
+ {online ? : proc.status === 'error' ? : } +
+
+
+ + {proc.name || 'QQ.exe'} + + + {processStatusLabel[proc.status]} + +
+
+ PID {proc.pid}{proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''} +
+ {proc.path && ( +
+ {proc.path} +
+ )} + {proc.error && ( +
+ {proc.error} +
+ )} +
+ +
+ ); + })} +
+ ) : ( +
+ +

未检测到可加载 QQ 主进程

+
+ )} +
+ + {/* Account list */} + {qqList.length > 0 && ( + +

+ 在线会话 +

+
+ {qqList.map((q, idx) => ( + +
+ {q.nickname[0]?.toUpperCase() || '?'} +
+
+
+ {q.nickname} +
+
+ {q.uin} +
+
+ +
+ ))} +
+
+ )} + + {qqList.length === 0 && ( + + +

暂无在线会话

+
+ )} +
+ ); +} diff --git a/webui/src/components/ui/EndpointRow.tsx b/webui/src/components/ui/EndpointRow.tsx new file mode 100644 index 00000000..c890b5a3 --- /dev/null +++ b/webui/src/components/ui/EndpointRow.tsx @@ -0,0 +1,30 @@ +import type { ReactNode } from 'react'; +import { X } from 'lucide-react'; +import { motion } from 'framer-motion'; + +interface EndpointRowProps { + onRemove: () => void; + children: ReactNode; +} + +export function EndpointRow({ onRemove, children }: EndpointRowProps) { + return ( +
+ {children} + { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.background = 'rgba(248,113,113,0.08)'; }} + onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-tertiary)'; e.currentTarget.style.background = 'transparent'; }} + > + + +
+ ); +} diff --git a/webui/src/components/ui/FieldInput.tsx b/webui/src/components/ui/FieldInput.tsx new file mode 100644 index 00000000..d843d88d --- /dev/null +++ b/webui/src/components/ui/FieldInput.tsx @@ -0,0 +1,34 @@ +interface FieldInputProps { + label: string; + placeholder?: string; + value?: string | number; + isNum?: boolean; + flex?: string; + grow?: boolean; + onChange: (v: string | number) => void; +} + +export function FieldInput({ label, placeholder, value, isNum, flex, grow, onChange }: FieldInputProps) { + return ( +
+ + onChange(isNum ? (parseInt(e.target.value) || 0) : e.target.value)} + className="h-9 px-3 rounded-lg text-sm outline-none" + style={{ + background: 'rgba(0,0,0,0.12)', + border: '1px solid var(--border-subtle)', + boxShadow: 'inset 0 2px 4px rgba(0,0,0,0.05)', + color: 'var(--text-primary)', + transition: 'all 0.3s ease', + ...(isNum ? { fontVariantNumeric: 'tabular-nums', fontFamily: 'var(--font-mono, monospace)' } : {}), + }} + onFocus={e => { e.target.style.borderColor = 'var(--border-focus)'; e.target.style.boxShadow = '0 0 0 2px var(--accent-subtle)'; }} + onBlur={e => { e.target.style.borderColor = 'var(--border-subtle)'; e.target.style.boxShadow = 'inset 0 2px 4px rgba(0,0,0,0.05)'; }} + /> +
+ ); +} diff --git a/webui/src/components/ui/SectionCard.tsx b/webui/src/components/ui/SectionCard.tsx new file mode 100644 index 00000000..bec05654 --- /dev/null +++ b/webui/src/components/ui/SectionCard.tsx @@ -0,0 +1,55 @@ +import type { ReactNode } from 'react'; +import { Plus } from 'lucide-react'; +import { motion } from 'framer-motion'; +import { useTheme } from '../../contexts/ThemeContext'; + +interface SectionCardProps { + title: string; + onAdd: () => void; + children: ReactNode; +} + +export function SectionCard({ title, onAdd, children }: SectionCardProps) { + const { resolved } = useTheme(); + const dark = resolved === 'dark'; + return ( +
+ {/* Header */} +
+

{title}

+ + + +
+ + {/* Body */} +
+ {!children ? ( +

未配置,点击 + 新增

+ ) : children} +
+
+ ); +} diff --git a/webui/src/components/ui/StatCard.tsx b/webui/src/components/ui/StatCard.tsx new file mode 100644 index 00000000..a6657a93 --- /dev/null +++ b/webui/src/components/ui/StatCard.tsx @@ -0,0 +1,61 @@ +import type { ReactNode } from 'react'; +import { motion } from 'framer-motion'; +import { useTheme } from '../../contexts/ThemeContext'; + +interface StatCardProps { + label: string; + value: string; + icon?: ReactNode; + accent?: 'default' | 'success' | 'warning' | 'danger'; +} + +const accentColors: Record = { + default: { icon: 'var(--accent)', value: 'var(--text-primary)', glow: 'var(--accent-glow)' }, + success: { icon: 'var(--color-success)', value: 'var(--color-success)', glow: 'rgba(52,211,153,0.1)' }, + warning: { icon: 'var(--color-warning)', value: 'var(--color-warning)', glow: 'rgba(251,191,36,0.1)' }, + danger: { icon: 'var(--color-danger)', value: 'var(--color-danger)', glow: 'rgba(248,113,113,0.1)' }, +}; + +export function StatCard({ label, value, icon, accent = 'default' }: StatCardProps) { + const colors = accentColors[accent]; + const { resolved } = useTheme(); + const dark = resolved === 'dark'; + return ( + +
+ + {label} + + {icon && ( +
+ {icon} +
+ )} +
+
+ {value} +
+
+ ); +} diff --git a/webui/src/components/ui/StatusBadge.tsx b/webui/src/components/ui/StatusBadge.tsx new file mode 100644 index 00000000..213351bd --- /dev/null +++ b/webui/src/components/ui/StatusBadge.tsx @@ -0,0 +1,27 @@ +interface StatusBadgeProps { + status: string; +} + +export function StatusBadge({ status }: StatusBadgeProps) { + const isOnline = status === '已连接'; + const isConnecting = status === '连接中'; + + const dotColor = isOnline + ? 'var(--color-success)' + : isConnecting + ? 'var(--color-warning)' + : 'var(--text-tertiary)'; + + return ( + + + {status} + + ); +} diff --git a/webui/src/contexts/ThemeContext.tsx b/webui/src/contexts/ThemeContext.tsx new file mode 100644 index 00000000..f43de1ec --- /dev/null +++ b/webui/src/contexts/ThemeContext.tsx @@ -0,0 +1,58 @@ +import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; + +export type ThemeMode = 'light' | 'dark' | 'system'; + +interface ThemeContextValue { + mode: ThemeMode; + resolved: 'light' | 'dark'; + setMode: (mode: ThemeMode) => void; +} + +const ThemeContext = createContext(null); + +function getSystemTheme(): 'light' | 'dark' { + return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; +} + +export function ThemeProvider({ children }: { children: ReactNode }) { + const [mode, setModeState] = useState(() => { + const saved = localStorage.getItem('snowluma_theme') as ThemeMode | null; + if (saved === 'light' || saved === 'dark' || saved === 'system') return saved; + return 'system'; + }); + + const [systemTheme, setSystemTheme] = useState<'light' | 'dark'>(getSystemTheme); + + useEffect(() => { + const mq = window.matchMedia('(prefers-color-scheme: dark)'); + const handler = (e: MediaQueryListEvent) => setSystemTheme(e.matches ? 'dark' : 'light'); + mq.addEventListener('change', handler); + return () => mq.removeEventListener('change', handler); + }, []); + + const resolved: 'light' | 'dark' = mode === 'system' ? systemTheme : mode; + + useEffect(() => { + const root = document.documentElement; + root.className = resolved; + root.setAttribute('data-theme', resolved); + root.style.colorScheme = resolved; + }, [resolved]); + + const setMode = (m: ThemeMode) => { + setModeState(m); + localStorage.setItem('snowluma_theme', m); + }; + + return ( + + {children} + + ); +} + +export function useTheme() { + const ctx = useContext(ThemeContext); + if (!ctx) throw new Error('useTheme must be used within ThemeProvider'); + return ctx; +} diff --git a/webui/src/index.css b/webui/src/index.css new file mode 100644 index 00000000..d7847312 --- /dev/null +++ b/webui/src/index.css @@ -0,0 +1,78 @@ +@import "tailwindcss"; + +/* ── Global Reset & Base ── */ +:root { + color-scheme: light dark; +} + +/* ── HeroUI Avatar base ── */ +.avatar { + position: relative; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + border-radius: 9999px; + flex-shrink: 0; +} +.avatar__image { + width: 100%; + height: 100%; + object-fit: cover; + aspect-ratio: 1 / 1; +} +.avatar__fallback { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; +} + +body { + margin: 0; + width: 100vw; + height: 100vh; + overflow: hidden; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + font-family: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif; + line-height: 1.5; + color: var(--text-primary); + background-color: var(--bg-body); + transition: background-color 0.3s ease, color 0.3s ease; +} + +#root { + width: 100%; + height: 100%; +} + +* { + box-sizing: border-box; +} + +h1, h2, h3, h4, p { + margin: 0; +} + +/* ── Scrollbar ── */ +::-webkit-scrollbar { + width: 6px; +} +::-webkit-scrollbar-track { + background: transparent; +} +::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.08); + border-radius: 3px; +} +::-webkit-scrollbar-thumb:hover { + background: rgba(255, 255, 255, 0.15); +} + +/* ── Selection ── */ +::selection { + background: rgba(56, 189, 248, 0.25); + color: #f1f5f9; +} \ No newline at end of file diff --git a/webui/src/main.tsx b/webui/src/main.tsx new file mode 100644 index 00000000..0c272fdc --- /dev/null +++ b/webui/src/main.tsx @@ -0,0 +1,11 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import './index.css' +import './App.scss' +import App from './App.tsx' + +createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/webui/src/styles/_mixins.scss b/webui/src/styles/_mixins.scss new file mode 100644 index 00000000..075ff219 --- /dev/null +++ b/webui/src/styles/_mixins.scss @@ -0,0 +1,30 @@ +// Responsive breakpoint mixins +@mixin sm { + @media (min-width: 640px) { @content; } +} + +@mixin md { + @media (min-width: 768px) { @content; } +} + +@mixin lg { + @media (min-width: 1024px) { @content; } +} + +// Flex shortcuts +@mixin flex-center { + display: flex; + align-items: center; + justify-content: center; +} + +@mixin flex-between { + display: flex; + align-items: center; + justify-content: space-between; +} + +@mixin flex-col { + display: flex; + flex-direction: column; +} diff --git a/webui/src/styles/_variables.scss b/webui/src/styles/_variables.scss new file mode 100644 index 00000000..cac6bdfa --- /dev/null +++ b/webui/src/styles/_variables.scss @@ -0,0 +1,103 @@ +// SnowLuma – Refined dark-first glassmorphism design system +// Palette: deep navy base, cool slate surfaces, cyan/indigo accent pair + +:root { + // Typography + --font-sans: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif; + --font-mono: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', ui-monospace, monospace; + + // Radii + --radius-xs: 6px; + --radius-sm: 8px; + --radius-md: 12px; + --radius-lg: 16px; + --radius-xl: 20px; + --radius-2xl: 24px; + --radius-full: 9999px; + + // Transitions + --transition-fast: all 0.15s cubic-bezier(0.4, 0, 0.2, 1); + --transition-base: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); + --transition-smooth: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +// Dark theme (default) +:root, +[data-theme='dark'], +.dark { + --bg-body: #080b12; + --bg-surface: rgba(15, 19, 28, 0.85); + --bg-card: rgba(20, 26, 38, 0.7); + --bg-card-hover: rgba(28, 35, 50, 0.8); + --bg-input: rgba(12, 16, 24, 0.8); + --bg-hover: rgba(99, 179, 237, 0.06); + --bg-active: rgba(99, 179, 237, 0.12); + + --border-subtle: rgba(255, 255, 255, 0.06); + --border-medium: rgba(255, 255, 255, 0.1); + --border-focus: rgba(56, 189, 248, 0.5); + + --text-primary: #f1f5f9; + --text-secondary: #94a3b8; + --text-tertiary: #475569; + --text-accent: #7dd3fc; + + --accent: #38bdf8; + --accent-hover: #7dd3fc; + --accent-subtle: rgba(56, 189, 248, 0.1); + --accent-glow: rgba(56, 189, 248, 0.15); + + --color-success: #34d399; + --color-warning: #fbbf24; + --color-danger: #f87171; + + --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.3); + --shadow-md: 0 8px 32px rgba(0, 0, 0, 0.4); + --shadow-lg: 0 24px 64px rgba(0, 0, 0, 0.5); + --shadow-glow: 0 0 40px rgba(56, 189, 248, 0.08); + --shadow-focus: 0 0 0 3px rgba(56, 189, 248, 0.2); + + --glass-bg: rgba(15, 19, 28, 0.75); + --glass-border: rgba(255, 255, 255, 0.08); + --glass-highlight: rgba(255, 255, 255, 0.04); +} + +// Light theme +[data-theme='light'], +.light { + --bg-body: #f8fafc; + --bg-surface: rgba(255, 255, 255, 0.85); + --bg-card: rgba(255, 255, 255, 0.9); + --bg-card-hover: rgba(248, 250, 252, 1); + --bg-input: rgba(241, 245, 249, 0.9); + --bg-hover: rgba(14, 165, 233, 0.05); + --bg-active: rgba(14, 165, 233, 0.1); + + --border-subtle: rgba(0, 0, 0, 0.06); + --border-medium: rgba(0, 0, 0, 0.1); + --border-focus: rgba(14, 165, 233, 0.5); + + --text-primary: #0f172a; + --text-secondary: #64748b; + --text-tertiary: #94a3b8; + --text-accent: #0284c7; + + --accent: #0ea5e9; + --accent-hover: #0284c7; + --accent-subtle: rgba(14, 165, 233, 0.08); + --accent-glow: rgba(14, 165, 233, 0.1); + + --color-success: #10b981; + --color-warning: #f59e0b; + --color-danger: #ef4444; + + --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.05); + --shadow-md: 0 8px 24px rgba(0, 0, 0, 0.08); + --shadow-lg: 0 16px 48px rgba(0, 0, 0, 0.1); + --shadow-glow: 0 0 40px rgba(14, 165, 233, 0.05); + --shadow-focus: 0 0 0 3px rgba(14, 165, 233, 0.15); + + --glass-bg: rgba(255, 255, 255, 0.8); + --glass-border: rgba(255, 255, 255, 0.6); + --glass-highlight: rgba(255, 255, 255, 0.5); +} diff --git a/webui/src/styles/components/_config.scss b/webui/src/styles/components/_config.scss new file mode 100644 index 00000000..dc691e4a --- /dev/null +++ b/webui/src/styles/components/_config.scss @@ -0,0 +1,402 @@ +// Config styles — now handled via Tailwind + CSS vars in components + + &.active { + background: var(--color-primary-subtle); + border-color: var(--border-focus); + + .qq-nik { + color: var(--color-primary); + } + } +} + +.qq-avatar { + width: 38px; + height: 38px; + border-radius: 50%; + background: linear-gradient(135deg, var(--color-primary) 0%, #818cf8 100%); + flex-shrink: 0; + box-shadow: 0 2px 8px rgba(14, 165, 233, 0.28); +} + +.qq-info { + @include flex-col; + gap: 2px; +} + +.qq-nik { + font-size: 0.875rem; + font-weight: 600; + color: var(--text-main); + transition: color 0.15s; +} + +.qq-uin { + font-size: 0.72rem; + color: var(--text-muted); + font-family: var(--font-mono); +} + +// ---- Editor Pane ---- +.editor-pane { + flex: 1; + min-height: 500px; + padding: 28px !important; + border-radius: var(--radius-lg) !important; +} + +.empty-state { + @include flex-col; + @include flex-center; + height: 100%; + min-height: 380px; + color: var(--text-muted); + font-size: 0.875rem; + opacity: 0.5; + gap: 14px; +} + +.editor-header { + @include flex-between; + align-items: flex-start; + margin-bottom: 24px; + padding-bottom: 20px; + border-bottom: 1px solid var(--border-subtle); +} + +.editor-title { + h2 { + font-size: 1.1rem; + font-weight: 700; + color: var(--text-main); + margin-bottom: 6px; + letter-spacing: -0.01em; + } +} + +.editor-subtitle { + font-size: 0.75rem; + color: var(--text-muted); + font-family: var(--font-mono); + background: var(--bg-input); + border: 1px solid var(--border-subtle); + padding: 2px 8px; + border-radius: var(--radius-xs); + display: inline-block; +} + +.editor-actions { + display: flex; + align-items: center; + gap: 12px; +} + +.save-status { + font-size: 0.8rem; + color: var(--text-muted); + padding: 4px 10px; + border-radius: var(--radius-xs); + background: var(--bg-input); + + &.ok { + color: var(--color-success); + background: rgba(16, 185, 129, 0.1); + } +} + +// ---- Config Sections ---- +.editor-sections { + @include flex-col; + gap: 10px; +} + +.cfg-section { + border-radius: var(--radius-md); + overflow: hidden; + border: 1px solid var(--border-subtle); + background: var(--bg-card); +} + +.cfg-section-header { + @include flex-between; + padding: 13px 18px; + background: var(--bg-input); + border-bottom: 1px solid var(--border-subtle); + + h4 { + font-size: 0.85rem; + color: var(--text-main); + font-weight: 600; + } +} + +.cfg-section-body { + @include flex-col; + gap: 0; + + .text-muted { + padding: 16px 18px; + font-size: 0.82rem; + } +} + +.endpoint-row { + display: flex; + align-items: flex-end; + gap: 12px; + padding: 14px 18px; + border-top: 1px solid var(--border-subtle); + transition: background 0.15s; + + &:hover { + background: var(--bg-hover); + } +} + +.endpoint-actions { + display: flex; + align-items: center; + padding-bottom: 1px; +} + +.input-group { + @include flex-col; + gap: 6px; + flex: 1; + + label { + font-size: 0.73rem; + color: var(--text-muted); + font-weight: 600; + letter-spacing: 0.03em; + text-transform: uppercase; + } + + input { + background: var(--bg-input); + border: 1.5px solid var(--border-subtle); + padding: 8px 12px; + border-radius: var(--radius-sm); + color: var(--text-main); + font-family: var(--font-sans); + font-size: 0.85rem; + transition: var(--transition-fast); + outline: none; + width: 100%; + + &::placeholder { + color: var(--text-placeholder); + } + + &:focus { + border-color: var(--border-focus); + box-shadow: var(--shadow-focus); + background: var(--bg-card-solid); + } + + &[type='number'] { + font-family: var(--font-mono); + } + } +} + + +.card-label { + font-size: 0.85rem; + color: var(--text-muted); +} + +.card-value { + font-size: 2rem; + font-weight: 600; + color: var(--text-main); + + &.status-ok { + color: #10b981; + } +} + +// ---- Config Layout ---- +.config-layout { + display: flex; + gap: 24px; + align-items: flex-start; +} + +.list-pane { + width: 280px; + padding: 16px; +} + +.pane-title { + font-size: 0.95rem; + color: var(--text-main); + margin-bottom: 16px; + font-weight: 600; +} + +.qq-list { + @include flex-col; + gap: 8px; +} + +.qq-item { + display: flex; + align-items: center; + gap: 12px; + padding: 10px; + border-radius: var(--radius-md); + cursor: pointer; + transition: background 0.2s; + border: 1px solid transparent; + + &:hover { + background: var(--bg-hover); + } + + &.active { + background: var(--bg-hover); + border-color: var(--border-active); + } +} + +.qq-avatar { + width: 36px; + height: 36px; + border-radius: 50%; + background: linear-gradient(135deg, var(--color-primary), #818cf8); + flex-shrink: 0; +} + +.qq-info { + @include flex-col; +} + +.qq-nik { + font-size: 0.9rem; + font-weight: 500; + color: var(--text-main); +} + +.qq-uin { + font-size: 0.75rem; + color: var(--text-muted); +} + +// ---- Editor Pane ---- +.editor-pane { + flex: 1; + min-height: 500px; + padding: 32px; +} + +.empty-state { + @include flex-col; + @include flex-center; + height: 100%; + color: var(--text-muted); + font-size: 0.9rem; + opacity: 0.7; + gap: 12px; +} + +.editor-header { + @include flex-between; + align-items: flex-start; + margin-bottom: 32px; + border-bottom: 1px solid var(--border-subtle); + padding-bottom: 16px; +} + +.editor-title { + h2 { + font-size: 1.25rem; + color: var(--text-main); + margin-bottom: 4px; + } +} + +.editor-subtitle { + font-size: 0.85rem; + color: var(--text-muted); + font-family: monospace; +} + +.editor-actions { + display: flex; + align-items: center; + gap: 16px; +} + +.save-status { + font-size: 0.85rem; + color: var(--text-muted); + + &.ok { + color: #10b981; + } +} + +// ---- Config Sections ---- +.cfg-section { + margin-bottom: 32px; +} + +.cfg-section-header { + @include flex-between; + margin-bottom: 16px; + + h4 { + font-size: 1rem; + color: var(--text-main); + font-weight: 600; + } +} + +.cfg-section-body { + @include flex-col; + gap: 16px; +} + +.endpoint-row { + display: flex; + align-items: center; + gap: 16px; + background: var(--bg-input); + border: 1px solid var(--border-subtle); + padding: 16px; + border-radius: var(--radius-md); +} + +.endpoint-actions { + display: flex; + align-items: center; + margin-top: 24px; +} + +.input-group { + @include flex-col; + gap: 8px; + flex: 1; + + label { + font-size: 0.8rem; + color: var(--text-muted); + } + + input { + background: var(--bg-card); + border: 1px solid var(--border-subtle); + padding: 8px 12px; + border-radius: var(--radius-sm); + color: var(--text-main); + font-family: monospace; + font-size: 0.85rem; + transition: border-color 0.2s; + outline: none; + + &:focus { + border-color: var(--border-focus); + } + } +} diff --git a/webui/src/styles/components/_layout.scss b/webui/src/styles/components/_layout.scss new file mode 100644 index 00000000..9a64a77b --- /dev/null +++ b/webui/src/styles/components/_layout.scss @@ -0,0 +1,61 @@ +// Layout styles — now handled via Tailwind + CSS vars in components + +.sidebar-footer { + padding: 12px; + border-top: 1px solid var(--border-subtle); + @include flex-col; + gap: 4px; +} + +// ---- Main Content ---- +.content { + flex: 1; + @include flex-col; + overflow: hidden; + min-width: 0; +} + +.header { + height: 64px; + flex-shrink: 0; + @include flex-between; + padding: 0 32px; + background: var(--glass-bg); + backdrop-filter: var(--glass-blur); + -webkit-backdrop-filter: var(--glass-blur); + border-bottom: 1px solid var(--glass-border); + box-shadow: var(--shadow-xs); + z-index: 5; +} + +.header-right { + @include flex-center; + gap: 8px; + font-size: 0.8rem; + color: var(--text-muted); + font-weight: 500; + letter-spacing: 0.01em; +} + +.main-scroll { + flex: 1; + overflow-y: auto; + padding: 28px 32px; + + &::-webkit-scrollbar { + width: 5px; + } + + &::-webkit-scrollbar-track { + background: transparent; + } + + &::-webkit-scrollbar-thumb { + background: var(--border-subtle); + border-radius: var(--radius-full); + + &:hover { + background: var(--text-muted); + } + } +} diff --git a/webui/src/styles/components/_shared.scss b/webui/src/styles/components/_shared.scss new file mode 100644 index 00000000..cd1a3cf2 --- /dev/null +++ b/webui/src/styles/components/_shared.scss @@ -0,0 +1,264 @@ +// Shared styles — now handled via Tailwind + CSS vars in components + color: #fff; + box-shadow: 0 2px 8px rgba(14, 165, 233, 0.28); + + &:hover { + background: var(--color-primary-hover); + box-shadow: 0 4px 16px rgba(14, 165, 233, 0.38); + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } +} + +.btn-ghost { + background: transparent; + color: var(--text-muted); + border-radius: var(--radius-md); + + &:hover { + background: var(--bg-hover); + color: var(--text-main); + } +} + +.btn-outline { + background: transparent; + border-color: var(--border-subtle); + color: var(--text-muted); + + &:hover { + background: var(--bg-hover); + color: var(--text-main); + border-color: var(--border-active); + } +} + +.btn-danger { + background: transparent; + border-color: var(--border-subtle); + color: var(--color-danger); + border-radius: var(--radius-sm); + + &:hover { + background: var(--color-danger); + border-color: var(--color-danger); + color: #fff; + box-shadow: 0 2px 8px rgba(239, 68, 68, 0.28); + } +} + +.btn-icon { + padding: 4px; + width: 28px; + height: 28px; +} + +// ---- Login Screen ---- +.login-screen { + position: fixed; + inset: 0; + z-index: 1000; + background: var(--bg-body); + background-image: var(--glass-body-gradient); + @include flex-center; +} + +.login-card { + width: 400px; + @include flex-col; + align-items: center; + padding: 48px 40px; + border-radius: var(--radius-xl); + background: var(--bg-card); + backdrop-filter: blur(20px) saturate(1.8); + -webkit-backdrop-filter: blur(20px) saturate(1.8); + border: 1px solid var(--glass-border); + box-shadow: var(--shadow-lg); +} + +.login-title { + font-size: 1.6rem; + font-weight: 700; + letter-spacing: -0.02em; + margin-bottom: 10px; + background: linear-gradient(135deg, var(--color-primary) 0%, #818cf8 100%); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; +} + +.login-desc { + font-size: 0.83rem; + color: var(--text-muted); + text-align: center; + line-height: 1.65; + margin-bottom: 32px; +} + +.login-form { + width: 100%; + @include flex-col; + gap: 16px; +} + +.login-submit-btn { + width: 100%; + padding: 10px; +} + +.login-error { + color: var(--color-danger); + font-size: 0.8rem; + text-align: center; + padding: 8px 12px; + background: rgba(239, 68, 68, 0.08); + border-radius: var(--radius-sm); +} + + +// Search input (header) +.search-input { + background: var(--bg-input); + border: 1px solid var(--border-subtle); + padding: 8px 14px; + border-radius: var(--radius-sm); + color: var(--text-main); + width: 260px; + font-size: 0.85rem; + transition: border-color 0.2s; + outline: none; + + &:focus { + border-color: var(--color-primary); + } +} + +// Generic card +.card { + background: var(--bg-card); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); + padding: 24px; +} + +// Muted helper +.text-muted { + color: var(--text-muted); + font-size: 0.85rem; +} + +// ---- Shared Button System ---- +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + padding: 8px 16px; + border-radius: var(--radius-md); + font-size: 0.85rem; + font-weight: 500; + cursor: pointer; + border: 1px solid transparent; + transition: all 0.2s; + outline: none; + font-family: inherit; +} + +.btn-primary { + background: var(--color-primary); + color: #fff; + + &:hover { background: var(--color-primary-hover); } +} + +.btn-ghost { + background: transparent; + color: var(--text-muted); + + &:hover { + background: var(--bg-hover); + color: var(--text-main); + } +} + +.btn-outline { + background: transparent; + border-color: var(--border-subtle); + color: var(--text-muted); + + &:hover { + background: var(--bg-hover); + color: var(--text-main); + } +} + +.btn-danger { + background: transparent; + border-color: var(--border-subtle); + color: var(--color-danger); + + &:hover { + background: var(--color-danger); + border-color: var(--color-danger); + color: #fff; + } +} + +.btn-icon { + padding: 4px; + width: 28px; + height: 28px; +} + +// ---- Login Screen ---- +.login-screen { + position: fixed; + inset: 0; + z-index: 1000; + background: var(--bg-body); + @include flex-center; +} + +.login-card { + width: 380px; + @include flex-col; + align-items: center; + padding: 40px; +} + +.login-title { + font-size: 1.5rem; + margin-bottom: 12px; + background: linear-gradient(90deg, var(--color-primary), #818cf8); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; +} + +.login-desc { + font-size: 0.85rem; + color: var(--text-muted); + text-align: center; + margin-bottom: 32px; +} + +.login-form { + width: 100%; + @include flex-col; + gap: 20px; +} + +.login-submit-btn { + width: 100%; + padding: 10px; +} + +.login-error { + color: var(--color-danger); + font-size: 0.8rem; + text-align: center; +} diff --git a/webui/src/styles/index.scss b/webui/src/styles/index.scss new file mode 100644 index 00000000..b51f69e0 --- /dev/null +++ b/webui/src/styles/index.scss @@ -0,0 +1,5 @@ +@use 'variables'; +@use 'mixins'; +@use 'components/layout'; +@use 'components/config'; +@use 'components/shared'; diff --git a/webui/src/types.ts b/webui/src/types.ts new file mode 100644 index 00000000..90702fdb --- /dev/null +++ b/webui/src/types.ts @@ -0,0 +1,57 @@ +export interface QQInfo { + uin: string; + nickname: string; +} + +export interface HookProcessInfo { + pid: number; + name: string; + path: string; + injected: boolean; + connected: boolean; + loggedIn: boolean; + uin: string; + status: 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected'; + error: string; + method: string; +} + +export interface HttpServerEndpoint { + name?: string; + host?: string; + port?: number; + path?: string; + accessToken?: string; +} + +export interface WsServerEndpoint { + name?: string; + host?: string; + port?: number; + path?: string; + role?: string; + accessToken?: string; +} + +export interface WsClientEndpoint { + name?: string; + url?: string; + role?: string; + reconnectIntervalMs?: number; + accessToken?: string; +} + +export interface HttpPostEndpoint { + name?: string; + url?: string; + accessToken?: string; + timeoutMs?: number; +} + +export interface OneBotConfig { + httpServers: HttpServerEndpoint[]; + httpPostEndpoints: HttpPostEndpoint[]; + wsServers: WsServerEndpoint[]; + wsClients: WsClientEndpoint[]; + musicSignUrl?: string; +} diff --git a/webui/tsconfig.app.json b/webui/tsconfig.app.json new file mode 100644 index 00000000..1d29c885 --- /dev/null +++ b/webui/tsconfig.app.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "esnext", + "types": ["vite/client"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"] +} diff --git a/webui/tsconfig.json b/webui/tsconfig.json new file mode 100644 index 00000000..1ffef600 --- /dev/null +++ b/webui/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/webui/tsconfig.node.json b/webui/tsconfig.node.json new file mode 100644 index 00000000..d3c52ea6 --- /dev/null +++ b/webui/tsconfig.node.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023"], + "module": "esnext", + "types": ["node"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["vite.config.ts"] +} diff --git a/webui/vite.config.ts b/webui/vite.config.ts new file mode 100644 index 00000000..4b527e8d --- /dev/null +++ b/webui/vite.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; +import tailwindcss from '@tailwindcss/vite'; + +export default defineConfig({ + plugins: [tailwindcss(), react()], + server: { + proxy: { + '/api': { + target: 'http://localhost:8080', + changeOrigin: true, + }, + }, + }, + build: { + outDir: '../dist/client', + emptyOutDir: true + } +});