initial code commit

This commit is contained in:
2024-12-14 22:55:58 -05:00
parent 32033c2d6d
commit 94ca6c8ccd
7 changed files with 1517 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
node_modules/
secrets/
+150
View File
@@ -0,0 +1,150 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TTY Login</title>
<style>
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: #000;
/* Black background for terminal feel */
color: #00ff00;
/* Green text for TTY style */
font-family: monospace;
font-size: 1rem;
}
.tty-container {
display: flex;
flex-direction: column;
width: 100%;
max-width: 600px;
padding: 1rem;
}
form {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
input {
background: transparent;
color: #00ff00;
border: none;
border-bottom: 1px solid #00ff00;
font-family: monospace;
font-size: 1rem;
padding: 0.25rem;
outline: none;
caret-color: #00ff00;
}
input::placeholder {
color: #008000;
/* Dim green for placeholder text */
}
input:focus {
border-bottom-color: #00ff00;
}
button {
display: none;
/* TTY doesn't have a visible button */
}
.tty-header {
margin-bottom: 1rem;
}
.tty-header h1 {
margin: 0;
font-size: 1.5rem;
color: #00ff00;
}
.tty-message {
margin-bottom: 0.5rem;
}
.tty-footer {
margin-top: 1rem;
font-size: 0.85rem;
color: #008000;
/* Dim green for footer */
}
.error-message {
color: red;
font-size: 0.9rem;
margin-top: 0.5rem;
}
</style>
</head>
<body>
<div class="tty-container">
<div class="tty-header">
<h1>TTY Login</h1>
</div>
<form id="loginForm">
<div class="tty-message">login:</div>
<input name="username" type="text" placeholder="Enter username" required autocomplete="off" />
<div class="tty-message">password:</div>
<input name="password" type="password" placeholder="Enter password" required />
<button type="submit">Login</button>
<div class="error-message" id="errorMessage"></div>
</form>
<div class="tty-footer">
Type your credentials and press <kbd>Enter</kbd>.
</div>
</div>
<script>
const form = document.querySelector('#loginForm');
const errorMessage = document.querySelector('#errorMessage');
form.addEventListener('submit', async (event) => {
event.preventDefault(); // Prevent form from submitting the traditional way
errorMessage.textContent = ''; // Clear previous error message
const formData = new FormData(form);
const payload = {
username: formData.get('username'),
password: formData.get('password')
};
try {
const response = await fetch('login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.status === 404) {
errorMessage.textContent = 'User not found.';
} else if (response.status === 401) {
errorMessage.textContent = 'Incorrect password.';
} else if (response.status === 500) {
errorMessage.textContent = 'Error logging in. Please try again later.';
} else if (response.ok) {
window.location.href = '/shell';
} else {
errorMessage.textContent = 'Unexpected error occurred.';
}
} catch (err) {
console.error(err);
errorMessage.textContent = 'Unable to connect to the server. Please try again later.';
}
});
</script>
</body>
</html>
+170
View File
@@ -0,0 +1,170 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shell</title>
<style>
body {
font-family: monospace;
background: #000000;
color: #ffffff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
padding: 0;
}
.terminal-container {
background: #000000;
border-radius: 5px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
gap: 1rem;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.terminal-header {
font-size: 1.5rem;
text-transform: uppercase;
color: #00ff00;
margin: 0;
}
.output {
flex-grow: 1;
width: 100%;
overflow: hidden;
/* border: 1px solid #444; */
background: #000000;
border-radius: 5px;
height: 100%;
margin: 0;
padding: 0;
}
/* For scrollbars */
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
background: #555;
}
::-webkit-scrollbar-thumb:hover {
background: #777;
}
</style>
<link rel="stylesheet" href="node_modules/@xterm/xterm/css/xterm.css" />
<script src="node_modules/@xterm/xterm/lib/xterm.js"></script>
<script src="node_modules/@xterm/addon-fit/lib/addon-fit.js"></script>
</head>
<body>
<div class="terminal-container">
<div class="output" id="output"></div>
</div>
<script>
function fitTerminalToScreen(term) {
const container = document.querySelector('#output'); // terminal container
const charWidth = term._core._renderService.dimensions.actualCellWidth;
const charHeight = term._core._renderService.dimensions.actualCellHeight;
console.log(term);
if (!charWidth || !charHeight) return;
// Calculate the number of columns and rows
const cols = Math.floor(container.offsetWidth / charWidth);
const rows = Math.floor(container.offsetHeight / charHeight);
console.log('Container height:', container.clientHeight);
console.log('Char height:', charHeight);
console.log('Rows calculated:', Math.floor(container.clientHeight / charHeight));
// Resize the terminal
term.resize(cols, rows);
}
</script>
<script>
// create terminal instance
const term = new Terminal({
// cols: 800,
// rows: 24,
cursorBlink: true,
theme: {
background: '#000000',
foreground: '#ffffff',
cursor: '#00ff00',
}
});
// mount terminal
const outputContainer = document.querySelector('#output');
term.open(outputContainer);
// create websocket connection
const protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
const ws = new WebSocket(`${protocol}${location.host}/shell-ws`);
// handle terminal input and send to websocket
term.onData(data => {
ws.send(data);
});
// handle incoming websocket messages and write to terminal
ws.addEventListener('message', event => {
const data = JSON.parse(event.data);
if (data.event) {
switch (data.event) {
case 'exit':
term.write('\r\nConnection closed. Redirecting...\r\n');
setTimeout(() => window.location.pathname = '/login', 2000);
break;
default:
console.error(`Unknown event: ${data.event}`);
term.write(`\r\nUnknown event: ${data.event}\r\n`);
break;
}
} else {
term.write(data.data);
}
});
// handle websocket closure
ws.addEventListener('close', event => {
term.write(`\r\nConnection closed with code ${event.code}\r\n`);
});
// handle websocket errors
ws.addEventListener('error', () => {
term.write('\r\nConnection error. Please try again later.\r\n');
});
window.addEventListener('resize', () => {
document.querySelector('.xterm-screen').style.width = `${window.innerWidth}px`;
document.querySelector('.xterm-screen').style.height = `${window.innerHeight}px`;
})
const fitAddon = new FitAddon.FitAddon();
term.loadAddon(fitAddon);
fitAddon.fit();
</script>
</body>
</html>
+2
View File
@@ -1,2 +1,4 @@
# web-to-fish
takes input from the browser and pipes it into fish
I basically just made this because I can't be bothered to figure out how to use ssh through cloudflared and the wifi here's blocked port 22/ssh in general
+124
View File
@@ -0,0 +1,124 @@
// file: index.js
// run: node index.js
// then open http://localhost:3000 in your browser
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import session from 'express-session';
import expressWs from 'express-ws';
import { spawn } from 'node-pty';
import json from './secrets/config.json' with { type: 'json' };
import stripAnsi from 'strip-ansi';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
expressWs(app); // enable websockets for the app
const PORT = 3000;
// configure session
app.use(session({
secret: json.secretkey,
resave: false,
saveUninitialized: false
}));
// parse form data
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ extended: true }));
app.use('/node_modules', express.static('node_modules'));
// simple hard-coded credentials (for demonstration)
const validUsername = 'user';
const validPassword = 'pass';
// authentication middleware
function requireAuth(req, res, next) {
if (req.session && req.session.authenticated) {
return next();
} else {
res.redirect('/login');
}
}
// serve login page
app.get('/login', (req, res) => {
res.sendFile('login.html', { root: path.join(__dirname, 'HTML') });
});
// process login
app.post('/login', (req, res) => {
try {
const username = req.body.username;
const password = req.body.password;
if (!username) return res.sendStatus(404);
else if (!password) return res.sendStatus(401);
const shell = spawn('su', [`${username}`], {
cwd: process.env.HOME,
env: process.env
});
req.on('end', () => shell.kill());
shell.onData((data) => {
if (data?.toLowerCase().trim() === 'password:') shell.write(password + '\n');
else if (data.includes('does not exist')) res.sendStatus(404);
else if (data.includes('Authentication failure')) res.sendStatus(401);
else if (data.includes('Welcome to fish')) {
req.session.authenticated = true;
res.redirect('/shell');
shell.kill();
}
else console.error(`unknown terminal output:\n${data}`);
});
}
catch (err) {
console.error(err);
}
});
// shell interface
app.get('/shell', requireAuth, (req, res) => {
res.sendFile('shell.html', { root: path.join(__dirname, 'HTML') });
});
// logout route
app.get('/logout', (req, res) => {
req.session.destroy(() => {
res.redirect('/login');
});
});
// when a websocket is opened at /shell-ws, spawn a fish shell in a pty
app.ws('/shell-ws', (ws, req) => {
// spawn a fish shell using node-pty, with a pseudo-terminal
const shell = spawn('fish', [], {
cols: 80,
rows: 24,
cwd: process.env.HOME,
env: process.env
});
// send any data from the shell to the client
shell.onData((data) => {
ws.send(JSON.stringify({ data }));
});
shell.onExit((e) => ws.send(JSON.stringify({ event: 'exit', code: e })));
// when the client sends data, write it to the shell's stdin
ws.on('message', (msg) => shell.write(msg));
// when the websocket closes, kill the shell
ws.on('close', () => shell.kill());
});
app.listen(PORT, () => {
console.log('server listening on http://localhost:' + PORT);
});
+1048
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
{
"name": "webtoconsole",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
"express": "^4.21.2",
"express-session": "^1.18.1",
"express-ws": "^5.0.2",
"node-pty": "^1.0.0",
"strip-ansi": "^7.1.0"
},
"type": "module"
}