@bom0792/herdgate 0.0.0-stage → 0.9.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +167 -2
- package/app-mod/herdgate/main.js +395 -0
- package/app-mod/herdgate/mod.json +5 -0
- package/bin/herdgate.mjs +91 -0
- package/dist-readme.md +48 -0
- package/package.json +36 -3
- package/plugin/herdr-plugin.toml +36 -0
- package/plugin/server/common.mjs +79 -0
- package/plugin/server/e2e.d.mts +43 -0
- package/plugin/server/e2e.mjs +268 -0
- package/plugin/server/index.mjs +454 -0
- package/plugin/server/ssh.mjs +241 -0
- package/scripts/build-host-bundle.sh +12 -0
- package/scripts/deploy-vps.sh +74 -0
- package/scripts/patch-ssh2.mjs +32 -0
- package/src/agent/adapter.ts +23 -0
- package/src/agent/index.ts +183 -0
- package/src/cloud/gateway.ts +946 -0
- package/src/cloud/main.ts +88 -0
- package/src/cloud/pairing.ts +81 -0
- package/src/cloud/ssh-bridge.ts +212 -0
- package/src/cloud/sshd.ts +412 -0
- package/src/cloud/static.ts +142 -0
- package/src/cloud/stores.ts +180 -0
- package/src/cloud/util.ts +47 -0
- package/src/cloud/vapid.ts +105 -0
- package/src/dev/edge-sim.ts +99 -0
- package/src/dev/main.ts +33 -0
- package/src/host/herdr.ts +316 -0
- package/src/host/main.ts +105 -0
- package/src/host/ssh.ts +317 -0
- package/src/index.ts +5 -0
- package/src/protocol/agent.ts +84 -0
- package/src/protocol/device.ts +90 -0
- package/src/protocol/envelope.ts +58 -0
- package/src/protocol/index.ts +3 -0
- package/src/web/app.css +312 -0
- package/src/web/app.js +835 -0
- package/src/web/app.webmanifest +15 -0
- package/src/web/e2e.js +268 -0
- package/src/web/herdgate-host.zip +0 -0
- package/src/web/icons/icon-192.png +0 -0
- package/src/web/icons/icon-512.png +0 -0
- package/src/web/icons/icon.svg +6 -0
- package/src/web/index.html +99 -0
- package/src/web/sw.js +98 -0
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SSH leg: phones reach the host's herdr-core through herdgate.
|
|
3
|
+
*
|
|
4
|
+
* phone (Herdr app "add machine") ──SSH──▶ herdgate sshd ──agent WS──▶ host bridge ──spawn──▶ hc connect
|
|
5
|
+
*
|
|
6
|
+
* What this module owns:
|
|
7
|
+
* - the SSH listener (ssh2): authenticates a PAIRED DEVICE (username = device id,
|
|
8
|
+
* password = the device secret `pair.granted` issued once), never an account token;
|
|
9
|
+
* - one SSH exec session ⇒ one bridge channel: bytes from the phone go to the host as
|
|
10
|
+
* opaque `ssh.*` frames (the cloud never inspects them — the host's bridge decides
|
|
11
|
+
* what a `read` device may do);
|
|
12
|
+
* - its own per-IP auth-failure strikes, host key minted once and persisted 0600.
|
|
13
|
+
*
|
|
14
|
+
* What it deliberately does NOT do: no shell, no sftp, no port forwarding, no agent
|
|
15
|
+
* forwarding. Only `exec` — the phone speaks the herdr-core API over stdin/stdout
|
|
16
|
+
* (`ssh <host> hc connect`), and that channel is relayed byte by byte.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { createHash, createPublicKey, generateKeyPairSync as nodeKeyPair, verify as cryptoVerify, type KeyObject } from "node:crypto";
|
|
20
|
+
import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync } from "node:fs";
|
|
21
|
+
import { dirname } from "node:path";
|
|
22
|
+
import ssh2Pkg from "ssh2";
|
|
23
|
+
import { type DeviceRecord, type State } from "./stores.ts";
|
|
24
|
+
import { randomToken } from "./util.ts";
|
|
25
|
+
|
|
26
|
+
const { Server } = ssh2Pkg;
|
|
27
|
+
const utils = (ssh2Pkg as unknown as { utils?: { generateKeyPairSync?(type: string): { private: string; public: string } } }).utils;
|
|
28
|
+
|
|
29
|
+
const MAX_CHANNELS_PER_DEVICE = 3;
|
|
30
|
+
const AUTH_STRIKES = 5;
|
|
31
|
+
const AUTH_BLOCK_MS = 60_000;
|
|
32
|
+
|
|
33
|
+
/** The algos herdgate authorizes for device keys. */
|
|
34
|
+
const SSH_KEY_ALGOS = new Set(["ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521"]);
|
|
35
|
+
|
|
36
|
+
/** Fingerprint of an SSH public key blob, OpenSSH style (`SHA256:…`, no padding). */
|
|
37
|
+
export function sshKeyFingerprint(b64: string): string {
|
|
38
|
+
return "SHA256:" + createHash("sha256").update(Buffer.from(b64, "base64")).digest("base64").replace(/=+$/, "");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Parse a `authorized_keys`-style line → { algo, b64, comment } | null. */
|
|
42
|
+
export function parseAuthorizedKey(line: string): { algo: string; b64: string; comment?: string } | null {
|
|
43
|
+
const parts = line.trim().split(/\s+/);
|
|
44
|
+
if (parts.length < 2) return null;
|
|
45
|
+
const [algo, b64, ...rest] = parts;
|
|
46
|
+
if (!SSH_KEY_ALGOS.has(algo) || !/^[A-Za-z0-9+/]+={0,2}$/.test(b64)) return null;
|
|
47
|
+
let blob: Buffer;
|
|
48
|
+
try {
|
|
49
|
+
blob = Buffer.from(b64, "base64");
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
// The blob must open with its own algo name (SSH wire format's first string).
|
|
54
|
+
if (blob.length < 8 || blob.readUInt32BE(0) !== algo.length || blob.subarray(4, 4 + algo.length).toString() !== algo) return null;
|
|
55
|
+
return { algo, b64, comment: rest.join(" ").slice(0, 200) || undefined };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** SSH wire pubkey blob → a node KeyObject for verification; null when unparsable. */
|
|
59
|
+
function sshPubKeyToKeyObject(algo: string, data: Buffer): KeyObject | null {
|
|
60
|
+
let off = 0;
|
|
61
|
+
const rstr = (): Buffer | null => {
|
|
62
|
+
if (off + 4 > data.length) return null;
|
|
63
|
+
const len = data.readUInt32BE(off);
|
|
64
|
+
off += 4;
|
|
65
|
+
if (off + len > data.length) return null;
|
|
66
|
+
const b = data.subarray(off, off + len);
|
|
67
|
+
off += len;
|
|
68
|
+
return b;
|
|
69
|
+
};
|
|
70
|
+
const mpintB64url = (b: Buffer): string => (b[0] === 0 ? b.subarray(1) : b).toString("base64url");
|
|
71
|
+
try {
|
|
72
|
+
if (algo === "ssh-ed25519") {
|
|
73
|
+
rstr(); // the algo string, redundant with the wire-level algorithm name
|
|
74
|
+
const raw = rstr();
|
|
75
|
+
if (!raw || raw.length !== 32) return null;
|
|
76
|
+
return createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: raw.toString("base64url") }, format: "jwk" });
|
|
77
|
+
}
|
|
78
|
+
if (algo === "ssh-rsa") {
|
|
79
|
+
rstr(); // the algo string
|
|
80
|
+
const e = rstr();
|
|
81
|
+
const n = rstr();
|
|
82
|
+
if (!e || !n) return null;
|
|
83
|
+
return createPublicKey({ key: { kty: "RSA", e: mpintB64url(e), n: mpintB64url(n) }, format: "jwk" });
|
|
84
|
+
}
|
|
85
|
+
const m = algo.match(/^ecdsa-sha2-nistp(256|384|521)$/);
|
|
86
|
+
if (m) {
|
|
87
|
+
rstr(); // the algo string
|
|
88
|
+
rstr(); // the curve name, redundant with the algo
|
|
89
|
+
const point = rstr();
|
|
90
|
+
if (!point || point[0] !== 4) return null;
|
|
91
|
+
const byteLen = { "256": 32, "384": 48, "521": 66 }[m[1] as "256" | "384" | "521"];
|
|
92
|
+
if (point.length !== 1 + 2 * byteLen) return null;
|
|
93
|
+
return createPublicKey({
|
|
94
|
+
key: { kty: "EC", crv: `P-${m[1]}`, x: point.subarray(1, 1 + byteLen).toString("base64url"), y: point.subarray(1 + byteLen).toString("base64url") },
|
|
95
|
+
format: "jwk",
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface SshConfig {
|
|
105
|
+
port?: number;
|
|
106
|
+
bind?: string;
|
|
107
|
+
/** Where the host key lives; `dirname(statePath)` by default. Ephemeral if absent. */
|
|
108
|
+
keyPath?: string;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface SshDeps {
|
|
112
|
+
config: SshConfig;
|
|
113
|
+
state: State;
|
|
114
|
+
log: (line: string) => void;
|
|
115
|
+
/**
|
|
116
|
+
* Gateway: deliver an opaque payload to the device's ROOM AGENT, addressed from the
|
|
117
|
+
* device (that is the channel the host bridge reads). False when the host is offline.
|
|
118
|
+
*/
|
|
119
|
+
sendAsDevice(deviceId: string, payload: Record<string, unknown>): boolean;
|
|
120
|
+
/** Gateway: is that device's socket open right now? */
|
|
121
|
+
deviceOnline(deviceId: string): boolean;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface SshHandle {
|
|
125
|
+
port: number | null;
|
|
126
|
+
bind: string | null;
|
|
127
|
+
hostKeyFingerprint: string | null;
|
|
128
|
+
/**
|
|
129
|
+
* Feed a virtual (non-TCP) socket into the SSH server — how the bridge leg
|
|
130
|
+
* (`/v1/bridge/ws`) delivers a phone's raw SSH bytes. Auth, strikes and the
|
|
131
|
+
* read-only allowlist apply unchanged; `socket.remoteAddress` is the strike key.
|
|
132
|
+
*/
|
|
133
|
+
inject(socket: import("node:stream").Duplex & { remoteAddress?: string }): void;
|
|
134
|
+
close(): Promise<void>;
|
|
135
|
+
/** Gateway calls this when a HOST sends an `ssh.*` frame to a device. */
|
|
136
|
+
onHostFrame(deviceId: string, payload: Record<string, unknown>): void;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
interface ChannelStream {
|
|
140
|
+
write(chunk: Buffer): boolean;
|
|
141
|
+
end(chunk?: Buffer): void;
|
|
142
|
+
exit(code: number): void;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
interface Channel {
|
|
146
|
+
deviceId: string;
|
|
147
|
+
ch: string;
|
|
148
|
+
stream: ChannelStream | null;
|
|
149
|
+
/** The phone keeps sending after we asked the host to stop; drop until CLOSE arrives. */
|
|
150
|
+
closing: boolean;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
154
|
+
// Enabled/disabled is the gateway's decision (`ssh` unset ⇒ no leg). Port 0 is a
|
|
155
|
+
// legitimate ephemeral listener (tests), not "off".
|
|
156
|
+
const port = deps.config.port ?? 2222;
|
|
157
|
+
const bind = deps.config.bind ?? "127.0.0.1";
|
|
158
|
+
|
|
159
|
+
const hostKey = loadOrMintHostKey(deps);
|
|
160
|
+
const channels = new Map<string, Channel>(); // `${deviceId}:${ch}` → channel
|
|
161
|
+
const strikes = new Map<string, { n: number; until: number }>();
|
|
162
|
+
|
|
163
|
+
const ipOf = (ctx: { ip?: string }): string => ctx.ip ?? "?";
|
|
164
|
+
const blocked = (ip: string): boolean => {
|
|
165
|
+
const f = strikes.get(ip);
|
|
166
|
+
return Boolean(f && f.until > Date.now());
|
|
167
|
+
};
|
|
168
|
+
const strike = (ip: string): void => {
|
|
169
|
+
const f = strikes.get(ip) ?? { n: 0, until: 0 };
|
|
170
|
+
f.n += 1;
|
|
171
|
+
if (f.n >= AUTH_STRIKES) {
|
|
172
|
+
f.until = Date.now() + AUTH_BLOCK_MS;
|
|
173
|
+
f.n = 0;
|
|
174
|
+
deps.log(`ssh: ${ip} blocked for ${AUTH_BLOCK_MS / 1000}s after repeated failures`);
|
|
175
|
+
}
|
|
176
|
+
strikes.set(ip, f);
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
const channelKey = (deviceId: string, ch: string): string => `${deviceId}:${ch}`;
|
|
180
|
+
const deviceChannels = (deviceId: string): Channel[] => [...channels.values()].filter((c) => c.deviceId === deviceId);
|
|
181
|
+
|
|
182
|
+
/** To the HOST, addressed as the device (the bridge on the host consumes these). */
|
|
183
|
+
const toHost = (deviceId: string, payload: Record<string, unknown>): boolean => deps.sendAsDevice(deviceId, payload);
|
|
184
|
+
|
|
185
|
+
const server = new Server({ hostKeys: [hostKey.private] }, (client, info) => {
|
|
186
|
+
const ip = info?.ip ?? "?";
|
|
187
|
+
let device: DeviceRecord | null = null;
|
|
188
|
+
|
|
189
|
+
client.on("error", () => {
|
|
190
|
+
/* the socket layer reports the close itself */
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
let dev: DeviceRecord | null = null; // narrowed alias for the closures below
|
|
194
|
+
client.on("authentication", (ctx) => {
|
|
195
|
+
if (blocked(ip)) return ctx.reject();
|
|
196
|
+
const id = ctx.username.trim();
|
|
197
|
+
const rec = /^d_[A-Za-z0-9]+$/.test(id) ? deps.state.deviceById(id) : null;
|
|
198
|
+
if (ctx.method === "publickey") {
|
|
199
|
+
// Non-interactive clients (herdr-core's `machine add` shells out to system ssh,
|
|
200
|
+
// which prefers keys and the agent) log in with a registered public key. ssh2
|
|
201
|
+
// parses the request; verifying the signature (RFC 4252 §7, `ctx.blob` is the
|
|
202
|
+
// exact signed bytes) is ours. A request WITHOUT a signature is the client
|
|
203
|
+
// asking "would you take this key?" — accepting answers PK_OK (ssh2 does that).
|
|
204
|
+
const pk = ctx as unknown as { key?: { algo: string; data: Buffer }; signature?: Buffer; blob?: Buffer; hashAlgo?: string };
|
|
205
|
+
const key = pk.key;
|
|
206
|
+
if (!rec || !key?.data) return ctx.reject();
|
|
207
|
+
const entry = rec.sshKeys?.find((k) => k.algo === key.algo && Buffer.from(k.b64, "base64").equals(key.data));
|
|
208
|
+
if (!entry) return ctx.reject(); // agent key not for us: no strike, just no
|
|
209
|
+
if (!pk.signature) return ctx.accept();
|
|
210
|
+
const keyObj = sshPubKeyToKeyObject(key.algo, key.data);
|
|
211
|
+
if (!keyObj || !cryptoVerify(pk.hashAlgo ?? undefined, pk.blob ?? Buffer.alloc(0), keyObj, pk.signature)) {
|
|
212
|
+
strike(ip);
|
|
213
|
+
deps.log(`ssh: bad key signature for ${rec.id} from ${ip}`);
|
|
214
|
+
return ctx.reject();
|
|
215
|
+
}
|
|
216
|
+
device = rec;
|
|
217
|
+
dev = rec;
|
|
218
|
+
deps.log(`ssh: device ${rec.id} (${rec.name}, ${rec.scope}) authenticated with key ${sshKeyFingerprint(entry.b64)} from ${ip}`);
|
|
219
|
+
return ctx.accept();
|
|
220
|
+
}
|
|
221
|
+
if (ctx.method !== "password") {
|
|
222
|
+
// Per-device passwords (and registered public keys) are the only ways in.
|
|
223
|
+
return ctx.reject();
|
|
224
|
+
}
|
|
225
|
+
const ok = rec ? deps.state.deviceByCredentials(id, ctx.password ?? "") : null;
|
|
226
|
+
if (!ok) {
|
|
227
|
+
strike(ip);
|
|
228
|
+
deps.log(`ssh: auth failed for "${id.slice(0, 12)}" from ${ip}`);
|
|
229
|
+
return ctx.reject();
|
|
230
|
+
}
|
|
231
|
+
device = ok;
|
|
232
|
+
dev = ok;
|
|
233
|
+
deps.log(`ssh: device ${ok.id} (${ok.name}, ${ok.scope}) authenticated from ${ip}`);
|
|
234
|
+
ctx.accept();
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
client.on("ready", () => {
|
|
238
|
+
client.on("session", (accept, reject) => {
|
|
239
|
+
const session = accept();
|
|
240
|
+
session.on("sftp", (acceptSftp, rejectSftp) => rejectSftp());
|
|
241
|
+
session.on("shell", (acceptShell, rejectShell) => rejectShell());
|
|
242
|
+
// Clients like herdr-core's `machine add` ask for a PTY while probing; the
|
|
243
|
+
// real process runs on the host leg over pipes regardless, so accepting the
|
|
244
|
+
// request (without allocating anything) is honest and keeps exec-only policy.
|
|
245
|
+
session.on("pty", (accept) => accept());
|
|
246
|
+
session.on("exec", (acceptExec, rejectExec, info) => {
|
|
247
|
+
const dvc = dev;
|
|
248
|
+
if (!dvc) return rejectExec();
|
|
249
|
+
if (blocked(ip)) return rejectExec();
|
|
250
|
+
|
|
251
|
+
// No device-socket gate here: a phone on the SSH leg has no WebSocket open.
|
|
252
|
+
// Reachability is the host agent's, and it fails honestly below (exit 111).
|
|
253
|
+
const ch = randomToken(6).replace(/[^A-Za-z0-9]/g, "").slice(0, 8);
|
|
254
|
+
if (deviceChannels(dvc.id).length >= MAX_CHANNELS_PER_DEVICE) {
|
|
255
|
+
deps.log(`ssh: ${dvc.id} hit the channel cap`);
|
|
256
|
+
return rejectExec();
|
|
257
|
+
}
|
|
258
|
+
const stream = acceptExec();
|
|
259
|
+
const channel: Channel = { deviceId: dvc.id, ch, stream, closing: false };
|
|
260
|
+
channels.set(channelKey(dvc.id, ch), channel);
|
|
261
|
+
|
|
262
|
+
// Ask the host to run it. The command travels inside the opaque payload; the
|
|
263
|
+
// host's bridge decides whether to run it and answers ssh.granted / ssh.denied.
|
|
264
|
+
const opened = toHost(dvc.id, { op: "ssh.open", ch, cmd: String(info.command ?? "") });
|
|
265
|
+
if (!opened) {
|
|
266
|
+
channels.delete(channelKey(dvc.id, ch));
|
|
267
|
+
stream.exit(111);
|
|
268
|
+
stream.end(Buffer.from("herdgate: the host is not connected\r\n"));
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
stream.on("data", (buf: Buffer) => {
|
|
273
|
+
if (channel.closing) return;
|
|
274
|
+
toHost(dvc.id, { op: "ssh.data", ch, b64: buf.toString("base64") });
|
|
275
|
+
});
|
|
276
|
+
stream.on("close", () => {
|
|
277
|
+
channels.delete(channelKey(dvc.id, ch));
|
|
278
|
+
toHost(dvc.id, { op: "ssh.close", ch });
|
|
279
|
+
});
|
|
280
|
+
stream.stderr?.on?.("data", () => {
|
|
281
|
+
/* stderr is merged by the phone side in exec mode; drop duplicates */
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
client.on("close", () => {
|
|
288
|
+
const dvc = dev;
|
|
289
|
+
if (dvc) {
|
|
290
|
+
for (const c of deviceChannels(dvc.id)) {
|
|
291
|
+
channels.delete(channelKey(c.deviceId, c.ch));
|
|
292
|
+
toHost(dvc.id, { op: "ssh.close", ch: c.ch });
|
|
293
|
+
}
|
|
294
|
+
if (deviceChannels(dvc.id).length === 0) deps.log(`ssh: device ${dvc.id} disconnected`);
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
await new Promise<void>((resolve, reject) => {
|
|
300
|
+
server.once("error", reject);
|
|
301
|
+
server.listen(port, bind, () => resolve());
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
const addr = server.address();
|
|
305
|
+
const realPort = typeof addr === "object" && addr ? addr.port : null;
|
|
306
|
+
deps.log(`ssh: listening on ${bind}:${realPort} (devices auth with their device id + key)`);
|
|
307
|
+
|
|
308
|
+
return {
|
|
309
|
+
port: realPort,
|
|
310
|
+
bind,
|
|
311
|
+
hostKeyFingerprint: hostKey.fingerprint,
|
|
312
|
+
inject(socket) {
|
|
313
|
+
// ssh2's official injection point; the socket only needs the stream API plus
|
|
314
|
+
// remoteAddress/remoteFamily/remotePort for logging and the strike map.
|
|
315
|
+
server.injectSocket(socket as unknown as import("node:net").Socket);
|
|
316
|
+
},
|
|
317
|
+
/** The HOST's ssh.* frames come back through the agent leg; write them into the phone's stream. */
|
|
318
|
+
onHostFrame(deviceId, payload) {
|
|
319
|
+
const op = typeof payload.op === "string" ? payload.op : "";
|
|
320
|
+
const ch = typeof payload.ch === "string" ? payload.ch : "";
|
|
321
|
+
const channel = channels.get(channelKey(deviceId, ch));
|
|
322
|
+
if (!channel) return;
|
|
323
|
+
|
|
324
|
+
if (op === "ssh.granted") {
|
|
325
|
+
channel.closing = false;
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (op === "ssh.denied") {
|
|
329
|
+
// The host refused (scope, command, no hc): close the channel honestly.
|
|
330
|
+
const reason = typeof payload.reason === "string" ? payload.reason : "refused by the host";
|
|
331
|
+
channel.closing = true;
|
|
332
|
+
channel.stream?.write(Buffer.from(`herdgate: ${reason}\r\n`));
|
|
333
|
+
channel.stream?.exit(111);
|
|
334
|
+
channel.stream?.end();
|
|
335
|
+
channels.delete(channelKey(deviceId, ch));
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (op === "ssh.data") {
|
|
339
|
+
const b64 = typeof payload.b64 === "string" ? payload.b64 : "";
|
|
340
|
+
if (b64.length > 400_000) return; // over the frame budget; the rate limiter catches floods
|
|
341
|
+
const buf = Buffer.from(b64, "base64");
|
|
342
|
+
try {
|
|
343
|
+
channel.stream?.write(buf);
|
|
344
|
+
} catch {
|
|
345
|
+
/* the phone vanished mid-write; close carries it */
|
|
346
|
+
}
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (op === "ssh.closed") {
|
|
350
|
+
channel.closing = true;
|
|
351
|
+
const code = typeof payload.code === "number" ? payload.code : 0;
|
|
352
|
+
const reason = typeof payload.reason === "string" ? payload.reason : undefined;
|
|
353
|
+
if (reason) channel.stream?.write(Buffer.from(`herdgate: ${reason}\r\n`));
|
|
354
|
+
channel.stream?.exit(code);
|
|
355
|
+
channel.stream?.end();
|
|
356
|
+
channels.delete(channelKey(deviceId, ch));
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
async close() {
|
|
361
|
+
for (const c of channels.values()) {
|
|
362
|
+
c.stream?.end();
|
|
363
|
+
}
|
|
364
|
+
channels.clear();
|
|
365
|
+
await new Promise<void>((done) => server.close(() => done()));
|
|
366
|
+
},
|
|
367
|
+
} satisfies SshHandle;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Mint once, keep at mode 0600; ephemeral (per-boot) when no key path is configured. */
|
|
371
|
+
function loadOrMintHostKey(deps: SshDeps): { private: string; public: string; fingerprint: string } {
|
|
372
|
+
const path = deps.config.keyPath;
|
|
373
|
+
if (path && existsSync(path)) {
|
|
374
|
+
try {
|
|
375
|
+
const f = JSON.parse(readFileSync(path, "utf8")) as { private: string; public: string; fingerprint: string };
|
|
376
|
+
if (f.private && f.public) return f;
|
|
377
|
+
} catch {
|
|
378
|
+
/* fall through and re-mint */
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
// ssh2.utils generates the OpenSSH format directly; the node-crypto path is the fallback.
|
|
382
|
+
const key =
|
|
383
|
+
utils?.generateKeyPairSync
|
|
384
|
+
? (() => {
|
|
385
|
+
const k = utils.generateKeyPairSync("ed25519");
|
|
386
|
+
return { private: k.private, public: k.public };
|
|
387
|
+
})()
|
|
388
|
+
: (() => {
|
|
389
|
+
const { publicKey, privateKey } = nodeKeyPair("ed25519");
|
|
390
|
+
return {
|
|
391
|
+
private: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
|
|
392
|
+
public: publicKey.export({ type: "spki", format: "pem" }).toString(),
|
|
393
|
+
};
|
|
394
|
+
})();
|
|
395
|
+
const fingerprint = fingerprintOf(key.public);
|
|
396
|
+
if (path) {
|
|
397
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
398
|
+
writeFileSync(path, JSON.stringify({ ...key, fingerprint }), { mode: 0o600 });
|
|
399
|
+
chmodSync(path, 0o600);
|
|
400
|
+
deps.log(`ssh: host key minted at ${path} (${fingerprint})`);
|
|
401
|
+
} else {
|
|
402
|
+
deps.log(`ssh: ephemeral host key (${fingerprint}) — set HERDGATE_SSH_KEY to keep it`);
|
|
403
|
+
}
|
|
404
|
+
return { ...key, fingerprint };
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** SHA256 fingerprint in the same `SHA256:…` shape OpenSSH prints. */
|
|
408
|
+
function fingerprintOf(publicKeyText: string): string {
|
|
409
|
+
const base64 = publicKeyText.replace(/^.*?\n/, "").replace(/\n.*$/, "").replace(/\s+/g, "");
|
|
410
|
+
const digest = createHash("sha256").update(Buffer.from(base64, "base64")).digest("base64").replace(/=+$/, "");
|
|
411
|
+
return `SHA256:${digest}`;
|
|
412
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small static file server for the PWA, deliberately boring:
|
|
3
|
+
*
|
|
4
|
+
* - only files under one root, resolved through `realpath` (no traversal, no symlink escape);
|
|
5
|
+
* - no directory listings, no dotfiles;
|
|
6
|
+
* - a fixed content-type table, `no-store` for the app shell and long cache for hashed assets;
|
|
7
|
+
* - a strict CSP: the PWA is same-origin and needs no inline script at all.
|
|
8
|
+
*
|
|
9
|
+
* The PWA lives at `src/web/` in this repo and is served by the same process that runs the
|
|
10
|
+
* gateway, so a device that opens the public hostname gets the app and the WS endpoint from
|
|
11
|
+
* one origin (no CORS, no second deployment).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { createReadStream, statSync } from "node:fs";
|
|
15
|
+
import { realpathSync } from "node:fs";
|
|
16
|
+
import { extname, join, resolve, sep } from "node:path";
|
|
17
|
+
import type { ServerResponse } from "node:http";
|
|
18
|
+
|
|
19
|
+
const TYPES: Record<string, string> = {
|
|
20
|
+
".html": "text/html; charset=utf-8",
|
|
21
|
+
".js": "text/javascript; charset=utf-8",
|
|
22
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
23
|
+
".css": "text/css; charset=utf-8",
|
|
24
|
+
".json": "application/json; charset=utf-8",
|
|
25
|
+
".webmanifest": "application/manifest+json; charset=utf-8",
|
|
26
|
+
".svg": "image/svg+xml",
|
|
27
|
+
".png": "image/png",
|
|
28
|
+
".ico": "image/x-icon",
|
|
29
|
+
".txt": "text/plain; charset=utf-8",
|
|
30
|
+
".zip": "application/zip",
|
|
31
|
+
".md": "text/markdown; charset=utf-8",
|
|
32
|
+
".woff2": "font/woff2",
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** The PWA is self-contained: same-origin only, and no inline script or style. */
|
|
36
|
+
export const CSP =
|
|
37
|
+
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; " +
|
|
38
|
+
"connect-src 'self' ws: wss:; manifest-src 'self'; base-uri 'none'; form-action 'none'; " +
|
|
39
|
+
"frame-ancestors 'none'";
|
|
40
|
+
|
|
41
|
+
export interface StaticResult {
|
|
42
|
+
status: number;
|
|
43
|
+
body?: Buffer;
|
|
44
|
+
filePath?: string;
|
|
45
|
+
headers: Record<string, string>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface StaticOptions {
|
|
49
|
+
/** Absolute or relative directory holding the PWA. */
|
|
50
|
+
root: string;
|
|
51
|
+
/** Served for `/` and for a directory-looking path. Default `index.html`. */
|
|
52
|
+
index?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Map a URL path onto a file under the root. Returns `null` when the request must not be
|
|
57
|
+
* served (traversal attempt, dotfile, missing file, directory). Pure enough to test without
|
|
58
|
+
* a server: it only touches the filesystem to `realpath` and `stat`.
|
|
59
|
+
*/
|
|
60
|
+
export function resolveStatic(root: string, urlPath: string, o: StaticOptions = { root }): StaticResult | null {
|
|
61
|
+
// Strip the query and decode once: `%2e%2e%2f` must not become `../`.
|
|
62
|
+
let decoded: string;
|
|
63
|
+
try {
|
|
64
|
+
decoded = decodeURIComponent(urlPath.split("?")[0].split("#")[0]);
|
|
65
|
+
} catch {
|
|
66
|
+
return null; // malformed escape
|
|
67
|
+
}
|
|
68
|
+
if (decoded.includes("\0")) return null;
|
|
69
|
+
|
|
70
|
+
const index = o.index ?? "index.html";
|
|
71
|
+
const wanted = decoded === "/" || decoded === "" ? `/${index}` : decoded;
|
|
72
|
+
if (!wanted.startsWith("/")) return null;
|
|
73
|
+
|
|
74
|
+
const rootAbs = resolve(o.root);
|
|
75
|
+
let rootReal: string;
|
|
76
|
+
try {
|
|
77
|
+
rootReal = realpathSync(rootAbs);
|
|
78
|
+
} catch {
|
|
79
|
+
return null; // no web root configured or missing on disk
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Reject dotfiles anywhere in the path: `.env`, `.git`, editor droppings.
|
|
83
|
+
const segments = wanted.split("/").filter((s) => s !== "");
|
|
84
|
+
if (segments.some((s) => s.startsWith("."))) return null;
|
|
85
|
+
if (segments.some((s) => s === ".." || s === "\\")) return null;
|
|
86
|
+
|
|
87
|
+
const candidate = resolve(rootReal, ...segments);
|
|
88
|
+
if (candidate !== rootReal && !candidate.startsWith(rootReal + sep)) return null;
|
|
89
|
+
|
|
90
|
+
let real: string;
|
|
91
|
+
let stat: ReturnType<typeof statSync>;
|
|
92
|
+
try {
|
|
93
|
+
real = realpathSync(candidate); // a symlink pointing outside the root is refused
|
|
94
|
+
if (real !== rootReal && !real.startsWith(rootReal + sep)) return null;
|
|
95
|
+
stat = statSync(real);
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
if (!stat.isFile()) return null;
|
|
100
|
+
|
|
101
|
+
const type = TYPES[extname(real).toLowerCase()] ?? "application/octet-stream";
|
|
102
|
+
// The shell must never be cached stale; icon/svg assets may be.
|
|
103
|
+
const cache = /\.(svg|png|ico|woff2)$/i.test(real) ? "public, max-age=604800" : "no-store";
|
|
104
|
+
return {
|
|
105
|
+
status: 200,
|
|
106
|
+
filePath: real,
|
|
107
|
+
headers: {
|
|
108
|
+
"content-type": type,
|
|
109
|
+
"cache-control": cache,
|
|
110
|
+
"content-length": String(stat.size),
|
|
111
|
+
"content-security-policy": CSP,
|
|
112
|
+
"referrer-policy": "no-referrer",
|
|
113
|
+
"x-content-type-options": "nosniff",
|
|
114
|
+
"x-frame-options": "DENY",
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Stream a resolved static file to a response. */
|
|
120
|
+
export function sendStatic(res: ServerResponse, hit: StaticResult): void {
|
|
121
|
+
res.writeHead(hit.status, hit.headers);
|
|
122
|
+
if (!hit.filePath) return void res.end();
|
|
123
|
+
const stream = createReadStream(hit.filePath);
|
|
124
|
+
stream.on("error", () => res.destroy());
|
|
125
|
+
stream.pipe(res);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Convenience wrapper: serve `urlPath` or answer 404. Returns whether it answered. */
|
|
129
|
+
export function serveStatic(res: ServerResponse, root: string | undefined, urlPath: string): boolean {
|
|
130
|
+
if (!root) return false;
|
|
131
|
+
const hit = resolveStatic(root, urlPath, { root });
|
|
132
|
+
if (!hit) {
|
|
133
|
+
res.writeHead(404, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
|
|
134
|
+
res.end("not found");
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
sendStatic(res, hit);
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Exported for tests: the head of the CSP the PWA runs under. */
|
|
142
|
+
export const cspFor = (): string => CSP;
|