Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f04ec3ec36 | ||
|
|
82c1721466 | ||
|
|
df73f58598 | ||
|
|
b6341145be | ||
|
|
8ca616ec3a | ||
|
|
252a65b833 | ||
|
|
5fb969da7c | ||
|
|
39f1672b29 | ||
|
|
6bba36bba6 | ||
|
|
02326b0968 | ||
|
|
bd40af2517 | ||
|
|
ac1ddee54e |
71
.github/workflows/dev-build.yml
vendored
71
.github/workflows/dev-build.yml
vendored
@@ -8,21 +8,11 @@ on:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
cleanup:
|
||||
runs-on: ubuntu-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
|
||||
@@ -48,6 +38,25 @@ jobs:
|
||||
page++;
|
||||
}
|
||||
|
||||
build:
|
||||
needs: cleanup
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- name: win-x64
|
||||
os: windows-latest
|
||||
target: win32-x64
|
||||
- name: linux-x64
|
||||
os: ubuntu-latest
|
||||
target: linux-x64
|
||||
- name: linux-arm64
|
||||
os: ubuntu-24.04-arm
|
||||
target: linux-arm64
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -66,29 +75,43 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||
- 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" }
|
||||
env:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
- name: Package artifact
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-${{ matrix.name }}-lite.zip"
|
||||
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev${{ matrix.suffix }}.zip"
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-${{ matrix.name }}.zip"
|
||||
|
||||
- name: Upload artifact
|
||||
- name: Package (linux)
|
||||
if: startsWith(matrix.os, 'ubuntu')
|
||||
run: |
|
||||
chmod +x dist/launcher.sh
|
||||
tar -czf "SnowLuma-dev-${{ matrix.name }}-lite.tar.gz" -C dist .
|
||||
cp "$(command -v node)" dist/node
|
||||
chmod +x dist/node
|
||||
tar -czf "SnowLuma-dev-${{ matrix.name }}.tar.gz" -C dist .
|
||||
|
||||
# Single upload step — glob picks up both variants (.zip on Windows,
|
||||
# .tar.gz on Linux) for this matrix row.
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: SnowLuma-dev-${{ github.sha }}${{ matrix.suffix }}
|
||||
path: SnowLuma-dev${{ matrix.suffix }}.zip
|
||||
name: SnowLuma-dev-${{ github.sha }}-${{ matrix.name }}
|
||||
path: SnowLuma-dev-${{ matrix.name }}*
|
||||
retention-days: 3
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
|
||||
123
.github/workflows/release.yml
vendored
123
.github/workflows/release.yml
vendored
@@ -14,14 +14,21 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- name: "win-x64"
|
||||
script: "build"
|
||||
- name: "win-x64-webui"
|
||||
script: "build:all"
|
||||
runs-on: windows-latest
|
||||
- name: win-x64
|
||||
os: windows-latest
|
||||
target: win32-x64
|
||||
- name: linux-x64
|
||||
os: ubuntu-latest
|
||||
target: linux-x64
|
||||
- name: linux-arm64
|
||||
os: ubuntu-24.04-arm
|
||||
target: linux-arm64
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
@@ -38,29 +45,115 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||
- 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" }
|
||||
env:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
- name: Package release
|
||||
# Naming convention:
|
||||
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}-lite.zip"
|
||||
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.zip"
|
||||
|
||||
- name: Package (linux)
|
||||
if: startsWith(matrix.os, 'ubuntu')
|
||||
run: |
|
||||
chmod +x dist/launcher.sh
|
||||
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}-lite.tar.gz" -C dist .
|
||||
cp "$(command -v node)" dist/node
|
||||
chmod +x dist/node
|
||||
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.tar.gz" -C dist .
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-${{ matrix.name }}
|
||||
path: SnowLuma-${{ github.ref_name }}-${{ matrix.name }}*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout (for git log)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Collect release assets
|
||||
run: |
|
||||
mkdir -p release
|
||||
find artifacts -type f \( -name '*.zip' -o -name '*.tar.gz' \) -exec cp {} release/ \;
|
||||
ls -lh release/
|
||||
|
||||
- name: Generate release note
|
||||
shell: bash
|
||||
run: |
|
||||
tag="${GITHUB_REF_NAME}"
|
||||
previousTag="$(git describe --tags --abbrev=0 "${tag}^" 2>/dev/null || true)"
|
||||
if [[ -n "$previousTag" ]]; then
|
||||
changes="$(git log --pretty=format:'- %s (%h)' "$previousTag..$tag")"
|
||||
else
|
||||
changes="$(git log --pretty=format:'- %s (%h)' "$tag")"
|
||||
fi
|
||||
[[ -z "$changes" ]] && changes="- No commit changes detected."
|
||||
cat > release-notes.md <<EOF
|
||||
# SnowLuma ${tag}
|
||||
|
||||
## 发布概览
|
||||
本次发布提供 SnowLuma 的 Windows x64 / Linux x64 / Linux arm64 构建产物,默认包含 WebUI。
|
||||
|
||||
## 下载说明
|
||||
命名约定:
|
||||
- 无后缀 \`.zip/.tar.gz\`:完整版本,内置 \`node\`/\`node.exe\` 与运行时依赖,解压即可使用。
|
||||
- \`-lite\` 后缀:精简版本,不含 Node.js 运行时,需自行安装 Node.js 22+。
|
||||
|
||||
Windows:
|
||||
- \`SnowLuma-${tag}-win-x64.zip\`
|
||||
- \`SnowLuma-${tag}-win-x64-lite.zip\`
|
||||
|
||||
Linux x64:
|
||||
- \`SnowLuma-${tag}-linux-x64.tar.gz\`
|
||||
- \`SnowLuma-${tag}-linux-x64-lite.tar.gz\`
|
||||
|
||||
Linux arm64:
|
||||
- \`SnowLuma-${tag}-linux-arm64.tar.gz\`
|
||||
- \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\`
|
||||
|
||||
## 更新内容
|
||||
${changes}
|
||||
|
||||
## 使用说明
|
||||
- Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。
|
||||
- Linux:\`./launcher.sh\` 或 \`node index.mjs\`。
|
||||
- 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:8080。
|
||||
- Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。
|
||||
EOF
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: SnowLuma-*.zip
|
||||
generate_release_notes: true
|
||||
files: |
|
||||
release/*.zip
|
||||
release/*.tar.gz
|
||||
body_path: release-notes.md
|
||||
overwrite_files: true
|
||||
draft: false
|
||||
prerelease: ${{ contains(github.ref_name, '-') }}
|
||||
|
||||
11
.gitignore
vendored
11
.gitignore
vendored
@@ -8,6 +8,7 @@ CMakePresets.json
|
||||
*.obj
|
||||
*.exe
|
||||
*.so
|
||||
!native/snowluma-linux-x64.so
|
||||
*.dylib
|
||||
*.a
|
||||
*.lib
|
||||
@@ -22,6 +23,10 @@ _deps/
|
||||
|
||||
# Runtime generated
|
||||
config.json
|
||||
/node_modules
|
||||
/dist
|
||||
/.vscode
|
||||
|
||||
# Node / pnpm / monorepo
|
||||
node_modules/
|
||||
**/node_modules/
|
||||
dist/
|
||||
**/dist/
|
||||
.vscode/
|
||||
|
||||
13
.npmrc
Normal file
13
.npmrc
Normal file
@@ -0,0 +1,13 @@
|
||||
registry=https://registry.npmmirror.com/
|
||||
@moonrepo:registry=https://registry.npmmirror.com/
|
||||
|
||||
# Mirrors for binary downloads (sharp, esbuild, swc, electron etc.)
|
||||
disturl=https://npmmirror.com/dist
|
||||
electron_mirror=https://npmmirror.com/mirrors/electron/
|
||||
sass_binary_site=https://npmmirror.com/mirrors/node-sass/
|
||||
sharp_binary_host=https://npmmirror.com/mirrors/sharp
|
||||
sharp_libvips_binary_host=https://npmmirror.com/mirrors/sharp-libvips
|
||||
puppeteer_download_host=https://npmmirror.com/mirrors
|
||||
|
||||
auto-install-peers=true
|
||||
strict-peer-dependencies=false
|
||||
53
README.md
53
README.md
@@ -5,6 +5,59 @@
|
||||
## 关于项目
|
||||
项目处于开发初期,仅支持部分功能,持续高速迭代中,仅支持有头。
|
||||
|
||||
## 仓库结构
|
||||
|
||||
本仓库使用 **pnpm workspace** 进行多包管理。
|
||||
|
||||
```
|
||||
SnowLuma/
|
||||
├─ packages/
|
||||
│ ├─ core/ @snowluma/core - Node.js 运行时(NTQQ packet sniffer + Hook + OneBot)
|
||||
│ ├─ webui/ webui - React + Vite 前端
|
||||
│ └─ runtime/ @snowluma/runtime - 发行包资源
|
||||
│ ├─ launcher.bat
|
||||
│ ├─ package.json (随 dist 一起发布的运行时依赖清单)
|
||||
│ └─ native/ 平台预编译产物 (snowluma-win32-x64.{dll,node})
|
||||
├─ tools/ 辅助脚本(如 Python OneBot WS 测试)
|
||||
├─ tsconfig.base.json
|
||||
├─ tsconfig.json monorepo 根 TS 项目(仅含 references)
|
||||
├─ pnpm-workspace.yaml
|
||||
└─ package.json monorepo 根(脚本委托给 pnpm filter)
|
||||
```
|
||||
|
||||
构建产物统一输出到仓库根 `dist/`,与发行流水线保持兼容。
|
||||
|
||||
## 常用命令
|
||||
|
||||
```bash
|
||||
# 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 开发 — 核心运行时(tsx)
|
||||
pnpm dev
|
||||
|
||||
# 开发 — WebUI 前端(vite dev server)
|
||||
pnpm dev:web
|
||||
|
||||
# 仅构建核心
|
||||
pnpm build
|
||||
|
||||
# 仅构建 WebUI
|
||||
pnpm build:webui
|
||||
|
||||
# 一次构建核心 + WebUI 完整发行版(顺序固定 core → webui)
|
||||
pnpm build:all
|
||||
|
||||
# 单元测试 / 类型检查 / Lint
|
||||
pnpm test
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
|
||||
# 直接对单个包操作
|
||||
pnpm --filter @snowluma/core dev
|
||||
pnpm --filter webui build
|
||||
```
|
||||
|
||||
## 鸣谢
|
||||
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"name": "snowluma",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
"dependencies": {
|
||||
"ws": "^8.20.0"
|
||||
}
|
||||
}
|
||||
BIN
native/snowluma-linux-x64.node
Normal file
BIN
native/snowluma-linux-x64.node
Normal file
Binary file not shown.
BIN
native/snowluma-linux-x64.so
Normal file
BIN
native/snowluma-linux-x64.so
Normal file
Binary file not shown.
39
package.json
39
package.json
@@ -1,36 +1,23 @@
|
||||
{
|
||||
"name": "snowluma",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "0.1.0",
|
||||
"description": "SnowLuma - NTQQ packet sniffer with Node.js native addon",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.mjs",
|
||||
"scripts": {
|
||||
"testtypes": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"build": "vite build",
|
||||
"build": "pnpm --filter @snowluma/core 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",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter webui build",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
"test": "pnpm --filter @snowluma/core test",
|
||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "pnpm -r --if-present lint",
|
||||
"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"
|
||||
"typescript": "catalog:"
|
||||
},
|
||||
"pnpm": {
|
||||
"peerDependencyRules": {
|
||||
@@ -38,5 +25,9 @@
|
||||
"eslint-plugin-react-hooks>eslint": "10"
|
||||
}
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
31
packages/core/package.json
Normal file
31
packages/core/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "0.1.0",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "../../dist/index.mjs",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"build:all": "cross-env BUILD_WEBUI=true vite build",
|
||||
"dev": "tsx src/index.ts",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hono/node-server": "^1.19.14",
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "^24.12.2",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.14",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vite-plugin-cp": "^6.0.3",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,16 @@ export class HookManager {
|
||||
state.path = proc.path;
|
||||
}
|
||||
|
||||
// Probe every freshly-enumerated PID in parallel to detect hooks left over
|
||||
// from a previous SnowLuma run. Positive hits are reconnected immediately
|
||||
// so the login-state snapshot can update the UI without a manual load.
|
||||
await Promise.all(
|
||||
processes
|
||||
.map(proc => this.states.get(proc.pid)!)
|
||||
.filter(state => !state.injected && !this.loadTasks.has(state.pid))
|
||||
.map(state => this.probeAndSeed(state)),
|
||||
);
|
||||
|
||||
const seen = new Set(processes.map(proc => proc.pid));
|
||||
const result: HookProcessInfo[] = [];
|
||||
for (const proc of processes) {
|
||||
@@ -109,10 +119,18 @@ export class HookManager {
|
||||
|
||||
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);
|
||||
// Fast path: if QQ.exe still hosts a hook DLL from a previous SnowLuma
|
||||
// run, the control pipe is already listed. Skip re-injection on a hit.
|
||||
if (await QqHookClient.probePipe(pid)) {
|
||||
state.injected = true;
|
||||
state.method = 'reconnect';
|
||||
log.info('SnowLuma reconnected to existing hook in PID=%d', pid);
|
||||
} else {
|
||||
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);
|
||||
@@ -248,11 +266,14 @@ export class HookManager {
|
||||
}
|
||||
|
||||
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
const previousUin = state.uin;
|
||||
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;
|
||||
if (wasLoggedIn && previousUin === state.uin) return;
|
||||
|
||||
this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender);
|
||||
log.success('login detected: PID=%d UIN=%s', state.pid, state.uin);
|
||||
@@ -37,21 +37,36 @@ function loadNativeAddon(addonPath: string): NativeHookAddon {
|
||||
return mod.exports as unknown as NativeHookAddon;
|
||||
}
|
||||
|
||||
function platformBinaryName(ext: 'node' | 'dll'): string {
|
||||
type HookBinaryExt = 'node' | 'dll' | 'so';
|
||||
|
||||
function platformBinaryName(ext: HookBinaryExt): string {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
}
|
||||
|
||||
function platformInjectableExt(): 'dll' | 'so' {
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Repo bundled build (dist/index.mjs): __dirname=<root>/dist, native at <root>/dist/native
|
||||
// 3. Dev via tsx (packages/core/src/hook/injector.ts): __dirname=<root>/packages/core/src/hook
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
return [
|
||||
path.resolve(__dirname, '..', '..', 'native'),
|
||||
path.resolve(__dirname, '..', 'native'),
|
||||
path.resolve(__dirname, 'native'),
|
||||
path.resolve(__dirname, '..', '..', '..', 'runtime', 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
export function resolveHookNativePath(ext: 'node' | 'dll'): string | null {
|
||||
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
|
||||
const fileName = platformBinaryName(ext);
|
||||
for (const dir of nativeSearchDirs()) {
|
||||
const fullPath = path.join(dir, fileName);
|
||||
@@ -87,7 +102,7 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
.filter(pid => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: 'QQ.exe', path: '' }));
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
export function injectHookProcess(pid: number): HookInjectResult {
|
||||
@@ -95,9 +110,10 @@ export function injectHookProcess(pid: number): HookInjectResult {
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
const dllPath = resolveHookNativePath('dll');
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook DLL found for ${process.platform}-${process.arch}`);
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import net from 'net';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
export const PIPE_MAGIC = 0x31504851;
|
||||
@@ -81,8 +84,22 @@ interface PendingAck {
|
||||
wantReply: boolean;
|
||||
}
|
||||
|
||||
function linuxRuntimeDir(): string {
|
||||
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
if (explicit && explicit.length > 0) return explicit;
|
||||
const xdg = process.env.XDG_RUNTIME_DIR;
|
||||
if (xdg && xdg.length > 0) return xdg;
|
||||
// Mirrors hook_stub.cpp runtime_dir() fallback.
|
||||
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
|
||||
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
|
||||
return `/tmp/snowluma-${uid}`;
|
||||
}
|
||||
|
||||
function mojoPipeName(pid: number, suffix: string): string {
|
||||
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
|
||||
if (process.platform === 'win32') {
|
||||
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
|
||||
}
|
||||
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
|
||||
}
|
||||
|
||||
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
|
||||
@@ -266,6 +283,27 @@ export class QqHookClient extends EventEmitter {
|
||||
return mojoPipeName(pid, 'recv');
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight liveness check for the control pipe. Used to detect whether an
|
||||
* existing SnowLuma hook is still hosted inside the QQ.exe process without
|
||||
* opening the pipe, so probing cannot disturb the first real client connect.
|
||||
*/
|
||||
static async probePipe(pid: number): Promise<boolean> {
|
||||
try {
|
||||
const pipeFileName = process.platform === 'win32'
|
||||
? `mojo.${pid}.control`
|
||||
: `mojo.${pid}.control.sock`;
|
||||
if (process.platform === 'win32') {
|
||||
const names = await fs.readdir('\\\\.\\pipe\\');
|
||||
return names.some(name => name.toLowerCase() === pipeFileName.toLowerCase());
|
||||
}
|
||||
const names = await fs.readdir(linuxRuntimeDir());
|
||||
return names.includes(pipeFileName);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async connect(): Promise<QqHookHello> {
|
||||
if (this.closed) {
|
||||
throw new Error('qq_hook client is closed');
|
||||
@@ -576,8 +614,8 @@ export class QqHookClient extends EventEmitter {
|
||||
const previous = this.loginState;
|
||||
const next = { loggedIn, uin, uinNumber };
|
||||
this.loginState = next;
|
||||
this.emit('loginState', next);
|
||||
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
|
||||
this.emit('loginState', next);
|
||||
if (next.loggedIn) {
|
||||
const waiters = this.loginWaiters;
|
||||
this.loginWaiters = [];
|
||||
@@ -1,13 +1,6 @@
|
||||
import type { JsonObject, OneBotConfig } from './types';
|
||||
import type { JsonObject, OneBotConfig, HttpPostEndpoint } 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;
|
||||
@@ -17,29 +10,34 @@ const log = createLogger('OneBot.POST');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostTransport {
|
||||
private readonly config: OneBotConfig;
|
||||
private readonly context: HttpPostTransportContext;
|
||||
private endpoints: HttpPostEndpoint[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
||||
this.config = config;
|
||||
this.endpoints = [...config.httpPostEndpoints];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
const count = this.config.httpPostEndpoints?.length ?? 0;
|
||||
const count = this.endpoints.length;
|
||||
if (count > 0) {
|
||||
log.info('configured %d HTTP POST endpoint(s)', count);
|
||||
}
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
this.endpoints = [...config.httpPostEndpoints];
|
||||
log.info('reloaded %d HTTP POST endpoint(s)', this.endpoints.length);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
publishEvent(event: JsonObject): void {
|
||||
const endpoints = this.config.httpPostEndpoints;
|
||||
const endpoints = this.endpoints;
|
||||
if (!endpoints || endpoints.length === 0) return;
|
||||
|
||||
const payload = JSON.stringify(event);
|
||||
@@ -1,12 +1,11 @@
|
||||
import {
|
||||
createServer,
|
||||
type IncomingHttpHeaders,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { OneBotConfig } from './types';
|
||||
import type { HttpServerEndpoint, OneBotConfig } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export interface HttpTransportContext {
|
||||
@@ -16,42 +15,65 @@ export interface HttpTransportContext {
|
||||
const log = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpTransport {
|
||||
private readonly config: OneBotConfig;
|
||||
private readonly context: HttpTransportContext;
|
||||
private readonly servers: Server[] = [];
|
||||
private readonly servers = new Map<string, Server>();
|
||||
private endpoints: HttpServerEndpoint[] = [];
|
||||
|
||||
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
||||
this.config = config;
|
||||
this.endpoints = [...config.httpServers];
|
||||
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);
|
||||
});
|
||||
for (const endpoint of this.endpoints) this.startEndpoint(endpoint);
|
||||
}
|
||||
|
||||
server.on('listening', () => {
|
||||
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
||||
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
|
||||
});
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
const nextEndpoints = [...config.httpServers];
|
||||
const nextKeys = new Set(nextEndpoints.map(httpServerKey));
|
||||
|
||||
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);
|
||||
for (const [key, server] of this.servers) {
|
||||
if (!nextKeys.has(key)) {
|
||||
server.close();
|
||||
this.servers.delete(key);
|
||||
log.info('stopped %s', key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextEndpoints) {
|
||||
if (!this.servers.has(httpServerKey(endpoint))) {
|
||||
this.startEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
this.endpoints = nextEndpoints;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
for (const server of this.servers) {
|
||||
for (const server of this.servers.values()) {
|
||||
server.close();
|
||||
}
|
||||
this.servers.length = 0;
|
||||
this.servers.clear();
|
||||
}
|
||||
|
||||
private startEndpoint(endpoint: HttpServerEndpoint): void {
|
||||
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.set(httpServerKey(endpoint), server);
|
||||
}
|
||||
|
||||
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
@@ -154,6 +176,10 @@ function normalizePath(pathValue: string): string {
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
function httpServerKey(endpoint: HttpServerEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}${normalizePath(endpoint.path ?? '/')}#${endpoint.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
// 1. Header auth
|
||||
@@ -103,6 +103,12 @@ export class OneBotInstance {
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
this.httpTransport.reloadConfig(config);
|
||||
this.httpPostTransport.reloadConfig(config);
|
||||
this.wsTransport.reloadConfig(config);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.online = false;
|
||||
this.stopHeartbeat();
|
||||
@@ -137,6 +143,10 @@ export class OneBotInstance {
|
||||
return this.pids.has(pid);
|
||||
}
|
||||
|
||||
getPids(): number[] {
|
||||
return [...this.pids];
|
||||
}
|
||||
|
||||
get empty(): boolean {
|
||||
return this.pids.size === 0;
|
||||
}
|
||||
@@ -34,6 +34,16 @@ export class OneBotManager {
|
||||
return [...this.instances.values()];
|
||||
}
|
||||
|
||||
reloadConfig(uin: string): boolean {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
instance.reloadConfig(config);
|
||||
log.info('configuration reloaded: UIN=%s', uin);
|
||||
return true;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const instance of this.instances.values()) {
|
||||
instance.dispose();
|
||||
@@ -1,7 +1,7 @@
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
import type { IncomingHttpHeaders, IncomingMessage } from 'http';
|
||||
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { JsonObject, OneBotConfig, WsRole } from './types';
|
||||
import type { JsonObject, OneBotConfig, WsClientEndpoint, WsRole, WsServerEndpoint } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
interface ForwardConnection {
|
||||
@@ -14,6 +14,7 @@ interface ReverseConnection {
|
||||
role: WsRole;
|
||||
endpointUrl: string;
|
||||
reconnectIntervalMs: number;
|
||||
key: string;
|
||||
}
|
||||
|
||||
export interface WsTransportContext {
|
||||
@@ -26,17 +27,19 @@ export interface WsTransportContext {
|
||||
const log = createLogger('OneBot.WS');
|
||||
|
||||
export class WsTransport {
|
||||
private readonly config: OneBotConfig;
|
||||
private readonly context: WsTransportContext;
|
||||
|
||||
private readonly servers: WebSocketServer[] = [];
|
||||
private readonly servers = new Map<string, WebSocketServer>();
|
||||
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
||||
private readonly reverseConnections = new Set<ReverseConnection>();
|
||||
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
||||
private serverEndpoints: WsServerEndpoint[] = [];
|
||||
private clientEndpoints: WsClientEndpoint[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(config: OneBotConfig, context: WsTransportContext) {
|
||||
this.config = config;
|
||||
this.serverEndpoints = [...config.wsServers];
|
||||
this.clientEndpoints = [...config.wsClients];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@@ -46,6 +49,45 @@ export class WsTransport {
|
||||
this.startReverseClients();
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
const nextServers = [...config.wsServers];
|
||||
const nextClients = [...config.wsClients];
|
||||
const nextServerKeys = new Set(nextServers.map(wsServerKey));
|
||||
const nextClientKeys = new Set(nextClients.map(wsClientKey));
|
||||
|
||||
for (const [key, server] of this.servers) {
|
||||
if (!nextServerKeys.has(key)) {
|
||||
server.close();
|
||||
this.servers.delete(key);
|
||||
log.info('stopped forward server %s', key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextServers) {
|
||||
if (!this.servers.has(wsServerKey(endpoint))) {
|
||||
this.startServerEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
for (const conn of [...this.reverseConnections]) {
|
||||
if (!nextClientKeys.has(conn.key)) {
|
||||
safeClose(conn.socket);
|
||||
this.reverseConnections.delete(conn);
|
||||
log.info('stopped reverse client %s', conn.endpointUrl);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextClients) {
|
||||
const key = wsClientKey(endpoint);
|
||||
if (![...this.reverseConnections].some(conn => conn.key === key)) {
|
||||
this.startClientEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
this.serverEndpoints = nextServers;
|
||||
this.clientEndpoints = nextClients;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
||||
@@ -65,10 +107,10 @@ export class WsTransport {
|
||||
}
|
||||
this.reverseConnections.clear();
|
||||
|
||||
for (const server of this.servers) {
|
||||
for (const server of this.servers.values()) {
|
||||
server.close();
|
||||
}
|
||||
this.servers.length = 0;
|
||||
this.servers.clear();
|
||||
}
|
||||
|
||||
publishEvent(event: JsonObject): void {
|
||||
@@ -88,7 +130,12 @@ export class WsTransport {
|
||||
}
|
||||
|
||||
private startServers(): void {
|
||||
for (const endpoint of this.config.wsServers) {
|
||||
for (const endpoint of this.serverEndpoints) {
|
||||
this.startServerEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private startServerEndpoint(endpoint: WsServerEndpoint): void {
|
||||
const wss = new WebSocketServer({
|
||||
host: endpoint.host,
|
||||
port: endpoint.port,
|
||||
@@ -110,7 +157,7 @@ export class WsTransport {
|
||||
const conn: ForwardConnection = { socket, role };
|
||||
this.forwardConnections.set(socket, conn);
|
||||
|
||||
socket.on('message', (raw) => {
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
|
||||
@@ -118,27 +165,28 @@ export class WsTransport {
|
||||
this.forwardConnections.delete(socket);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
socket.on('error', (error: Error) => {
|
||||
log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
this.sendBootstrapMetaEvents(socket, role);
|
||||
});
|
||||
|
||||
wss.on('error', (error) => {
|
||||
wss.on('error', (error: Error) => {
|
||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
this.servers.push(wss);
|
||||
}
|
||||
this.servers.set(wsServerKey(endpoint), 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);
|
||||
}
|
||||
for (const endpoint of this.clientEndpoints) this.startClientEndpoint(endpoint);
|
||||
}
|
||||
|
||||
private startClientEndpoint(endpoint: WsClientEndpoint): void {
|
||||
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 {
|
||||
@@ -155,7 +203,7 @@ export class WsTransport {
|
||||
}
|
||||
|
||||
const socket = new WebSocket(endpointUrl, { headers });
|
||||
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs };
|
||||
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs, key: wsClientPartsKey(endpointUrl, role, reconnectIntervalMs, accessToken) };
|
||||
this.reverseConnections.add(conn);
|
||||
|
||||
socket.on('open', () => {
|
||||
@@ -164,7 +212,7 @@ export class WsTransport {
|
||||
this.sendBootstrapMetaEvents(socket, role);
|
||||
});
|
||||
|
||||
socket.on('message', (raw) => {
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
|
||||
@@ -180,12 +228,12 @@ export class WsTransport {
|
||||
this.reconnectTimers.add(timer);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
socket.on('error', (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<void> {
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||
if (role !== 'api' && role !== 'universal') return;
|
||||
|
||||
const text = rawDataToString(raw);
|
||||
@@ -223,6 +271,26 @@ function parseRequestPath(urlValue: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeWsPath(pathValue: string | undefined): string {
|
||||
const path = (pathValue ?? '/').trim() || '/';
|
||||
if (path === '/') return '/';
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
function wsServerKey(endpoint: WsServerEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}${normalizeWsPath(endpoint.path)}#${endpoint.role ?? 'auto'}#${endpoint.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
function wsClientPartsKey(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string): string {
|
||||
return `${endpointUrl}#${role}#${reconnectIntervalMs}#${accessToken}`;
|
||||
}
|
||||
|
||||
function wsClientKey(endpoint: WsClientEndpoint): string {
|
||||
const role = endpoint.role ?? 'universal';
|
||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
||||
return wsClientPartsKey(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '');
|
||||
}
|
||||
|
||||
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
// 1. Header auth
|
||||
@@ -241,9 +309,9 @@ function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
function rawDataToString(raw: WebSocket.RawData): string {
|
||||
function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
|
||||
if (typeof raw === 'string') return raw;
|
||||
if (raw instanceof Buffer) return raw.toString('utf8');
|
||||
if (Buffer.isBuffer(raw)) 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)) {
|
||||
@@ -254,7 +322,7 @@ function rawDataToString(raw: WebSocket.RawData): string {
|
||||
|
||||
function safeSend(socket: WebSocket, payload: string): void {
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
socket.send(payload, (error) => {
|
||||
socket.send(payload, (error?: Error | null) => {
|
||||
if (error) {
|
||||
log.warn('send error: %s', error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
@@ -2,6 +2,15 @@ import { format } from 'util';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
}
|
||||
@@ -33,6 +42,10 @@ const COLOR_CODE: Record<LogLevel, number> = {
|
||||
const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
const logEntries: LogEntry[] = [];
|
||||
const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
@@ -82,9 +95,38 @@ function render(level: LogLevel, scope: string, args: unknown[]): string {
|
||||
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
if (!shouldLog(level)) return;
|
||||
const message = format(...args);
|
||||
const line = render(level, options.scope, args);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
message,
|
||||
line,
|
||||
};
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
stream.write(line + '\n');
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. ESC (0x1B) is preserved so the
|
||||
// ANSI color sequences emitted by render() actually reach the terminal.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
|
||||
return logEntries.slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
@@ -1,7 +1,7 @@
|
||||
import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import { Hono } from 'hono';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
||||
import { randomBytes } from 'crypto';
|
||||
import type { OneBotManager } from '../onebot/manager';
|
||||
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
||||
@@ -22,6 +22,10 @@ const loginAttempts = new Map<string, { count: number; resetAt: number }>();
|
||||
const LOGIN_MAX_ATTEMPTS = 5;
|
||||
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; // 15 minutes
|
||||
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
|
||||
|
||||
function purgeExpiredTokens() {
|
||||
const now = Date.now();
|
||||
@@ -34,6 +38,23 @@ function getClientIp(req: Request): string {
|
||||
return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1';
|
||||
}
|
||||
|
||||
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
|
||||
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
|
||||
headers: {
|
||||
'User-Agent': 'SnowLuma WebUI',
|
||||
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`avatar upstream responded with ${response.status}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type') || 'image/jpeg';
|
||||
const body = new Uint8Array(await response.arrayBuffer());
|
||||
return { body, contentType };
|
||||
}
|
||||
|
||||
export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hookManager?: HookManager) {
|
||||
const app = new Hono();
|
||||
|
||||
@@ -52,12 +73,14 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
}
|
||||
|
||||
const authHeader = c.req.header('Authorization');
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
const queryToken = c.req.query('token') ?? '';
|
||||
const token = bearerToken || queryToken;
|
||||
if (!token) {
|
||||
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);
|
||||
@@ -98,6 +121,33 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/avatar/:uin', async (c) => {
|
||||
const uin = c.req.param('uin');
|
||||
if (!/^\d{5,12}$/.test(uin)) {
|
||||
return c.text('invalid uin', 400);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
let cached = avatarCache.get(uin);
|
||||
if (!cached || cached.expiresAt <= now) {
|
||||
try {
|
||||
const avatar = await fetchQqAvatar(uin);
|
||||
cached = { ...avatar, expiresAt: now + AVATAR_CACHE_TTL_MS };
|
||||
avatarCache.set(uin, cached);
|
||||
} catch (err) {
|
||||
log.warn('failed to proxy avatar for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
|
||||
if (!cached) return c.text('avatar unavailable', 502);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(cached.body, {
|
||||
headers: {
|
||||
'Content-Type': cached.contentType,
|
||||
'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// API Routes
|
||||
app.get('/api/status', (c) => {
|
||||
return c.json({ status: 'running' });
|
||||
@@ -112,6 +162,43 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
return c.json({ list });
|
||||
});
|
||||
|
||||
app.get('/api/logs', (c) => {
|
||||
const limit = Number(c.req.query('limit') ?? 300);
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
});
|
||||
|
||||
app.get('/api/logs/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
const send = (event: unknown) => {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
};
|
||||
send({ type: 'ready' });
|
||||
const unsubscribe = subscribeLogs((entry) => send(entry));
|
||||
const heartbeat = setInterval(() => {
|
||||
controller.enqueue(encoder.encode(': heartbeat\n\n'));
|
||||
}, 15000);
|
||||
c.req.raw.signal.addEventListener('abort', () => {
|
||||
clearInterval(heartbeat);
|
||||
unsubscribe();
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/processes', async (c) => {
|
||||
if (!hookManager) return c.json({ list: [] });
|
||||
try {
|
||||
@@ -160,8 +247,13 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
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: '配置保存成功,将在下次会话重连时生效。' });
|
||||
const reloaded = oneBotManager.reloadConfig(uin);
|
||||
log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : '');
|
||||
return c.json({
|
||||
success: true,
|
||||
reloaded,
|
||||
message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。',
|
||||
});
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: String(err) }, 400);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { loadOneBotConfig, makeDefaultOneBotConfig } from '../onebot/config';
|
||||
import { loadOneBotConfig, makeDefaultOneBotConfig } from '../src/onebot/config';
|
||||
|
||||
describe('makeDefaultOneBotConfig', () => {
|
||||
it('returns default config structure', () => {
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { protoDecode, protoEncode, type ProtoSchema } from '../protobuf/decode';
|
||||
import { WireMessage, encodeKey, encodeVarint, WireType } from '../protobuf/wire';
|
||||
import { protoDecode, protoEncode, type ProtoSchema } from '../src/protobuf/decode';
|
||||
import { WireMessage, encodeKey, encodeVarint, WireType } from '../src/protobuf/wire';
|
||||
|
||||
describe('protoDecode', () => {
|
||||
const SimpleSchema = {
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { toHex, fromHex, hexPreview } from '../utils/hex';
|
||||
import { toHex, fromHex, hexPreview } from '../src/utils/hex';
|
||||
|
||||
describe('toHex', () => {
|
||||
it('converts empty buffer', () => {
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../onebot/message-id';
|
||||
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id';
|
||||
|
||||
describe('hashMessageIdInt32', () => {
|
||||
it('returns consistent hash for same inputs', () => {
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseMessage } from '../onebot/message-parser';
|
||||
import { parseMessage } from '../src/onebot/message-parser';
|
||||
|
||||
describe('parseMessage', () => {
|
||||
describe('plain text', () => {
|
||||
@@ -151,7 +151,8 @@ describe('parseMessage', () => {
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('json');
|
||||
const parsed = JSON.parse(result[0].text);
|
||||
expect(result[0].text).toBeDefined();
|
||||
const parsed = JSON.parse(result[0].text!);
|
||||
expect(parsed.app).toBe('com.tencent.structmsg');
|
||||
expect(parsed.meta.news.title).toBe('Test');
|
||||
});
|
||||
@@ -204,7 +205,8 @@ describe('parseMessage', () => {
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('json');
|
||||
const parsed = JSON.parse(result[0].text);
|
||||
expect(result[0].text).toBeDefined();
|
||||
const parsed = JSON.parse(result[0].text!);
|
||||
expect(parsed.app).toBe('com.tencent.map');
|
||||
expect(parsed.meta.Location.lat).toBe('39.9');
|
||||
});
|
||||
@@ -216,7 +218,8 @@ describe('parseMessage', () => {
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('json');
|
||||
const parsed = JSON.parse(result[0].text);
|
||||
expect(result[0].text).toBeDefined();
|
||||
const parsed = JSON.parse(result[0].text!);
|
||||
expect(parsed.meta.contact.type).toBe('group');
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
fieldAsUint32,
|
||||
fieldAsString,
|
||||
fieldAsBool,
|
||||
} from '../protobuf/wire';
|
||||
} from '../src/protobuf/wire';
|
||||
|
||||
// Helper to build bytes from number array
|
||||
function bytes(...vals: number[]): Uint8Array {
|
||||
13
packages/core/tsconfig.json
Normal file
13
packages/core/tsconfig.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
// Tests live outside src/ so we don't pin rootDir; tsc --noEmit doesn't write output anyway.
|
||||
"types": ["node", "vitest/globals"],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*", "tests/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
119
packages/core/vite.config.ts
Normal file
119
packages/core/vite.config.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { defineConfig, PluginOption, UserConfig } from 'vite';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { builtinModules } from 'module';
|
||||
import cp from 'vite-plugin-cp';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
const distDir = path.resolve(repoRoot, 'dist');
|
||||
const runtimeDir = path.resolve(repoRoot, 'packages', 'runtime');
|
||||
const nativeDir = path.resolve(runtimeDir, 'native');
|
||||
|
||||
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
|
||||
const toPosix = (p: string) => p.replace(/\\/g, '/');
|
||||
|
||||
// `@snowluma/websocket` is bundled (it's an in-tree TS workspace package), so
|
||||
// it must NOT be marked external. Only Node builtins stay external.
|
||||
const external: string[] = [];
|
||||
|
||||
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat();
|
||||
|
||||
const runtimeSrc = toPosix(runtimeDir);
|
||||
const nativeSrc = toPosix(nativeDir);
|
||||
|
||||
// Target selection: `SNOWLUMA_TARGET=<platform>-<arch>` overrides the host
|
||||
// detection, enabling cross-target packaging on CI.
|
||||
const targetTriple = process.env.SNOWLUMA_TARGET ?? `${process.platform}-${process.arch}`;
|
||||
const targetPlatform = targetTriple.split('-')[0];
|
||||
|
||||
// Runtime scaffolding files copied into dist/. The NTQQ hook is Windows-only,
|
||||
// so its launcher/shell script differ per target.
|
||||
const runtimeDistFiles = ['package.json',
|
||||
targetPlatform === 'win32' ? 'launcher.bat' : 'launcher.sh',
|
||||
];
|
||||
|
||||
// Native binaries shipped for the selected target:
|
||||
// * `snowluma-*.{dll,node}` – NTQQ hook (Windows-only).
|
||||
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
|
||||
const nativeFiles = [
|
||||
`websocket-${targetTriple}.node`,
|
||||
...(targetPlatform === 'win32'
|
||||
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
|
||||
: []),
|
||||
];
|
||||
|
||||
// Fail fast if any expected native binary is missing from packages/runtime/native/.
|
||||
// vite-plugin-cp only emits a warning on missing source files; we want a hard
|
||||
// error so CI can't accidentally ship an incomplete archive.
|
||||
const missingNatives = nativeFiles.filter(
|
||||
(f) => !fs.existsSync(path.join(nativeDir, f)),
|
||||
);
|
||||
if (missingNatives.length > 0) {
|
||||
throw new Error(
|
||||
`Missing native binaries for target ${targetTriple}:\n` +
|
||||
missingNatives.map((f) => ` - ${path.join(nativeDir, f)}`).join('\n'),
|
||||
);
|
||||
}
|
||||
|
||||
const BaseConfigPlugin: PluginOption[] = [
|
||||
cp({
|
||||
targets: [
|
||||
...runtimeDistFiles.map((file) => ({
|
||||
src: `${runtimeSrc}/${file}`,
|
||||
dest: distDir,
|
||||
flatten: true,
|
||||
})),
|
||||
...nativeFiles.map((f) => ({
|
||||
src: `${nativeSrc}/${f}`,
|
||||
dest: path.join(distDir, '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]
|
||||
},
|
||||
// Emit to monorepo root dist/ so the existing release pipeline keeps working.
|
||||
outDir: distDir,
|
||||
// Required since outDir is outside the vite project root.
|
||||
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]
|
||||
};
|
||||
});
|
||||
17
packages/core/vitest.config.ts
Normal file
17
packages/core/vitest.config.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, 'src')
|
||||
}
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node'
|
||||
}
|
||||
});
|
||||
1
packages/runtime/.gitignore
vendored
Normal file
1
packages/runtime/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
node_modules
|
||||
16
packages/runtime/launcher.sh
Normal file
16
packages/runtime/launcher.sh
Normal file
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
# Prefer bundled node when present; fall back to $PATH.
|
||||
if [[ -x "./node" ]]; then
|
||||
NODE_BIN="./node"
|
||||
else
|
||||
NODE_BIN="$(command -v node || true)"
|
||||
if [[ -z "$NODE_BIN" ]]; then
|
||||
echo "error: 'node' not found on PATH and no bundled ./node; install Node.js >= 22." >&2
|
||||
exit 127
|
||||
fi
|
||||
fi
|
||||
|
||||
exec "$NODE_BIN" ./index.mjs "$@"
|
||||
BIN
packages/runtime/native/websocket-linux-arm64.node
Normal file
BIN
packages/runtime/native/websocket-linux-arm64.node
Normal file
Binary file not shown.
BIN
packages/runtime/native/websocket-linux-x64.node
Normal file
BIN
packages/runtime/native/websocket-linux-x64.node
Normal file
Binary file not shown.
BIN
packages/runtime/native/websocket-win32-x64.node
Normal file
BIN
packages/runtime/native/websocket-win32-x64.node
Normal file
Binary file not shown.
8
packages/runtime/package.json
Normal file
8
packages/runtime/package.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
"description": "SnowLuma runtime distribution manifest: ships into dist/ (launcher.bat, package.json, native/*.dll, native/*.node). Native libraries are loaded via process.dlopen()."
|
||||
}
|
||||
19
packages/websocket/package.json
Normal file
19
packages/websocket/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"description": "SnowLuma in-tree WebSocket implementation. Loads packages/runtime/native/websocket-<platform>-<arch>.node via process.dlopen().",
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
273
packages/websocket/src/client.ts
Normal file
273
packages/websocket/src/client.ts
Normal file
@@ -0,0 +1,273 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import net from 'node:net';
|
||||
import tls from 'node:tls';
|
||||
import crypto from 'node:crypto';
|
||||
import { URL } from 'node:url';
|
||||
import type { Socket } from 'node:net';
|
||||
import native from './native';
|
||||
import {
|
||||
type AcceptedPerMessageDeflate,
|
||||
type PerMessageDeflateConfig,
|
||||
offerPerMessageDeflate,
|
||||
parseAcceptedPerMessageDeflate,
|
||||
} from './extensions';
|
||||
import { WebSocket as InternalWebSocket, CONNECTING, OPEN, CLOSED, isValidCloseCode, type SendCallback, type SendOptions } from './websocket';
|
||||
|
||||
interface ParsedHandshakeResponse {
|
||||
statusCode: number;
|
||||
statusMessage: string;
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
function parseHeaders(headerBlock: string): ParsedHandshakeResponse {
|
||||
const lines = headerBlock.split('\r\n');
|
||||
const status = lines.shift() as string;
|
||||
const m = /^HTTP\/1\.1\s+(\d+)\s*(.*)$/.exec(status);
|
||||
if (!m) throw new Error('Bad HTTP status line: ' + status);
|
||||
const headers: Record<string, string> = Object.create(null);
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
const idx = line.indexOf(':');
|
||||
if (idx < 0) continue;
|
||||
const k = line.slice(0, idx).trim().toLowerCase();
|
||||
const v = line.slice(idx + 1).trim();
|
||||
headers[k] = v;
|
||||
}
|
||||
return { statusCode: Number(m[1]), statusMessage: m[2] ?? '', headers };
|
||||
}
|
||||
|
||||
export interface WebSocketClientOptions {
|
||||
maxPayload?: number;
|
||||
perMessageDeflate?: boolean | PerMessageDeflateConfig;
|
||||
headers?: Record<string, string>;
|
||||
socketOptions?: net.NetConnectOpts | tls.ConnectionOptions;
|
||||
// Convenience: any TLS option also accepted at top-level (mirrors the `ws` API).
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export class WebSocketClient extends EventEmitter {
|
||||
static readonly CONNECTING = 0;
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSING = 2;
|
||||
static readonly CLOSED = 3;
|
||||
static Server: unknown;
|
||||
|
||||
private readonly _url: URL;
|
||||
private readonly _secure: boolean;
|
||||
private _readyState: number;
|
||||
private readonly _maxPayload: number | undefined;
|
||||
private _ws: InternalWebSocket | null = null;
|
||||
private _pendingQueue: Array<{ data: Parameters<InternalWebSocket['send']>[0]; options?: SendOptions; cb?: SendCallback }> = [];
|
||||
private readonly _perMessageDeflate: boolean | PerMessageDeflateConfig | undefined;
|
||||
private readonly _protocols: string[] | undefined;
|
||||
public protocol = '';
|
||||
public extensions = '';
|
||||
|
||||
private readonly _socket: Socket;
|
||||
private _handshakeBuf: Buffer = Buffer.alloc(0);
|
||||
private _wsKey: string;
|
||||
private _expectedAccept: string;
|
||||
|
||||
constructor(
|
||||
address: string,
|
||||
protocols?: string | string[] | WebSocketClientOptions,
|
||||
options?: WebSocketClientOptions,
|
||||
) {
|
||||
super();
|
||||
if (typeof protocols === 'object' && !Array.isArray(protocols) && protocols !== null) {
|
||||
options = protocols as WebSocketClientOptions;
|
||||
protocols = undefined;
|
||||
}
|
||||
options = options || {};
|
||||
this._url = new URL(address);
|
||||
if (this._url.protocol !== 'ws:' && this._url.protocol !== 'wss:') {
|
||||
throw new Error('Only ws: and wss: URLs are supported');
|
||||
}
|
||||
this._secure = this._url.protocol === 'wss:';
|
||||
this._readyState = CONNECTING;
|
||||
this._maxPayload = options.maxPayload;
|
||||
this._perMessageDeflate = options.perMessageDeflate;
|
||||
this._protocols = Array.isArray(protocols) ? protocols.map(String) : (typeof protocols === 'string' ? [protocols] : undefined);
|
||||
|
||||
const host = this._url.hostname;
|
||||
const port = this._url.port ? Number(this._url.port) : (this._secure ? 443 : 80);
|
||||
|
||||
// Generate random 16-byte Sec-WebSocket-Key per RFC 6455 §4.1.
|
||||
const keyBytes = crypto.randomBytes(16);
|
||||
this._wsKey = keyBytes.toString('base64');
|
||||
this._expectedAccept = native.computeAcceptKey(this._wsKey);
|
||||
|
||||
const connectOpts: net.NetConnectOpts & tls.ConnectionOptions = {
|
||||
host,
|
||||
port,
|
||||
...(options.socketOptions || {}),
|
||||
} as net.NetConnectOpts & tls.ConnectionOptions;
|
||||
|
||||
const onConnect = () => {
|
||||
const pathAndQuery = (this._url.pathname || '/') + (this._url.search || '');
|
||||
const hostHeader = (this._url.port && Number(this._url.port) !== (this._secure ? 443 : 80))
|
||||
? `${host}:${this._url.port}`
|
||||
: host;
|
||||
const reqLines = [
|
||||
`GET ${pathAndQuery} HTTP/1.1`,
|
||||
`Host: ${hostHeader}`,
|
||||
'Upgrade: websocket',
|
||||
'Connection: Upgrade',
|
||||
`Sec-WebSocket-Key: ${this._wsKey}`,
|
||||
'Sec-WebSocket-Version: 13',
|
||||
];
|
||||
if (this._protocols && this._protocols.length > 0) {
|
||||
reqLines.push(`Sec-WebSocket-Protocol: ${this._protocols.join(', ')}`);
|
||||
}
|
||||
const extensionOffer = offerPerMessageDeflate(this._perMessageDeflate);
|
||||
if (extensionOffer) {
|
||||
reqLines.push(`Sec-WebSocket-Extensions: ${extensionOffer}`);
|
||||
}
|
||||
if (options!.headers) {
|
||||
for (const [k, v] of Object.entries(options!.headers)) {
|
||||
reqLines.push(`${k}: ${v}`);
|
||||
}
|
||||
}
|
||||
reqLines.push('', '');
|
||||
this._socket.write(reqLines.join('\r\n'));
|
||||
};
|
||||
|
||||
if (this._secure && (connectOpts as tls.ConnectionOptions).servername === undefined && net.isIP(host) === 0) {
|
||||
(connectOpts as tls.ConnectionOptions).servername = host;
|
||||
}
|
||||
|
||||
this._socket = this._secure
|
||||
? tls.connect(connectOpts as tls.ConnectionOptions, onConnect)
|
||||
: net.connect(connectOpts as net.NetConnectOpts, onConnect);
|
||||
|
||||
this._socket.setNoDelay?.(true);
|
||||
this._socket.on('data', (chunk: Buffer) => this._onHandshakeData(chunk));
|
||||
this._socket.on('error', (err: Error) => this._onEarlyError(err));
|
||||
this._socket.on('close', () => this._onEarlyClose());
|
||||
}
|
||||
|
||||
get readyState(): number {
|
||||
return this._ws ? this._ws.readyState : this._readyState;
|
||||
}
|
||||
|
||||
private _onHandshakeData(chunk: Buffer): void {
|
||||
this._handshakeBuf = Buffer.concat([this._handshakeBuf, chunk]);
|
||||
const idx = this._handshakeBuf.indexOf('\r\n\r\n');
|
||||
if (idx < 0) {
|
||||
if (this._handshakeBuf.length > 16384) {
|
||||
this._abort('Handshake response too large');
|
||||
}
|
||||
return;
|
||||
}
|
||||
const headBlock = this._handshakeBuf.slice(0, idx).toString('latin1');
|
||||
const rest = this._handshakeBuf.slice(idx + 4);
|
||||
let parsed: ParsedHandshakeResponse;
|
||||
try {
|
||||
parsed = parseHeaders(headBlock);
|
||||
} catch (e) {
|
||||
return this._abort((e as Error).message);
|
||||
}
|
||||
|
||||
if (parsed.statusCode !== 101) {
|
||||
return this._abort(`Unexpected response status ${parsed.statusCode}`);
|
||||
}
|
||||
if ((parsed.headers['upgrade'] || '').toLowerCase() !== 'websocket') {
|
||||
return this._abort('Missing/invalid Upgrade header');
|
||||
}
|
||||
if (!/\bupgrade\b/i.test(parsed.headers['connection'] || '')) {
|
||||
return this._abort('Missing Connection: Upgrade header');
|
||||
}
|
||||
if (parsed.headers['sec-websocket-accept'] !== this._expectedAccept) {
|
||||
return this._abort('Invalid Sec-WebSocket-Accept');
|
||||
}
|
||||
let acceptedExtensions: AcceptedPerMessageDeflate | null;
|
||||
try {
|
||||
acceptedExtensions = parseAcceptedPerMessageDeflate(
|
||||
parsed.headers['sec-websocket-extensions'],
|
||||
this._perMessageDeflate,
|
||||
);
|
||||
} catch (e) {
|
||||
return this._abort((e as Error).message);
|
||||
}
|
||||
if (parsed.headers['sec-websocket-extensions'] && !acceptedExtensions) {
|
||||
return this._abort('Unexpected Sec-WebSocket-Extensions');
|
||||
}
|
||||
const protocol = parsed.headers['sec-websocket-protocol'] || '';
|
||||
if (protocol && (!this._protocols || !this._protocols.includes(protocol))) {
|
||||
return this._abort('Unexpected Sec-WebSocket-Protocol');
|
||||
}
|
||||
|
||||
this._socket.removeAllListeners('data');
|
||||
this._socket.removeAllListeners('error');
|
||||
this._socket.removeAllListeners('close');
|
||||
|
||||
this._readyState = OPEN;
|
||||
this._ws = new InternalWebSocket(this._socket, {
|
||||
isServer: false,
|
||||
maxPayload: this._maxPayload,
|
||||
extensions: acceptedExtensions ? { perMessageDeflate: acceptedExtensions } : undefined,
|
||||
protocol,
|
||||
readyState: OPEN,
|
||||
});
|
||||
this.protocol = protocol;
|
||||
this.extensions = acceptedExtensions ? 'permessage-deflate' : '';
|
||||
this._ws.on('message', (d: Buffer, isBinary: boolean) => this.emit('message', d, isBinary));
|
||||
this._ws.on('ping', (d: Buffer) => this.emit('ping', d));
|
||||
this._ws.on('pong', (d: Buffer) => this.emit('pong', d));
|
||||
this._ws.on('close', (c: number, r: string) => this.emit('close', c, r));
|
||||
this._ws.on('error', (e: Error) => this.emit('error', e));
|
||||
|
||||
this.emit('upgrade', parsed);
|
||||
this.emit('open');
|
||||
|
||||
if (rest.length > 0) this._ws._onData(rest);
|
||||
|
||||
for (const entry of this._pendingQueue) this._ws.send(entry.data, entry.options, entry.cb);
|
||||
this._pendingQueue = [];
|
||||
}
|
||||
|
||||
private _onEarlyError(err: Error): void {
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
private _onEarlyClose(): void {
|
||||
if (!this._ws) {
|
||||
this._readyState = CLOSED;
|
||||
this.emit('close', 1006, '');
|
||||
}
|
||||
}
|
||||
|
||||
private _abort(msg: string): void {
|
||||
const err = new Error('WebSocket handshake failed: ' + msg);
|
||||
try { this._socket.destroy(); } catch { /* noop */ }
|
||||
this.emit('error', err);
|
||||
this._readyState = CLOSED;
|
||||
this.emit('close', 1006, '');
|
||||
}
|
||||
|
||||
send(data: Parameters<InternalWebSocket['send']>[0], options?: SendOptions | SendCallback, cb?: SendCallback): void {
|
||||
if (this._ws) return this._ws.send(data, options, cb);
|
||||
if (typeof options === 'function') { cb = options; options = undefined; }
|
||||
this._pendingQueue.push({ data, options, cb });
|
||||
}
|
||||
|
||||
ping(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void {
|
||||
this._ws?.ping(data, mask, cb);
|
||||
}
|
||||
pong(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void {
|
||||
this._ws?.pong(data, mask, cb);
|
||||
}
|
||||
|
||||
close(code?: number, reason?: string): void {
|
||||
if (code !== undefined && !isValidCloseCode(code)) {
|
||||
throw new RangeError(`Invalid close code: ${code}`);
|
||||
}
|
||||
if (this._ws) return this._ws.close(code, reason);
|
||||
try { this._socket.destroy(); } catch { /* noop */ }
|
||||
}
|
||||
|
||||
terminate(): void {
|
||||
if (this._ws) return this._ws.terminate();
|
||||
try { this._socket.destroy(); } catch { /* noop */ }
|
||||
}
|
||||
}
|
||||
180
packages/websocket/src/extensions.ts
Normal file
180
packages/websocket/src/extensions.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import zlib from 'node:zlib';
|
||||
|
||||
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
|
||||
|
||||
export interface PerMessageDeflateConfig {
|
||||
clientNoContextTakeover?: boolean;
|
||||
serverNoContextTakeover?: boolean;
|
||||
threshold?: number;
|
||||
}
|
||||
|
||||
export interface AcceptedPerMessageDeflate {
|
||||
enabled: true;
|
||||
requestNoContextTakeover: boolean;
|
||||
responseNoContextTakeover: boolean;
|
||||
threshold: number;
|
||||
}
|
||||
|
||||
interface ParsedOffer {
|
||||
name: string;
|
||||
params: Record<string, string | true>;
|
||||
}
|
||||
|
||||
export function parseHeader(header: string | undefined | null): ParsedOffer[] {
|
||||
const offers: ParsedOffer[] = [];
|
||||
if (!header) return offers;
|
||||
for (const rawOffer of String(header).split(',')) {
|
||||
const parts = rawOffer.split(';').map(p => p.trim()).filter(Boolean);
|
||||
if (parts.length === 0) continue;
|
||||
const name = (parts.shift() as string).toLowerCase();
|
||||
const params: Record<string, string | true> = Object.create(null);
|
||||
for (const part of parts) {
|
||||
const eq = part.indexOf('=');
|
||||
if (eq === -1) {
|
||||
params[part.toLowerCase()] = true;
|
||||
} else {
|
||||
const key = part.slice(0, eq).trim().toLowerCase();
|
||||
let value = part.slice(eq + 1).trim();
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
params[key] = value;
|
||||
}
|
||||
}
|
||||
offers.push({ name, params });
|
||||
}
|
||||
return offers;
|
||||
}
|
||||
|
||||
function normalizePerMessageDeflateOptions(
|
||||
value: unknown,
|
||||
): PerMessageDeflateConfig | null {
|
||||
if (value === undefined || value === false || value === null) return null;
|
||||
if (value === true) {
|
||||
return { clientNoContextTakeover: true, serverNoContextTakeover: true };
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
return {
|
||||
clientNoContextTakeover: true,
|
||||
serverNoContextTakeover: true,
|
||||
...(value as PerMessageDeflateConfig),
|
||||
};
|
||||
}
|
||||
return { clientNoContextTakeover: true, serverNoContextTakeover: true };
|
||||
}
|
||||
|
||||
export function acceptPerMessageDeflate(
|
||||
requestHeader: string | undefined,
|
||||
options: unknown,
|
||||
): { header: string; options: AcceptedPerMessageDeflate } | null {
|
||||
const config = normalizePerMessageDeflateOptions(options);
|
||||
if (!config) return null;
|
||||
const offer = parseHeader(requestHeader).find(item => item.name === 'permessage-deflate');
|
||||
if (!offer) return null;
|
||||
const responseParams: string[] = [];
|
||||
|
||||
if (config.serverNoContextTakeover !== false || offer.params.server_no_context_takeover) {
|
||||
responseParams.push('server_no_context_takeover');
|
||||
}
|
||||
if (config.clientNoContextTakeover !== false || offer.params.client_no_context_takeover) {
|
||||
responseParams.push('client_no_context_takeover');
|
||||
}
|
||||
|
||||
const accepted: AcceptedPerMessageDeflate = {
|
||||
enabled: true,
|
||||
requestNoContextTakeover: responseParams.includes('client_no_context_takeover'),
|
||||
responseNoContextTakeover: responseParams.includes('server_no_context_takeover'),
|
||||
threshold: config.threshold ?? 1024,
|
||||
};
|
||||
|
||||
return {
|
||||
header: ['permessage-deflate', ...responseParams].join('; '),
|
||||
options: accepted,
|
||||
};
|
||||
}
|
||||
|
||||
export function offerPerMessageDeflate(options: unknown): string | null {
|
||||
const config = normalizePerMessageDeflateOptions(options);
|
||||
if (!config) return null;
|
||||
const params = ['permessage-deflate'];
|
||||
if (config.clientNoContextTakeover !== false) params.push('client_no_context_takeover');
|
||||
if (config.serverNoContextTakeover !== false) params.push('server_no_context_takeover');
|
||||
return params.join('; ');
|
||||
}
|
||||
|
||||
export function parseAcceptedPerMessageDeflate(
|
||||
responseHeader: string | undefined,
|
||||
requestedOptions: unknown,
|
||||
): AcceptedPerMessageDeflate | null {
|
||||
const config = normalizePerMessageDeflateOptions(requestedOptions);
|
||||
if (!config) return null;
|
||||
const accepted = parseHeader(responseHeader).find(item => item.name === 'permessage-deflate');
|
||||
if (!accepted) return null;
|
||||
for (const key of Object.keys(accepted.params)) {
|
||||
if (key !== 'client_no_context_takeover' && key !== 'server_no_context_takeover') {
|
||||
throw new Error(`Unsupported permessage-deflate parameter: ${key}`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
enabled: true,
|
||||
requestNoContextTakeover: !!accepted.params.server_no_context_takeover,
|
||||
responseNoContextTakeover: !!accepted.params.client_no_context_takeover,
|
||||
threshold: config.threshold ?? 1024,
|
||||
};
|
||||
}
|
||||
|
||||
export function compressRaw(data: Buffer): Buffer {
|
||||
const compressed = zlib.deflateRawSync(data, { flush: zlib.constants.Z_SYNC_FLUSH });
|
||||
if (compressed.length >= 4 && compressed.subarray(compressed.length - 4).equals(TRAILER)) {
|
||||
return compressed.subarray(0, compressed.length - 4);
|
||||
}
|
||||
return compressed;
|
||||
}
|
||||
|
||||
export function decompressRaw(data: Buffer, maxPayload?: number): Buffer {
|
||||
const inflated = zlib.inflateRawSync(Buffer.concat([data, TRAILER]), {
|
||||
finishFlush: zlib.constants.Z_SYNC_FLUSH,
|
||||
});
|
||||
if (maxPayload !== undefined && inflated.length > maxPayload) {
|
||||
const err = new Error('Message too large after inflate') as Error & { code?: number };
|
||||
err.code = 1009;
|
||||
throw err;
|
||||
}
|
||||
return inflated;
|
||||
}
|
||||
|
||||
export function normalizeProtocolList(
|
||||
protocols: string | string[] | Set<string> | undefined | null,
|
||||
): string[] {
|
||||
if (!protocols) return [];
|
||||
if (typeof protocols === 'string') {
|
||||
return protocols.split(',').map(p => p.trim()).filter(Boolean);
|
||||
}
|
||||
if (Array.isArray(protocols)) {
|
||||
return protocols.map(String).map(p => p.trim()).filter(Boolean);
|
||||
}
|
||||
if (protocols instanceof Set) {
|
||||
return Array.from(protocols).map(String).map(p => p.trim()).filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function chooseSubprotocol(
|
||||
requestHeader: string | undefined,
|
||||
protocols: string | string[] | Set<string> | ((requested: string[]) => string | null | undefined) | undefined,
|
||||
): string | null {
|
||||
const requested = normalizeProtocolList(requestHeader);
|
||||
if (typeof protocols === 'function') {
|
||||
const selected = protocols(requested);
|
||||
return selected && requested.includes(String(selected)) ? String(selected) : null;
|
||||
}
|
||||
const supported = normalizeProtocolList(protocols);
|
||||
if (requested.length === 0 || supported.length === 0) return null;
|
||||
for (const protocol of supported) {
|
||||
if (requested.includes(protocol)) return protocol;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
54
packages/websocket/src/index.ts
Normal file
54
packages/websocket/src/index.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { EventEmitter } from 'node:events';
|
||||
import { WebSocket as InternalWebSocket } from './websocket';
|
||||
import { WebSocketServer } from './server';
|
||||
import { WebSocketClient } from './client';
|
||||
import native from './native';
|
||||
import type { SendOptions, SendCallback } from './websocket';
|
||||
|
||||
WebSocketClient.Server = WebSocketServer;
|
||||
|
||||
// `WebSocket` mirrors the `ws` package's default export shape. We use
|
||||
// declaration merging (const + interface) so the name resolves to the client
|
||||
// constructor in value space AND a structural interface in type space. The
|
||||
// interface is intentionally narrow enough to cover both `WebSocketClient`
|
||||
// (constructed by the user) and the internal `WebSocket` (emitted by the
|
||||
// server's `connection` event). It also shadows Node 22+'s global DOM-style
|
||||
// `WebSocket` type that ships with @types/node.
|
||||
export const WebSocket: typeof WebSocketClient = WebSocketClient;
|
||||
export interface WebSocket extends EventEmitter {
|
||||
readonly readyState: number;
|
||||
readonly protocol: string;
|
||||
readonly extensions: string;
|
||||
send(
|
||||
data: string | Buffer | Uint8Array | ArrayBuffer,
|
||||
options?: SendOptions | SendCallback,
|
||||
cb?: SendCallback,
|
||||
): void;
|
||||
ping(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void;
|
||||
pong(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate(): void;
|
||||
on(event: 'message', listener: (data: Buffer, isBinary: boolean) => void): this;
|
||||
on(event: 'open', listener: () => void): this;
|
||||
on(event: 'close', listener: (code: number, reason: string) => void): this;
|
||||
on(event: 'error', listener: (err: Error) => void): this;
|
||||
on(event: 'ping' | 'pong', listener: (data: Buffer) => void): this;
|
||||
on(event: string | symbol, listener: (...args: unknown[]) => void): this;
|
||||
}
|
||||
|
||||
const Server = WebSocketServer;
|
||||
const _internal = { WebSocket: InternalWebSocket, native };
|
||||
|
||||
export {
|
||||
WebSocketClient,
|
||||
WebSocketServer,
|
||||
Server,
|
||||
InternalWebSocket,
|
||||
_internal,
|
||||
};
|
||||
|
||||
export type { SendOptions, SendCallback, WebSocketRawData } from './websocket';
|
||||
export type { WebSocketClientOptions } from './client';
|
||||
export type { WebSocketServerOptions, SubprotocolSelector } from './server';
|
||||
|
||||
export default WebSocketClient;
|
||||
88
packages/websocket/src/native.ts
Normal file
88
packages/websocket/src/native.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface ParserOptions {
|
||||
isServer: boolean;
|
||||
maxPayload: number;
|
||||
allowedRsv: number;
|
||||
}
|
||||
|
||||
export interface ParsedFrame {
|
||||
fin: boolean;
|
||||
opcode: number;
|
||||
payload: Buffer;
|
||||
rsv?: number;
|
||||
}
|
||||
|
||||
export interface ParseResult {
|
||||
frames: ParsedFrame[];
|
||||
error?: boolean;
|
||||
code?: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface ParserInstance {
|
||||
push(chunk: Buffer): ParseResult;
|
||||
}
|
||||
|
||||
export interface NativeAddon {
|
||||
Parser: new (options: ParserOptions) => ParserInstance;
|
||||
buildFrame(
|
||||
opcode: number,
|
||||
fin: boolean,
|
||||
payload: Buffer,
|
||||
maskKey: Buffer | null,
|
||||
rsv: number,
|
||||
): Buffer;
|
||||
computeAcceptKey(key: string): string;
|
||||
}
|
||||
|
||||
function platformBinaryName(): string {
|
||||
return `websocket-${process.platform}-${process.arch}.node`;
|
||||
}
|
||||
|
||||
// The same binary ships under several layouts, depending on whether we're
|
||||
// running from source (tsx), from the bundled monorepo dist/, or from a
|
||||
// flattened release zip. Probe each candidate in priority order.
|
||||
function searchDirs(): string[] {
|
||||
return [
|
||||
// Released zip (flattened): <root>/native, called from <root>/index.mjs
|
||||
path.resolve(__dirname, 'native'),
|
||||
// Bundled into <root>/dist/index.mjs → natives at <root>/dist/native
|
||||
path.resolve(__dirname, '..', 'native'),
|
||||
// Dev (tsx) — packages/websocket/src → packages/runtime/native
|
||||
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
|
||||
// Fallback when invoked from repo root
|
||||
path.resolve(process.cwd(), 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
function resolveAddonPath(): string {
|
||||
const fileName = platformBinaryName();
|
||||
for (const dir of searchDirs()) {
|
||||
const full = path.join(dir, fileName);
|
||||
if (existsSync(full)) return full;
|
||||
}
|
||||
throw new Error(
|
||||
`[snowluma/websocket] native addon not found: ${fileName}. Searched: ${searchDirs().join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
function loadAddon(): NativeAddon {
|
||||
const addonPath = resolveAddonPath();
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
// process.dlopen expects a NodeModule-shaped object; mod.exports is mutated in-place.
|
||||
(process as unknown as { dlopen: (m: { exports: unknown }, file: string) => void }).dlopen(
|
||||
mod,
|
||||
addonPath,
|
||||
);
|
||||
return mod.exports as unknown as NativeAddon;
|
||||
}
|
||||
|
||||
const addon: NativeAddon = loadAddon();
|
||||
export default addon;
|
||||
285
packages/websocket/src/server.ts
Normal file
285
packages/websocket/src/server.ts
Normal file
@@ -0,0 +1,285 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import type { IncomingMessage, Server as HttpServer, ServerResponse } from 'node:http';
|
||||
import type { Server as HttpsServer } from 'node:https';
|
||||
import type { Duplex } from 'node:stream';
|
||||
import native from './native';
|
||||
import {
|
||||
type PerMessageDeflateConfig,
|
||||
acceptPerMessageDeflate,
|
||||
chooseSubprotocol,
|
||||
} from './extensions';
|
||||
import { WebSocket, OPEN } from './websocket';
|
||||
|
||||
function computeAccept(key: string): string {
|
||||
return native.computeAcceptKey(key);
|
||||
}
|
||||
|
||||
function abortUpgrade(socket: Duplex, status: number, message?: string): void {
|
||||
try {
|
||||
const body = message ? message : http.STATUS_CODES[status] || '';
|
||||
const head =
|
||||
`HTTP/1.1 ${status} ${http.STATUS_CODES[status] || 'Error'}\r\n` +
|
||||
'Connection: close\r\n' +
|
||||
`Content-Length: ${Buffer.byteLength(body)}\r\n` +
|
||||
'Content-Type: text/plain\r\n\r\n';
|
||||
socket.write(head + body);
|
||||
} catch { /* noop */ }
|
||||
try { socket.destroy(); } catch { /* noop */ }
|
||||
}
|
||||
|
||||
const TLS_OPTION_KEYS = [
|
||||
'ALPNProtocols',
|
||||
'SNICallback',
|
||||
'ca',
|
||||
'cert',
|
||||
'ciphers',
|
||||
'clientCertEngine',
|
||||
'crl',
|
||||
'dhparam',
|
||||
'ecdhCurve',
|
||||
'honorCipherOrder',
|
||||
'key',
|
||||
'maxVersion',
|
||||
'minVersion',
|
||||
'passphrase',
|
||||
'pfx',
|
||||
'privateKeyEngine',
|
||||
'privateKeyIdentifier',
|
||||
'requestCert',
|
||||
'rejectUnauthorized',
|
||||
'secureOptions',
|
||||
'secureProtocol',
|
||||
'sessionIdContext',
|
||||
'sigalgs',
|
||||
'ticketKeys',
|
||||
] as const;
|
||||
|
||||
type TlsOptions = Record<string, unknown>;
|
||||
|
||||
function getTlsOptions(options: WebSocketServerOptions & TlsOptions): TlsOptions {
|
||||
const tlsOptions: TlsOptions = {};
|
||||
for (const key of TLS_OPTION_KEYS) {
|
||||
if ((options as TlsOptions)[key] !== undefined) tlsOptions[key] = (options as TlsOptions)[key];
|
||||
}
|
||||
if (options.tls && typeof options.tls === 'object') {
|
||||
Object.assign(tlsOptions, options.tls);
|
||||
}
|
||||
return tlsOptions;
|
||||
}
|
||||
|
||||
export type SubprotocolSelector = (requested: string[]) => string | null | undefined;
|
||||
|
||||
export interface WebSocketServerOptions {
|
||||
port?: number;
|
||||
host?: string;
|
||||
server?: HttpServer | HttpsServer;
|
||||
noServer?: boolean;
|
||||
path?: string;
|
||||
maxPayload?: number;
|
||||
verifyClient?: ((info: { origin?: string; secure: boolean; req: IncomingMessage }) => boolean) | ((info: { origin?: string; secure: boolean; req: IncomingMessage }, cb: (allow: boolean, code?: number, message?: string, headers?: Record<string, string>) => void) => void);
|
||||
protocols?: string | string[] | Set<string> | SubprotocolSelector;
|
||||
perMessageDeflate?: boolean | PerMessageDeflateConfig;
|
||||
backlog?: number;
|
||||
tls?: TlsOptions;
|
||||
}
|
||||
|
||||
type UpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => void;
|
||||
|
||||
export class WebSocketServer extends EventEmitter {
|
||||
public readonly options: WebSocketServerOptions & { tls?: TlsOptions };
|
||||
public readonly clients = new Set<WebSocket>();
|
||||
private _server: HttpServer | HttpsServer | null = null;
|
||||
private _externalServer: HttpServer | HttpsServer | null = null;
|
||||
private _upgradeHandler: UpgradeHandler | null = null;
|
||||
|
||||
constructor(options?: WebSocketServerOptions) {
|
||||
super();
|
||||
options = options || {};
|
||||
this.options = {
|
||||
port: options.port,
|
||||
host: options.host,
|
||||
server: options.server,
|
||||
noServer: !!options.noServer,
|
||||
path: options.path,
|
||||
maxPayload: options.maxPayload,
|
||||
verifyClient: options.verifyClient,
|
||||
protocols: options.protocols,
|
||||
perMessageDeflate: options.perMessageDeflate,
|
||||
backlog: options.backlog,
|
||||
tls: options.tls,
|
||||
};
|
||||
const tlsOptions = getTlsOptions(options as WebSocketServerOptions & TlsOptions);
|
||||
this.options.tls = Object.keys(tlsOptions).length > 0 ? tlsOptions : undefined;
|
||||
|
||||
if (this.options.noServer) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.options.server) {
|
||||
this._externalServer = this.options.server;
|
||||
this._attachToServer(this._externalServer);
|
||||
} else if (this.options.port !== undefined) {
|
||||
const requestHandler = (_req: IncomingMessage, res: ServerResponse) => {
|
||||
const body = http.STATUS_CODES[426] ?? '';
|
||||
res.writeHead(426, {
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'Content-Type': 'text/plain',
|
||||
});
|
||||
res.end(body);
|
||||
};
|
||||
this._server = this.options.tls
|
||||
? https.createServer(this.options.tls, requestHandler)
|
||||
: http.createServer(requestHandler);
|
||||
this._attachToServer(this._server);
|
||||
this._server.listen(
|
||||
this.options.port,
|
||||
this.options.host,
|
||||
this.options.backlog,
|
||||
() => this.emit('listening'),
|
||||
);
|
||||
this._server.on('error', (err: Error) => this.emit('error', err));
|
||||
} else {
|
||||
throw new Error('WebSocketServer requires { port } or { server } or { noServer: true }');
|
||||
}
|
||||
}
|
||||
|
||||
address(): ReturnType<HttpServer['address']> | null {
|
||||
if (this._server) return this._server.address();
|
||||
if (this._externalServer && this._externalServer.address) return this._externalServer.address();
|
||||
return null;
|
||||
}
|
||||
|
||||
private _attachToServer(server: HttpServer | HttpsServer): void {
|
||||
const handler: UpgradeHandler = (req, socket, head) => {
|
||||
if (this.options.path) {
|
||||
const urlPath = (req.url ?? '/').split('?')[0];
|
||||
if (urlPath !== this.options.path) {
|
||||
if (server.listenerCount('upgrade') === 1) {
|
||||
abortUpgrade(socket, 400, 'Bad path for WebSocket');
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.handleUpgrade(req, socket, head, (ws) => {
|
||||
this.emit('connection', ws, req);
|
||||
});
|
||||
};
|
||||
this._upgradeHandler = handler;
|
||||
server.on('upgrade', handler);
|
||||
}
|
||||
|
||||
handleUpgrade(
|
||||
request: IncomingMessage,
|
||||
socket: Duplex,
|
||||
head: Buffer,
|
||||
cb: (ws: WebSocket, request: IncomingMessage) => void,
|
||||
): void {
|
||||
const upgrade = (request.headers['upgrade'] ?? '').toLowerCase();
|
||||
const connection = (Array.isArray(request.headers['connection']) ? request.headers['connection'].join(',') : (request.headers['connection'] ?? '')).toLowerCase();
|
||||
const version = request.headers['sec-websocket-version'];
|
||||
const key = request.headers['sec-websocket-key'];
|
||||
|
||||
if (request.method !== 'GET') return abortUpgrade(socket, 405, 'Method not allowed');
|
||||
if (upgrade !== 'websocket') return abortUpgrade(socket, 400, 'Upgrade header must be websocket');
|
||||
if (!/\bupgrade\b/i.test(connection)) return abortUpgrade(socket, 400, 'Connection header must contain "upgrade"');
|
||||
if (version !== '13') {
|
||||
try {
|
||||
socket.write(
|
||||
'HTTP/1.1 426 Upgrade Required\r\n' +
|
||||
'Sec-WebSocket-Version: 13\r\n' +
|
||||
'Connection: close\r\n\r\n');
|
||||
} catch { /* noop */ }
|
||||
try { socket.destroy(); } catch { /* noop */ }
|
||||
return;
|
||||
}
|
||||
if (typeof key !== 'string' || !/^[+/0-9A-Za-z]{22}==$/.test(key)) {
|
||||
return abortUpgrade(socket, 400, 'Invalid Sec-WebSocket-Key');
|
||||
}
|
||||
|
||||
const doAccept = () => {
|
||||
const accept = computeAccept(key);
|
||||
const extension = acceptPerMessageDeflate(
|
||||
request.headers['sec-websocket-extensions'] as string | undefined,
|
||||
this.options.perMessageDeflate,
|
||||
);
|
||||
const protocol = chooseSubprotocol(
|
||||
request.headers['sec-websocket-protocol'] as string | undefined,
|
||||
this.options.protocols,
|
||||
);
|
||||
const responseHeaders = [
|
||||
'HTTP/1.1 101 Switching Protocols',
|
||||
'Upgrade: websocket',
|
||||
'Connection: Upgrade',
|
||||
`Sec-WebSocket-Accept: ${accept}`,
|
||||
];
|
||||
if (extension) responseHeaders.push(`Sec-WebSocket-Extensions: ${extension.header}`);
|
||||
if (protocol) responseHeaders.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
||||
try {
|
||||
socket.write(responseHeaders.join('\r\n') + '\r\n\r\n');
|
||||
} catch {
|
||||
try { socket.destroy(); } catch { /* noop */ }
|
||||
return;
|
||||
}
|
||||
|
||||
const ns = socket as Duplex & { setTimeout?: (ms: number) => void; setNoDelay?: (b: boolean) => void };
|
||||
ns.setTimeout?.(0);
|
||||
ns.setNoDelay?.(true);
|
||||
|
||||
const ws = new WebSocket(socket as unknown as import('node:net').Socket, {
|
||||
isServer: true,
|
||||
maxPayload: this.options.maxPayload,
|
||||
extensions: extension ? { perMessageDeflate: extension.options } : undefined,
|
||||
protocol: protocol ?? '',
|
||||
readyState: OPEN,
|
||||
});
|
||||
this.clients.add(ws);
|
||||
ws.on('close', () => this.clients.delete(ws));
|
||||
|
||||
if (head && head.length > 0) ws._onData(head);
|
||||
|
||||
cb(ws, request);
|
||||
};
|
||||
|
||||
const verify = this.options.verifyClient;
|
||||
if (typeof verify === 'function') {
|
||||
type VerifyInfo = { origin?: string; secure: boolean; req: IncomingMessage };
|
||||
const info: VerifyInfo = {
|
||||
origin: request.headers['origin'] as string | undefined,
|
||||
secure: !!((socket as unknown as { encrypted?: boolean }).encrypted),
|
||||
req: request,
|
||||
};
|
||||
if (verify.length >= 2) {
|
||||
(verify as (i: VerifyInfo, cb: (allow: boolean, code?: number, message?: string) => void) => void)(
|
||||
info,
|
||||
(allow, code, message) => {
|
||||
if (!allow) return abortUpgrade(socket, code || 401, message);
|
||||
doAccept();
|
||||
},
|
||||
);
|
||||
} else {
|
||||
const allow = (verify as (i: VerifyInfo) => boolean)(info);
|
||||
if (!allow) return abortUpgrade(socket, 401, 'Unauthorized');
|
||||
doAccept();
|
||||
}
|
||||
} else {
|
||||
doAccept();
|
||||
}
|
||||
}
|
||||
|
||||
close(cb?: (err?: Error) => void): void {
|
||||
if (this._externalServer && this._upgradeHandler) {
|
||||
this._externalServer.removeListener('upgrade', this._upgradeHandler);
|
||||
this._upgradeHandler = null;
|
||||
}
|
||||
for (const ws of this.clients) {
|
||||
try { ws.close(1001, 'Server shutting down'); } catch { /* noop */ }
|
||||
}
|
||||
if (this._server) {
|
||||
this._server.close((err?: Error) => cb && cb(err));
|
||||
} else if (cb) {
|
||||
setImmediate(cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
482
packages/websocket/src/websocket.ts
Normal file
482
packages/websocket/src/websocket.ts
Normal file
@@ -0,0 +1,482 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import crypto from 'node:crypto';
|
||||
import type { Socket } from 'node:net';
|
||||
import native, { type ParsedFrame, type ParserInstance } from './native';
|
||||
import {
|
||||
type AcceptedPerMessageDeflate,
|
||||
compressRaw,
|
||||
decompressRaw,
|
||||
} from './extensions';
|
||||
|
||||
// RFC 6455 opcodes.
|
||||
export const OP_CONT = 0x0;
|
||||
export const OP_TEXT = 0x1;
|
||||
export const OP_BIN = 0x2;
|
||||
export const OP_CLOSE = 0x8;
|
||||
export const OP_PING = 0x9;
|
||||
export const OP_PONG = 0xA;
|
||||
export const RSV1 = 0x40;
|
||||
|
||||
// Ready states (mirror the standard WebSocket API numbers).
|
||||
export const CONNECTING = 0;
|
||||
export const OPEN = 1;
|
||||
export const CLOSING = 2;
|
||||
export const CLOSED = 3;
|
||||
|
||||
const DEFAULT_MAX_PAYLOAD = 100 * 1024 * 1024;
|
||||
|
||||
export function isValidCloseCode(code: number): boolean {
|
||||
if (
|
||||
code === 1000 || code === 1001 || code === 1002 || code === 1003 ||
|
||||
code === 1007 || code === 1008 || code === 1009 || code === 1010 ||
|
||||
code === 1011
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (code >= 3000 && code <= 4999) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function encodeClosePayload(code: number | undefined | null, reason?: string): Buffer {
|
||||
const reasonBuf = reason ? Buffer.from(String(reason), 'utf8') : Buffer.alloc(0);
|
||||
if (code === undefined || code === null) {
|
||||
if (reasonBuf.length > 0) {
|
||||
throw new Error('Cannot send close reason without a code');
|
||||
}
|
||||
return Buffer.alloc(0);
|
||||
}
|
||||
const buf = Buffer.allocUnsafe(2 + reasonBuf.length);
|
||||
buf.writeUInt16BE(code & 0xFFFF, 0);
|
||||
reasonBuf.copy(buf, 2);
|
||||
return buf;
|
||||
}
|
||||
|
||||
// Streaming UTF-8 validator used while a text message is being received in
|
||||
// fragments. Returns false if invalid; `done()` checks code-point boundary.
|
||||
class Utf8Validator {
|
||||
private state = 0;
|
||||
private codepoint = 0;
|
||||
private minNext = 0;
|
||||
|
||||
push(buf: Buffer): boolean {
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
const b = buf[i]!;
|
||||
if (this.state === 0) {
|
||||
if ((b & 0x80) === 0) continue;
|
||||
if ((b & 0xE0) === 0xC0) {
|
||||
if (b < 0xC2) return false;
|
||||
this.codepoint = b & 0x1F;
|
||||
this.state = 1;
|
||||
this.minNext = 0x80;
|
||||
} else if ((b & 0xF0) === 0xE0) {
|
||||
this.codepoint = b & 0x0F;
|
||||
this.state = 2;
|
||||
this.minNext = (b === 0xE0) ? 0xA0 : 0x80;
|
||||
} else if ((b & 0xF8) === 0xF0) {
|
||||
if (b > 0xF4) return false;
|
||||
this.codepoint = b & 0x07;
|
||||
this.state = 3;
|
||||
this.minNext = (b === 0xF0) ? 0x90 : 0x80;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (b < this.minNext || b > 0xBF) return false;
|
||||
if (this.state === 2 && this.codepoint === 0xD && (b & 0x20)) {
|
||||
return false;
|
||||
}
|
||||
if (this.codepoint === 0xD && this.state === 2 && b >= 0xA0) {
|
||||
return false;
|
||||
}
|
||||
this.codepoint = (this.codepoint << 6) | (b & 0x3F);
|
||||
this.state--;
|
||||
this.minNext = 0x80;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
done(): boolean {
|
||||
return this.state === 0;
|
||||
}
|
||||
}
|
||||
|
||||
export function randomMaskKey(): Buffer {
|
||||
const b = Buffer.allocUnsafe(4);
|
||||
crypto.randomFillSync(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
export interface SendOptions {
|
||||
binary?: boolean;
|
||||
compress?: boolean;
|
||||
}
|
||||
|
||||
export type SendCallback = (err?: Error | null) => void;
|
||||
|
||||
export type WebSocketRawData = Buffer;
|
||||
|
||||
export interface WebSocketEvents {
|
||||
message: (data: Buffer, isBinary: boolean) => void;
|
||||
ping: (data: Buffer) => void;
|
||||
pong: (data: Buffer) => void;
|
||||
close: (code: number, reason: string) => void;
|
||||
error: (err: Error) => void;
|
||||
}
|
||||
|
||||
export interface WebSocketOptions {
|
||||
isServer?: boolean;
|
||||
maxPayload?: number;
|
||||
readyState?: number;
|
||||
extensions?: { perMessageDeflate?: AcceptedPerMessageDeflate };
|
||||
protocol?: string;
|
||||
}
|
||||
|
||||
// Shared WebSocket connection handling logic (post-handshake).
|
||||
export class WebSocket extends EventEmitter {
|
||||
protected readonly _socket: Socket;
|
||||
protected readonly _isServer: boolean;
|
||||
protected readonly _maxPayload: number;
|
||||
protected _readyState: number;
|
||||
protected readonly _perMessageDeflate?: AcceptedPerMessageDeflate;
|
||||
public protocol: string;
|
||||
public extensions: string;
|
||||
|
||||
protected readonly _parser: ParserInstance;
|
||||
|
||||
// Fragmented message assembly state.
|
||||
protected _msgOpcode = 0;
|
||||
protected _msgChunks: Buffer[] = [];
|
||||
protected _msgSize = 0;
|
||||
protected _msgValidator: Utf8Validator | null = null;
|
||||
protected _msgCompressed = false;
|
||||
|
||||
// Close state.
|
||||
protected _closeCodeSent: number | null = null;
|
||||
protected _closeCodeReceived: number | null = null;
|
||||
protected _closeReasonReceived = '';
|
||||
protected _closeFrameSent = false;
|
||||
protected _closeTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
// Ready state constants exposed as instance fields (for ws compatibility).
|
||||
static readonly CONNECTING = CONNECTING;
|
||||
static readonly OPEN = OPEN;
|
||||
static readonly CLOSING = CLOSING;
|
||||
static readonly CLOSED = CLOSED;
|
||||
|
||||
constructor(socket: Socket, options?: WebSocketOptions) {
|
||||
super();
|
||||
options = options || {};
|
||||
this._socket = socket;
|
||||
this._isServer = !!options.isServer;
|
||||
this._maxPayload = options.maxPayload ?? DEFAULT_MAX_PAYLOAD;
|
||||
this._readyState = options.readyState ?? OPEN;
|
||||
this._perMessageDeflate = options.extensions?.perMessageDeflate;
|
||||
this.protocol = options.protocol || '';
|
||||
this.extensions = this._perMessageDeflate ? 'permessage-deflate' : '';
|
||||
|
||||
this._parser = new native.Parser({
|
||||
isServer: this._isServer,
|
||||
maxPayload: this._maxPayload,
|
||||
allowedRsv: this._perMessageDeflate ? RSV1 : 0,
|
||||
});
|
||||
|
||||
this._bindSocket();
|
||||
}
|
||||
|
||||
get readyState(): number { return this._readyState; }
|
||||
get isServer(): boolean { return this._isServer; }
|
||||
|
||||
protected _bindSocket(): void {
|
||||
const sock = this._socket;
|
||||
sock.on('data', (chunk: Buffer) => this._onData(chunk));
|
||||
sock.on('end', () => this._onEnd());
|
||||
sock.on('close', () => this._onSocketClose());
|
||||
sock.on('error', (err: Error) => this._onError(err));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
_onData(chunk: Buffer): void {
|
||||
if (this._readyState === CLOSED) return;
|
||||
const res = this._parser.push(chunk);
|
||||
if (res.error) {
|
||||
this._failConnection(res.code || 1002, res.message || 'Protocol error');
|
||||
return;
|
||||
}
|
||||
for (const f of res.frames) {
|
||||
this._handleFrame(f);
|
||||
if (this._readyState === CLOSED) return;
|
||||
}
|
||||
}
|
||||
|
||||
protected _onEnd(): void {
|
||||
if (this._readyState !== CLOSED) {
|
||||
if (this._closeCodeReceived === null) {
|
||||
this._closeCodeReceived = 1006;
|
||||
this._closeReasonReceived = '';
|
||||
}
|
||||
this._destroySocket();
|
||||
}
|
||||
}
|
||||
|
||||
protected _onSocketClose(): void {
|
||||
if (this._readyState === CLOSED) return;
|
||||
if (this._closeCodeReceived === null) {
|
||||
this._closeCodeReceived = 1006;
|
||||
}
|
||||
this._readyState = CLOSED;
|
||||
if (this._closeTimer) { clearTimeout(this._closeTimer); this._closeTimer = null; }
|
||||
this.emit('close', this._closeCodeReceived, this._closeReasonReceived);
|
||||
}
|
||||
|
||||
protected _onError(err: Error): void {
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
protected _handleFrame(f: ParsedFrame): void {
|
||||
const { fin, opcode, payload } = f;
|
||||
const rsv = f.rsv ?? 0;
|
||||
if (opcode === OP_PING) {
|
||||
this.emit('ping', payload);
|
||||
if (this._readyState === OPEN) this._sendControl(OP_PONG, payload);
|
||||
return;
|
||||
}
|
||||
if (opcode === OP_PONG) {
|
||||
this.emit('pong', payload);
|
||||
return;
|
||||
}
|
||||
if (opcode === OP_CLOSE) {
|
||||
this._handleCloseFrame(payload);
|
||||
return;
|
||||
}
|
||||
|
||||
if (opcode === OP_TEXT || opcode === OP_BIN) {
|
||||
if (this._msgOpcode !== 0) {
|
||||
this._failConnection(1002, 'New data frame started before previous fragmented message finished');
|
||||
return;
|
||||
}
|
||||
if ((rsv & RSV1) && !this._perMessageDeflate) {
|
||||
this._failConnection(1002, 'Compressed frame without negotiated permessage-deflate');
|
||||
return;
|
||||
}
|
||||
this._msgOpcode = opcode;
|
||||
this._msgChunks = [];
|
||||
this._msgSize = 0;
|
||||
this._msgCompressed = (rsv & RSV1) !== 0;
|
||||
this._msgValidator = (opcode === OP_TEXT) ? new Utf8Validator() : null;
|
||||
} else if (opcode === OP_CONT) {
|
||||
if (this._msgOpcode === 0) {
|
||||
this._failConnection(1002, 'Continuation frame without active message');
|
||||
return;
|
||||
}
|
||||
if (rsv !== 0) {
|
||||
this._failConnection(1002, 'RSV bits set on continuation frame');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this._msgSize += payload.length;
|
||||
if (this._msgSize > this._maxPayload) {
|
||||
this._failConnection(1009, 'Message too large');
|
||||
return;
|
||||
}
|
||||
if (payload.length > 0) this._msgChunks.push(payload);
|
||||
|
||||
if (fin) {
|
||||
let data = this._msgChunks.length === 1
|
||||
? this._msgChunks[0]!
|
||||
: Buffer.concat(this._msgChunks, this._msgSize);
|
||||
if (this._msgCompressed) {
|
||||
try {
|
||||
data = decompressRaw(data, this._maxPayload);
|
||||
} catch (err) {
|
||||
const e = err as Error & { code?: number };
|
||||
this._failConnection(e.code || 1007, e.message || 'Invalid compressed payload');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this._msgValidator) {
|
||||
if (!this._msgValidator.push(data) || !this._msgValidator.done()) {
|
||||
this._failConnection(1007, 'Invalid UTF-8');
|
||||
return;
|
||||
}
|
||||
}
|
||||
const isBinary = this._msgOpcode === OP_BIN;
|
||||
this._msgOpcode = 0;
|
||||
this._msgChunks = [];
|
||||
this._msgSize = 0;
|
||||
this._msgValidator = null;
|
||||
this._msgCompressed = false;
|
||||
this.emit('message', data, isBinary);
|
||||
}
|
||||
}
|
||||
|
||||
protected _handleCloseFrame(payload: Buffer): void {
|
||||
let code = 1005;
|
||||
let reason = '';
|
||||
if (payload.length === 1) {
|
||||
this._failConnection(1002, 'Close payload length 1');
|
||||
return;
|
||||
}
|
||||
if (payload.length >= 2) {
|
||||
code = payload.readUInt16BE(0);
|
||||
if (!isValidCloseCode(code)) {
|
||||
this._failConnection(1002, 'Invalid close code');
|
||||
return;
|
||||
}
|
||||
if (payload.length > 2) {
|
||||
try {
|
||||
reason = new TextDecoder('utf-8', { fatal: true }).decode(payload.subarray(2));
|
||||
} catch {
|
||||
this._failConnection(1007, 'Invalid UTF-8 in close reason');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
this._closeCodeReceived = code;
|
||||
this._closeReasonReceived = reason;
|
||||
|
||||
if (this._readyState === OPEN) {
|
||||
this._readyState = CLOSING;
|
||||
const echo = encodeClosePayload(code === 1005 ? undefined : code, '');
|
||||
this._sendControl(OP_CLOSE, echo);
|
||||
this._closeFrameSent = true;
|
||||
this._endSocketSoon();
|
||||
} else if (this._readyState === CLOSING) {
|
||||
this._endSocketSoon();
|
||||
}
|
||||
}
|
||||
|
||||
protected _endSocketSoon(): void {
|
||||
try { this._socket.end(); } catch { /* noop */ }
|
||||
if (this._closeTimer) clearTimeout(this._closeTimer);
|
||||
this._closeTimer = setTimeout(() => this._destroySocket(), 30000);
|
||||
this._closeTimer.unref?.();
|
||||
}
|
||||
|
||||
protected _destroySocket(): void {
|
||||
try { this._socket.destroy(); } catch { /* noop */ }
|
||||
}
|
||||
|
||||
protected _failConnection(code: number, reason: string): void {
|
||||
if (this._readyState === CLOSED) return;
|
||||
const payload = encodeClosePayload(code, reason);
|
||||
let frame: Buffer | null = null;
|
||||
try {
|
||||
frame = native.buildFrame(OP_CLOSE, true, payload,
|
||||
this._isServer ? null : randomMaskKey(), 0);
|
||||
} catch { /* noop */ }
|
||||
this._closeCodeSent = code;
|
||||
this._readyState = CLOSING;
|
||||
const err = new Error(`WebSocket protocol error: ${reason}`) as Error & { code?: number };
|
||||
err.code = code;
|
||||
this.emit('error', err);
|
||||
try {
|
||||
if (frame) this._socket.end(frame);
|
||||
else this._socket.end();
|
||||
} catch { /* noop */ }
|
||||
if (this._closeTimer) clearTimeout(this._closeTimer);
|
||||
this._closeTimer = setTimeout(() => this._destroySocket(), 2000);
|
||||
this._closeTimer.unref?.();
|
||||
}
|
||||
|
||||
protected _sendControl(opcode: number, payload?: Buffer): void {
|
||||
const data = payload ?? Buffer.alloc(0);
|
||||
const frame = native.buildFrame(opcode, true, data, this._isServer ? null : randomMaskKey(), 0);
|
||||
this._socket.write(frame);
|
||||
}
|
||||
|
||||
// Public API -------------------------------------------------------------
|
||||
|
||||
send(data: string | Buffer | Uint8Array | ArrayBuffer, options?: SendOptions | SendCallback, cb?: SendCallback): void {
|
||||
if (typeof options === 'function') { cb = options; options = undefined; }
|
||||
const opts: SendOptions = options || {};
|
||||
if (this._readyState !== OPEN) {
|
||||
const err = new Error('WebSocket is not open');
|
||||
if (cb) { cb(err); return; }
|
||||
throw err;
|
||||
}
|
||||
let payload: Buffer;
|
||||
let opcode: number;
|
||||
if (typeof data === 'string') {
|
||||
payload = Buffer.from(data, 'utf8');
|
||||
opcode = opts.binary ? OP_BIN : OP_TEXT;
|
||||
} else if (Buffer.isBuffer(data)) {
|
||||
payload = data;
|
||||
opcode = opts.binary === false ? OP_TEXT : OP_BIN;
|
||||
} else if (data instanceof Uint8Array) {
|
||||
payload = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
||||
opcode = opts.binary === false ? OP_TEXT : OP_BIN;
|
||||
} else if (data instanceof ArrayBuffer) {
|
||||
payload = Buffer.from(data);
|
||||
opcode = opts.binary === false ? OP_TEXT : OP_BIN;
|
||||
} else {
|
||||
const err = new TypeError('Unsupported data type for send()');
|
||||
if (cb) { cb(err); return; }
|
||||
throw err;
|
||||
}
|
||||
let rsv = 0;
|
||||
if (this._perMessageDeflate && opts.compress !== false &&
|
||||
payload.length >= (this._perMessageDeflate.threshold ?? 1024)) {
|
||||
payload = compressRaw(payload);
|
||||
rsv = RSV1;
|
||||
}
|
||||
const maskKey = this._isServer ? null : randomMaskKey();
|
||||
const frame = native.buildFrame(opcode, true, payload, maskKey, rsv);
|
||||
this._socket.write(frame, cb);
|
||||
}
|
||||
|
||||
ping(data?: Buffer | string | SendCallback, _mask?: unknown, cb?: SendCallback): void {
|
||||
if (typeof data === 'function') { cb = data; data = undefined; }
|
||||
const payload = data
|
||||
? (Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8'))
|
||||
: Buffer.alloc(0);
|
||||
if (payload.length > 125) throw new Error('Ping payload must be <=125 bytes');
|
||||
if (this._readyState !== OPEN) {
|
||||
const err = new Error('WebSocket is not open');
|
||||
if (cb) { cb(err); return; }
|
||||
throw err;
|
||||
}
|
||||
const maskKey = this._isServer ? null : randomMaskKey();
|
||||
const frame = native.buildFrame(OP_PING, true, payload, maskKey, 0);
|
||||
this._socket.write(frame, cb);
|
||||
}
|
||||
|
||||
pong(data?: Buffer | string | SendCallback, _mask?: unknown, cb?: SendCallback): void {
|
||||
if (typeof data === 'function') { cb = data; data = undefined; }
|
||||
const payload = data
|
||||
? (Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8'))
|
||||
: Buffer.alloc(0);
|
||||
if (payload.length > 125) throw new Error('Pong payload must be <=125 bytes');
|
||||
if (this._readyState !== OPEN) {
|
||||
const err = new Error('WebSocket is not open');
|
||||
if (cb) { cb(err); return; }
|
||||
throw err;
|
||||
}
|
||||
const maskKey = this._isServer ? null : randomMaskKey();
|
||||
const frame = native.buildFrame(OP_PONG, true, payload, maskKey, 0);
|
||||
this._socket.write(frame, cb);
|
||||
}
|
||||
|
||||
close(code?: number, reason?: string): void {
|
||||
if (this._readyState === CLOSED || this._readyState === CLOSING) return;
|
||||
if (code !== undefined && !isValidCloseCode(code)) {
|
||||
throw new RangeError(`Invalid close code: ${code}`);
|
||||
}
|
||||
const reasonBuf = reason ? Buffer.from(String(reason), 'utf8') : Buffer.alloc(0);
|
||||
if (reasonBuf.length > 123) throw new RangeError('Close reason must be <=123 bytes');
|
||||
const payload = encodeClosePayload(code, reason);
|
||||
const maskKey = this._isServer ? null : randomMaskKey();
|
||||
const frame = native.buildFrame(OP_CLOSE, true, payload, maskKey, 0);
|
||||
this._readyState = CLOSING;
|
||||
this._closeCodeSent = code ?? null;
|
||||
this._socket.write(frame);
|
||||
this._closeFrameSent = true;
|
||||
this._endSocketSoon();
|
||||
}
|
||||
|
||||
terminate(): void {
|
||||
this._readyState = CLOSING;
|
||||
this._destroySocket();
|
||||
}
|
||||
}
|
||||
8
packages/websocket/tsconfig.json
Normal file
8
packages/websocket/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"typecheck": "tsc -b",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 9.3 KiB |
|
Before Width: | Height: | Size: 4.9 KiB After Width: | Height: | Size: 4.9 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user