This commit is contained in:
2025-11-27 19:20:46 +08:00
parent 7cba8ae8b1
commit 2838d6163e
37 changed files with 2553 additions and 256 deletions

View File

@@ -0,0 +1,69 @@
import { WebSocketServer } from 'ws';
import { nanoid } from 'nanoid';
import { WsProxyManager } from './manager.ts';
import { getLoginUser } from '@/modules/auth.ts';
import { logger } from '../logger.ts';
export const wsProxyManager = new WsProxyManager();
export const upgrade = async (request: any, socket: any, head: any) => {
const req = request as any;
const url = new URL(req.url, 'http://localhost');
const id = url.searchParams.get('id');
if (url.pathname === '/ws/proxy') {
console.log('upgrade', request.url, id);
wss.handleUpgrade(req, socket, head, (ws) => {
// 这里手动触发 connection 事件
// @ts-ignore
wss.emit('connection', ws, req);
});
return true;
}
return false;
};
export const wss = new WebSocketServer({
noServer: true,
path: '/ws/proxy',
});
wss.on('connection', async (ws, req) => {
console.log('connected', req.url);
const url = new URL(req.url, 'http://localhost');
const id = url?.searchParams?.get('id') || nanoid();
const loginUser = await getLoginUser(req);
if (!loginUser) {
ws.send(JSON.stringify({ code: 401, message: 'No Login' }));
ws.close();
return;
}
const user = loginUser.tokenUser?.username;
wsProxyManager.register(id, { user, ws });
ws.send(
JSON.stringify({
type: 'connected',
user: user,
id,
}),
);
ws.on('message', async (event: Buffer) => {
const eventData = event.toString();
if (!eventData) {
return;
}
const data = JSON.parse(eventData);
logger.debug('message', data);
});
ws.on('close', () => {
logger.debug('ws closed');
wsProxyManager.unregister(id, user);
});
});
export class WssApp {
wss: WebSocketServer;
constructor() {
this.wss = wss;
}
upgrade(request: any, socket: any, head: any) {
return upgrade(request, socket, head);
}
}