added ws authentication
This commit is contained in:
@@ -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) => {
|
||||
|
||||
Reference in New Issue
Block a user