Skip to content

Commit

Permalink
Enhanced DNS handling and added shell command execution support
Browse files Browse the repository at this point in the history
  • Loading branch information
micthiesen committed Oct 18, 2024
1 parent ca44a76 commit e44ee76
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 7 deletions.
3 changes: 2 additions & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
},
"suspicious": {
"noExplicitAny": "off",
"noShadowRestrictedNames": "off"
"noShadowRestrictedNames": "off",
"noControlCharactersInRegex": "off"
}
}
},
Expand Down
10 changes: 9 additions & 1 deletion src/dns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ const ALT_DNS_SERVERS: [string, string] = ["1.1.1.1", "1.0.0.1"];
export async function toggleDns(ssh: SNodeSSH) {
if (timeoutId) clearTimeout(timeoutId);

const originalDnsServers = parseDnsServers(await ssh.execSafe("show"));
await ssh.shellSafe("echo $");
await ssh.shellSafe("echo $SHELL");
await ssh.shellSafe("echo $TERM");
await ssh.shellSafe("echo $-");
await ssh.shellSafe("shopt login_shell");

const originalDnsServers = parseDnsServers(
await ssh.shellSafe("show dns forwarding nameservers"),
);
console.log(`Found existing DNS servers: ${originalDnsServers}`);

console.log("Setting alternative DNS servers...");
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ app.get("/toggle-dns", async (c) => {
await toggleDns(ssh);
return c.text("DNS servers toggled");
} catch (err: any) {
console.warn(err.message);
return c.text(`Error: ${err.message}`);
} finally {
if (ssh) ssh.dispose();
}
});

serve({ fetch: app.fetch, port: 5888 }, (info) => {
console.log(`\nListening on http://localhost:${info.port}`);
console.log(`Listening on http://localhost:${info.port}`);
});
75 changes: 71 additions & 4 deletions src/ssh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import env from "./env";

export type SNodeSSH = NodeSSH & {
execSafe: (command: string) => Promise<string>;
shellSafe: (command: string) => Promise<string>;
};

export async function getSshConnection(): Promise<SNodeSSH> {
Expand All @@ -16,9 +17,17 @@ export async function getSshConnection(): Promise<SNodeSSH> {
ssh.execSafe = async (command: string) => {
console.log(`>>> ${command}`);
const result = await ssh.execCommand(command);
if (result.stderr) console.warn(prefixCaret(result.stderr));
if (result.stderr) console.warn(prefixBar(result.stderr));
if (result.stderr) throw new Error(`Error executing command: ${result.stderr}`);
if (result.stdout) console.log(prefixCaret(result.stdout));
if (result.stdout) console.log(prefixBar(result.stdout));
return result.stdout;
};
ssh.shellSafe = async (command: string) => {
console.log(`>>> ${command}`);
const result = await withShell(ssh, command);
if (result.stderr) console.warn(prefixBar(result.stderr));
if (result.stderr) throw new Error(`Error executing command: ${result.stderr}`);
if (result.stdout) console.log(prefixBar(result.stdout));
return result.stdout;
};

Expand All @@ -30,6 +39,64 @@ export async function getSshConnection(): Promise<SNodeSSH> {
return ssh;
}

function prefixCaret(text: string): string {
return text.replace(/^/gm, "> ");
async function withShell(
ssh: SNodeSSH,
command: string,
): Promise<{ stdout: string; stderr: string }> {
let stdout = "";
let stderr = "";

await ssh.withShell(
async (channel) => {
return new Promise<void>((resolve, reject) => {
channel.on("data", (data: Buffer) => {
stdout += data.toString();
});

channel.stderr.on("data", (data: Buffer) => {
stderr += data.toString();
});

channel.on("close", () => {
resolve();
});

channel.on("error", (err: any) => {
reject(err);
});

channel.write(`${command}\nexit\n`);
});
},
{
modes: {
ECHO: 1, // Enable echoing
ICANON: 1, // Enable canonical input
ISIG: 1, // Enable signals like INTR, QUIT, SUSP
IEXTEN: 1, // Enable extensions
OPOST: 1, // Enable output processing
ONLCR: 1, // Translate newline to CR-NL
TTY_OP_ISPEED: 9600, // Input baud rate
TTY_OP_OSPEED: 9600, // Output baud rate
},
},
);

return { stdout: extractCommandOutput(stdout), stderr };
}

const shellOutputRegex = /(?<=@ubnt:~\$.+\n)([\s\S]+?)(?=\n.+@ubnt:~\$ exit)/gims;
function extractCommandOutput(fullOutput: string): string {
const matches = fullOutput.match(shellOutputRegex);
if (!matches) return "";
const lines = matches.map(cleanLine);
return lines.join("\n");
}

function cleanLine(line: string): string {
return line.replace(/\x1B\[[0-9;]*[a-zA-Z]|\x1B\[[0-9;]*m/g, "").trim();
}

function prefixBar(text: string): string {
return text.replace(/^/gm, "| ");
}

0 comments on commit e44ee76

Please sign in to comment.