@yunuseon/kayra 0.16.0 → 0.16.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.
@@ -97,6 +97,14 @@ d="$(mktemp -d)" && (cd "$d" && npm pack @yunuseon/kayra@<version> --silent && t
97
97
 
98
98
  Test-only paths (`test/`, `ci/`) are meant to stay out.
99
99
 
100
+ Look for what must still be there too, not only for what is new: a build
101
+ step can remove files another one made. 0.16.0 shipped without
102
+ `cli/dist/web/*.js`, because the browser build emptied the directory tsc had
103
+ put the server's modules in, and no command started. Listing the new browser
104
+ files did not show that. `release.yml` now runs
105
+ `scripts/local/packed-runs.sh` before `npm publish`: it packs, installs and
106
+ runs the CLI as a fleet would. Run it yourself before opening the bump PR.
107
+
100
108
  ## 5. Afterwards
101
109
 
102
110
  - Remove the worktree and the local branch.
package/cli/dist/main.js CHANGED
@@ -124,8 +124,8 @@ else {
124
124
  : statusView(looks, { frame: "", room: screens.out.live ? screens.out.columns : Infinity, offline })).forEach(io.out);
125
125
  }
126
126
  else if (args.command.name === "ui") {
127
- // The browser side: web/dist in a checkout, cli/dist/web in the package.
128
- const assets = [join(kayra, "web", "dist"), join(kayra, "cli", "dist", "web")].find((dir) => existsSync(join(dir, "index.html")));
127
+ // The browser side: web/dist in a checkout, cli/dist/browser in the package.
128
+ const assets = [join(kayra, "web", "dist"), join(kayra, "cli", "dist", "browser")].find((dir) => existsSync(join(dir, "index.html")));
129
129
  const { port, noOpen } = args.command;
130
130
  const listening = await serveUi({ kayra, fleet: fleet.value, version, assets, short, network: network(2_000) }, port);
131
131
  io.err([strong("kayra ui"), muted(` · ${fleet.value.servers.length.toString()} servers · kayra ${version} · Ctrl-C stops it`)]);
@@ -0,0 +1,36 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ /** Cookies are shared by every port of a host: the name carries the port, so another local server's cookie is not ours. */
3
+ export const cookieName = (port) => `kayra_ui_${String(port)}`;
4
+ const origins = (port) => [`127.0.0.1:${String(port)}`, `localhost:${String(port)}`];
5
+ const same = (a, b) => {
6
+ const left = Buffer.from(a);
7
+ const right = Buffer.from(b);
8
+ return left.length === right.length && timingSafeEqual(left, right);
9
+ };
10
+ const cookieValue = (header, name) => header
11
+ ?.split(";")
12
+ .map((pair) => pair.trim().split("="))
13
+ .find(([key]) => key === name)?.[1];
14
+ const refuse = (status, why) => ({ admitted: false, status, why });
15
+ /**
16
+ * Whether a request may reach kayra ui. Every request: a Host of this
17
+ * listener (a page elsewhere cannot rebind a name to it). A write: an Origin
18
+ * of this listener (no other site's form posts here). The API: the launch's
19
+ * token, as its cookie.
20
+ */
21
+ export const admit = (asked, port, token) => {
22
+ if (asked.host === undefined || !origins(port).includes(asked.host))
23
+ return refuse(403, "not this listener's host");
24
+ const writes = asked.method !== "GET" && asked.method !== "HEAD";
25
+ if (writes && !origins(port).some((each) => asked.origin === `http://${each}`))
26
+ return refuse(403, "not this listener's origin");
27
+ if (!asked.path.startsWith("/api/"))
28
+ return { admitted: true };
29
+ const presented = cookieValue(asked.cookie, cookieName(port));
30
+ return presented !== undefined && same(presented, token) ? { admitted: true } : refuse(401, "no token: open the URL kayra ui printed");
31
+ };
32
+ /** The token the opened URL carries, if it is this launch's. */
33
+ export const tokenIn = (query, token) => {
34
+ const given = query.get("token");
35
+ return given !== null && same(given, token);
36
+ };
@@ -0,0 +1,102 @@
1
+ import { z } from "zod";
2
+ import { appName } from "../brand.js";
3
+ import { err, flatMap, map, ok } from "../result.js";
4
+ const onServer = z.enum(["up", "provision", "deploy", "setup", "plan", "verify", "apps", "down", "adopt", "backup test"]);
5
+ /** What the browser may send; anything else is refused before the fleet is asked. */
6
+ export const commandInput = z.discriminatedUnion("name", [
7
+ z.object({ name: onServer, server: z.string() }),
8
+ z.object({ name: z.literal("app deploy"), server: z.string(), app: z.string(), ref: z.string().min(1).exactOptional() }),
9
+ z.object({ name: z.literal("app rollback"), server: z.string(), app: z.string(), sha: z.string().regex(/^[0-9a-f]{7,40}$/) }),
10
+ z.object({ name: z.literal("app purge"), server: z.string(), app: z.string() }),
11
+ z.object({ name: z.literal("job"), server: z.string(), job: z.enum(["gc", "renovate"]), noPrs: z.boolean() }),
12
+ z.object({ name: z.literal("doctor") }),
13
+ ]);
14
+ /** The commands that read and change nothing: everything else asks first on a real server. */
15
+ const reading = ["plan", "verify", "doctor"];
16
+ export const changes = (input) => !reading.includes(input.name);
17
+ const serverOf = (fleet, name) => {
18
+ const found = fleet.servers.find((each) => each.name === name);
19
+ return found === undefined ? err(`no server '${name}' in this fleet`) : ok(found);
20
+ };
21
+ /** The server a command acts on, if one. */
22
+ export const targetOf = (fleet, input) => input.name === "doctor" ? ok(undefined) : serverOf(fleet, input.server);
23
+ const appOf = (server, name) => flatMap(appName(name), (app) => server.apps.some((each) => each.name === app) ? ok(app) : err(`'${name}' is not an app of ${server.name}`));
24
+ /** The command as the CLI would have parsed it, checked against the fleet. */
25
+ export const toPlanned = (fleet, input) => {
26
+ if (input.name === "doctor")
27
+ return ok({ name: "doctor" });
28
+ return flatMap(serverOf(fleet, input.server), (server) => {
29
+ switch (input.name) {
30
+ case "app deploy":
31
+ return map(appOf(server, input.app), (app) => ({ name: "app deploy", server: server.name, app, more: input.ref }));
32
+ case "app rollback":
33
+ return map(appOf(server, input.app), (app) => ({ name: "app rollback", server: server.name, app, more: input.sha }));
34
+ case "app purge":
35
+ return map(appOf(server, input.app), (app) => ({ name: "app purge", server: server.name, app }));
36
+ case "job":
37
+ return ok({ name: "job", server: server.name, job: input.job, noPrs: input.noPrs });
38
+ case "up":
39
+ case "provision":
40
+ case "deploy":
41
+ case "setup":
42
+ case "plan":
43
+ case "verify":
44
+ case "apps":
45
+ case "down":
46
+ case "adopt":
47
+ case "backup test":
48
+ return ok({ name: input.name, server: server.name });
49
+ }
50
+ });
51
+ };
52
+ /** The command's words, as typed on the command line. */
53
+ export const words = (input) => {
54
+ const said = (...parts) => ["kayra", ...parts.filter((part) => part !== undefined)].join(" ");
55
+ switch (input.name) {
56
+ case "doctor":
57
+ return said("doctor");
58
+ case "app deploy":
59
+ return said("app", "deploy", input.server, input.app, input.ref);
60
+ case "app rollback":
61
+ return said("app", "rollback", input.server, input.app, input.sha);
62
+ case "app purge":
63
+ return said("app", "purge", input.server, input.app);
64
+ case "job":
65
+ return said("job", input.server, input.job, input.noPrs ? "--no-prs" : undefined);
66
+ case "up":
67
+ case "provision":
68
+ case "deploy":
69
+ case "setup":
70
+ case "plan":
71
+ case "verify":
72
+ case "apps":
73
+ case "down":
74
+ case "adopt":
75
+ case "backup test":
76
+ return said(input.name, input.server);
77
+ }
78
+ };
79
+ /** What the browser offers for a server, the everyday ones first. */
80
+ export const offered = (server) => {
81
+ const creates = server.terraform || server.vm;
82
+ return [
83
+ ...(server.kind === "platform" ? ["deploy", "apps", "verify"] : []),
84
+ "setup",
85
+ "plan",
86
+ ...(server.target === "multipass" && server.kind === "platform" ? ["up"] : []),
87
+ ...(creates ? ["provision"] : []),
88
+ ...(server.backupDir === undefined ? [] : ["backup test"]),
89
+ ...(server.kind === "platform" ? ["job"] : []),
90
+ ...(server.target === "multipass" ? [] : ["adopt"]),
91
+ ...(server.terraform ? ["down"] : []),
92
+ ];
93
+ };
94
+ export const facts = (server) => ({
95
+ name: server.name,
96
+ kind: server.kind,
97
+ target: server.target,
98
+ domain: server.domain,
99
+ apps: server.apps.map((app) => app.name),
100
+ commands: offered(server),
101
+ needsTerminal: server.vault.kind === "ask",
102
+ });
@@ -0,0 +1,7 @@
1
+ /**
2
+ * What kayra ui's server and the browser say to each other. Standalone: web/
3
+ * imports these types and nothing else of the CLI. The server assigns its own
4
+ * values to them, so a change on either side that breaks the other does not
5
+ * compile.
6
+ */
7
+ export {};
@@ -0,0 +1,9 @@
1
+ import { spawn } from "node:child_process";
2
+ /** macOS's open, xdg-open elsewhere; a browser that does not start leaves the printed URL. */
3
+ export const systemBrowser = {
4
+ open: (url) => {
5
+ spawn(process.platform === "darwin" ? "open" : "xdg-open", [url], { stdio: "ignore", detached: true })
6
+ .on("error", () => undefined)
7
+ .unref();
8
+ },
9
+ };
@@ -0,0 +1,49 @@
1
+ /** Sortable by time (an ISO 8601 instant), unique by its tail. */
2
+ export const runId = (iso, random) => `${iso.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${random}`;
3
+ export const stateOf = (events) => {
4
+ const ended = events.findLast((event) => event.kind === "ended");
5
+ if (ended?.kind !== "ended")
6
+ return "running";
7
+ if (ended.stop?.why === "interrupted")
8
+ return "interrupted";
9
+ if (ended.stop?.why === "declined")
10
+ return "declined";
11
+ return ended.failures === 0 ? "passed" : "failed";
12
+ };
13
+ export const summary = (run) => ({
14
+ id: run.id,
15
+ command: run.command,
16
+ ...(run.server === undefined ? {} : { server: run.server }),
17
+ started: run.started,
18
+ state: stateOf(run.events),
19
+ });
20
+ /** What a run's record holds: the run, then each event, one JSON value per line. */
21
+ export const recordLine = (value) => `${JSON.stringify(value)}\n`;
22
+ const isObject = (value) => typeof value === "object" && value !== null;
23
+ /** A record as kayra ui wrote it; a run killed mid-write keeps what it had, and what it had says "running". */
24
+ export const readRecord = (text) => {
25
+ const [head, ...rest] = text
26
+ .split("\n")
27
+ .filter((line) => line !== "")
28
+ .flatMap((line) => {
29
+ try {
30
+ return [JSON.parse(line)];
31
+ }
32
+ catch {
33
+ return [];
34
+ }
35
+ });
36
+ if (!isObject(head) || typeof head["id"] !== "string" || typeof head["command"] !== "string" || typeof head["started"] !== "string")
37
+ return undefined;
38
+ // Written by this kayra ui, the lines are its own events.
39
+ const events = rest.filter((each) => isObject(each) && typeof each["kind"] === "string");
40
+ return {
41
+ id: head["id"],
42
+ command: head["command"],
43
+ ...(typeof head["server"] === "string" ? { server: head["server"] } : {}),
44
+ started: head["started"],
45
+ events,
46
+ };
47
+ };
48
+ /** A server is busy while a run on it has not ended: one at a time, as on the command line. */
49
+ export const busy = (runs, server) => server !== undefined && runs.some((run) => run.server === server && stateOf(run.events) === "running");
@@ -0,0 +1,336 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { createServer } from "node:http";
4
+ import { extname, join, normalize, sep } from "node:path";
5
+ import { within } from "../brand.js";
6
+ import { planFor } from "../commands/index.js";
7
+ import { look, opentofu, statusJson } from "../commands/status.js";
8
+ import { findings, validateJson } from "../commands/validate.js";
9
+ import { json, send } from "../deployer/http.js";
10
+ import { gather } from "../gather.js";
11
+ import { capture, interpret } from "../interpret.js";
12
+ import { needsTerminal } from "../plan.js";
13
+ import { err, flatMap, ok } from "../result.js";
14
+ import { listed, reporting } from "../ui/progress.js";
15
+ import { follow } from "../ui/terminal.js";
16
+ import { parsed, releasesSchema, runsSchema } from "../ui/views.js";
17
+ import { admit, cookieName, tokenIn } from "./auth.js";
18
+ import { changes, commandInput, facts, targetOf, toPlanned, words } from "./commands.js";
19
+ import { busy, readRecord, recordLine, runId, stateOf, summary } from "./runs.js";
20
+ /** kayra ui's one mutable cell: the runs it started, swapped whole on every change. */
21
+ // eslint-disable-next-line functional/prefer-immutable-types -- kayra ui's state lives here, nowhere else
22
+ const cell = { live: {} };
23
+ const swap = (id, change) => {
24
+ const current = cell.live[id];
25
+ // eslint-disable-next-line functional/immutable-data -- kayra ui's state lives here, nowhere else
26
+ if (current !== undefined)
27
+ cell.live = { ...cell.live, [id]: change(current) };
28
+ };
29
+ const runsDir = (fleet) => within(fleet.root, ".cache", "ui", "runs");
30
+ const recorded = (fleet) => {
31
+ const dir = runsDir(fleet);
32
+ if (!existsSync(dir))
33
+ return [];
34
+ return readdirSync(dir)
35
+ .filter((name) => name.endsWith(".jsonl"))
36
+ .flatMap((name) => {
37
+ const run = readRecord(readFileSync(join(dir, name), "utf8"));
38
+ return run === undefined ? [] : [run];
39
+ });
40
+ };
41
+ /** Every run kayra ui knows: those it runs now, and those its records keep. */
42
+ const allRuns = (fleet) => {
43
+ const live = Object.values(cell.live).map((each) => each.run);
44
+ return [...live, ...recorded(fleet).filter((run) => !live.some((each) => each.id === run.id))].toSorted((a, b) => b.id.localeCompare(a.id));
45
+ };
46
+ /** Ansible colours its output for a terminal only; the browser draws the colours too. */
47
+ const coloured = (plan) => plan.map((step) => (step.kind === "run" ? { ...step, env: { ...step.env, ANSIBLE_FORCE_COLOR: "1" } } : step));
48
+ /** A server-sent stream; `end` says everything is said, so the browser closes instead of reconnecting. */
49
+ const sse = (response) => {
50
+ response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
51
+ return {
52
+ say: (data) => {
53
+ response.write(`data: ${JSON.stringify(data)}\n\n`);
54
+ },
55
+ end: () => {
56
+ response.end("event: end\ndata: {}\n\n");
57
+ },
58
+ };
59
+ };
60
+ const answerJson = (response, status, value) => {
61
+ send(response, status, JSON.stringify(value), "application/json; charset=utf-8");
62
+ };
63
+ const invocationOf = (ui, input) => flatMap(targetOf(ui.fleet, input), (target) => ok({
64
+ command: words(input),
65
+ ...(target === undefined ? {} : { server: target.name }),
66
+ about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${ui.version}`],
67
+ }));
68
+ const planOf = (ui, input) => flatMap(toPlanned(ui.fleet, input), (planned) => planFor({ kayra: ui.kayra, fleet: ui.fleet.root }, ui.fleet, planned));
69
+ const preview = (ui, input) => flatMap(planOf(ui, input), (plan) => flatMap(invocationOf(ui, input), (invocation) => ok({ invocation, steps: listed(plan, ui.short), changes: changes(input) })));
70
+ /** Starts a run, or says why it cannot: one per server, a terminal it needs, a real server not confirmed. */
71
+ const start = (ui, input, confirm) => {
72
+ const target = targetOf(ui.fleet, input);
73
+ const plan = planOf(ui, input);
74
+ const invocation = invocationOf(ui, input);
75
+ if (!target.ok || !plan.ok || !invocation.ok)
76
+ return err([400, [target, plan, invocation].flatMap((each) => (each.ok ? [] : [each.error])).join("; ")]);
77
+ const server = target.value;
78
+ if (needsTerminal(plan.value))
79
+ return err([400, "its vault password is asked on a terminal: run it there, or give the server a vault_password_file"]);
80
+ if (busy(allRuns(ui.fleet), server?.name))
81
+ return err([409, `a run on ${server?.name ?? ""} has not ended`]);
82
+ if (changes(input) && server !== undefined && server.target !== "multipass" && confirm !== server.name)
83
+ return err([403, `this changes ${server.name}: confirm with its name`]);
84
+ const started = new Date().toISOString();
85
+ const id = runId(started, randomBytes(3).toString("hex"));
86
+ const run = { id, command: words(input), ...(server === undefined ? {} : { server: server.name }), started, events: [] };
87
+ const file = join(runsDir(ui.fleet), `${id}.jsonl`);
88
+ mkdirSync(runsDir(ui.fleet), { recursive: true });
89
+ appendFileSync(file, recordLine({ id: run.id, command: run.command, ...(server === undefined ? {} : { server: server.name }), started }));
90
+ // eslint-disable-next-line functional/immutable-data -- kayra ui's state lives here, nowhere else
91
+ cell.live = { ...cell.live, [id]: { run, listeners: [], stop: new AbortController(), answer: undefined } };
92
+ const emit = (event) => {
93
+ appendFileSync(file, recordLine(event));
94
+ swap(id, (live) => ({ ...live, run: { ...live.run, events: [...live.run.events, event] } }));
95
+ cell.live[id]?.listeners.forEach((listener) => {
96
+ listener(event);
97
+ });
98
+ };
99
+ const stop = cell.live[id]?.stop;
100
+ const io = {
101
+ out: (text) => {
102
+ emit({ kind: "said", stream: "out", text });
103
+ },
104
+ err: (text) => {
105
+ emit({ kind: "said", stream: "err", text });
106
+ },
107
+ ask: (prompt) => new Promise((resolve) => {
108
+ swap(id, (live) => ({
109
+ ...live,
110
+ answer: (text) => {
111
+ swap(id, (after) => ({ ...after, answer: undefined }));
112
+ emit({ kind: "answered" });
113
+ resolve(text);
114
+ },
115
+ }));
116
+ emit({ kind: "ask", prompt });
117
+ }),
118
+ output: (chunk, stream) => {
119
+ emit({ kind: "output", stream, chunk });
120
+ },
121
+ ...(stop === undefined ? {} : { signal: stop.signal }),
122
+ };
123
+ void interpret(coloured(plan.value), io, reporting(emit, invocation.value, ui.short), () => stop?.signal.aborted === true);
124
+ return ok(id);
125
+ };
126
+ /** A run's events from the start, then each as it happens, until it has ended. */
127
+ const watchRun = (ui, id, response) => {
128
+ const live = cell.live[id];
129
+ const run = live?.run ?? recorded(ui.fleet).find((each) => each.id === id);
130
+ if (run === undefined) {
131
+ send(response, 404, `no run ${id}\n`);
132
+ return;
133
+ }
134
+ const { say, end } = sse(response);
135
+ run.events.forEach(say);
136
+ if (live === undefined || stateOf(run.events) !== "running") {
137
+ end();
138
+ return;
139
+ }
140
+ const listener = (event) => {
141
+ say(event);
142
+ if (event.kind === "ended")
143
+ end();
144
+ };
145
+ swap(id, (current) => ({ ...current, listeners: [...current.listeners, listener] }));
146
+ response.on("close", () => {
147
+ swap(id, (current) => ({ ...current, listeners: current.listeners.filter((each) => each !== listener) }));
148
+ });
149
+ };
150
+ /** What a deployer's ctl answers, captured over SSH as `kayra app …` asks it. */
151
+ const ctl = async (ui, input) => {
152
+ const server = ui.fleet.servers.find((each) => each.name === input.server);
153
+ if (server === undefined)
154
+ return err(`no server '${input.server}'`);
155
+ const app = server.apps.find((each) => each.name === input.app);
156
+ if (app === undefined)
157
+ return err(`'${input.app}' is not an app of ${server.name}`);
158
+ const plan = planFor({ kayra: ui.kayra, fleet: ui.fleet.root }, ui.fleet, { name: input.name, server: server.name, app: app.name, more: input.more });
159
+ if (!plan.ok)
160
+ return plan;
161
+ const [step] = plan.value;
162
+ if (step?.kind !== "run")
163
+ return err("the deployer's plan has no step");
164
+ const [program, ...args] = step.argv;
165
+ const argv = args.flatMap((arg) => (typeof arg === "string" ? [arg] : []));
166
+ const exit = await capture([program, ...argv], "capture");
167
+ return exit.code === 0 ? ok(exit.stdout) : err(exit.stderr.trim() === "" ? `exit ${String(exit.code)}` : exit.stderr.trim());
168
+ };
169
+ const types = {
170
+ ".html": "text/html; charset=utf-8",
171
+ ".js": "text/javascript; charset=utf-8",
172
+ ".css": "text/css; charset=utf-8",
173
+ ".svg": "image/svg+xml",
174
+ ".png": "image/png",
175
+ ".ico": "image/x-icon",
176
+ ".woff2": "font/woff2",
177
+ ".json": "application/json; charset=utf-8",
178
+ };
179
+ const unbuilt = `<!doctype html><meta charset="utf-8"><title>kayra ui</title>
180
+ <body style="font:15px system-ui;margin:3rem auto;max-width:40rem"><h1>kayra ui</h1>
181
+ <p>The browser side is not built in this checkout:</p><pre>npm --prefix web ci &amp;&amp; npm --prefix web run build</pre>
182
+ <p>The API is up at <code>/api/fleet</code>.</p></body>`;
183
+ /** The built browser side; a path that is no file is the app's own route, answered by its index. */
184
+ const asset = (ui, path, response) => {
185
+ if (ui.assets === undefined) {
186
+ send(response, 200, unbuilt, "text/html; charset=utf-8");
187
+ return;
188
+ }
189
+ const file = normalize(join(ui.assets, decodeURIComponent(path)));
190
+ const inside = file.startsWith(ui.assets + sep) && existsSync(file) && statSync(file).isFile();
191
+ const chosen = inside ? file : join(ui.assets, "index.html");
192
+ response.writeHead(200, {
193
+ "Content-Type": types[extname(chosen)] ?? "application/octet-stream",
194
+ "Cache-Control": chosen.includes(`${sep}assets${sep}`) ? "public, max-age=31536000, immutable" : "no-cache",
195
+ });
196
+ response.end(readFileSync(chosen));
197
+ };
198
+ const route = async (ui, port, token, request, response) => {
199
+ const url = new URL(request.url ?? "/", `http://127.0.0.1:${String(port)}`);
200
+ const path = url.pathname;
201
+ const method = request.method ?? "GET";
202
+ const admission = admit({ method, path, host: request.headers.host, origin: request.headers.origin, cookie: request.headers.cookie }, port, token);
203
+ if (!admission.admitted) {
204
+ send(response, admission.status, `${admission.why}\n`);
205
+ return;
206
+ }
207
+ if (path === "/login") {
208
+ if (!tokenIn(url.searchParams, token)) {
209
+ send(response, 401, "not this launch's token: open the URL kayra ui printed\n");
210
+ return;
211
+ }
212
+ response.writeHead(303, { "Set-Cookie": `${cookieName(port)}=${token}; HttpOnly; SameSite=Strict; Path=/`, Location: "/" });
213
+ response.end();
214
+ return;
215
+ }
216
+ if (!path.startsWith("/api/")) {
217
+ asset(ui, path, response);
218
+ return;
219
+ }
220
+ const app = /^\/api\/servers\/([^/]+)\/apps\/([^/]+)\/(runs|releases|logs)(?:\/([^/]+))?$/.exec(path);
221
+ const runPath = /^\/api\/runs\/([^/]+)\/(events|answer|cancel)$/.exec(path);
222
+ if (method === "GET" && path === "/api/fleet") {
223
+ const fleetFacts = { fleet: ui.fleet.root.split(sep).at(-1) ?? "", version: ui.version, servers: ui.fleet.servers.map(facts) };
224
+ answerJson(response, 200, fleetFacts);
225
+ }
226
+ else if (method === "GET" && path === "/api/status") {
227
+ const { say, end } = sse(response);
228
+ const { initial, updates } = look(ui.fleet, opentofu, ui.network);
229
+ await follow(initial, updates, (looks) => {
230
+ const status = statusJson(looks);
231
+ say(status);
232
+ });
233
+ end();
234
+ }
235
+ else if (method === "GET" && path === "/api/validate") {
236
+ const reports = await Promise.all(ui.fleet.servers.map(async (server) => ({ server, findings: findings(await gather(ui.fleet.root, server)) })));
237
+ const validation = validateJson(reports);
238
+ answerJson(response, 200, validation);
239
+ }
240
+ else if (method === "GET" && app !== null) {
241
+ const [, server = "", name = "", what, more] = app;
242
+ const asked = { server: decodeURIComponent(server), app: decodeURIComponent(name) };
243
+ const answer = await ctl(ui, {
244
+ ...asked,
245
+ name: what === "runs" ? "app runs" : what === "releases" ? "app rollback" : "app logs",
246
+ ...(more === undefined ? {} : { more: decodeURIComponent(more) }),
247
+ });
248
+ if (!answer.ok)
249
+ send(response, 502, `${answer.error}\n`);
250
+ else if (what === "logs")
251
+ send(response, 200, answer.value);
252
+ else {
253
+ const value = what === "runs" ? parsed(runsSchema, answer.value) : parsed(releasesSchema, answer.value);
254
+ if (value === undefined)
255
+ send(response, 502, "the server's deployer answered in a form this kayra does not read: deploy it with this kayra\n");
256
+ else
257
+ answerJson(response, 200, value);
258
+ }
259
+ }
260
+ else if (method === "POST" && path === "/api/plan") {
261
+ const input = commandInput.safeParse(await json(request));
262
+ const shown = input.success ? preview(ui, input.data) : err(input.error.issues.at(0)?.message ?? "not a command");
263
+ if (shown.ok)
264
+ answerJson(response, 200, shown.value);
265
+ else
266
+ send(response, 400, `${shown.error}\n`);
267
+ }
268
+ else if (method === "GET" && path === "/api/runs") {
269
+ const runs = allRuns(ui.fleet).slice(0, 50).map(summary);
270
+ answerJson(response, 200, runs);
271
+ }
272
+ else if (method === "POST" && path === "/api/runs") {
273
+ const body = await json(request);
274
+ const input = commandInput.safeParse(typeof body === "object" && body !== null && "command" in body ? body.command : undefined);
275
+ const confirm = typeof body === "object" && body !== null && "confirm" in body ? body.confirm : undefined;
276
+ const started = input.success ? start(ui, input.data, confirm) : err([400, input.error.issues.at(0)?.message ?? "not a command"]);
277
+ if (started.ok)
278
+ answerJson(response, 201, { id: started.value });
279
+ else
280
+ send(response, started.error[0], `${started.error[1]}\n`);
281
+ }
282
+ else if (runPath !== null) {
283
+ const [, id = "", what] = runPath;
284
+ const live = cell.live[id];
285
+ if (method === "GET" && what === "events")
286
+ watchRun(ui, id, response);
287
+ else if (method === "POST" && what === "cancel" && live !== undefined) {
288
+ live.stop.abort();
289
+ send(response, 202, "stopping\n");
290
+ }
291
+ else if (method === "POST" && what === "answer" && live?.answer !== undefined) {
292
+ const body = await json(request);
293
+ live.answer(typeof body === "object" && body !== null && "text" in body && typeof body.text === "string" ? body.text : "");
294
+ send(response, 204, "");
295
+ }
296
+ else
297
+ send(response, 404, `nothing to ${what ?? ""} for run ${id}\n`);
298
+ }
299
+ else
300
+ send(response, 404, "not found\n");
301
+ };
302
+ /** kayra ui: listens on 127.0.0.1 only; the URL it returns carries this launch's token. */
303
+ export const serveUi = (ui, port) => {
304
+ const token = randomBytes(32).toString("base64url");
305
+ return new Promise((resolve, reject) => {
306
+ const server = createServer((request, response) => {
307
+ route(ui, listening(), token, request, response).catch((error) => {
308
+ if (!response.headersSent)
309
+ send(response, 500, `${error instanceof Error ? error.message : String(error)}\n`);
310
+ else
311
+ response.end();
312
+ });
313
+ });
314
+ const listening = () => {
315
+ const address = server.address();
316
+ return typeof address === "object" && address !== null ? address.port : port;
317
+ };
318
+ server.once("error", reject);
319
+ server.listen(port, "127.0.0.1", () => {
320
+ const actual = listening();
321
+ resolve({
322
+ url: `http://127.0.0.1:${String(actual)}/login?token=${token}`,
323
+ port: actual,
324
+ close: () => new Promise((done) => {
325
+ Object.values(cell.live).forEach((live) => {
326
+ live.stop.abort();
327
+ });
328
+ server.closeAllConnections();
329
+ server.close(() => {
330
+ done();
331
+ });
332
+ }),
333
+ });
334
+ });
335
+ });
336
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunuseon/kayra",
3
- "version": "0.16.0",
3
+ "version": "0.16.1",
4
4
  "description": "A self-hosted app platform and the CLI that runs it: Traefik, Authelia, a registry, rootless BuildKit and a small deployer per server, set up with OpenTofu and Ansible.",
5
5
  "license": "MIT",
6
6
  "author": "Yunus Öztürk",
@@ -34,7 +34,7 @@
34
34
  "scripts": {
35
35
  "kayra": "node cli/src/main.ts",
36
36
  "build": "tsc -p cli/tsconfig.build.json",
37
- "build:web": "npm --prefix web ci --silent && npm --prefix web run build -- --outDir ../cli/dist/web --emptyOutDir",
37
+ "build:web": "npm --prefix web ci --silent && npm --prefix web run build -- --outDir ../cli/dist/browser --emptyOutDir",
38
38
  "prepack": "npm run build && npm run build:web",
39
39
  "typecheck": "tsc -p cli --noEmit",
40
40
  "lint": "cd cli && eslint --flag unstable_native_nodejs_ts_config .",
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env bash
2
+ # Packs kayra as npm publishes it, installs the tarball the way a fleet does,
3
+ # and runs it: its version, its help, and kayra ui answering with its browser
4
+ # side. Run by release.yml before npm publish, and by hand before a release.
5
+ # bash scripts/local/packed-runs.sh
6
+ set -euo pipefail
7
+ here="$(cd "$(dirname "$0")/../.." && pwd)"
8
+ work="$(mktemp -d)"
9
+ trap 'kill "${ui:-}" 2>/dev/null || true; rm -rf "$work"' EXIT
10
+
11
+ tarball="$(cd "$here" && npm pack --silent --pack-destination "$work" | tail -1)"
12
+ mkdir -p "${work}/fleet/servers"
13
+ printf 'acme_email: ops@example.com\n' > "${work}/fleet/servers/defaults.yml"
14
+ (cd "${work}/fleet" && npm init -y >/dev/null && npm install --silent --no-audit --no-fund "${work}/${tarball}")
15
+ kayra="${work}/fleet/node_modules/@yunuseon/kayra/bin/kayra.js"
16
+
17
+ version="$(cd "${work}/fleet" && node "$kayra" --version)"
18
+ expected="$(node -p "require('${here}/package.json').version")"
19
+ [ "$version" = "$expected" ] || { echo "✗ the packed kayra says ${version}, not ${expected}" >&2; exit 1; }
20
+ (cd "${work}/fleet" && node "$kayra" --help >/dev/null)
21
+
22
+ (cd "${work}/fleet" && node "$kayra" ui --no-open --port 0 > "${work}/ui.out" 2>&1) &
23
+ ui=$!
24
+ for _ in $(seq 1 50); do grep -q '/login?token=' "${work}/ui.out" && break; sleep 0.2; done
25
+ url="$(grep -o 'http://127.0.0.1:[0-9]*/login?token=[A-Za-z0-9_-]*' "${work}/ui.out")" || { cat "${work}/ui.out" >&2; echo "✗ kayra ui did not start" >&2; exit 1; }
26
+ page="$(curl -sf -L -c "${work}/jar" -b "${work}/jar" "$url")"
27
+ grep -q '<script type="module"' <<< "$page" || { echo "✗ kayra ui serves no built browser side" >&2; exit 1; }
28
+ echo "✓ the packed kayra ${version} runs, and kayra ui serves its browser side"
File without changes