@bom0792/herdgate 0.9.20 → 0.9.21
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 +72 -1
- package/bin/herdgate.mjs +37 -5
- package/dist-readme.md +27 -2
- package/package.json +3 -2
- package/plugin/server/herdr-ssh-win.mjs +43 -0
- package/plugin/server/herdr-ssh.mjs +102 -0
- package/plugin/server/index.mjs +42 -12
- package/plugin/server/publish-tui.mjs +89 -0
- package/plugin/server/publisher-tui-lifecycle.mjs +117 -0
- package/plugin/server/ssh.d.mts +23 -0
- package/plugin/server/ssh.mjs +122 -37
- package/scripts/build-host-bundle.sh +3 -3
- package/src/cloud/gateway.ts +4 -1
- package/src/cloud/sshd.ts +27 -23
- package/src/host/ssh.ts +5 -315
- package/src/web/herdgate-host.zip +0 -0
- package/windows/cli.mjs +46 -0
- package/windows/install-cli.mjs +129 -0
package/src/host/ssh.ts
CHANGED
|
@@ -1,317 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* The cloud relays `ssh.*` payloads opaquely; THIS module is the trusted decision point:
|
|
5
|
-
*
|
|
6
|
-
* - a channel runs exactly one command, and only `hc …` (argv split, `shell: false`) —
|
|
7
|
-
* never a shell, never anything else;
|
|
8
|
-
* - a `read` device gets a filtered plain-mode channel: mutating JSON-RPC methods are
|
|
9
|
-
* refused AT THIS GATE (the phone sees an honest JSON-RPC error; herdr-core never
|
|
10
|
-
* sees the call), a `framed: true` hello is downgraded to plain mode, and a stream
|
|
11
|
-
* of garbage is cut off;
|
|
12
|
-
* - an `act` device (approved by a human on this host) gets byte-transparent access —
|
|
13
|
-
* framed mode, attach, everything herdr-core offers;
|
|
14
|
-
* - output back to the phone is coalesced (~20 ms) so a chatty terminal stays under
|
|
15
|
-
* the wire's frame-rate limits.
|
|
16
|
-
*/
|
|
1
|
+
// The standalone host and self-contained plugin enforce the same SSH policy.
|
|
2
|
+
import { createSshBridge as create, type SshBridgeOptions } from "../../plugin/server/ssh.mjs";
|
|
3
|
+
export { READ_METHODS, translateBootstrap, type SshBridge } from "../../plugin/server/ssh.mjs";
|
|
17
4
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
import { homedir } from "node:os";
|
|
21
|
-
import { join } from "node:path";
|
|
22
|
-
|
|
23
|
-
/** Methods a `read` device may call on herdr-core. Everything else is refused here. */
|
|
24
|
-
export const READ_METHODS = new Set([
|
|
25
|
-
"hello",
|
|
26
|
-
"rpc.discover",
|
|
27
|
-
"server.status",
|
|
28
|
-
"terminal.list",
|
|
29
|
-
"terminal.get",
|
|
30
|
-
"terminal.read",
|
|
31
|
-
"terminal.wait",
|
|
32
|
-
"templates.list",
|
|
33
|
-
"events.subscribe",
|
|
34
|
-
"doc.get",
|
|
35
|
-
"machine.list",
|
|
36
|
-
]);
|
|
37
|
-
|
|
38
|
-
const FLUSH_MS = 20;
|
|
39
|
-
const FLUSH_BYTES = 64 * 1024;
|
|
40
|
-
const MAX_MALFORMED = 50;
|
|
41
|
-
|
|
42
|
-
export interface SshBridgeOptions {
|
|
43
|
-
/** Route an opaque payload to one device. */
|
|
44
|
-
send(device: string, payload: Record<string, unknown>): void;
|
|
45
|
-
/** The device's scope in this room (`null` when unknown). */
|
|
46
|
-
scopeOf(device: string): "read" | "act" | null;
|
|
47
|
-
log?(line: string): void;
|
|
48
|
-
/** Where herdr-core is; resolved once per channel by default. */
|
|
49
|
-
resolveHc?: () => string | null;
|
|
50
|
-
spawnImpl?: (bin: string, args: string[], opts: { stdio: ("pipe" | null)[]; shell: boolean }) => ChildProcess;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
interface HostChannel {
|
|
54
|
-
device: string;
|
|
55
|
-
ch: string;
|
|
56
|
-
scope: "read" | "act";
|
|
57
|
-
proc: ChildProcess | null;
|
|
58
|
-
/** Bytes from the phone awaiting a newline (read scope parses line by line). */
|
|
59
|
-
inBuf: Buffer;
|
|
60
|
-
/** Bytes from hc awaiting the next flush. */
|
|
61
|
-
outBuf: Buffer;
|
|
62
|
-
flushTimer: NodeJS.Timeout | null;
|
|
63
|
-
malformed: number;
|
|
64
|
-
closed: boolean;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export interface SshBridge {
|
|
68
|
-
/** Handle one frame payload; returns true when it was an ssh.* op this module owns. */
|
|
69
|
-
handle(device: string, payload: unknown): boolean;
|
|
70
|
-
/** Drop every channel of a device (device disconnected from the cloud). */
|
|
71
|
-
dropDevice(device: string): void;
|
|
72
|
-
closeAll(): void;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
/** Extract `hc <verb>` from herdr-core's known machine-add probes (null = not one). */
|
|
77
|
-
export function translateBootstrap(cmd: string): string | null {
|
|
78
|
-
// POSIX: sh -c 'p=$(command -v herdr-core) …; exec "$p" connect'
|
|
79
|
-
const posix = cmd.match(/exec "\$p"\s+([^'"\n]+?)['"]?\s*$/);
|
|
80
|
-
if (posix) {
|
|
81
|
-
const args = posix[1].trim();
|
|
82
|
-
// Strict whitelist: flags, words, equals — never shell metacharacters.
|
|
83
|
-
if (/^[-a-z0-9][-a-z0-9 =]*$/i.test(args)) return `hc ${args}`;
|
|
84
|
-
}
|
|
85
|
-
// Windows: cmd /d /c "…herdr-core.exe connect) …"
|
|
86
|
-
const win = cmd.match(/herdr-core\.exe\)?\s+\(?([a-z][a-z0-9-]*)\)/);
|
|
87
|
-
if (win) return `hc ${win[1]}`;
|
|
88
|
-
return null;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
export function createSshBridge(o: SshBridgeOptions): SshBridge {
|
|
92
|
-
const log = o.log ?? (() => {});
|
|
93
|
-
const spawnFn = o.spawnImpl ?? spawn;
|
|
94
|
-
const channels = new Map<string, HostChannel>();
|
|
95
|
-
const key = (device: string, ch: string): string => `${device}:${ch}`;
|
|
96
|
-
|
|
97
|
-
const resolveHc =
|
|
98
|
-
o.resolveHc ??
|
|
99
|
-
((): string | null => {
|
|
100
|
-
const env = process.env.HERDGATE_HC_BIN?.trim();
|
|
101
|
-
if (env && existsSync(env)) return env;
|
|
102
|
-
const local = join(homedir(), ".local", "bin", "hc");
|
|
103
|
-
if (existsSync(local)) return local;
|
|
104
|
-
return existsSync("/usr/bin/hc") ? "/usr/bin/hc" : "hc"; // let spawn report ENOENT honestly
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
const sendOut = (c: HostChannel, final: boolean, code?: number, reason?: string): void => {
|
|
108
|
-
if (c.outBuf.length > 0) {
|
|
109
|
-
o.send(c.device, { op: "ssh.data", ch: c.ch, b64: c.outBuf.toString("base64") });
|
|
110
|
-
c.outBuf = Buffer.alloc(0);
|
|
111
|
-
}
|
|
112
|
-
if (final) {
|
|
113
|
-
o.send(c.device, { op: "ssh.closed", ch: c.ch, ...(code !== undefined ? { code } : {}), ...(reason ? { reason } : {}) });
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
|
|
117
|
-
const scheduleFlush = (c: HostChannel): void => {
|
|
118
|
-
if (c.flushTimer) return;
|
|
119
|
-
c.flushTimer = setTimeout(() => {
|
|
120
|
-
c.flushTimer = null;
|
|
121
|
-
if (!c.closed) sendOut(c, false);
|
|
122
|
-
}, FLUSH_MS);
|
|
123
|
-
c.flushTimer.unref?.();
|
|
124
|
-
};
|
|
125
|
-
|
|
126
|
-
const deny = (c: HostChannel, reason: string): void => {
|
|
127
|
-
o.send(c.device, { op: "ssh.denied", ch: c.ch, reason });
|
|
128
|
-
};
|
|
129
|
-
|
|
130
|
-
/** A refused call never reaches herdr-core: the phone gets a real JSON-RPC error. */
|
|
131
|
-
const refuseCall = (c: HostChannel, id: unknown, method: string): void => {
|
|
132
|
-
const err = JSON.stringify({
|
|
133
|
-
jsonrpc: "2.0",
|
|
134
|
-
id: id ?? null,
|
|
135
|
-
error: { code: -32600, message: `herdgate: "${method}" needs the act scope (this device is read-only)`, data: { kind: "forbidden", method } },
|
|
136
|
-
});
|
|
137
|
-
c.outBuf = Buffer.concat([c.outBuf, Buffer.from(`${err}\n`)]);
|
|
138
|
-
scheduleFlush(c);
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
/** Feed phone bytes into the channel; `read` scope parses, `act` pipes blind. */
|
|
142
|
-
const feed = (c: HostChannel, buf: Buffer): void => {
|
|
143
|
-
if (c.closed || !c.proc?.stdin) return;
|
|
144
|
-
if (c.scope === "act") {
|
|
145
|
-
c.proc.stdin.write(buf);
|
|
146
|
-
return;
|
|
147
|
-
}
|
|
148
|
-
c.inBuf = Buffer.concat([c.inBuf, buf]);
|
|
149
|
-
for (;;) {
|
|
150
|
-
const nl = c.inBuf.indexOf(0x0a);
|
|
151
|
-
if (nl < 0) break;
|
|
152
|
-
const line = c.inBuf.subarray(0, nl);
|
|
153
|
-
c.inBuf = c.inBuf.subarray(nl + 1);
|
|
154
|
-
const text = line.toString("utf8").trim();
|
|
155
|
-
if (!text) continue;
|
|
156
|
-
let msg: { method?: unknown; id?: unknown; params?: Record<string, unknown> } | null = null;
|
|
157
|
-
try {
|
|
158
|
-
msg = JSON.parse(text);
|
|
159
|
-
} catch {
|
|
160
|
-
msg = null;
|
|
161
|
-
}
|
|
162
|
-
if (!msg || typeof msg !== "object" || typeof msg.method !== "string") {
|
|
163
|
-
c.malformed += 1;
|
|
164
|
-
if (c.malformed > MAX_MALFORMED) {
|
|
165
|
-
log(`ssh: ${c.device}/${c.ch} cut off after ${c.malformed} malformed lines`);
|
|
166
|
-
kill(c, "too much malformed input");
|
|
167
|
-
return;
|
|
168
|
-
}
|
|
169
|
-
continue;
|
|
170
|
-
}
|
|
171
|
-
const method = msg.method;
|
|
172
|
-
if (method === "hello" && msg.params && typeof msg.params === "object") {
|
|
173
|
-
// Live terminals (framed attach) are byte streams a read-only device must not
|
|
174
|
-
// write into; downgrade to plain mode so list/read still work honestly.
|
|
175
|
-
if (msg.params.framed === true) {
|
|
176
|
-
msg.params.framed = false;
|
|
177
|
-
log(`ssh: ${c.device}/${c.ch} hello framed:true downgraded (read scope)`);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
if (!READ_METHODS.has(method)) {
|
|
181
|
-
refuseCall(c, msg.id, method);
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
c.proc.stdin.write(`${JSON.stringify(msg)}\n`);
|
|
185
|
-
}
|
|
186
|
-
};
|
|
187
|
-
|
|
188
|
-
const kill = (c: HostChannel, reason: string): void => {
|
|
189
|
-
c.closed = true;
|
|
190
|
-
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
191
|
-
c.proc?.kill("SIGKILL");
|
|
192
|
-
channels.delete(key(c.device, c.ch));
|
|
193
|
-
sendOut(c, true, 130, reason);
|
|
194
|
-
};
|
|
195
|
-
|
|
196
|
-
const handle = (device: string, payload: unknown): boolean => {
|
|
197
|
-
if (typeof payload !== "object" || payload === null) return false;
|
|
198
|
-
const op = (payload as { op?: unknown }).op;
|
|
199
|
-
if (typeof op !== "string" || !op.startsWith("ssh.")) return false;
|
|
200
|
-
const p = payload as Record<string, unknown>;
|
|
201
|
-
const ch = typeof p.ch === "string" ? p.ch : "";
|
|
202
|
-
|
|
203
|
-
if (op === "ssh.open") {
|
|
204
|
-
const scope = o.scopeOf(device);
|
|
205
|
-
if (!scope) {
|
|
206
|
-
o.send(device, { op: "ssh.denied", ch, reason: "this device is not paired to this room" });
|
|
207
|
-
return true;
|
|
208
|
-
}
|
|
209
|
-
const cmd = typeof p.cmd === "string" ? p.cmd.trim() : "";
|
|
210
|
-
// herdr-core's `machine add` probes with shell wrappers that locate a binary
|
|
211
|
-
// named `herdr-core` and `exec` it (POSIX and Windows templates). We never run
|
|
212
|
-
// shell lines: translate the KNOWN templates to the equivalent `hc <verb>` and
|
|
213
|
-
// let the normal path spawn it. Anything else shell-shaped is refused below.
|
|
214
|
-
const bootstrap = cmd.includes("herdr-core") ? translateBootstrap(cmd) : null;
|
|
215
|
-
const parts = (bootstrap ?? cmd).split(/\s+/).filter(Boolean);
|
|
216
|
-
if (parts.length > 0 && parts[0] === "exit" && (parts.length === 1 || parts[1] === "0")) {
|
|
217
|
-
// SSH clients end probe sessions with `exit` — acknowledge and close clean.
|
|
218
|
-
o.send(device, { op: "ssh.granted", ch, scope });
|
|
219
|
-
o.send(device, { op: "ssh.closed", ch, code: 0 });
|
|
220
|
-
return true;
|
|
221
|
-
}
|
|
222
|
-
if (parts.length === 0 || parts[0] !== "hc") {
|
|
223
|
-
// One command family only: the phone speaks herdr-core through this leg.
|
|
224
|
-
o.send(device, { op: "ssh.denied", ch, reason: `herdgate bridges "hc …" only, got "${cmd.slice(0, 60) || "(empty)"}"` });
|
|
225
|
-
return true;
|
|
226
|
-
}
|
|
227
|
-
const bin = resolveHc();
|
|
228
|
-
const args = parts.slice(1);
|
|
229
|
-
let proc: ChildProcess;
|
|
230
|
-
try {
|
|
231
|
-
proc = spawnFn(bin ?? "hc", args, { stdio: ["pipe", "pipe", "pipe"], shell: false });
|
|
232
|
-
} catch (e) {
|
|
233
|
-
o.send(device, { op: "ssh.denied", ch, reason: `could not start herdr-core: ${e instanceof Error ? e.message : String(e)}` });
|
|
234
|
-
return true;
|
|
235
|
-
}
|
|
236
|
-
const c: HostChannel = { device, ch, scope, proc, inBuf: Buffer.alloc(0), outBuf: Buffer.alloc(0), flushTimer: null, malformed: 0, closed: false };
|
|
237
|
-
channels.set(key(device, ch), c);
|
|
238
|
-
|
|
239
|
-
proc.stdout?.on("data", (chunk: Buffer) => {
|
|
240
|
-
c.outBuf = Buffer.concat([c.outBuf, chunk]);
|
|
241
|
-
scheduleFlush(c);
|
|
242
|
-
});
|
|
243
|
-
proc.stderr?.on("data", (chunk: Buffer) => {
|
|
244
|
-
// herdr-core writes diagnostics to stderr; the phone shows them as output too.
|
|
245
|
-
c.outBuf = Buffer.concat([c.outBuf, chunk]);
|
|
246
|
-
scheduleFlush(c);
|
|
247
|
-
});
|
|
248
|
-
proc.on("error", (e) => {
|
|
249
|
-
const enoent = (e as NodeJS.ErrnoException).code === "ENOENT";
|
|
250
|
-
log(`ssh: spawn failed for ${device}/${ch}: ${e.message}`);
|
|
251
|
-
channels.delete(key(device, ch));
|
|
252
|
-
c.closed = true;
|
|
253
|
-
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
254
|
-
o.send(device, {
|
|
255
|
-
op: "ssh.denied",
|
|
256
|
-
ch,
|
|
257
|
-
reason: enoent ? "herdr-core (hc) was not found on this host" : `could not start herdr-core: ${e.message}`,
|
|
258
|
-
});
|
|
259
|
-
});
|
|
260
|
-
proc.on("close", (code, signal) => {
|
|
261
|
-
if (c.closed) return;
|
|
262
|
-
c.closed = true;
|
|
263
|
-
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
264
|
-
channels.delete(key(device, ch));
|
|
265
|
-
sendOut(c, true, code ?? (signal ? 130 : 1), signal ? `terminated by ${signal}` : undefined);
|
|
266
|
-
});
|
|
267
|
-
|
|
268
|
-
o.send(device, { op: "ssh.granted", ch, scope });
|
|
269
|
-
log(`ssh: ${device}/${ch} → ${cmd} (${scope})`);
|
|
270
|
-
return true;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
if (op === "ssh.data") {
|
|
274
|
-
const c = channels.get(key(device, ch));
|
|
275
|
-
if (!c) return true; // unknown or already closed: drop
|
|
276
|
-
const b64 = typeof p.b64 === "string" ? p.b64 : "";
|
|
277
|
-
if (b64.length > 400_000) return true;
|
|
278
|
-
feed(c, Buffer.from(b64, "base64"));
|
|
279
|
-
return true;
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
if (op === "ssh.close") {
|
|
283
|
-
const c = channels.get(key(device, ch));
|
|
284
|
-
if (!c) return true;
|
|
285
|
-
c.closed = true;
|
|
286
|
-
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
287
|
-
c.proc?.kill("SIGTERM");
|
|
288
|
-
channels.delete(key(device, ch));
|
|
289
|
-
sendOut(c, true, 0, "closed by the device");
|
|
290
|
-
return true;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
return false; // an ssh.* op we don't know: tell the adapter layer it's not ours to read
|
|
294
|
-
};
|
|
295
|
-
|
|
296
|
-
return {
|
|
297
|
-
handle,
|
|
298
|
-
dropDevice(device: string): void {
|
|
299
|
-
for (const [k, c] of [...channels]) {
|
|
300
|
-
if (c.device === device) {
|
|
301
|
-
c.closed = true;
|
|
302
|
-
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
303
|
-
c.proc?.kill("SIGTERM");
|
|
304
|
-
channels.delete(k);
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
},
|
|
308
|
-
closeAll(): void {
|
|
309
|
-
for (const [, c] of [...channels]) {
|
|
310
|
-
c.closed = true;
|
|
311
|
-
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
312
|
-
c.proc?.kill("SIGTERM");
|
|
313
|
-
}
|
|
314
|
-
channels.clear();
|
|
315
|
-
},
|
|
316
|
-
};
|
|
5
|
+
export function createSshBridge(options: Omit<SshBridgeOptions, "resolve"> & { resolveHc?: SshBridgeOptions["resolve"] }) {
|
|
6
|
+
return create({ ...options, resolve: options.resolveHc });
|
|
317
7
|
}
|
|
Binary file
|
package/windows/cli.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const release = realpathSync(fileURLToPath(new URL("../", import.meta.url)));
|
|
7
|
+
const releases = dirname(release);
|
|
8
|
+
const root = dirname(releases);
|
|
9
|
+
const usage = `herdgate-tui start [path-to-herdr.exe]
|
|
10
|
+
herdgate-tui status | stop | version | versions
|
|
11
|
+
herdgate-tui use <release-id>`;
|
|
12
|
+
|
|
13
|
+
function run(file, args) {
|
|
14
|
+
const result = spawnSync(process.execPath, [join(release, file), ...args], { stdio: "inherit", windowsHide: true, shell: false });
|
|
15
|
+
if (result.error) throw result.error;
|
|
16
|
+
process.exitCode = result.status ?? 1;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
const [cmd, ...args] = process.argv.slice(2);
|
|
21
|
+
if ((!cmd || cmd === "help" || cmd === "--help") && !args.length) {
|
|
22
|
+
console.log(usage);
|
|
23
|
+
} else if (cmd === "version" && !args.length) {
|
|
24
|
+
console.log(readFileSync(join(release, "release.txt"), "utf8").trim());
|
|
25
|
+
} else if (cmd === "versions" && !args.length) {
|
|
26
|
+
for (const entry of readdirSync(releases, { withFileTypes: true })) {
|
|
27
|
+
if (entry.isDirectory() && /^tui-[a-f0-9]{16}$/.test(entry.name)) {
|
|
28
|
+
console.log(`${entry.name}${entry.name === basename(release) ? " (current)" : ""}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
} else if (cmd === "use" && args.length === 1) {
|
|
32
|
+
run("windows/install-cli.mjs", ["--root", root, "--use", args[0]]);
|
|
33
|
+
} else if ((cmd === "status" || cmd === "stop") && !args.length) {
|
|
34
|
+
run("plugin/server/publish-tui.mjs", [cmd]);
|
|
35
|
+
} else if (cmd === "start" && args.length <= 1) {
|
|
36
|
+
const pilot = process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "HerdrPilot", "v0.9.5", "herdr.exe");
|
|
37
|
+
const bin = args[0] || process.env.HERDGATE_HERDR_BIN || (pilot && existsSync(pilot) ? pilot : null);
|
|
38
|
+
if (!bin) throw new Error("give the full path to Herdr 0.9.5: herdgate-tui start <path-to-herdr.exe>");
|
|
39
|
+
run("plugin/server/publish-tui.mjs", [cmd, bin]);
|
|
40
|
+
} else {
|
|
41
|
+
throw new Error(usage);
|
|
42
|
+
}
|
|
43
|
+
} catch (e) {
|
|
44
|
+
console.error(`herdgate-tui: ${e instanceof Error ? e.message : String(e)}`);
|
|
45
|
+
process.exitCode = 1;
|
|
46
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Per-user installation. On Windows, directory junctions do not need admin or Developer Mode.
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
const source = fileURLToPath(new URL("../", import.meta.url));
|
|
8
|
+
const releasePattern = /^tui-[a-f0-9]{16}$/;
|
|
9
|
+
const stat = (p) => { try { return lstatSync(p); } catch (e) { if (e.code === "ENOENT") return null; throw e; } };
|
|
10
|
+
const pathKey = (p) => process.platform === "win32" ? p.toLowerCase() : p;
|
|
11
|
+
const samePath = (a, b) => pathKey(a) === pathKey(b);
|
|
12
|
+
|
|
13
|
+
function directory(path) {
|
|
14
|
+
mkdirSync(path, { recursive: true });
|
|
15
|
+
if (!lstatSync(path).isDirectory()) throw new Error(`expected a real directory: ${path}`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function inputs() {
|
|
19
|
+
return ["plugin/server", "windows"].flatMap((dir) => readdirSync(join(source, dir), { withFileTypes: true })
|
|
20
|
+
.filter((file) => file.isFile() && file.name.endsWith(".mjs"))
|
|
21
|
+
.map((file) => `${dir}/${file.name}`)).sort();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function installRelease(releases) {
|
|
25
|
+
const files = inputs().map((name) => [name, readFileSync(join(source, name))]);
|
|
26
|
+
const hash = createHash("sha256");
|
|
27
|
+
for (const [name, contents] of files) hash.update(`${name}\0${contents.length}\0`).update(contents);
|
|
28
|
+
const id = `tui-${hash.digest("hex").slice(0, 16)}`;
|
|
29
|
+
const dest = join(releases, id);
|
|
30
|
+
if (stat(dest)) {
|
|
31
|
+
if (!lstatSync(dest).isDirectory() || readFileSync(join(dest, "release.txt"), "utf8").trim() !== id) {
|
|
32
|
+
throw new Error(`invalid existing release: ${dest}`);
|
|
33
|
+
}
|
|
34
|
+
return id;
|
|
35
|
+
}
|
|
36
|
+
const stage = mkdtempSync(join(releases, ".stage-"));
|
|
37
|
+
try {
|
|
38
|
+
for (const [name, data] of files) {
|
|
39
|
+
mkdirSync(dirname(join(stage, name)), { recursive: true });
|
|
40
|
+
writeFileSync(join(stage, name), data, { flag: "wx" });
|
|
41
|
+
}
|
|
42
|
+
writeFileSync(join(stage, "release.txt"), `${id}\n`);
|
|
43
|
+
renameSync(stage, dest);
|
|
44
|
+
} finally {
|
|
45
|
+
rmSync(stage, { force: true, recursive: true });
|
|
46
|
+
}
|
|
47
|
+
return id;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function selectRelease(root, releases, id) {
|
|
51
|
+
if (!releasePattern.test(id)) throw new Error("invalid release ID");
|
|
52
|
+
const dest = join(releases, id);
|
|
53
|
+
if (!stat(dest)?.isDirectory() || readFileSync(join(dest, "release.txt"), "utf8").trim() !== id) {
|
|
54
|
+
throw new Error(`release not installed: ${id}`);
|
|
55
|
+
}
|
|
56
|
+
const current = join(root, "current");
|
|
57
|
+
const old = stat(current);
|
|
58
|
+
if (old) {
|
|
59
|
+
if (!old.isSymbolicLink()) throw new Error(`refusing to replace a real file or directory: ${current}`);
|
|
60
|
+
const target = realpathSync(current);
|
|
61
|
+
if (!releasePattern.test(basename(target)) || !samePath(dirname(target), realpathSync(releases))) {
|
|
62
|
+
throw new Error(`refusing to replace a link outside the managed releases: ${current}`);
|
|
63
|
+
}
|
|
64
|
+
if (samePath(target, realpathSync(dest))) return;
|
|
65
|
+
}
|
|
66
|
+
const slot = join(root, `.next-${randomUUID()}`);
|
|
67
|
+
const backup = `${slot}.old`;
|
|
68
|
+
symlinkSync(dest, slot, process.platform === "win32" ? "junction" : "dir");
|
|
69
|
+
try {
|
|
70
|
+
if (old) renameSync(current, backup);
|
|
71
|
+
try { renameSync(slot, current); }
|
|
72
|
+
catch (e) {
|
|
73
|
+
if (old) renameSync(backup, current);
|
|
74
|
+
throw e;
|
|
75
|
+
}
|
|
76
|
+
if (old) unlinkSync(backup);
|
|
77
|
+
} finally {
|
|
78
|
+
if (stat(slot)?.isSymbolicLink()) unlinkSync(slot);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function installShim(root) {
|
|
83
|
+
const bin = join(root, "bin");
|
|
84
|
+
directory(bin);
|
|
85
|
+
const shim = join(bin, "herdgate-tui.cmd");
|
|
86
|
+
const previous = stat(shim);
|
|
87
|
+
if (previous && (!previous.isFile() || !readFileSync(shim, "utf8").startsWith("@rem Herdgate TUI CLI\r\n"))) {
|
|
88
|
+
throw new Error(`refusing to overwrite an unmanaged shim: ${shim}`);
|
|
89
|
+
}
|
|
90
|
+
const staged = `${shim}.${randomUUID()}`;
|
|
91
|
+
try {
|
|
92
|
+
// Match the Node used for install, not a node.exe from the caller's cwd.
|
|
93
|
+
const node = process.execPath.replaceAll("%", "%%");
|
|
94
|
+
writeFileSync(staged, `@rem Herdgate TUI CLI\r\n@echo off\r\nsetlocal DisableDelayedExpansion\r\n"${node}" "%~dp0..\\current\\windows\\cli.mjs" %*\r\nexit /b %errorlevel%\r\n`, { flag: "wx" });
|
|
95
|
+
renameSync(staged, shim);
|
|
96
|
+
} finally {
|
|
97
|
+
rmSync(staged, { force: true });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
try {
|
|
102
|
+
const args = process.argv.slice(2);
|
|
103
|
+
let root = process.platform === "win32" && process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Herdgate", "cli") : null;
|
|
104
|
+
let use = null;
|
|
105
|
+
while (args.length) {
|
|
106
|
+
const flag = args.shift();
|
|
107
|
+
const value = args.shift();
|
|
108
|
+
if (flag === "--root" && value) root = resolve(value);
|
|
109
|
+
else if (flag === "--use" && value) use = value;
|
|
110
|
+
else throw new Error("usage: node windows/install-cli.mjs [--root <dir>] [--use <release-id>]");
|
|
111
|
+
}
|
|
112
|
+
if (!root) throw new Error("this installer defaults to %LOCALAPPDATA% on Windows");
|
|
113
|
+
directory(root);
|
|
114
|
+
const releases = join(root, "releases");
|
|
115
|
+
directory(releases);
|
|
116
|
+
const lock = join(root, ".installing");
|
|
117
|
+
mkdirSync(lock);
|
|
118
|
+
try {
|
|
119
|
+
const id = use ?? installRelease(releases);
|
|
120
|
+
selectRelease(root, releases, id);
|
|
121
|
+
installShim(root);
|
|
122
|
+
console.log(`Herdgate TUI CLI: ${id}\nShim: ${join(root, "bin", "herdgate-tui.cmd")}`);
|
|
123
|
+
} finally {
|
|
124
|
+
rmSync(lock, { force: true, recursive: true });
|
|
125
|
+
}
|
|
126
|
+
} catch (e) {
|
|
127
|
+
console.error(`herdgate install: ${e instanceof Error ? e.message : String(e)}`);
|
|
128
|
+
process.exitCode = 1;
|
|
129
|
+
}
|