-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh-api.ts
More file actions
232 lines (203 loc) · 6.45 KB
/
Copy pathssh-api.ts
File metadata and controls
232 lines (203 loc) · 6.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { readFileSync } from "node:fs";
import { Client } from "ssh2";
import {
SSHError,
SSHConnectionError,
SSHAuthError,
SSHTimeoutError,
CommandFailedError,
UnsafeCommandError,
} from "./errors.js";
const DANGEROUS_PATTERNS: Array<[RegExp, string]> = [
[/\brm\s+-[a-z]*r[a-z]*f?[a-z]*\s+(--no-preserve-root\s+)?\/(\s|\*|$)/i, "rm -rf /"],
[/\bmkfs(\.\w+)?\s+\/dev\//i, "mkfs on block device"],
[/\bdd\b[^|;&]*\bof=\/dev\//i, "dd to block device"],
[/:\(\)\s*\{\s*:\|:&\s*\};:/, "fork bomb"],
[/\bchmod\s+-R\s+777\s+\//, "chmod -R 777 /"],
[/\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(sh|bash)\b/i, "curl|sh pipe"],
[/\b(shutdown\s+-h|halt|poweroff)\b/i, "host power off"],
];
export function assertCommandSafe(command: string): void {
if (process.env.HOMELAB_ALLOW_DANGEROUS_COMMANDS === "true") return;
for (const [re, label] of DANGEROUS_PATTERNS) {
if (re.test(command)) throw new UnsafeCommandError(command, label);
}
}
const CONNECT_TIMEOUT_MS = 10_000;
const EXEC_TIMEOUT_MS = 30_000;
interface NodeConfig {
host: string;
username: string;
keyPath: string;
}
function getDefaultConfig(): NodeConfig {
return {
host: process.env.HOMELAB_PI_HOST || "raspberrypi.local",
username: process.env.HOMELAB_PI_USER || "pi",
keyPath: process.env.HOMELAB_PI_KEY_PATH || "",
};
}
function getNodesRegistry(): Record<string, NodeConfig> {
const raw = process.env.HOMELAB_NODES;
if (!raw) return {};
try {
const parsed = JSON.parse(raw);
const registry: Record<string, NodeConfig> = {};
for (const [name, cfg] of Object.entries(parsed)) {
const c = cfg as Record<string, string>;
registry[name] = {
host: c.host || "",
username: c.user || c.username || "pi",
keyPath: c.keyPath || "",
};
}
return registry;
} catch {
return {};
}
}
export function getNodeConfig(node?: string): NodeConfig {
if (!node) return getDefaultConfig();
const registry = getNodesRegistry();
if (registry[node]) return registry[node];
if (node === "default") return getDefaultConfig();
throw new SSHError(`Unknown node "${node}". Available nodes: ${listNodes().map((n) => n.name).join(", ") || "(none -- set HOMELAB_NODES)"}`);
}
export function listNodes(): { name: string; host: string }[] {
const defaultCfg = getDefaultConfig();
const nodes: { name: string; host: string }[] = [
{ name: "default", host: defaultCfg.host },
];
const registry = getNodesRegistry();
for (const [name, cfg] of Object.entries(registry)) {
nodes.push({ name, host: cfg.host });
}
return nodes;
}
export async function execSSH(
command: string,
node?: string,
): Promise<string> {
assertCommandSafe(command);
if (process.env.HOMELAB_DRY_RUN && process.env.HOMELAB_DRY_RUN !== "false") {
const cfg = getNodeConfig(node);
return `[dry-run] would execute on ${cfg.host}: ${command}`;
}
const { host, username, keyPath } = getNodeConfig(node);
return new Promise((resolve, reject) => {
const conn = new Client();
let stdout = "";
let stderr = "";
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
conn.end();
reject(new SSHTimeoutError(EXEC_TIMEOUT_MS));
}, EXEC_TIMEOUT_MS);
conn
.on("ready", () => {
conn.exec(command, (err, stream) => {
if (err) {
clearTimeout(timer);
conn.end();
return reject(new SSHError(err.message, command));
}
stream
.on("close", (code: number) => {
clearTimeout(timer);
conn.end();
if (timedOut) return;
if (code !== 0 && code !== null) {
reject(new CommandFailedError(command, code, stderr));
} else {
resolve(stdout.trim());
}
})
.on("data", (data: Buffer) => {
stdout += data.toString();
})
.stderr.on("data", (data: Buffer) => {
stderr += data.toString();
});
});
})
.on("error", (err: Error & { level?: string }) => {
clearTimeout(timer);
if (timedOut) return;
if (
err.message.includes("authentication") ||
err.message.includes("All configured authentication methods failed")
) {
reject(new SSHAuthError());
} else if (
err.message.includes("ECONNREFUSED") ||
err.message.includes("ENOTFOUND") ||
err.message.includes("ETIMEDOUT") ||
err.level === "client-timeout"
) {
reject(new SSHConnectionError(host));
} else {
reject(new SSHError(err.message));
}
})
.connect({
host,
port: 22,
username,
privateKey: keyPath ? readFileSync(keyPath) : undefined,
agent: process.env.SSH_AUTH_SOCK,
readyTimeout: CONNECT_TIMEOUT_MS,
});
});
}
export async function checkSSHAvailable(): Promise<void> {
try {
await execSSH("echo ok");
} catch (error) {
throw error;
}
}
export function errorResponse(error: unknown): {
content: { type: "text"; text: string }[];
isError: true;
} {
if (error instanceof SSHError) {
const parts: string[] = [`[${error.name}] ${error.message}`];
if (error.command) {
parts.push(`Command: ${error.command}`);
}
const suggestion = getErrorSuggestion(error);
if (suggestion) {
parts.push(`Suggestion: ${suggestion}`);
}
return {
content: [{ type: "text" as const, text: parts.join("\n") }],
isError: true,
};
}
if (error instanceof Error) {
return {
content: [{ type: "text" as const, text: error.message }],
isError: true,
};
}
return {
content: [{ type: "text" as const, text: "An unknown error occurred." }],
isError: true,
};
}
function getErrorSuggestion(error: SSHError): string | null {
if (error instanceof SSHConnectionError) {
return "Check that the Pi is powered on and reachable. Verify HOMELAB_PI_HOST is correct.";
}
if (error instanceof SSHAuthError) {
return "Verify HOMELAB_PI_KEY_PATH points to a valid private key and HOMELAB_PI_USER is correct.";
}
if (error instanceof SSHTimeoutError) {
return "The Pi may be under heavy load or unreachable. Try again or check network connectivity.";
}
if (error instanceof CommandFailedError) {
return "The command failed on the Pi. Check the error output above for details.";
}
return null;
}