-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cjs
More file actions
198 lines (170 loc) · 6.16 KB
/
server.cjs
File metadata and controls
198 lines (170 loc) · 6.16 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
const http = require("http");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const pty = require("/app/node_modules/node-pty");
const WebSocket = require("/app/node_modules/ws");
const PORT = parseInt(process.env.PORT || "18789");
// Anti-CSWSH token: browsers don't enforce same-origin on WebSocket upgrades,
// so without this any site could connect to /umbrel/api/terminal and hijack the PTY.
// APP_SEED (per-app secret from umbrelOS) is embedded in the served HTML.
const SETUP_TOKEN = process.env.APP_SEED || "";
const DATA_DIR = "/opt/data";
const DASHBOARD_HOST = "127.0.0.1";
const DASHBOARD_PORT = 9119;
let ptyProcess = null;
const TERMINAL_HTML = fs.readFileSync("/app/terminal.html", "utf8");
const LOGO = fs.readFileSync(path.join(__dirname, "logo.png"));
function blockHermesUpdate(req, res) {
res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
res.end("Hermes updates are managed by umbrelOS app updates.");
}
function blockGatewayRestart(req, res) {
res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
res.end("Gateway restarts are managed by umbrelOS. Restart Hermes from the umbrelOS homescreen.");
}
// Proxy HTTP requests to the dashboard container
function proxyToDashboard(req, res) {
const options = {
hostname: DASHBOARD_HOST,
port: DASHBOARD_PORT,
path: req.url,
method: req.method,
headers: {
...req.headers,
// Hermes validates Host against its loopback dashboard bind address.
// Rewriting is safe in Umbrel because app_proxy authenticates requests
// before they reach this wrapper; direct network exposure is not supported.
host: DASHBOARD_HOST + ":" + DASHBOARD_PORT,
},
};
const proxy = http.request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});
proxy.on("error", () => {
res.writeHead(502, { "Content-Type": "text/html", "Cache-Control": "no-store" });
res.end("<html><body><h2>Dashboard is starting...</h2><p>Please wait a moment and refresh.</p></body></html>");
});
req.pipe(proxy);
}
const server = http.createServer((req, res) => {
const requestUrl = new URL(req.url || "/", "http://localhost");
const requestPath = requestUrl.pathname.replace(/\/+$/, "");
// Serve terminal page at /terminal (Umbrel app manifest points here)
if (requestPath === "/terminal") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(TERMINAL_HTML.replace("__SETUP_TOKEN__", SETUP_TOKEN));
return;
}
// Serve static assets for terminal UI
if (requestPath === "/logo.png") {
res.writeHead(200, { "Content-Type": "image/png", "Cache-Control": "public, max-age=86400" });
res.end(LOGO);
return;
}
// Block the dashboard's `hermes update` action; Umbrel updates Hermes via app images.
// Match the parsed pathname so query strings cannot bypass the block.
if (req.method === "POST" && requestPath === "/api/hermes/update") {
blockHermesUpdate(req, res);
return;
}
// Upstream documents separate dashboard/gateway containers, but this action
// still shells out locally. In Umbrel that would run from the web container
// instead of restarting the gateway container managed by umbrelOS/Docker.
if (req.method === "POST" && requestPath === "/api/gateway/restart") {
blockGatewayRestart(req, res);
return;
}
// Everything else proxied to dashboard (behind umbrelOS auth)
proxyToDashboard(req, res);
});
// WebSocket server for the interactive terminal
const wss = new WebSocket.Server({ noServer: true });
wss.on("connection", (ws) => {
console.log("Terminal WebSocket connected");
// One session at a time — kill any existing PTY (e.g. stale tab)
if (ptyProcess) {
try { ptyProcess.kill(); } catch (e) {}
ptyProcess = null;
}
ptyProcess = pty.spawn("/app/start-hermes.sh", [], {
name: "xterm-256color",
cols: 80,
rows: 24,
cwd: DATA_DIR,
env: {
...process.env,
TERM: "xterm-256color",
HOME: DATA_DIR,
},
});
ptyProcess.onData((data) => {
try {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: "output", data }));
}
} catch (e) {
console.error("Error sending PTY output:", e.message);
}
});
ptyProcess.onExit(({ exitCode }) => {
console.log(`PTY exited with code ${exitCode}`);
try {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: "exit", code: exitCode }));
}
} catch (e) {
console.error("Error sending exit message:", e.message);
}
ptyProcess = null;
});
ws.on("message", (msg) => {
try {
const parsed = JSON.parse(msg);
if (parsed.type === "input" && ptyProcess) {
ptyProcess.write(parsed.data);
} else if (parsed.type === "resize" && ptyProcess) {
ptyProcess.resize(parsed.cols, parsed.rows);
}
} catch (e) {
console.error("Error processing terminal input:", e.message);
}
});
ws.on("close", () => {
console.log("Terminal WebSocket closed");
if (ptyProcess) {
try { ptyProcess.kill(); } catch (e) {}
ptyProcess = null;
}
});
});
server.on("upgrade", (req, socket, head) => {
const url = new URL(req.url, `http://${req.headers.host}`);
if (url.pathname === "/umbrel/api/terminal") {
// Validate anti-CSWSH token
const provided = url.searchParams.get("token") || "";
if (!SETUP_TOKEN || provided.length !== SETUP_TOKEN.length ||
!crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(SETUP_TOKEN))) {
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit("connection", ws, req);
});
return;
}
socket.end("HTTP/1.1 404 Not Found\r\n\r\n");
});
server.listen(PORT, "0.0.0.0", () => {
console.log(`Hermes terminal server listening on port ${PORT}`);
});
// Graceful shutdown
process.on("SIGTERM", () => {
console.log("Received SIGTERM, shutting down...");
if (ptyProcess) {
try { ptyProcess.kill(); } catch (e) {}
}
server.close();
});