Modularize portfolio commands and owner chat

This commit is contained in:
2026-07-27 09:27:57 +09:00
parent 79f2386a24
commit e499ae5adc
3 changed files with 49 additions and 27 deletions
+6 -24
View File
@@ -5,7 +5,8 @@ import net from 'node:net';
import crypto from 'node:crypto';
import ssh2 from 'ssh2';
import { loadConfig, configPath } from './config.js';
import { color, clear, wrap } from './terminal.js';
import { color, clear } from './terminal.js';
import { createCommandRouter } from './commands.js';
const { Server } = ssh2;
@@ -23,29 +24,10 @@ function render(ctx, body = '') {
const title = `${p.name || 'Your Name'}${p.tagline || ''}`; const users = `${count()} connected`; const gap = ' '.repeat(Math.max(2, (ctx.cols || 80) - title.length - users.length));
return `${clear}${color(primary, title)}${gap}${color(config.theme?.muted || 'brightBlack', users)}\n${color(config.theme?.muted || 'brightBlack', p.location || '')}\n\n${body}\n\n${color(primary, 'portfolio')} ${isAdmin(ctx) ? color('yellow', '[admin]') : ''}> `;
}
function page(ctx, name) {
const p = config.pages?.[name]; if (!p) return `${color('red', `No page named “${name}”.`)}\nTry: pages`;
return `${color(config.theme?.accent || 'yellow', p.title || name)}\n${wrap((p.lines || []).join('\n')).join('\n')}`;
}
function home(ctx) { const p = config.persona || {}; return `${color(config.theme?.accent || 'yellow', `Welcome to ${p.name || 'my portfolio'}`)}\n\n${wrap(p.bio || 'You are exploring a portfolio over SSH. Type “help” to get started.').join('\n')}\n\nCommands: home · pages · open <page> · chat · contact · clear · quit`; }
function help(ctx) { return `help Show this help\nhome Return home\npages List available pages\nopen <page> Open a page\nchat <message> Chat with the owner/visitors\ncontact Show contact details\nclear Clear the screen\nquit Disconnect${isAdmin(ctx) ? '\n\nAdmin: reload · theme <color> · announce <message>' : ''}`; }
function execute(ctx, input) {
const [command, ...rest] = input.trim().split(/\s+/); const arg = rest.join(' ');
if (!command) return home(ctx);
if (command === 'help') return help(ctx); if (command === 'home') return home(ctx); if (command === 'clear') return '';
if (command === 'pages') return Object.entries(config.pages || {}).map(([k, v]) => `${color(config.theme?.accent || 'yellow', k.padEnd(14))} ${v.title || ''}`).join('\n') || 'No pages configured.';
if (command === 'open') return arg ? page(ctx, arg) : 'Usage: open <page>';
if (command === 'contact') return `Email: ${config.persona?.email || 'not configured'}`;
if (command === 'chat') { if (!arg) return 'Usage: chat <message>'; const author = isAdmin(ctx) ? `${config.persona?.name || 'Owner'} [owner]` : (ctx.username || 'visitor'); const line = `${author}: ${arg}`; for (const s of sessions) s.channel.write(`\r\n${color(config.theme?.accent || 'yellow', line)}\r\n` + render(s.ctx)); sendNotification(line); return 'Message sent.'; }
if (command === 'reload' && isAdmin(ctx)) { Object.assign(config, loadConfig()); return 'Configuration reloaded.'; }
if (command === 'theme' && isAdmin(ctx) && arg) { config.theme.primary = arg; return `Primary color set to ${arg} (runtime only; edit config to persist).`; }
if (command === 'announce' && isAdmin(ctx) && arg) { for (const s of sessions) s.channel.write(`\r\n${color(config.theme?.accent || 'yellow', `OWNER: ${arg}`)}\r\n` + render(s.ctx)); sendNotification(`OWNER: ${arg}`); return 'Announcement sent.'; }
if (command === 'quit' || command === 'exit') { ctx.channel.end(); return ''; }
return `Unknown command: ${command}. Try “help”.`;
}
const router = createCommandRouter({ config, isAdmin, ownerOnline: () => [...sessions].some(s => s.ctx.admin), sendNotification, reload: () => Object.assign(config, loadConfig()), broadcast: line => { for (const s of sessions) s.channel.write(`\r\n${color(config.theme?.accent || 'yellow', line)}\r\n` + render(s.ctx)); } });
function handleSession(channel, ctx) {
let buffer = ''; ctx.channel = channel; const active = { channel, ctx }; sessions.add(active); channel.write(render(ctx, home(ctx)));
channel.on('data', data => { for (const byte of data.toString()) { if (byte === '\r' || byte === '\n') { channel.write(`\r\n${execute(ctx, buffer)}\n` + render(ctx)); buffer = ''; } else if (byte === '\x7f') { if (buffer) { buffer = buffer.slice(0, -1); channel.write('\b \b'); } } else if (byte >= ' ') { buffer += byte; channel.write(byte); } } });
let buffer = ''; ctx.channel = channel; const active = { channel, ctx }; sessions.add(active); channel.write(render(ctx, router.home(ctx)));
channel.on('data', data => { for (const byte of data.toString()) { if (byte === '\r' || byte === '\n') { channel.write(`\r\n${router.execute(ctx, buffer)}\n` + render(ctx)); buffer = ''; } else if (byte === '\x7f') { if (buffer) { buffer = buffer.slice(0, -1); channel.write('\b \b'); } } else if (byte >= ' ') { buffer += byte; channel.write(byte); } } });
channel.on('close', () => sessions.delete(active));
}
const server = new Server({ hostKeys: [fs.readFileSync(hostKey)], ident: 'ssh-portfolio' }, client => {
@@ -59,7 +41,7 @@ const server = new Server({ hostKeys: [fs.readFileSync(hostKey)], ident: 'ssh-po
if (allowed && (!ctxAuth.signature || ctxAuth.key.verify(ctxAuth.blob, ctxAuth.signature, ctxAuth.hashAlgo))) { ctx.admin = true; ctxAuth.accept(); return; }
}
ctxAuth.reject(['none', 'publickey']);
}).on('ready', () => client.on('session', accept => { const sshSession = accept(); sshSession.on('pty', (acceptPty, rejectPty, info) => { ctx.cols = info.cols || 80; acceptPty(); }); sshSession.on('shell', (acceptShell) => handleSession(acceptShell(), ctx)); sshSession.on('exec', (acceptExec, rejectExec, info) => { const e = acceptExec(); e.write((execute(ctx, info.command) || '') + '\n'); e.exit(0); e.end(); }); })).on('error', () => {});
}).on('ready', () => client.on('session', accept => { const sshSession = accept(); sshSession.on('pty', (acceptPty, rejectPty, info) => { ctx.cols = info.cols || 80; acceptPty(); }); sshSession.on('shell', (acceptShell) => handleSession(acceptShell(), ctx)); sshSession.on('exec', (acceptExec, rejectExec, info) => { const e = acceptExec(); e.write((router.execute(ctx, info.command) || '') + '\n'); e.exit(0); e.end(); }); })).on('error', () => {});
});
server.listen(config.host.port, '0.0.0.0', () => console.log(`SSH portfolio listening on port ${config.host.port}; config: ${configPath}`));
net.createServer(socket => { notifications.add(socket); socket.on('data', () => {}); socket.on('close', () => notifications.delete(socket)); }).listen(config.host.notificationPort, '127.0.0.1');