@yunuseon/kayra 0.16.1 → 0.17.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.
Files changed (117) hide show
  1. package/README.md +4 -0
  2. package/ansible/roles/platform/tasks/main.yml +31 -0
  3. package/cli/dist/browser/assets/{index-3W_NFATj.css → index-Ct0Eudk4.css} +1 -1
  4. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  5. package/cli/dist/browser/assets/xterm-CerOhKYV.js +16 -0
  6. package/cli/dist/browser/index.html +2 -2
  7. package/cli/dist/clients/api/api.js +189 -0
  8. package/cli/dist/clients/api/auth.js +37 -0
  9. package/cli/dist/clients/api/commands.js +63 -0
  10. package/cli/dist/clients/api/contract.gen.js +1 -0
  11. package/cli/dist/clients/api/contract.js +91 -0
  12. package/cli/dist/clients/api/directories.js +20 -0
  13. package/cli/dist/clients/api/discovery.js +43 -0
  14. package/cli/dist/clients/api/live.js +40 -0
  15. package/cli/dist/clients/api/protocol.js +68 -0
  16. package/cli/dist/clients/api/queries.js +20 -0
  17. package/cli/dist/{web → clients/api}/runs.js +14 -11
  18. package/cli/dist/clients/api/start.js +97 -0
  19. package/cli/dist/clients/api/status.js +29 -0
  20. package/cli/dist/clients/api/validate.js +13 -0
  21. package/cli/dist/{ui → clients/cli}/explain.js +10 -8
  22. package/cli/dist/clients/cli/framed.js +67 -0
  23. package/cli/dist/clients/cli/invocation.js +84 -0
  24. package/cli/dist/clients/cli/paint.js +23 -0
  25. package/cli/dist/{cli.js → clients/cli/parser.js} +38 -32
  26. package/cli/dist/clients/cli/questions.js +89 -0
  27. package/cli/dist/clients/cli/status.js +75 -0
  28. package/cli/dist/{ui → clients/cli}/terminal.js +5 -15
  29. package/cli/dist/{ui → clients/cli}/text.js +15 -24
  30. package/cli/dist/clients/cli/validate.js +32 -0
  31. package/cli/dist/clients/cli/values.js +19 -0
  32. package/cli/dist/{ui → clients/cli}/views.js +28 -60
  33. package/cli/dist/clients/ui/assets.js +36 -0
  34. package/cli/dist/core/adapters/fs.js +18 -0
  35. package/cli/dist/{net.js → core/adapters/network.js} +20 -5
  36. package/cli/dist/core/adapters/opentofu.js +24 -0
  37. package/cli/dist/core/ctl/answers.js +32 -0
  38. package/cli/dist/core/fleet/brand.js +45 -0
  39. package/cli/dist/{schemas.js → core/fleet/docs.js} +4 -3
  40. package/cli/dist/core/fleet/load.js +44 -0
  41. package/cli/dist/core/fleet/model.js +1 -0
  42. package/cli/dist/{fleet.js → core/fleet/parse.js} +61 -41
  43. package/cli/dist/{settings.js → core/fleet/settings.js} +10 -3
  44. package/cli/dist/{validate.js → core/fleet/shape.js} +6 -5
  45. package/cli/dist/core/interpreter/events.js +81 -0
  46. package/cli/dist/core/interpreter/io.js +18 -0
  47. package/cli/dist/core/interpreter/loop.js +101 -0
  48. package/cli/dist/core/interpreter/needs.js +47 -0
  49. package/cli/dist/core/interpreter/process.js +107 -0
  50. package/cli/dist/core/interpreter/progress.js +15 -0
  51. package/cli/dist/core/interpreter/pty.js +8 -0
  52. package/cli/dist/core/operations/catalog.js +169 -0
  53. package/cli/dist/core/operations/dispatch.js +142 -0
  54. package/cli/dist/{plan.js → core/plan/describe.js} +13 -16
  55. package/cli/dist/core/plan/model.js +14 -0
  56. package/cli/dist/{commands → core/recipes}/app-check.js +11 -16
  57. package/cli/dist/core/recipes/apps.js +63 -0
  58. package/cli/dist/core/recipes/backup.js +34 -0
  59. package/cli/dist/core/recipes/certs.js +4 -0
  60. package/cli/dist/{commands → core/recipes}/doctor.js +20 -35
  61. package/cli/dist/core/recipes/host.js +104 -0
  62. package/cli/dist/core/recipes/ssh.js +20 -0
  63. package/cli/dist/core/recipes/steps.js +82 -0
  64. package/cli/dist/core/status/look.js +55 -0
  65. package/cli/dist/core/status/model.js +6 -0
  66. package/cli/dist/core/status/ports.js +1 -0
  67. package/cli/dist/core/status/updates.js +13 -0
  68. package/cli/dist/core/text/plural.js +2 -0
  69. package/cli/dist/core/text/spans.js +22 -0
  70. package/cli/dist/core/text/time.js +12 -0
  71. package/cli/dist/core/validation/facts.js +49 -0
  72. package/cli/dist/{commands/validate.js → core/validation/findings.js} +31 -66
  73. package/cli/dist/deployer/app.js +2 -1
  74. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  75. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  76. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  77. package/cli/dist/deployer/cron.js +2 -2
  78. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  79. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  80. package/cli/dist/deployer/deployer.js +23 -22
  81. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  82. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  83. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  84. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  85. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  86. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  87. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  88. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  89. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  90. package/cli/dist/deployer/main.js +2 -2
  91. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  92. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  93. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  94. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  95. package/cli/dist/main.js +98 -99
  96. package/cli/dist/result.js +11 -1
  97. package/cli/dist/serve.js +77 -0
  98. package/cli/dist/typed.js +2 -0
  99. package/package.json +4 -2
  100. package/scripts/agent/guard.sh +9 -2
  101. package/scripts/local/packed-runs.sh +20 -5
  102. package/scripts/local/setup-hosts.sh +9 -2
  103. package/cli/dist/brand.js +0 -39
  104. package/cli/dist/browser/assets/index-DRFX9Q77.js +0 -2
  105. package/cli/dist/commands/index.js +0 -52
  106. package/cli/dist/commands/server.js +0 -289
  107. package/cli/dist/commands/status.js +0 -194
  108. package/cli/dist/gather.js +0 -61
  109. package/cli/dist/interpret.js +0 -141
  110. package/cli/dist/load.js +0 -64
  111. package/cli/dist/ui/line.js +0 -39
  112. package/cli/dist/ui/progress.js +0 -144
  113. package/cli/dist/web/auth.js +0 -36
  114. package/cli/dist/web/commands.js +0 -102
  115. package/cli/dist/web/contract.js +0 -7
  116. package/cli/dist/web/server.js +0 -336
  117. /package/cli/dist/{web → clients/ui}/opener.js +0 -0
@@ -1,36 +0,0 @@
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
- };
@@ -1,102 +0,0 @@
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
- });
@@ -1,7 +0,0 @@
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 {};
@@ -1,336 +0,0 @@
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
- };
File without changes