( socket: AuthenticatedSocket, next: NextFunction )
| 27 | } |
| 28 | |
| 29 | async function authenticateSocket( |
| 30 | socket: AuthenticatedSocket, |
| 31 | next: NextFunction |
| 32 | ): Promise<void> { |
| 33 | const headers = socket.request.headers |
| 34 | const isTunnel = !!(headers['cf-connecting-ip'] || headers['cf-ray']) |
| 35 | const cookieToken = extractTunnelSessionTokenFromCookieHeader(headers.cookie) |
| 36 | |
| 37 | if (isTunnel && TunnelService.isRunning()) { |
| 38 | if (!cookieToken || !TunnelService.validateToken(cookieToken)) { |
| 39 | return next(new Error('Unauthorized: valid tunnel session cookie required')) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | const internalToken = headers[INTERNAL_API_TOKEN_HEADER] |
| 44 | const normalizedInternalToken = Array.isArray(internalToken) ? internalToken[0] : internalToken |
| 45 | if (internalToken !== undefined) { |
| 46 | if (!validateInternalApiToken(normalizedInternalToken)) { |
| 47 | return next(new Error('Unauthorized: invalid internal token')) |
| 48 | } |
| 49 | socket.accessAuthSessionSecretGeneration = AccessAuthService.getSessionSecretGeneration() |
| 50 | } else { |
| 51 | const accessToken = AccessAuthService.extractCookieFromHeader(headers.cookie) |
| 52 | const accessAuthResult = await AccessAuthService.validateSessionTokenWithGeneration(accessToken) |
| 53 | if (!accessAuthResult.valid) { |
| 54 | return next(new Error('Unauthorized: access password required')) |
| 55 | } |
| 56 | socket.accessAuthSessionSecretGeneration = accessAuthResult.generation |
| 57 | } |
| 58 | |
| 59 | // 设置用户标识 |
| 60 | if (cookieToken) { |
| 61 | socket.userId = cookieToken |
| 62 | socket.username = `User-${cookieToken.slice(0, 6)}` |
| 63 | } else { |
| 64 | socket.userId = `anonymous-${socket.id.slice(0, 8)}` |
| 65 | socket.username = 'Anonymous' |
| 66 | } |
| 67 | |
| 68 | next() |
| 69 | } |
no test coverage detected