@k-electron/k-bench 0.0.0 → 0.1.1
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/LICENSE +21 -0
- package/README.md +69 -2
- package/dist/js/scripts/command-lib.js +56 -0
- package/dist/js/scripts/install-lib.js +187 -0
- package/dist/js/scripts/install.js +233 -0
- package/dist/js/scripts/k-bench.js +53 -0
- package/dist/js/scripts/status.js +178 -0
- package/dist/js/scripts/tailscale-serve.js +135 -0
- package/dist/js/scripts/uninstall.js +150 -0
- package/dist/js/src/server/access-guard.js +63 -0
- package/dist/js/src/server/app.js +122 -0
- package/dist/js/src/server/attachments.js +273 -0
- package/dist/js/src/server/config.js +42 -0
- package/dist/js/src/server/directories.js +34 -0
- package/dist/js/src/server/events.js +31 -0
- package/dist/js/src/server/main.js +42 -0
- package/dist/js/src/server/naming.js +9 -0
- package/dist/js/src/server/reconciler.js +41 -0
- package/dist/js/src/server/server.js +86 -0
- package/dist/js/src/server/service.js +217 -0
- package/dist/js/src/server/state-feed.js +115 -0
- package/dist/js/src/server/static.js +46 -0
- package/dist/js/src/server/store.js +127 -0
- package/dist/js/src/server/terminal.js +64 -0
- package/dist/js/src/server/tmux.js +323 -0
- package/dist/js/src/shared/terminal-protocol.js +67 -0
- package/dist/web/assets/index-BeaoLAfY.css +2 -0
- package/dist/web/assets/index-rujAJZxv.js +68 -0
- package/dist/web/index.html +13 -0
- package/package.json +91 -3
- package/scripts/fix-node-pty.mjs +21 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// `k-bench status`: a one-command health check of the Installed instance. Each check prints
|
|
2
|
+
// as ok or FAIL, a failure with a one-line fix, and the exit status is non-zero when any
|
|
3
|
+
// check failed. It only looks: it never changes the machine, the tailnet or the app.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
import { resolveConfig } from "../src/server/config.js";
|
|
9
|
+
import { appDirIn, BUILD_INFO_FILE, LAUNCH_AGENT_LABEL, LOG_HINT, launchAgentLoaded, pathDirs as pathDirsOf, } from "./command-lib.js";
|
|
10
|
+
import { findExecutable, parseTailscaleStatus, resolveTailscaleCli, } from "./install-lib.js";
|
|
11
|
+
import { findOwnEntry, readServeConfig, serveUrl } from "./tailscale-serve.js";
|
|
12
|
+
/** The header `tailscale serve` adds to every request it proxies; the server's login check. */
|
|
13
|
+
const LOGIN_HEADER = "Tailscale-User-Login";
|
|
14
|
+
const ok = (name, detail) => ({ name, result: "ok", detail });
|
|
15
|
+
const fail = (name, problem, fix) => ({
|
|
16
|
+
name,
|
|
17
|
+
result: "fail",
|
|
18
|
+
problem,
|
|
19
|
+
fix,
|
|
20
|
+
});
|
|
21
|
+
const skip = (name, why) => ({ name, result: "skip", why });
|
|
22
|
+
/** What `tailscale status --json` says about the node's login and HTTPS certificates. */
|
|
23
|
+
function readTailscaleStatus(tailscale) {
|
|
24
|
+
let json;
|
|
25
|
+
try {
|
|
26
|
+
json = execFileSync(tailscale, ["status", "--json"], {
|
|
27
|
+
encoding: "utf8",
|
|
28
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return {
|
|
33
|
+
running: false,
|
|
34
|
+
why: "`tailscale status --json` failed (is Tailscale running?)",
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
const parsed = JSON.parse(json);
|
|
39
|
+
if (parsed.BackendState !== "Running") {
|
|
40
|
+
return {
|
|
41
|
+
running: false,
|
|
42
|
+
why: `Tailscale is not up and logged in (state: ${parsed.BackendState ?? "unknown"})`,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
return { running: true, json, certDomains: parsed.CertDomains ?? [] };
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return { running: false, why: "`tailscale status --json` did not print JSON" };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Asks the running server's health check, as the owner when their login is known. */
|
|
52
|
+
async function checkServer(port, login) {
|
|
53
|
+
const name = "the server answers its health check";
|
|
54
|
+
const notAnswering = fail(name, `nothing answered on 127.0.0.1:${port}`, `run \`k-bench install\` to start it again, or look in ${LOG_HINT} for why it stopped`);
|
|
55
|
+
let response;
|
|
56
|
+
try {
|
|
57
|
+
response = await fetch(`http://127.0.0.1:${port}/api/health`, {
|
|
58
|
+
headers: login ? { [LOGIN_HEADER]: login } : {},
|
|
59
|
+
signal: AbortSignal.timeout(5000),
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return notAnswering;
|
|
64
|
+
}
|
|
65
|
+
if (response.status === 200) {
|
|
66
|
+
const body = (await response.json().catch(() => ({})));
|
|
67
|
+
return body.status === "ok"
|
|
68
|
+
? ok(name)
|
|
69
|
+
: fail(name, `127.0.0.1:${port} answered, but not like k-bench`, "something else is using the port: stop it, then run `k-bench install`");
|
|
70
|
+
}
|
|
71
|
+
if (response.status === 403) {
|
|
72
|
+
// Up, and guarded. Without a login there was nothing more to ask.
|
|
73
|
+
return login
|
|
74
|
+
? fail(name, `the server is up but refused the login ${login}`, "run `k-bench install` to set the allowed login again")
|
|
75
|
+
: ok(name, "up (could not ask as the owner: no Tailscale login)");
|
|
76
|
+
}
|
|
77
|
+
return fail(name, `the server answered HTTP ${response.status}`, `look in ${LOG_HINT}, then run \`k-bench install\``);
|
|
78
|
+
}
|
|
79
|
+
/** The version `k-bench install` recorded in the installed app, e.g. `0.1.0`. */
|
|
80
|
+
function installedVersion(appDir) {
|
|
81
|
+
try {
|
|
82
|
+
const info = JSON.parse(readFileSync(join(appDir, BUILD_INFO_FILE), "utf8"));
|
|
83
|
+
if (!info.version)
|
|
84
|
+
return undefined;
|
|
85
|
+
const commit = info.commit
|
|
86
|
+
? ` (commit ${info.commit.slice(0, 7)}${info.dirty ? "+uncommitted" : ""})`
|
|
87
|
+
: "";
|
|
88
|
+
return `${info.version}${commit}`;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export async function status(argv) {
|
|
95
|
+
parseArgs({ args: argv, options: {}, allowPositionals: false });
|
|
96
|
+
// Explicit env: status describes the Installed instance, whatever the shell has set. The
|
|
97
|
+
// one override, K_BENCH_STATUS_PORT, is for the tests, to ask a throwaway server instead
|
|
98
|
+
// of the one on the Installed instance's port.
|
|
99
|
+
const config = resolveConfig({ K_BENCH_INSTANCE: "installed" });
|
|
100
|
+
const override = process.env.K_BENCH_STATUS_PORT;
|
|
101
|
+
const port = override && /^\d+$/.test(override) ? Number(override) : config.port;
|
|
102
|
+
const appDir = appDirIn(config.dataDir);
|
|
103
|
+
const pathDirs = pathDirsOf();
|
|
104
|
+
const checks = [];
|
|
105
|
+
const tmux = findExecutable("tmux", pathDirs);
|
|
106
|
+
checks.push(tmux
|
|
107
|
+
? ok("tmux is found", tmux)
|
|
108
|
+
: fail("tmux is found", "tmux is not on PATH", "install it with `brew install tmux`"));
|
|
109
|
+
const tailscale = resolveTailscaleCli({ pathDirs });
|
|
110
|
+
let login;
|
|
111
|
+
let dnsName;
|
|
112
|
+
let loggedIn = false;
|
|
113
|
+
if (!tailscale) {
|
|
114
|
+
checks.push(fail("the Tailscale CLI is found", "the Tailscale CLI is on neither PATH nor inside /Applications/Tailscale.app", "install Tailscale from https://tailscale.com/download"), skip("Tailscale is logged in", "needs the Tailscale CLI"), skip("HTTPS certificates are available", "needs the Tailscale CLI"));
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
checks.push(ok("the Tailscale CLI is found", tailscale));
|
|
118
|
+
const tailscaleStatus = readTailscaleStatus(tailscale);
|
|
119
|
+
if (!tailscaleStatus.running) {
|
|
120
|
+
checks.push(fail("Tailscale is logged in", tailscaleStatus.why, "open the Tailscale app and log in or turn it on (or run `tailscale up`)"), skip("HTTPS certificates are available", "needs a logged-in Tailscale"));
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
loggedIn = true;
|
|
124
|
+
try {
|
|
125
|
+
({ login, dnsName } = parseTailscaleStatus(tailscaleStatus.json));
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// A running node with no readable owner: the server is still asked, without a login.
|
|
129
|
+
}
|
|
130
|
+
checks.push(ok("Tailscale is logged in", login));
|
|
131
|
+
checks.push(tailscaleStatus.certDomains.length > 0
|
|
132
|
+
? ok("HTTPS certificates are available", tailscaleStatus.certDomains[0])
|
|
133
|
+
: fail("HTTPS certificates are available", "HTTPS certificates are not turned on for your tailnet", "turn on HTTPS Certificates at https://login.tailscale.com/admin/dns"));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
checks.push(launchAgentLoaded()
|
|
137
|
+
? ok("the LaunchAgent is loaded", LAUNCH_AGENT_LABEL)
|
|
138
|
+
: fail("the LaunchAgent is loaded", `${LAUNCH_AGENT_LABEL} is not loaded in launchd`, "run `k-bench install` to install and load it"));
|
|
139
|
+
checks.push(await checkServer(port, login));
|
|
140
|
+
// What the checks don't say: the version installed and where it is reachable.
|
|
141
|
+
const version = installedVersion(appDir);
|
|
142
|
+
let url;
|
|
143
|
+
if (!tailscale || !loggedIn || !dnsName) {
|
|
144
|
+
url = "unknown (needs a logged-in Tailscale)";
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
try {
|
|
148
|
+
const own = findOwnEntry(readServeConfig(tailscale), port);
|
|
149
|
+
url = own
|
|
150
|
+
? serveUrl(dnsName, own.port)
|
|
151
|
+
: "not published on the tailnet (run `k-bench install`)";
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
url = `unknown (${error.message})`;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
console.log("k-bench status\n");
|
|
158
|
+
for (const check of checks) {
|
|
159
|
+
if (check.result === "ok") {
|
|
160
|
+
console.log(` ok ${check.name}${check.detail ? ` (${check.detail})` : ""}`);
|
|
161
|
+
}
|
|
162
|
+
else if (check.result === "skip") {
|
|
163
|
+
console.log(` skip ${check.name} (${check.why})`);
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
console.log(` FAIL ${check.name}: ${check.problem}`);
|
|
167
|
+
console.log(` fix: ${check.fix}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
console.log(`\n version ${version ?? (existsSync(appDir) ? "unknown" : "not installed (run `k-bench install`)")}`);
|
|
171
|
+
console.log(` url ${url}\n`);
|
|
172
|
+
const failed = checks.filter((check) => check.result === "fail").length;
|
|
173
|
+
if (failed > 0) {
|
|
174
|
+
console.log(`${failed} of ${checks.length} checks failed.`);
|
|
175
|
+
process.exit(1);
|
|
176
|
+
}
|
|
177
|
+
console.log("All checks passed.");
|
|
178
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Reading the tailnet's `tailscale serve` configuration, shared by the `k-bench` commands:
|
|
2
|
+
// install checks that its HTTPS port is free, uninstall removes only k-bench's own entry,
|
|
3
|
+
// status prints where k-bench is reachable. The parsing is pure (`parseServeConfig` and the
|
|
4
|
+
// functions after it take plain data); `readServeConfig` is the one thin call to the CLI.
|
|
5
|
+
//
|
|
6
|
+
// The input is `tailscale serve status --json`, whose shape (confirmed against Tailscale
|
|
7
|
+
// itself) is, for k-bench published on the default port:
|
|
8
|
+
//
|
|
9
|
+
// { "TCP": { "443": { "HTTPS": true } },
|
|
10
|
+
// "Web": { "<host>.<tailnet>.ts.net:443": { "Handlers": { "/": { "Proxy": "http://127.0.0.1:7680" } } } } }
|
|
11
|
+
//
|
|
12
|
+
// `Web` is keyed `<host>:<port>`; a handler is a `Proxy` (a URL), a `Path` (files), a `Text`
|
|
13
|
+
// or a `Redirect`. A raw TCP forward lives only under `TCP`, as `{ "TCPForward": "host:port" }`.
|
|
14
|
+
// Nothing configured prints `{}`.
|
|
15
|
+
import { execFileSync } from "node:child_process";
|
|
16
|
+
/** The HTTPS port k-bench is published on unless `--https-port` says otherwise. */
|
|
17
|
+
export const DEFAULT_HTTPS_PORT = 443;
|
|
18
|
+
function describeHandler(path, handler) {
|
|
19
|
+
if (handler.Proxy !== undefined) {
|
|
20
|
+
return { path, proxy: handler.Proxy, description: `${path} -> ${handler.Proxy}` };
|
|
21
|
+
}
|
|
22
|
+
if (handler.Path !== undefined)
|
|
23
|
+
return { path, description: `${path} serves files` };
|
|
24
|
+
if (handler.Redirect !== undefined) {
|
|
25
|
+
return { path, description: `${path} redirects to ${handler.Redirect}` };
|
|
26
|
+
}
|
|
27
|
+
return { path, description: `${path} serves a fixed response` };
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Reads the output of `tailscale serve status --json`. Throws when it isn't JSON; nothing
|
|
31
|
+
* configured (`{}` or no output) is an empty configuration.
|
|
32
|
+
*/
|
|
33
|
+
export function parseServeConfig(json) {
|
|
34
|
+
const text = json.trim();
|
|
35
|
+
const raw = text === "" ? {} : JSON.parse(text);
|
|
36
|
+
const entries = [];
|
|
37
|
+
const webPorts = new Set();
|
|
38
|
+
for (const [hostPort, web] of Object.entries(raw.Web ?? {})) {
|
|
39
|
+
const port = Number(hostPort.slice(hostPort.lastIndexOf(":") + 1));
|
|
40
|
+
if (!Number.isInteger(port))
|
|
41
|
+
continue;
|
|
42
|
+
webPorts.add(port);
|
|
43
|
+
const targets = Object.entries(web.Handlers ?? {}).map(([path, handler]) => describeHandler(path, handler));
|
|
44
|
+
entries.push({ port, kind: "web", targets });
|
|
45
|
+
}
|
|
46
|
+
// A TCP port with a web entry is that entry's listener; any other is a raw forward.
|
|
47
|
+
for (const [portText, tcp] of Object.entries(raw.TCP ?? {})) {
|
|
48
|
+
const port = Number(portText);
|
|
49
|
+
if (!Number.isInteger(port) || webPorts.has(port))
|
|
50
|
+
continue;
|
|
51
|
+
entries.push({
|
|
52
|
+
port,
|
|
53
|
+
kind: "tcp",
|
|
54
|
+
targets: [
|
|
55
|
+
{
|
|
56
|
+
description: tcp.TCPForward
|
|
57
|
+
? `TCP forward to ${tcp.TCPForward}`
|
|
58
|
+
: "a TCP listener",
|
|
59
|
+
},
|
|
60
|
+
],
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return { entries };
|
|
64
|
+
}
|
|
65
|
+
/** The local address k-bench's server listens on, which its own entry proxies to. */
|
|
66
|
+
export function kBenchLocalUrl(localPort) {
|
|
67
|
+
return `http://127.0.0.1:${localPort}`;
|
|
68
|
+
}
|
|
69
|
+
function isKBenchProxy(proxy, localPort) {
|
|
70
|
+
if (proxy === undefined)
|
|
71
|
+
return false;
|
|
72
|
+
const normalised = proxy.replace(/\/+$/, "").replace("://localhost:", "://127.0.0.1:");
|
|
73
|
+
return normalised === kBenchLocalUrl(localPort);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Whether an entry is k-bench's own: a web entry whose only handler is `/` proxying to
|
|
77
|
+
* k-bench's local address (`localPort`, 7680 for the Installed instance). An entry that also
|
|
78
|
+
* serves other paths is somebody else's setup that k-bench shares a port with.
|
|
79
|
+
*/
|
|
80
|
+
function isOwnEntry(entry, localPort) {
|
|
81
|
+
return (entry.kind === "web" &&
|
|
82
|
+
entry.targets.length === 1 &&
|
|
83
|
+
entry.targets[0]?.path === "/" &&
|
|
84
|
+
isKBenchProxy(entry.targets[0].proxy, localPort));
|
|
85
|
+
}
|
|
86
|
+
/** Every one of k-bench's own entries, one per port it is published on. */
|
|
87
|
+
export function findOwnEntries(config, localPort) {
|
|
88
|
+
return config.entries.filter((entry) => isOwnEntry(entry, localPort));
|
|
89
|
+
}
|
|
90
|
+
/** The first of k-bench's own entries, on whichever port; undefined when not published. */
|
|
91
|
+
export function findOwnEntry(config, localPort) {
|
|
92
|
+
return findOwnEntries(config, localPort)[0];
|
|
93
|
+
}
|
|
94
|
+
export function portUse(config, port, localPort) {
|
|
95
|
+
const onPort = config.entries.filter((entry) => entry.port === port);
|
|
96
|
+
const [first] = onPort;
|
|
97
|
+
if (!first)
|
|
98
|
+
return { kind: "free" };
|
|
99
|
+
const foreign = onPort.find((entry) => !isOwnEntry(entry, localPort));
|
|
100
|
+
return foreign ? { kind: "other", entry: foreign } : { kind: "own", entry: first };
|
|
101
|
+
}
|
|
102
|
+
/** The URL a device on the tailnet opens: the port is left out when it is the default. */
|
|
103
|
+
export function serveUrl(dnsName, port) {
|
|
104
|
+
return `https://${dnsName.replace(/\.$/, "")}${port === DEFAULT_HTTPS_PORT ? "" : `:${port}`}/`;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The arguments that remove an entry (`tailscale serve --https=<port> off`, or `--tcp=` for
|
|
108
|
+
* a raw forward), for replacing it (`install --force`) or removing k-bench's own (uninstall).
|
|
109
|
+
*/
|
|
110
|
+
export function serveOffArgs(entry) {
|
|
111
|
+
return ["serve", `--${entry.kind === "tcp" ? "tcp" : "https"}=${entry.port}`, "off"];
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Asks Tailscale what it is serving. Throws a readable error when the CLI fails (for
|
|
115
|
+
* example Tailscale isn't running) or answers with something that isn't the expected JSON.
|
|
116
|
+
*/
|
|
117
|
+
export function readServeConfig(tailscale) {
|
|
118
|
+
let output;
|
|
119
|
+
try {
|
|
120
|
+
output = execFileSync(tailscale, ["serve", "status", "--json"], {
|
|
121
|
+
encoding: "utf8",
|
|
122
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
const detail = error.stderr?.trim();
|
|
127
|
+
throw new Error(`could not read the tailscale serve configuration (\`tailscale serve status --json\` failed${detail ? `: ${detail}` : ""}). Is Tailscale running?`);
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
return parseServeConfig(output);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
throw new Error("could not read the tailscale serve configuration: `tailscale serve status --json` did not print JSON.");
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// `k-bench uninstall`: removes the Installed instance without the owner needing to know how
|
|
2
|
+
// it was installed. By default it stops the LaunchAgent and removes it, removes k-bench's own
|
|
3
|
+
// `tailscale serve` entry (on whichever port; every other entry stays) and deletes the app
|
|
4
|
+
// folder, keeping the database and the `k-bench` tmux server, so running Sessions carry on
|
|
5
|
+
// and a reinstall restores everything. `--purge` also deletes the data folder and the logs
|
|
6
|
+
// and ends the tmux server, which ends every Session. `--dry-run` prints every step and
|
|
7
|
+
// changes nothing. Each step says so when there is nothing for it to remove.
|
|
8
|
+
import { existsSync, rmSync } from "node:fs";
|
|
9
|
+
import { dirname } from "node:path";
|
|
10
|
+
import { parseArgs } from "node:util";
|
|
11
|
+
import { resolveConfig } from "../src/server/config.js";
|
|
12
|
+
import { appDirIn, LAUNCH_AGENT_LABEL, launchAgentLoaded, launchAgentPlistPath, launchdDomain, logPath, pathDirs as pathDirsOf, reporter, succeeds, } from "./command-lib.js";
|
|
13
|
+
import { findExecutable, resolveTailscaleCli } from "./install-lib.js";
|
|
14
|
+
import { findOwnEntries, readServeConfig, serveOffArgs } from "./tailscale-serve.js";
|
|
15
|
+
export async function uninstall(argv) {
|
|
16
|
+
const { values: flags } = parseArgs({
|
|
17
|
+
args: argv,
|
|
18
|
+
options: {
|
|
19
|
+
"dry-run": { type: "boolean", default: false },
|
|
20
|
+
purge: { type: "boolean", default: false },
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
const dryRun = flags["dry-run"];
|
|
24
|
+
const purge = flags.purge;
|
|
25
|
+
// Explicit env, as in the install: never a K_BENCH_* override from the shell.
|
|
26
|
+
const config = resolveConfig({ K_BENCH_INSTANCE: "installed" });
|
|
27
|
+
const appDir = appDirIn(config.dataDir);
|
|
28
|
+
const logDir = dirname(logPath());
|
|
29
|
+
const plistPath = launchAgentPlistPath();
|
|
30
|
+
const domain = launchdDomain();
|
|
31
|
+
const pathDirs = pathDirsOf();
|
|
32
|
+
let failed = false;
|
|
33
|
+
const { say, step } = reporter(dryRun);
|
|
34
|
+
say(dryRun
|
|
35
|
+
? "k-bench uninstall: dry run, nothing will be changed.\n"
|
|
36
|
+
: "k-bench uninstall\n");
|
|
37
|
+
if (purge) {
|
|
38
|
+
say(`--purge: this deletes the database (every Workspace and Session) in ${config.dataDir} ` +
|
|
39
|
+
`and ends the "${config.tmuxSocket}" tmux server, which ends every Session. ` +
|
|
40
|
+
"It cannot be undone.\n");
|
|
41
|
+
}
|
|
42
|
+
// 1. The service. launchctl bootout stops the server; it leaves tmux, and so every
|
|
43
|
+
// Session, running (AbandonProcessGroup, ADR-0001).
|
|
44
|
+
if (launchAgentLoaded()) {
|
|
45
|
+
await step(`stop the LaunchAgent (launchctl bootout ${domain}/${LAUNCH_AGENT_LABEL})`, () => {
|
|
46
|
+
if (!succeeds("launchctl", ["bootout", `${domain}/${LAUNCH_AGENT_LABEL}`])) {
|
|
47
|
+
console.error("k-bench uninstall: launchctl could not stop the LaunchAgent.");
|
|
48
|
+
process.exit(1);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
say("no LaunchAgent is loaded: nothing to stop");
|
|
54
|
+
}
|
|
55
|
+
if (existsSync(plistPath)) {
|
|
56
|
+
await step(`delete the LaunchAgent ${plistPath} (k-bench stops starting at login)`, () => rmSync(plistPath, { force: true }));
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
say(`no LaunchAgent file at ${plistPath}: nothing to delete`);
|
|
60
|
+
}
|
|
61
|
+
// 2. k-bench's own tailscale serve entry, on whichever port it is.
|
|
62
|
+
const tailscale = resolveTailscaleCli({ pathDirs });
|
|
63
|
+
if (!tailscale) {
|
|
64
|
+
say("the Tailscale CLI was not found: not looking for a tailscale serve entry. " +
|
|
65
|
+
"If k-bench was published, remove it with `tailscale serve status` and `tailscale serve --https=<port> off`.");
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
try {
|
|
69
|
+
const serveConfig = readServeConfig(tailscale);
|
|
70
|
+
// Every port k-bench is published on (a reinstall on another --https-port leaves the
|
|
71
|
+
// earlier entry behind), and nothing else.
|
|
72
|
+
const own = findOwnEntries(serveConfig, config.port);
|
|
73
|
+
if (own.length > 0) {
|
|
74
|
+
for (const entry of own) {
|
|
75
|
+
const offArgs = serveOffArgs(entry);
|
|
76
|
+
await step(`remove k-bench's tailscale serve entry on port ${entry.port}: ${tailscale} ${offArgs.join(" ")}`, () => {
|
|
77
|
+
if (!succeeds(tailscale, offArgs)) {
|
|
78
|
+
failed = true;
|
|
79
|
+
console.error(`k-bench uninstall: could not remove the entry on port ${entry.port}. Remove it yourself with \`tailscale serve ${offArgs.slice(1).join(" ")}\`.`);
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const others = serveConfig.entries.filter((entry) => !own.includes(entry));
|
|
84
|
+
if (others.length > 0) {
|
|
85
|
+
say(`leaving ${others.length === 1 ? "the other tailscale serve entry" : `the ${others.length} other tailscale serve entries`} alone (port ${others.map((entry) => entry.port).join(", ")})`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
say(`no tailscale serve entry for k-bench (a proxy to ${`http://127.0.0.1:${config.port}`}): nothing to remove`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
failed = true;
|
|
94
|
+
console.error(`k-bench uninstall: ${error.message}\nk-bench's tailscale serve entry, if any, was not removed.`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// 3. The app folder (and leftovers of an interrupted install). Never the database beside it.
|
|
98
|
+
const appFolders = [appDir, `${appDir}.staging`, `${appDir}.previous`].filter((dir) => existsSync(dir));
|
|
99
|
+
if (appFolders.length > 0) {
|
|
100
|
+
await step(`delete the app folder ${appFolders.join(", ")}`, () => {
|
|
101
|
+
for (const dir of appFolders)
|
|
102
|
+
rmSync(dir, { recursive: true, force: true });
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
say(`no app folder at ${appDir}: nothing to delete`);
|
|
107
|
+
}
|
|
108
|
+
// 4. Purge: the Sessions, then the data.
|
|
109
|
+
if (purge) {
|
|
110
|
+
const tmux = findExecutable("tmux", pathDirs);
|
|
111
|
+
const tmuxArgs = ["-L", config.tmuxSocket];
|
|
112
|
+
if (tmux && succeeds(tmux, [...tmuxArgs, "list-sessions"])) {
|
|
113
|
+
await step(`end the "${config.tmuxSocket}" tmux server: this ends every Session (tmux -L ${config.tmuxSocket} kill-server)`, () => {
|
|
114
|
+
succeeds(tmux, [...tmuxArgs, "kill-server"]);
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
say(`no "${config.tmuxSocket}" tmux server is running: no Sessions to end`);
|
|
119
|
+
}
|
|
120
|
+
if (existsSync(config.dataDir)) {
|
|
121
|
+
await step(`delete the data folder ${config.dataDir}, including the database: every Workspace and Session is lost`, () => rmSync(config.dataDir, { recursive: true, force: true }));
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
say(`no data folder at ${config.dataDir}: nothing to delete`);
|
|
125
|
+
}
|
|
126
|
+
if (existsSync(logDir)) {
|
|
127
|
+
await step(`delete the logs ${logDir}`, () => rmSync(logDir, { recursive: true, force: true }));
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
say(`no logs at ${logDir}: nothing to delete`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
say("");
|
|
134
|
+
if (purge) {
|
|
135
|
+
say(dryRun
|
|
136
|
+
? "Dry run finished: nothing was changed. With --purge nothing of k-bench would be kept."
|
|
137
|
+
: "Removed k-bench and its data. Nothing of it was kept.");
|
|
138
|
+
say("The k-bench command itself is still installed: remove it with `npm uninstall -g @k-electron/k-bench`.");
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
say(dryRun ? "Dry run finished: nothing was changed." : "Removed the k-bench service.");
|
|
142
|
+
say(dryRun ? "It would keep:" : "Kept:");
|
|
143
|
+
say(` ${config.dataDir}: the database, so every Workspace and Session is still listed`);
|
|
144
|
+
say(` the "${config.tmuxSocket}" tmux server: running Sessions carry on until you end them or restart the Mac`);
|
|
145
|
+
say(` ${logDir}: the logs`);
|
|
146
|
+
say("Run `k-bench install` to restore the service; `k-bench uninstall --purge` removes the data and ends every Session.");
|
|
147
|
+
}
|
|
148
|
+
if (failed)
|
|
149
|
+
process.exit(1);
|
|
150
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** The header `tailscale serve` adds to every request it proxies. */
|
|
2
|
+
export const LOGIN_HEADER = "tailscale-user-login";
|
|
3
|
+
const FORBIDDEN_BODY = "Forbidden\n";
|
|
4
|
+
/**
|
|
5
|
+
* Whether a request's `Origin` header says it comes from a page served by this very instance.
|
|
6
|
+
* Browsers attach `Origin` to every WebSocket upgrade and cross-site request, and `tailscale
|
|
7
|
+
* serve` adds the owner's login to anything their browser sends, so without this check any
|
|
8
|
+
* web page the owner visits could drive the app. A request with no `Origin` is not from a
|
|
9
|
+
* browser page (curl, tests, the install health check) and passes; anything else must name
|
|
10
|
+
* the `Host` the request was addressed to, which is the tailnet name behind `tailscale serve`
|
|
11
|
+
* and the dev server's own address behind the Vite proxy.
|
|
12
|
+
*/
|
|
13
|
+
export function isSameSite(origin, host) {
|
|
14
|
+
if (origin === undefined)
|
|
15
|
+
return true;
|
|
16
|
+
if (host === undefined || host === "")
|
|
17
|
+
return false;
|
|
18
|
+
try {
|
|
19
|
+
return new URL(origin).host.toLowerCase() === host.toLowerCase();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false; // "null" from a sandboxed frame, or garbage.
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The access guard (ADR-0003): a request gets in only when its `Tailscale-User-Login` header
|
|
27
|
+
* equals the instance's configured login exactly. A missing header, any other value, and an
|
|
28
|
+
* unset (empty) configured login are all refused, so a misconfigured instance fails closed.
|
|
29
|
+
* A request from a page on another origin is refused too (see `isSameSite`).
|
|
30
|
+
*/
|
|
31
|
+
export class AccessGuard {
|
|
32
|
+
allowedLogin;
|
|
33
|
+
constructor(allowedLogin) {
|
|
34
|
+
this.allowedLogin = allowedLogin;
|
|
35
|
+
}
|
|
36
|
+
allows(login) {
|
|
37
|
+
return this.allowedLogin !== "" && login === this.allowedLogin;
|
|
38
|
+
}
|
|
39
|
+
/** Wraps a fetch handler so that it only ever sees allowed requests. */
|
|
40
|
+
wrapFetch(fetch) {
|
|
41
|
+
return (request) => this.allows(request.headers.get(LOGIN_HEADER)) &&
|
|
42
|
+
isSameSite(request.headers.get("origin") ?? undefined, request.headers.get("host") ?? undefined)
|
|
43
|
+
? fetch(request)
|
|
44
|
+
: new Response(FORBIDDEN_BODY, { status: 403 });
|
|
45
|
+
}
|
|
46
|
+
/** Wraps a WebSocket upgrade handler. A refused upgrade is answered with a plain 403. */
|
|
47
|
+
wrapUpgrade(handler) {
|
|
48
|
+
return (request, socket, head) => {
|
|
49
|
+
const login = request.headers[LOGIN_HEADER];
|
|
50
|
+
if (typeof login === "string" &&
|
|
51
|
+
this.allows(login) &&
|
|
52
|
+
isSameSite(request.headers.origin, request.headers.host)) {
|
|
53
|
+
handler(request, socket, head);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
socket.end("HTTP/1.1 403 Forbidden\r\n" +
|
|
57
|
+
"Content-Type: text/plain\r\n" +
|
|
58
|
+
`Content-Length: ${FORBIDDEN_BODY.length}\r\n` +
|
|
59
|
+
"Connection: close\r\n\r\n" +
|
|
60
|
+
FORBIDDEN_BODY);
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { HTTPException } from "hono/http-exception";
|
|
3
|
+
import { DirectoryError, listDirectories } from "./directories.js";
|
|
4
|
+
import { ServiceError } from "./service.js";
|
|
5
|
+
import { mountStatic } from "./static.js";
|
|
6
|
+
/**
|
|
7
|
+
* The JSON object in a request body ({} when there is none). A body must be declared
|
|
8
|
+
* `application/json`: a page on another site cannot send that without a preflight the
|
|
9
|
+
* server never grants, so it is a second line behind the Origin check.
|
|
10
|
+
*/
|
|
11
|
+
async function jsonBody(request) {
|
|
12
|
+
const text = await request.text();
|
|
13
|
+
if (text === "")
|
|
14
|
+
return {};
|
|
15
|
+
const type = request.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
16
|
+
if (type !== "application/json") {
|
|
17
|
+
throw new HTTPException(415, { message: "Send the body as application/json" });
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
const body = JSON.parse(text);
|
|
21
|
+
return body && typeof body === "object" ? body : {};
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function optionalString(value) {
|
|
28
|
+
return typeof value === "string" ? value : undefined;
|
|
29
|
+
}
|
|
30
|
+
/** The JSON HTTP API. */
|
|
31
|
+
export function createApp(service, options = {}) {
|
|
32
|
+
const app = new Hono();
|
|
33
|
+
app.onError((error, c) => {
|
|
34
|
+
if (error instanceof HTTPException) {
|
|
35
|
+
return c.json({ error: error.message }, error.status);
|
|
36
|
+
}
|
|
37
|
+
if (error instanceof ServiceError) {
|
|
38
|
+
const status = error.kind === "not_found" ? 404 : error.kind === "conflict" ? 409 : 422;
|
|
39
|
+
return c.json({ error: error.message }, status);
|
|
40
|
+
}
|
|
41
|
+
console.error(error);
|
|
42
|
+
return c.json({ error: "Internal error" }, 500);
|
|
43
|
+
});
|
|
44
|
+
// Any API call that is not a read and succeeded may have changed the state.
|
|
45
|
+
app.use("/api/*", async (c, next) => {
|
|
46
|
+
await next();
|
|
47
|
+
if (c.req.method === "GET" || c.res.status >= 400)
|
|
48
|
+
return;
|
|
49
|
+
const revision = options.onMutation?.();
|
|
50
|
+
if (revision !== undefined)
|
|
51
|
+
c.res.headers.set("State-Revision", String(revision));
|
|
52
|
+
});
|
|
53
|
+
// `k-bench status` asks this. It is behind the access guard like everything else, so the
|
|
54
|
+
// caller must send the owner's login.
|
|
55
|
+
app.get("/api/health", (c) => c.json({ status: "ok" }));
|
|
56
|
+
app.get("/api/state", async (c) => c.json(await service.getState()));
|
|
57
|
+
// The folder picker. Defaults to the configured root.
|
|
58
|
+
app.get("/api/directories", (c) => {
|
|
59
|
+
const path = c.req.query("path") || options.pickerRoot;
|
|
60
|
+
if (!path)
|
|
61
|
+
throw new ServiceError("invalid", "path is required");
|
|
62
|
+
try {
|
|
63
|
+
return c.json(listDirectories(path));
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error instanceof DirectoryError) {
|
|
67
|
+
throw new ServiceError("invalid", error.message);
|
|
68
|
+
}
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
app.post("/api/workspaces", async (c) => {
|
|
73
|
+
const body = await jsonBody(c.req.raw);
|
|
74
|
+
const folder = optionalString(body.folder);
|
|
75
|
+
if (!folder)
|
|
76
|
+
throw new ServiceError("invalid", "folder is required");
|
|
77
|
+
const workspace = service.createWorkspace({
|
|
78
|
+
folder,
|
|
79
|
+
name: optionalString(body.name),
|
|
80
|
+
});
|
|
81
|
+
return c.json(workspace, 201);
|
|
82
|
+
});
|
|
83
|
+
// Declared before `/:id` routes so "order" is never taken for an id.
|
|
84
|
+
app.put("/api/workspaces/order", async (c) => {
|
|
85
|
+
const { ids } = await jsonBody(c.req.raw);
|
|
86
|
+
if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) {
|
|
87
|
+
throw new ServiceError("invalid", "ids must be a list of Workspace ids");
|
|
88
|
+
}
|
|
89
|
+
service.reorderWorkspaces(ids);
|
|
90
|
+
return c.json({ ids });
|
|
91
|
+
});
|
|
92
|
+
app.patch("/api/workspaces/:id", async (c) => {
|
|
93
|
+
const body = await jsonBody(c.req.raw);
|
|
94
|
+
const workspace = service.updateWorkspace(c.req.param("id"), {
|
|
95
|
+
name: optionalString(body.name),
|
|
96
|
+
folder: optionalString(body.folder),
|
|
97
|
+
});
|
|
98
|
+
return c.json(workspace);
|
|
99
|
+
});
|
|
100
|
+
app.delete("/api/workspaces/:id", async (c) => {
|
|
101
|
+
await service.deleteWorkspace(c.req.param("id"));
|
|
102
|
+
return c.body(null, 204);
|
|
103
|
+
});
|
|
104
|
+
app.post("/api/workspaces/:id/sessions", async (c) => {
|
|
105
|
+
const body = await jsonBody(c.req.raw);
|
|
106
|
+
const session = await service.createSession(c.req.param("id"), optionalString(body.name));
|
|
107
|
+
return c.json(session, 201);
|
|
108
|
+
});
|
|
109
|
+
app.patch("/api/sessions/:id", async (c) => {
|
|
110
|
+
const body = await jsonBody(c.req.raw);
|
|
111
|
+
return c.json(service.renameSession(c.req.param("id"), optionalString(body.name) ?? ""));
|
|
112
|
+
});
|
|
113
|
+
app.delete("/api/sessions/:id", async (c) => {
|
|
114
|
+
await service.deleteSession(c.req.param("id"));
|
|
115
|
+
return c.body(null, 204);
|
|
116
|
+
});
|
|
117
|
+
app.post("/api/sessions/:id/restart", async (c) => c.json(await service.restartSession(c.req.param("id"))));
|
|
118
|
+
// Last, so it only answers what the API did not.
|
|
119
|
+
if (options.webDir)
|
|
120
|
+
mountStatic(app, options.webDir);
|
|
121
|
+
return app;
|
|
122
|
+
}
|