@bom0792/herdgate 0.9.29 → 0.9.34
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/.agents/skills/herdr/SKILL.md +81 -0
- package/.agents/skills/herdr/herdr_pi.py +272 -0
- package/.agents/skills/herdr/profiles.example.toml +18 -0
- package/.agents/skills/herdr-advisor/SKILL.md +12 -0
- package/.agents/skills/herdr-committee/SKILL.md +13 -0
- package/.agents/skills/herdr-handoff/SKILL.md +19 -0
- package/.agents/skills/herdr-help/SKILL.md +14 -0
- package/.agents/skills/herdr-plugin/SKILL.md +21 -0
- package/DEPLOY.md +106 -120
- package/DESIGN.md +9 -4
- package/README.md +55 -2
- package/bin/herdgate.mjs +12 -2
- package/bin/home-tui.mjs +2 -0
- package/bin/pi-skills.mjs +99 -0
- package/dist-readme.md +9 -2
- package/package.json +38 -9
- package/plugin/server/e2e.d.mts +2 -2
- package/plugin/server/e2e.mjs +51 -32
- package/plugin/server/index.mjs +128 -32
- package/plugin/server/pi-receipts.d.mts +28 -0
- package/plugin/server/pi-receipts.mjs +77 -0
- package/plugin/server/pi-worker.d.mts +47 -0
- package/plugin/server/pi-worker.mjs +127 -0
- package/plugin/server/ssh.mjs +12 -4
- package/scripts/bench-mobile-tui.mjs +246 -0
- package/scripts/build-host-bundle.sh +14 -8
- package/scripts/build-release.sh +47 -0
- package/scripts/deploy-vps.sh +5 -78
- package/scripts/install-pi-skills.mjs +4 -0
- package/src/cloud/gateway.ts +163 -134
- package/src/cloud/main.ts +72 -15
- package/src/cloud/pairing.ts +7 -2
- package/src/cloud/push.ts +54 -0
- package/src/cloud/sshd.ts +76 -38
- package/src/cloud/util.ts +5 -5
- package/src/host/mobile-tui.ts +11 -1
- package/src/web/app.js +88 -61
- package/src/web/e2e.js +51 -32
- package/src/web/sw.js +1 -1
- package/templates/cloud/.dockerignore +7 -0
- package/templates/cloud/Caddyfile.example +3 -0
- package/templates/cloud/Dockerfile +10 -0
- package/templates/cloud/README.md +74 -0
- package/templates/cloud/compose.env.example +18 -0
- package/templates/cloud/compose.yml +41 -0
- package/templates/cloud/gitignore.example +4 -0
- package/templates/cloud/herdgate-cloud-edge.service +18 -0
- package/templates/cloud/herdgate-cloud.service +26 -0
- package/tsconfig.cloud.json +11 -0
- package/tsconfig.json +18 -0
- package/windows/install-cli.mjs +15 -5
- package/windows/setup-tui.mjs +1 -0
- package/src/web/herdgate-host.zip +0 -0
package/src/cloud/main.ts
CHANGED
|
@@ -3,18 +3,24 @@
|
|
|
3
3
|
* HERDGATE_PORT listen port (default 8787)
|
|
4
4
|
* HERDGATE_BIND bind address (default 127.0.0.1)
|
|
5
5
|
* HERDGATE_STATE state JSON path (default: none, in-memory)
|
|
6
|
-
* HERDGATE_ACCOUNT_TOKEN
|
|
6
|
+
* HERDGATE_ACCOUNT_TOKEN or HERDGATE_ACCOUNT_TOKEN_FILE (required; pick one)
|
|
7
7
|
* HERDGATE_ACCOUNT_NAME display name (default "owner")
|
|
8
8
|
* HERDGATE_PUBLIC_HOST enforce this Host header (the cloudflared hostname)
|
|
9
9
|
* HERDGATE_PUBLIC_URL shown in pairing URLs (e.g. https://herd.example.com)
|
|
10
10
|
* HERDGATE_WEB_ROOT the PWA directory (default: src/web beside this file)
|
|
11
11
|
* HERDGATE_NO_WEB "1" disables the PWA (API only)
|
|
12
|
-
*
|
|
12
|
+
* HERDGATE_NO_SSH "1" disables both SSH listeners (TCP and WSS)
|
|
13
|
+
* HERDGATE_SSH_PORT the SSH leg for phones (default 2222; 0 picks a free port)
|
|
13
14
|
* HERDGATE_SSH_BIND its bind address (default 127.0.0.1; 0.0.0.0 for LAN)
|
|
14
15
|
* HERDGATE_SSH_KEY host key file (default: beside the state file)
|
|
15
|
-
*
|
|
16
|
+
* HERDGATE_ENABLE_PUSH "1" enables wake via supported HTTPS push providers (off by default)
|
|
17
|
+
* HERDGATE_NO_PUSH "1" overrides that opt-in and disables push
|
|
16
18
|
* HERDGATE_SSH_HOST the hostname phones dial for SSH (a DNS-only name)
|
|
17
|
-
*
|
|
19
|
+
* HERDGATE_SSH_PUBLIC_PORT optional port advertised for an external TCP edge
|
|
20
|
+
* HERDGATE_TRUSTED_PROXY "1" trusts a proxy header (below) as the client address
|
|
21
|
+
* HERDGATE_REAL_IP_HEADER the trusted header name (default CF-Connecting-IP)
|
|
22
|
+
* HERDGATE_SSH_TUNNELS_PER_IP per-client SSH-over-WSS cap (default 6)
|
|
23
|
+
* HERDGATE_SSH_TUNNELS_TOTAL global SSH-over-WSS cap (default 64)
|
|
18
24
|
*/
|
|
19
25
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
20
26
|
import { dirname, join } from "node:path";
|
|
@@ -23,10 +29,28 @@ import { startCloud } from "./gateway.ts";
|
|
|
23
29
|
import { generateVapidKeys, loadVapidKeys, type VapidKeys } from "./vapid.ts";
|
|
24
30
|
|
|
25
31
|
const env = process.env;
|
|
26
|
-
const token =
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
32
|
+
const token = accountToken();
|
|
33
|
+
|
|
34
|
+
function accountToken(): string {
|
|
35
|
+
const direct = env.HERDGATE_ACCOUNT_TOKEN;
|
|
36
|
+
const file = env.HERDGATE_ACCOUNT_TOKEN_FILE;
|
|
37
|
+
if (direct !== undefined && file !== undefined) {
|
|
38
|
+
console.error("herdgate: set only one of HERDGATE_ACCOUNT_TOKEN and HERDGATE_ACCOUNT_TOKEN_FILE");
|
|
39
|
+
process.exit(2);
|
|
40
|
+
}
|
|
41
|
+
let value = direct;
|
|
42
|
+
if (file !== undefined) {
|
|
43
|
+
try { value = readFileSync(file, "utf8").trim(); }
|
|
44
|
+
catch {
|
|
45
|
+
console.error("herdgate: could not read HERDGATE_ACCOUNT_TOKEN_FILE");
|
|
46
|
+
process.exit(2);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (!value) {
|
|
50
|
+
console.error("herdgate: HERDGATE_ACCOUNT_TOKEN or a nonempty HERDGATE_ACCOUNT_TOKEN_FILE is required");
|
|
51
|
+
process.exit(2);
|
|
52
|
+
}
|
|
53
|
+
return value;
|
|
30
54
|
}
|
|
31
55
|
|
|
32
56
|
/** Default web root: the `src/web` directory beside this file, so `npm start` serves the PWA. */
|
|
@@ -35,22 +59,43 @@ const defaultWebRoot = join(here, "..", "web");
|
|
|
35
59
|
const webRoot = env.HERDGATE_NO_WEB === "1" ? undefined : (env.HERDGATE_WEB_ROOT ?? defaultWebRoot);
|
|
36
60
|
|
|
37
61
|
const sshPort = Number(env.HERDGATE_SSH_PORT ?? 2222);
|
|
62
|
+
const sshPublicPort = env.HERDGATE_SSH_PUBLIC_PORT === undefined ? undefined : Number(env.HERDGATE_SSH_PUBLIC_PORT);
|
|
63
|
+
if (sshPublicPort !== undefined && (!Number.isInteger(sshPublicPort) || sshPublicPort < 1 || sshPublicPort > 65535)) {
|
|
64
|
+
console.error("herdgate: HERDGATE_SSH_PUBLIC_PORT must be a port from 1 to 65535");
|
|
65
|
+
process.exit(2);
|
|
66
|
+
}
|
|
38
67
|
const sshKeyPath =
|
|
39
68
|
env.HERDGATE_SSH_KEY ?? (env.HERDGATE_STATE ? join(dirname(env.HERDGATE_STATE), "ssh_host_ed25519.json") : undefined);
|
|
40
69
|
|
|
70
|
+
// Abuse-limit client addressing. Behind a same-host proxy (cloudflared) loopback
|
|
71
|
+
// connections already get per-connection budgets; trusted-proxy mode restores
|
|
72
|
+
// real per-client keys when the edge forwards one (e.g. CF-Connecting-IP).
|
|
73
|
+
const portOption = (name: string): number | undefined => {
|
|
74
|
+
if (env[name] === undefined) return undefined;
|
|
75
|
+
const value = Number(env[name]);
|
|
76
|
+
if (!Number.isInteger(value) || value < 1 || value > 65_535) {
|
|
77
|
+
console.error(`herdgate: ${name} must be a port from 1 to 65535`);
|
|
78
|
+
process.exit(2);
|
|
79
|
+
}
|
|
80
|
+
return value;
|
|
81
|
+
};
|
|
82
|
+
const tunnelPerKey = portOption("HERDGATE_SSH_TUNNELS_PER_IP");
|
|
83
|
+
const tunnelTotal = portOption("HERDGATE_SSH_TUNNELS_TOTAL");
|
|
84
|
+
|
|
41
85
|
// Push wake (VAPID): keys live beside the state file so the public key browsers
|
|
42
|
-
// subscribed to never changes behind their backs.
|
|
86
|
+
// subscribed to never changes behind their backs. Off unless explicitly enabled.
|
|
43
87
|
let push: { keys: VapidKeys; sub: string } | null = null;
|
|
44
|
-
if (env.HERDGATE_NO_PUSH !== "1") {
|
|
88
|
+
if (env.HERDGATE_ENABLE_PUSH === "1" && env.HERDGATE_NO_PUSH !== "1") {
|
|
45
89
|
const vapidPath = env.HERDGATE_STATE ? join(dirname(env.HERDGATE_STATE), "vapid.json") : undefined;
|
|
46
90
|
let keys: VapidKeys | undefined;
|
|
47
91
|
if (vapidPath) {
|
|
48
92
|
try {
|
|
49
93
|
keys = loadVapidKeys(JSON.parse(readFileSync(vapidPath, "utf8")).jwk);
|
|
50
|
-
} catch {
|
|
94
|
+
} catch (e) {
|
|
95
|
+
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw new Error("herdgate: cannot load existing VAPID key; restore it from backup");
|
|
51
96
|
keys = generateVapidKeys();
|
|
52
|
-
mkdirSync(dirname(vapidPath), { recursive: true });
|
|
53
|
-
writeFileSync(vapidPath, JSON.stringify({ jwk: keys.privateJwk }), { mode: 0o600 });
|
|
97
|
+
mkdirSync(dirname(vapidPath), { recursive: true, mode: 0o700 });
|
|
98
|
+
writeFileSync(vapidPath, JSON.stringify({ jwk: keys.privateJwk }), { mode: 0o600, flag: "wx" });
|
|
54
99
|
}
|
|
55
100
|
} else {
|
|
56
101
|
keys = generateVapidKeys();
|
|
@@ -65,17 +110,29 @@ const cloud = await startCloud({
|
|
|
65
110
|
expectedHost: env.HERDGATE_PUBLIC_HOST,
|
|
66
111
|
publicUrl: env.HERDGATE_PUBLIC_URL ?? null,
|
|
67
112
|
webRoot,
|
|
68
|
-
ssh: {
|
|
113
|
+
ssh: env.HERDGATE_NO_SSH === "1" ? undefined : {
|
|
69
114
|
port: sshPort,
|
|
70
115
|
bind: env.HERDGATE_SSH_BIND ?? "127.0.0.1",
|
|
71
116
|
keyPath: sshKeyPath,
|
|
72
117
|
},
|
|
73
118
|
push,
|
|
74
|
-
sshHost: env.HERDGATE_SSH_HOST,
|
|
119
|
+
sshHost: env.HERDGATE_SSH_HOST || undefined,
|
|
120
|
+
sshPublicPort,
|
|
121
|
+
trustedProxy: env.HERDGATE_TRUSTED_PROXY === "1",
|
|
122
|
+
realIpHeader: env.HERDGATE_REAL_IP_HEADER || "CF-Connecting-IP",
|
|
123
|
+
...(tunnelPerKey !== undefined || tunnelTotal !== undefined
|
|
124
|
+
? { sshTunnelLimits: { ...(tunnelPerKey !== undefined ? { perKey: tunnelPerKey } : {}), ...(tunnelTotal !== undefined ? { total: tunnelTotal } : {}) } }
|
|
125
|
+
: {}),
|
|
75
126
|
accounts: [{ id: "a_owner", name: env.HERDGATE_ACCOUNT_NAME ?? "owner", token }],
|
|
76
127
|
log: (l) => console.error(`herdgate: ${l}`),
|
|
77
128
|
});
|
|
78
129
|
|
|
130
|
+
if (env.HERDGATE_NO_SSH !== "1" && !cloud.ssh) {
|
|
131
|
+
await cloud.close();
|
|
132
|
+
console.error("herdgate: refusing to start without the configured SSH leg");
|
|
133
|
+
process.exit(1);
|
|
134
|
+
}
|
|
135
|
+
|
|
79
136
|
console.error(`herdgate: listening on http://${env.HERDGATE_BIND ?? "127.0.0.1"}:${cloud.port}`);
|
|
80
137
|
console.error(`herdgate: app on ${env.HERDGATE_PUBLIC_URL ?? `http://${env.HERDGATE_BIND ?? "127.0.0.1"}:${cloud.port}`}/${webRoot ? "" : " (disabled)"}`);
|
|
81
138
|
console.error(`herdgate: pair a host: curl -XPOST ${env.HERDGATE_PUBLIC_URL ?? `http://127.0.0.1:${cloud.port}`}/v1/agent/code -d '{"name":"my-mac"}'`);
|
package/src/cloud/pairing.ts
CHANGED
|
@@ -33,14 +33,19 @@ export class AgentCodes {
|
|
|
33
33
|
readonly #entries: Entry[] = [];
|
|
34
34
|
readonly #now: () => number;
|
|
35
35
|
readonly #publicUrl: string | null;
|
|
36
|
+
readonly #maxPending: number;
|
|
36
37
|
|
|
37
|
-
constructor(now: () => number = Date.now, publicUrl: string | null = null) {
|
|
38
|
+
constructor(now: () => number = Date.now, publicUrl: string | null = null, maxPending = 256) {
|
|
38
39
|
this.#now = now;
|
|
39
40
|
this.#publicUrl = publicUrl;
|
|
41
|
+
this.#maxPending = Math.max(1, maxPending);
|
|
40
42
|
}
|
|
41
43
|
|
|
42
|
-
mint(hostName: string): MintedCode {
|
|
44
|
+
mint(hostName: string): MintedCode | null {
|
|
43
45
|
this.#prune();
|
|
46
|
+
// A bounded inventory: an unauthenticated mint loop must not grow memory
|
|
47
|
+
// without limit (audit pairing:unbounded-code-mint).
|
|
48
|
+
if (this.#entries.length >= this.#maxPending) return null;
|
|
44
49
|
const e: Entry = { code: randomCode(8), hostName, expires: this.#now() + AGENT_CODE_TTL_MS, approved: false, roomToken: null, roomId: null };
|
|
45
50
|
this.#entries.push(e);
|
|
46
51
|
return { code: e.code, url: this.#publicUrl ? `${this.#publicUrl.replace(/\/$/, "")}/pair?code=${e.code}` : e.code, expiresIn: AGENT_CODE_TTL_MS / 1000 };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { lookup } from "node:dns/promises";
|
|
2
|
+
import { request } from "node:https";
|
|
3
|
+
import { BlockList, isIPv4 } from "node:net";
|
|
4
|
+
import { vapidHeader, type VapidKeys } from "./vapid.ts";
|
|
5
|
+
|
|
6
|
+
const providers = new Set(["fcm.googleapis.com", "updates.push.services.mozilla.com", "web.push.apple.com"]);
|
|
7
|
+
|
|
8
|
+
export function pushEndpoint(value: string): URL | null {
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(value);
|
|
11
|
+
return url.protocol === "https:" && !url.username && !url.password && !url.port && !url.hash &&
|
|
12
|
+
providers.has(url.hostname) ? url : null;
|
|
13
|
+
} catch { return null; }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Deliberately use IPv4 only for push: reject private, link-local, reserved and
|
|
17
|
+
// other non-global space. Connect to that exact checked address, not a second DNS lookup.
|
|
18
|
+
const nonPublic = new BlockList();
|
|
19
|
+
for (const [address, bits] of [
|
|
20
|
+
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8],
|
|
21
|
+
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24],
|
|
22
|
+
["192.88.99.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24],
|
|
23
|
+
["203.0.113.0", 24], ["224.0.0.0", 3],
|
|
24
|
+
] as const) nonPublic.addSubnet(address, bits);
|
|
25
|
+
|
|
26
|
+
export function publicPushAddress(address: string): boolean {
|
|
27
|
+
return isIPv4(address) && !nonPublic.check(address, "ipv4");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function sendWake(endpoint: URL, keys: VapidKeys, sub: string): Promise<void> {
|
|
31
|
+
const { hostname, pathname, search, href } = endpoint;
|
|
32
|
+
// Keep the DNS lookup part of the in-flight quota even if it is slow.
|
|
33
|
+
const signal = AbortSignal.timeout(5000);
|
|
34
|
+
const { address } = await lookup(hostname, { family: 4 });
|
|
35
|
+
signal.throwIfAborted();
|
|
36
|
+
if (!publicPushAddress(address)) throw new Error("push endpoint resolved to a non-public address");
|
|
37
|
+
await new Promise<void>((resolve, reject) => {
|
|
38
|
+
const req = request({
|
|
39
|
+
hostname: address, servername: hostname, path: pathname + search,
|
|
40
|
+
method: "POST", agent: false, rejectUnauthorized: true, signal,
|
|
41
|
+
headers: {
|
|
42
|
+
Host: hostname, TTL: "60", Urgency: "normal", "content-length": "0",
|
|
43
|
+
Authorization: vapidHeader(href, keys, sub),
|
|
44
|
+
},
|
|
45
|
+
}, (res) => {
|
|
46
|
+
// No response body or redirect is needed for a wake notification.
|
|
47
|
+
res.destroy();
|
|
48
|
+
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) resolve();
|
|
49
|
+
else reject(new Error("push provider rejected wake"));
|
|
50
|
+
});
|
|
51
|
+
req.once("error", reject);
|
|
52
|
+
req.end();
|
|
53
|
+
});
|
|
54
|
+
}
|
package/src/cloud/sshd.ts
CHANGED
|
@@ -17,10 +17,12 @@
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { createHash, createPublicKey, generateKeyPairSync as nodeKeyPair, verify as cryptoVerify, type KeyObject } from "node:crypto";
|
|
20
|
-
import { mkdirSync, readFileSync, writeFileSync
|
|
20
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
21
|
+
import { createServer as tcpServer, type Socket } from "node:net";
|
|
21
22
|
import { dirname } from "node:path";
|
|
23
|
+
import type { Duplex } from "node:stream";
|
|
22
24
|
import ssh2Pkg from "ssh2";
|
|
23
|
-
import { type
|
|
25
|
+
import { type State } from "./stores.ts";
|
|
24
26
|
import { randomToken } from "./util.ts";
|
|
25
27
|
|
|
26
28
|
const { Server } = ssh2Pkg;
|
|
@@ -106,6 +108,8 @@ export interface SshConfig {
|
|
|
106
108
|
bind?: string;
|
|
107
109
|
/** Where the host key lives; `dirname(statePath)` by default. Ephemeral if absent. */
|
|
108
110
|
keyPath?: string;
|
|
111
|
+
/** Deadline from transport accept through successful SSH user authentication. */
|
|
112
|
+
authTimeoutMs?: number;
|
|
109
113
|
}
|
|
110
114
|
|
|
111
115
|
export interface SshDeps {
|
|
@@ -130,7 +134,9 @@ export interface SshHandle {
|
|
|
130
134
|
* (`/v1/bridge/ws`) delivers a phone's raw SSH bytes. Auth, strikes and the
|
|
131
135
|
* read-only allowlist apply unchanged; `socket.remoteAddress` is the strike key.
|
|
132
136
|
*/
|
|
133
|
-
inject(socket:
|
|
137
|
+
inject(socket: Duplex & { remoteAddress?: string }): void;
|
|
138
|
+
/** Disconnect a revoked device, or just sessions authenticated with a removed key. */
|
|
139
|
+
revoke(deviceId: string, fingerprint?: string): void;
|
|
134
140
|
close(): Promise<void>;
|
|
135
141
|
/** Gateway calls this when a HOST sends an `ssh.*` frame to a device. */
|
|
136
142
|
onHostFrame(deviceId: string, payload: Record<string, unknown>): boolean;
|
|
@@ -177,6 +183,17 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
177
183
|
strikes.set(ip, f);
|
|
178
184
|
};
|
|
179
185
|
|
|
186
|
+
type Transport = Duplex & { remoteAddress?: string };
|
|
187
|
+
interface Peer {
|
|
188
|
+
socket: Transport;
|
|
189
|
+
ip: string;
|
|
190
|
+
deadline: NodeJS.Timeout | null;
|
|
191
|
+
deviceId?: string;
|
|
192
|
+
fingerprint?: string;
|
|
193
|
+
}
|
|
194
|
+
const peers = new Map<Transport, Peer>();
|
|
195
|
+
const authTimeoutMs = deps.config.authTimeoutMs ?? 12_000;
|
|
196
|
+
|
|
180
197
|
const channelKey = (deviceId: string, ch: string): string => `${deviceId}:${ch}`;
|
|
181
198
|
const deviceChannels = (deviceId: string): Channel[] => [...channels.values()].filter((c) => c.deviceId === deviceId);
|
|
182
199
|
|
|
@@ -184,14 +201,13 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
184
201
|
const toHost = (deviceId: string, payload: Record<string, unknown>): boolean => deps.sendAsDevice(deviceId, payload);
|
|
185
202
|
|
|
186
203
|
const server = new Server({ hostKeys: [hostKey.private] }, (client, info) => {
|
|
204
|
+
// ssh2's server-side Client stores the socket supplied to injectSocket as
|
|
205
|
+
// _sock (1.17). Do not authorize a connection if that transport is unknown.
|
|
206
|
+
const socket = (client as unknown as { _sock?: Transport })._sock;
|
|
207
|
+
const peer = socket && peers.get(socket);
|
|
208
|
+
client.on("error", () => socket?.destroy());
|
|
209
|
+
if (!peer) { client.end(); return; }
|
|
187
210
|
const ip = info?.ip ?? "?";
|
|
188
|
-
let device: DeviceRecord | null = null;
|
|
189
|
-
|
|
190
|
-
client.on("error", () => {
|
|
191
|
-
/* the socket layer reports the close itself */
|
|
192
|
-
});
|
|
193
|
-
|
|
194
|
-
let dev: DeviceRecord | null = null; // narrowed alias for the closures below
|
|
195
211
|
client.on("authentication", (ctx) => {
|
|
196
212
|
if (blocked(ip)) return ctx.reject();
|
|
197
213
|
// The initial `none` request discovers supported methods. An empty list
|
|
@@ -218,9 +234,9 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
218
234
|
deps.log(`ssh: bad key signature for ${rec.id} from ${ip}`);
|
|
219
235
|
return reject();
|
|
220
236
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
deps.log(`ssh: device ${rec.id} (${rec.name}, ${rec.scope}) authenticated with key ${
|
|
237
|
+
peer.deviceId = rec.id;
|
|
238
|
+
peer.fingerprint = sshKeyFingerprint(entry.b64);
|
|
239
|
+
deps.log(`ssh: device ${rec.id} (${rec.name}, ${rec.scope}) authenticated with key ${peer.fingerprint} from ${ip}`);
|
|
224
240
|
return ctx.accept();
|
|
225
241
|
}
|
|
226
242
|
if (ctx.method !== "password") {
|
|
@@ -233,8 +249,8 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
233
249
|
deps.log(`ssh: auth failed for "${id.slice(0, 12)}" from ${ip}`);
|
|
234
250
|
return reject();
|
|
235
251
|
}
|
|
236
|
-
|
|
237
|
-
|
|
252
|
+
peer.deviceId = ok.id;
|
|
253
|
+
peer.fingerprint = undefined;
|
|
238
254
|
deps.log(`ssh: device ${ok.id} (${ok.name}, ${ok.scope}) authenticated from ${ip}`);
|
|
239
255
|
ctx.accept();
|
|
240
256
|
});
|
|
@@ -248,7 +264,10 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
248
264
|
};
|
|
249
265
|
|
|
250
266
|
client.on("ready", () => {
|
|
267
|
+
if (peer.deadline) clearTimeout(peer.deadline);
|
|
268
|
+
peer.deadline = null;
|
|
251
269
|
client.on("session", (accept, reject) => {
|
|
270
|
+
if (peer.socket.destroyed || !peer.deviceId || !deps.state.deviceById(peer.deviceId)) return reject();
|
|
252
271
|
const session = accept();
|
|
253
272
|
session.on("sftp", (acceptSftp, rejectSftp) => rejectSftp());
|
|
254
273
|
session.on("shell", (acceptShell, rejectShell) => rejectShell());
|
|
@@ -257,8 +276,8 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
257
276
|
// request (without allocating anything) is honest and keeps exec-only policy.
|
|
258
277
|
session.on("pty", (accept) => accept());
|
|
259
278
|
session.on("exec", (acceptExec, rejectExec, info) => {
|
|
260
|
-
const dvc =
|
|
261
|
-
if (!dvc) return rejectExec();
|
|
279
|
+
const dvc = peer.deviceId ? deps.state.deviceById(peer.deviceId) : null;
|
|
280
|
+
if (peer.socket.destroyed || !dvc || (peer.fingerprint && !dvc.sshKeys?.some(k => sshKeyFingerprint(k.b64) === peer.fingerprint))) return rejectExec();
|
|
262
281
|
if (blocked(ip)) return rejectExec();
|
|
263
282
|
|
|
264
283
|
// No device-socket gate here: a phone on the SSH leg has no WebSocket open.
|
|
@@ -302,16 +321,35 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
302
321
|
|
|
303
322
|
client.on("close", () => {
|
|
304
323
|
for (const c of owned.values()) closeChannel(c);
|
|
305
|
-
if (
|
|
324
|
+
if (peer.deviceId && deviceChannels(peer.deviceId).length === 0) deps.log(`ssh: device ${peer.deviceId} disconnected`);
|
|
306
325
|
});
|
|
307
326
|
});
|
|
308
327
|
|
|
328
|
+
const inject = (socket: Transport): void => {
|
|
329
|
+
const ip = socket.remoteAddress ?? "?";
|
|
330
|
+
const pending = [...peers.values()].filter(p => p.deadline !== null);
|
|
331
|
+
if (peers.size >= 128 || pending.length >= 32 || pending.filter(p => p.ip === ip).length >= 12) {
|
|
332
|
+
socket.destroy();
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const peer: Peer = { socket, ip, deadline: setTimeout(() => socket.destroy(), authTimeoutMs) };
|
|
336
|
+
peer.deadline?.unref();
|
|
337
|
+
peers.set(socket, peer);
|
|
338
|
+
socket.once("close", () => {
|
|
339
|
+
if (peer.deadline) clearTimeout(peer.deadline);
|
|
340
|
+
peers.delete(socket);
|
|
341
|
+
});
|
|
342
|
+
socket.on("error", () => socket.destroy());
|
|
343
|
+
try { server.injectSocket(socket as Socket); }
|
|
344
|
+
catch { socket.destroy(); }
|
|
345
|
+
};
|
|
346
|
+
const tcp = tcpServer(inject);
|
|
309
347
|
await new Promise<void>((resolve, reject) => {
|
|
310
|
-
|
|
311
|
-
|
|
348
|
+
tcp.once("error", reject);
|
|
349
|
+
tcp.listen(port, bind, () => resolve());
|
|
312
350
|
});
|
|
313
351
|
|
|
314
|
-
const addr =
|
|
352
|
+
const addr = tcp.address();
|
|
315
353
|
const realPort = typeof addr === "object" && addr ? addr.port : null;
|
|
316
354
|
deps.log(`ssh: listening on ${bind}:${realPort} (devices auth with their device id + key)`);
|
|
317
355
|
|
|
@@ -319,10 +357,13 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
319
357
|
port: realPort,
|
|
320
358
|
bind,
|
|
321
359
|
hostKeyFingerprint: hostKey.fingerprint,
|
|
322
|
-
inject
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
360
|
+
inject,
|
|
361
|
+
revoke(deviceId, fingerprint) {
|
|
362
|
+
for (const peer of peers.values()) {
|
|
363
|
+
if (peer.deviceId === deviceId && (fingerprint === undefined || peer.fingerprint === fingerprint)) {
|
|
364
|
+
peer.socket.destroy();
|
|
365
|
+
}
|
|
366
|
+
}
|
|
326
367
|
},
|
|
327
368
|
/** The HOST's ssh.* frames come back through the agent leg; write them into the phone's stream. */
|
|
328
369
|
onHostFrame(deviceId, payload) {
|
|
@@ -366,11 +407,8 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
366
407
|
return true;
|
|
367
408
|
},
|
|
368
409
|
async close() {
|
|
369
|
-
for (const
|
|
370
|
-
|
|
371
|
-
}
|
|
372
|
-
channels.clear();
|
|
373
|
-
await new Promise<void>((done) => server.close(() => done()));
|
|
410
|
+
for (const peer of peers.values()) peer.socket.destroy();
|
|
411
|
+
await new Promise<void>((done) => tcp.close(() => done()));
|
|
374
412
|
},
|
|
375
413
|
} satisfies SshHandle;
|
|
376
414
|
}
|
|
@@ -378,12 +416,13 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
378
416
|
/** Mint once, keep at mode 0600; ephemeral (per-boot) when no key path is configured. */
|
|
379
417
|
function loadOrMintHostKey(deps: SshDeps): { private: string; public: string; fingerprint: string } {
|
|
380
418
|
const path = deps.config.keyPath;
|
|
381
|
-
if (path
|
|
419
|
+
if (path) {
|
|
382
420
|
try {
|
|
383
|
-
const f = JSON.parse(readFileSync(path, "utf8")) as { private: string; public: string
|
|
384
|
-
if (f.private
|
|
385
|
-
|
|
386
|
-
|
|
421
|
+
const f = JSON.parse(readFileSync(path, "utf8")) as { private: string; public: string };
|
|
422
|
+
if (typeof f.private !== "string" || !f.private || typeof f.public !== "string" || !f.public) throw new Error("invalid key");
|
|
423
|
+
return { private: f.private, public: f.public, fingerprint: fingerprintOf(f.public) };
|
|
424
|
+
} catch (e) {
|
|
425
|
+
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw new Error("cannot load existing SSH host key; restore it from backup");
|
|
387
426
|
}
|
|
388
427
|
}
|
|
389
428
|
// ssh2.utils generates the OpenSSH format directly; the node-crypto path is the fallback.
|
|
@@ -402,9 +441,8 @@ function loadOrMintHostKey(deps: SshDeps): { private: string; public: string; fi
|
|
|
402
441
|
})();
|
|
403
442
|
const fingerprint = fingerprintOf(key.public);
|
|
404
443
|
if (path) {
|
|
405
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
406
|
-
writeFileSync(path, JSON.stringify({ ...key, fingerprint }), { mode: 0o600 });
|
|
407
|
-
chmodSync(path, 0o600);
|
|
444
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
445
|
+
writeFileSync(path, JSON.stringify({ ...key, fingerprint }), { mode: 0o600, flag: "wx" });
|
|
408
446
|
deps.log(`ssh: host key minted at ${path} (${fingerprint})`);
|
|
409
447
|
} else {
|
|
410
448
|
deps.log(`ssh: ephemeral host key (${fingerprint}) — set HERDGATE_SSH_KEY to keep it`);
|
package/src/cloud/util.ts
CHANGED
|
@@ -33,12 +33,12 @@ export function randomId(prefix: string): string {
|
|
|
33
33
|
export async function readJsonBody(req: import("node:http").IncomingMessage, maxBytes = 4096): Promise<Record<string, unknown> | null> {
|
|
34
34
|
const chunks: Buffer[] = [];
|
|
35
35
|
let size = 0;
|
|
36
|
-
for await (const c of req) {
|
|
37
|
-
size += (c as Buffer).length;
|
|
38
|
-
if (size > maxBytes) return null;
|
|
39
|
-
chunks.push(c as Buffer);
|
|
40
|
-
}
|
|
41
36
|
try {
|
|
37
|
+
for await (const c of req) {
|
|
38
|
+
size += (c as Buffer).length;
|
|
39
|
+
if (size > maxBytes) return null;
|
|
40
|
+
chunks.push(c as Buffer);
|
|
41
|
+
}
|
|
42
42
|
const v = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
43
43
|
return typeof v === "object" && v !== null && !Array.isArray(v) ? v as Record<string, unknown> : null;
|
|
44
44
|
} catch {
|
package/src/host/mobile-tui.ts
CHANGED
|
@@ -9,6 +9,13 @@ const url = new URL(process.env.HERDGATE_URL);
|
|
|
9
9
|
if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
10
10
|
throw new Error("HERDGATE_URL must be an HTTPS origin");
|
|
11
11
|
}
|
|
12
|
+
const loopback = process.env.HERDGATE_AGENT_LOOPBACK_PORT;
|
|
13
|
+
if (loopback !== undefined && (!/^[1-9]\d{0,4}$/.test(loopback) || Number(loopback) > 65535)) {
|
|
14
|
+
throw new Error("HERDGATE_AGENT_LOOPBACK_PORT must be a port from 1 to 65535");
|
|
15
|
+
}
|
|
16
|
+
const endpoint = loopback
|
|
17
|
+
? `ws://127.0.0.1:${loopback}/v1/agent/ws`
|
|
18
|
+
: `wss://${url.host}/v1/agent/ws`;
|
|
12
19
|
const token = process.env.HERDGATE_ROOM_TOKEN;
|
|
13
20
|
if (!token) throw new Error("configure a dedicated room token for the TUI mobile pilot");
|
|
14
21
|
const name = process.env.HERDGATE_HOST_NAME || "home-tui-mobile";
|
|
@@ -35,7 +42,10 @@ const bridge = createSshBridge({
|
|
|
35
42
|
});
|
|
36
43
|
|
|
37
44
|
const agent = new HerdGateAgent({
|
|
38
|
-
endpoint
|
|
45
|
+
endpoint, roomToken: token,
|
|
46
|
+
log: (line) => log(loopback && line.startsWith("cloud hello:") ? `${line} via loopback 127.0.0.1:${loopback}` : line),
|
|
47
|
+
// Only a co-located Gate may use plaintext. Preserve its public Host check.
|
|
48
|
+
wsOptions: loopback ? { headers: { Host: url.host }, agent: false, handshakeTimeout: 5000, perMessageDeflate: false } : undefined,
|
|
39
49
|
adapter: {
|
|
40
50
|
info: () => ({ name, version: "tui-core-pilot", capabilities: [controller ? "interactive" : "read-only"] }),
|
|
41
51
|
onPairAsk: () => false,
|