sshception/main.js

81 lines
No EOL
2.4 KiB
JavaScript

import {
spawn
} from 'node:child_process';
import {
readFileSync
} from 'node:fs';
import '@lu.se/console';
import ssh2 from 'ssh2';
import { getLastGitCommitIdSync } from 'last-git-commit-id';
import { getString } from './strings.js';
import getStreamManager from './src/main.js';
import cli from './src/cli/main.js';
import tui from './src/tui/main.js';
import packageJson from './package.json' assert { type: 'json' };
import {
sshPort
} from './config.js';
if(!process.env.NO_RESPAWN) process.on(
'uncaughtException',
() => {
process.once(
'exit',
() => spawn(
process.argv.shift(),
process.argv,
{
cwd: process.cwd(),
detached: true,
stdio: 'inherit'
}
)
);
process.exit();
}
);
new ssh2.Server({
hostKeys: [ readFileSync('./host.rsa.key'), readFileSync('./host.ed25519.key') ],
banner: getString('banner', { packageJson, lastCommitId: getLastGitCommitIdSync().slice(0, 7) })
}, client => {
client.on('authentication', async authentication => {
if(authentication.method !== 'password')
return authentication.reject(['password']);
const { username, password } = authentication;
if(!username || !password) return authentication.reject();
authentication.accept();
client.once('session', async accept => {
const
streamManager = await getStreamManager({
session: accept()
}),
{
env: {
IS_CLI,
IS_TUI
}
} = streamManager;
let ui;
if(typeof IS_CLI === 'string' && typeof IS_TUI === 'undefined')
ui = cli;
else if(typeof IS_TUI === 'string' && typeof IS_CLI === 'undefined')
ui = tui;
else
ui = cli;
ui({
streamManager,
username,
password,
end: () => client.end()
});
});
});
client.on('error', error => {
if(error.code === 'ECONNRESET') return;
console.error(error);
});
}).listen(sshPort, '0.0.0.0', () => console.log(`SSH server running on port ${sshPort}`));