added ws authentication

This commit is contained in:
Luan Estradioto
2024-08-15 02:38:06 -03:00
parent c2ea8996ee
commit 548fc21e40
6 changed files with 238 additions and 161 deletions

View File

@@ -1,6 +1,9 @@
import { WebSocketServer } from 'ws';
import http from 'http';
import pty from 'node-pty';
import axios from 'axios';
import cookie from 'cookie';
import 'dotenv/config'
const server = http.createServer((req, res) => {
if (req.url === '/ready') {
@@ -12,7 +15,45 @@ const server = http.createServer((req, res) => {
}
});
const wss = new WebSocketServer({ server, path: '/terminal' });
const verifyClient = async (info, callback) => {
const cookies = cookie.parse(info.req.headers.cookie || '');
const origin = new URL(info.origin);
const protocol = origin.protocol;
const xsrfToken = cookies['XSRF-TOKEN'];
// Generate session cookie name based on APP_NAME
const appName = process.env.APP_NAME || 'laravel';
const sessionCookieName = `${appName.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase()}_session`;
const laravelSession = cookies[sessionCookieName];
// Verify presence of required tokens
if (!laravelSession || !xsrfToken) {
return callback(false, 401, 'Unauthorized: Missing required tokens');
}
try {
// Authenticate with Laravel backend
const response = await axios.post(`${protocol}//coolify/terminal/auth`, null, {
headers: {
'Cookie': `${sessionCookieName}=${laravelSession}`,
'X-XSRF-TOKEN': xsrfToken
},
});
if (response.status === 200) {
// Authentication successful
callback(true);
} else {
callback(false, 401, 'Unauthorized: Invalid credentials');
}
} catch (error) {
console.error('Authentication error:', error.message);
callback(false, 500, 'Internal Server Error');
}
};
const wss = new WebSocketServer({ server, path: '/terminal', verifyClient: verifyClient });
const userSessions = new Map();
wss.on('connection', (ws) => {