import { z } from 'zod';
import { readFile } from 'fs/promises';
import { SessionManager } from '../core/session-manager.js';
import { getCredentials } from '../core/auth.js';
import { checkPort } from '../core/port-check.js';
import { AuthMode } from '../types/index.js';
export const schema = z.object({
host: z.string(),
port: z.number().default(22),
username: z.string().optional(),
auth_mode: z.enum(['password', 'key']),
password: z.string().optional(),
key_path: z.string().optional(),
force_new: z.boolean().default(false),
timeout_minutes: z.number().default(15),
});
export async function sshConnect(params: z.infer<typeof schema>) {
// Check connectivity first
const portCheck = await checkPort(params.host, params.port);
if (!portCheck.ok) {
return { session_id: '', status: 'error', message: `Cannot reach ${params.host}:${params.port} - ${portCheck.error}` };
}
// Get credentials
const result = await getCredentials(params.host, params.auth_mode as AuthMode, {
username: params.username,
password: params.password,
keyPath: params.key_path,
});
if (result.status === 'awaiting_credentials') {
return { session_id: '', status: 'awaiting_credentials', message: result.message };
}
const creds = result.credentials!;
let privateKey: string | undefined;
if (params.auth_mode === 'key' && creds.keyPath) {
privateKey = await readFile(creds.keyPath, 'utf8');
}
const sessionResult = await SessionManager.getInstance().createSession({
host: params.host,
port: params.port,
username: creds.username,
password: creds.password,
privateKey,
}, params.force_new, params.timeout_minutes);
return {
session_id: sessionResult.sessionId,
status: sessionResult.status,
reused: sessionResult.reused,
message: sessionResult.message,
};
}