@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,4 +1,5 @@
1
- export const empty = (limit) => ({ running: [], waiting: [], limit });
1
+ import { typed } from "../../typed.js";
2
+ export const empty = (limit) => typed({ running: [], waiting: [], limit });
2
3
  const exclusive = (request) => request.work.kind === "job" && request.work.job === "gc";
3
4
  /** Starts what may start, in order; a waiting exclusive request holds back everything behind it. */
4
5
  const fill = (queue) => {
@@ -13,10 +14,10 @@ const fill = (queue) => {
13
14
  const free = so.running.length < queue.limit && !so.running.some((running) => running.owner === request.owner);
14
15
  return free ? { ...so, running: [...so.running, request], start: [...so.start, request] } : so;
15
16
  }, { running: queue.running, blocked: false, start: [] });
16
- return {
17
+ return typed({
17
18
  queue: { ...queue, running: pick.running, waiting: queue.waiting.filter((request) => !pick.start.includes(request)) },
18
19
  start: pick.start,
19
- };
20
+ });
20
21
  };
21
22
  export const enqueue = (queue, request) => {
22
23
  const waits = queue.waiting.some((waiting) => waiting.owner === request.owner);
@@ -1,17 +1,18 @@
1
- import { runId, sha } from "./brand.js";
2
- import { field } from "./app.js";
1
+ import { runId, sha } from "../brand.js";
2
+ import { field } from "../app.js";
3
+ import { typed } from "../../typed.js";
3
4
  /** A release record's name: releases/<app>/<UTC time>-<sha>.env. registry-gc.sh reads the same files. */
4
5
  export const releaseName = (at, commit) => `${at.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${commit}.env`;
5
6
  /** Newest first, one per commit: the first is what runs now, the rest are what rollback offers. */
6
- export const releases = (names) => names
7
+ export const releases = (names) => Object.freeze(names
7
8
  .toSorted()
8
9
  .toReversed()
9
10
  .flatMap((name) => {
10
11
  const match = /^(\d{8}T\d{6}Z)-([0-9a-f]{40})\.env$/.exec(name);
11
12
  const commit = sha(match?.[2] ?? "");
12
- return match?.[1] === undefined || !commit.ok ? [] : [{ sha: commit.value, time: match[1] }];
13
+ return match?.[1] === undefined || !commit.ok ? Object.freeze([]) : Object.freeze([{ sha: commit.value, time: match[1] }]);
13
14
  })
14
- .filter((release, i, all) => all.findIndex((other) => other.sha === release.sha) === i);
15
+ .filter((release, i, all) => all.findIndex((other) => other.sha === release.sha) === i));
15
16
  /** The poll's question: has the ref moved to a commit neither the newest run tried nor the newest release runs? */
16
17
  export const moved = (resolved, lastRun, lastRelease) => resolved !== lastRun && resolved !== lastRelease;
17
18
  const whys = ["push", "poll", "deploy", "rollback", "schedule", "manual"];
@@ -33,7 +34,7 @@ export const parseMeta = (json) => {
33
34
  return undefined;
34
35
  if (!isWhy(why) || !isState(state))
35
36
  return undefined;
36
- return {
37
+ return typed({
37
38
  id: id.value,
38
39
  owner,
39
40
  what,
@@ -42,7 +43,7 @@ export const parseMeta = (json) => {
42
43
  started,
43
44
  ...(commit.ok ? { sha: commit.value } : {}),
44
45
  ...(typeof finished === "string" ? { finished } : {}),
45
- };
46
+ });
46
47
  };
47
48
  /** Run directories past the newest `keep`, oldest first: what retention deletes. */
48
- export const expired = (ids, keep) => ids.toSorted().slice(0, Math.max(0, ids.length - keep));
49
+ export const expired = (ids, keep) => Object.freeze(ids.toSorted().slice(0, Math.max(0, ids.length - keep)));
@@ -1,6 +1,7 @@
1
- import { err, ok } from "../result.js";
2
- import { imagesEnv, parseBundle } from "./bundle.js";
3
- import { config, policy, up } from "./compose.js";
1
+ import { err, ok } from "../../result.js";
2
+ import { imagesEnv, parseBundle } from "../build/bundle.js";
3
+ import { config, policy, up } from "../build/compose.js";
4
+ import { typed } from "../../typed.js";
4
5
  const step = async (fx, label, argv, options) => {
5
6
  fx.log(`── ${label}`);
6
7
  const exit = await fx.exec(argv, options);
@@ -38,7 +39,7 @@ export const deploy = async (app, ref, paths, fx) => {
38
39
  const commit = await fx.resolve(app, ref);
39
40
  if (!commit.ok) {
40
41
  fx.log(commit.error);
41
- return { ok: false };
42
+ return typed({ ok: false });
42
43
  }
43
44
  const sha = commit.value;
44
45
  fx.log(`── ${ref} is ${sha}`);
@@ -48,7 +49,7 @@ export const deploy = async (app, ref, paths, fx) => {
48
49
  if (!bundle.ok) {
49
50
  fx.log(bundle.error);
50
51
  await fx.status(app, sha, "kayra/build", "failure", "Build failed");
51
- return { ok: false, sha };
52
+ return typed({ ok: false, sha });
52
53
  }
53
54
  await fx.status(app, sha, "kayra/build", "success", "Images built");
54
55
  await fx.status(app, sha, "kayra/deploy", "pending", "Deploying");
@@ -56,21 +57,21 @@ export const deploy = async (app, ref, paths, fx) => {
56
57
  if (!deployed.ok) {
57
58
  fx.log(deployed.error);
58
59
  await fx.status(app, sha, "kayra/deploy", "failure", deployed.error);
59
- return { ok: false, sha };
60
+ return typed({ ok: false, sha });
60
61
  }
61
62
  fx.log(`Deployed ${sha}`);
62
63
  await fx.status(app, sha, "kayra/deploy", "success", "Deployed");
63
- return { ok: true, sha };
64
+ return typed({ ok: true, sha });
64
65
  };
65
66
  /** Renovate's settings, as the platform's .env holds them; the optional ones only when set. */
66
67
  export const renovate = (env, dryRun, image) => {
67
68
  const optional = ["RENOVATE_ENDPOINT", "RENOVATE_GIT_URL", "RENOVATE_HOST_RULES", "RENOVATE_GITHUB_COM_TOKEN"]
68
69
  .filter((key) => (env[key] ?? "") !== "")
69
70
  .flatMap((key) => ["-e", key]);
70
- return [
71
+ return typed([
71
72
  "docker", "run", "--rm", "--network", "platform-internal",
72
73
  "-e", "RENOVATE_TOKEN", "-e", "RENOVATE_PLATFORM", ...optional, "-e", "RENOVATE_REPOSITORIES",
73
74
  "-e", `RENOVATE_DRY_RUN=${dryRun ? "full" : "null"}`, "-e", "LOG_LEVEL=info",
74
75
  image,
75
- ];
76
+ ]);
76
77
  };
@@ -1,13 +1,14 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { owner as mintOwner, runId } from "./brand.js";
3
+ import { owner as mintOwner, runId } from "../brand.js";
4
4
  import { parseMeta } from "./records.js";
5
+ import { typed } from "../../typed.js";
5
6
  /** Reading runs/: <owner>/<id>/{meta.json,log}. Only the deployer writes there. */
6
- const entries = (dir) => (existsSync(dir) ? readdirSync(dir).toSorted() : []);
7
- export const owners = (runs) => entries(runs).flatMap((name) => {
7
+ const entries = (dir) => (existsSync(dir) ? readdirSync(dir).toSorted() : typed([]));
8
+ export const owners = (runs) => Object.freeze(entries(runs).flatMap((name) => {
8
9
  const minted = mintOwner(name);
9
- return minted.ok ? [minted.value] : [];
10
- });
10
+ return minted.ok ? Object.freeze([minted.value]) : Object.freeze([]);
11
+ }));
11
12
  export const meta = (runs, who, id) => {
12
13
  const path = join(runs, who, id, "meta.json");
13
14
  if (!existsSync(path))
@@ -20,11 +21,11 @@ export const meta = (runs, who, id) => {
20
21
  }
21
22
  };
22
23
  /** Newest first. */
23
- export const runsOf = (runs, who) => entries(join(runs, who)).toReversed().flatMap((name) => {
24
+ export const runsOf = (runs, who) => Object.freeze(entries(join(runs, who)).toReversed().flatMap((name) => {
24
25
  const id = runId(name);
25
26
  const found = id.ok ? meta(runs, who, id.value) : undefined;
26
- return found === undefined ? [] : [found];
27
- });
27
+ return found === undefined ? Object.freeze([]) : Object.freeze([found]);
28
+ }));
28
29
  export const log = (runs, who, id) => {
29
30
  const path = join(runs, who, id, "log");
30
31
  return existsSync(path) ? readFileSync(path, "utf8") : undefined;
package/cli/dist/main.js CHANGED
@@ -1,37 +1,50 @@
1
1
  #!/usr/bin/env node
2
2
  import { run } from "@optique/run";
3
- import { createInterface } from "node:readline/promises";
4
3
  import { existsSync, readFileSync } from "node:fs";
5
4
  import { homedir } from "node:os";
6
- import { join, resolve } from "node:path";
7
- import { absolutePath, fleetRoot, kayraRoot, within } from "./brand.js";
8
- import { appCheck } from "./commands/app-check.js";
9
- import { parser, runOptions } from "./cli.js";
10
- import { isDeployer, planFor } from "./commands/index.js";
11
- import { verbose } from "./commands/server.js";
12
- import { look, opentofu, statusJson, statusView } from "./commands/status.js";
13
- import { findings, overall, validateJson, validateView } from "./commands/validate.js";
14
- import { gather } from "./gather.js";
15
- import { interpret } from "./interpret.js";
16
- import { findFleetRoot, loadFleet } from "./load.js";
17
- import { systemBrowser } from "./web/opener.js";
18
- import { serveUi } from "./web/server.js";
19
- import { network } from "./net.js";
20
- import { render } from "./plan.js";
21
- import { flatMap, map, ok } from "./result.js";
22
- import { explain } from "./ui/explain.js";
23
- import { bad, muted, paint, strong } from "./ui/line.js";
24
- import { framed, silent } from "./ui/progress.js";
25
- import { screen, settle, watch } from "./ui/terminal.js";
26
- import { shortener, truncate } from "./ui/text.js";
5
+ import { join } from "node:path";
6
+ import { absolutePath, fleetRoot, kayraRoot, kayraVersion, within } from "./core/fleet/brand.js";
7
+ import { questions } from "./clients/cli/questions.js";
8
+ import { fromCommand } from "./clients/cli/invocation.js";
9
+ import { parser, runOptions } from "./clients/cli/parser.js";
10
+ import { verbose } from "./core/recipes/steps.js";
11
+ import { opentofu } from "./core/adapters/opentofu.js";
12
+ import { statusJson } from "./clients/api/status.js";
13
+ import { statusView } from "./clients/cli/status.js";
14
+ import { overall } from "./core/validation/findings.js";
15
+ import { validateJson } from "./clients/api/validate.js";
16
+ import { validateView } from "./clients/cli/validate.js";
17
+ import { interpret } from "./core/interpreter/loop.js";
18
+ import { findFleetRoot, loadFleet } from "./core/fleet/load.js";
19
+ import { operation as describe } from "./core/operations/catalog.js";
20
+ import { contextFor, hasPlan, planOf, query, serverOf, stream } from "./core/operations/dispatch.js";
21
+ import { systemBrowser } from "./clients/ui/opener.js";
22
+ import { serve } from "./serve.js";
23
+ import { network } from "./core/adapters/network.js";
24
+ import { render } from "./core/plan/describe.js";
25
+ import { err, flatMap, map, ok } from "./result.js";
26
+ import { explain } from "./clients/cli/explain.js";
27
+ import { draw } from "./clients/cli/views.js";
28
+ import { bad, muted, strong } from "./core/text/spans.js";
29
+ import { silent } from "./core/interpreter/progress.js";
30
+ import { heading } from "./core/interpreter/events.js";
31
+ import { settle } from "./core/status/updates.js";
32
+ import { framed } from "./clients/cli/framed.js";
33
+ import { paint } from "./clients/cli/paint.js";
34
+ import { screen, watch } from "./clients/cli/terminal.js";
35
+ import { shortener, truncate } from "./clients/cli/text.js";
27
36
  import { z } from "zod";
28
37
  const here = absolutePath(process.cwd());
29
38
  const engine = absolutePath(import.meta.dirname);
30
39
  if (!here.ok || !engine.ok)
31
40
  throw new Error("node reported a relative path");
32
41
  const kayra = kayraRoot(within(engine.value, "..", ".."));
33
- const version = z.object({ version: z.string() }).parse(JSON.parse(readFileSync(join(kayra, "package.json"), "utf8"))).version;
42
+ const declared = kayraVersion(z.object({ version: z.string() }).parse(JSON.parse(readFileSync(join(kayra, "package.json"), "utf8"))).version);
43
+ if (!declared.ok)
44
+ throw new Error(`kayra's package.json: version ${declared.error}`);
45
+ const version = declared.value;
34
46
  const screens = { out: screen(process.stdout, process.env), err: screen(process.stderr, process.env) };
47
+ const input = questions((text) => paint(text, screens.err.colors));
35
48
  const io = {
36
49
  out: (text) => {
37
50
  console.log(paint(text, screens.out.colors, screens.out.links));
@@ -39,34 +52,15 @@ const io = {
39
52
  err: (text) => {
40
53
  console.error(paint(text, screens.err.colors, screens.err.links));
41
54
  },
42
- ask: async (prompt) => {
43
- const terminal = createInterface({ input: process.stdin, output: process.stderr });
44
- // Ctrl-C at the prompt, or no more input: no answer, so nothing happens.
45
- const answer = await new Promise((resolve) => {
46
- terminal.once("SIGINT", () => {
47
- resolve("");
48
- });
49
- terminal.once("close", () => {
50
- resolve("");
51
- });
52
- void terminal.question(paint(prompt, screens.err.colors)).then(resolve, () => {
53
- resolve("");
54
- });
55
- });
56
- terminal.close();
57
- return answer;
58
- },
55
+ ask: (question) => input.ask(question),
56
+ draw: (answer, said) => draw(answer, said, Date.now()),
59
57
  };
60
58
  const fail = (message) => {
61
59
  io.err(screens.err.live ? [bad("✗"), " ", message] : `kayra: ${message}`);
62
60
  process.exit(1);
63
61
  };
64
- /** The heading's facts: what the server is, and which kayra runs. */
65
- const invocation = (target) => ({
66
- command: ["kayra", ...process.argv.slice(2).filter((word) => word !== "--dry-run")].join(" "),
67
- ...(target === undefined ? {} : { server: target.name }),
68
- about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${version}`],
69
- });
62
+ /** The heading: the command as typed, what it runs on, which kayra. */
63
+ const invocation = (target) => heading(["kayra", ...process.argv.slice(2).filter((word) => word !== "--dry-run")].join(" "), target, version);
70
64
  /** --dry-run: the plan as data, styled on a terminal, plain and copyable for a program. */
71
65
  const show = (steps, about, short) => {
72
66
  (screens.out.live ? explain(about, steps, short, screens.out.columns) : render(steps)).forEach(io.out);
@@ -82,40 +76,65 @@ const execute = async (steps, about, framing) => {
82
76
  const progress = framing
83
77
  ? framed(screens.err, (raw) => process.stderr.write(raw), about)
84
78
  : silent;
85
- const passed = await interpret(steps, io, progress, () => interrupt.signal.aborted);
79
+ const passed = await interpret(steps, { ...io, signal: interrupt.signal }, progress, () => interrupt.signal.aborted).finally(input.close);
86
80
  // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
87
81
  process.exitCode = interrupt.signal.aborted ? 130 : passed ? 0 : 1;
88
82
  };
89
83
  const found = flatMap(findFleetRoot(here.value), loadFleet);
90
- // Outside a fleet only `app check` runs: it works in an app's repository.
91
- const fleet = found.ok ? found : ok({ root: fleetRoot(here.value), servers: [] });
92
- if (!fleet.ok)
93
- fail(fleet.error);
84
+ // Outside a fleet only what works in an app's repository runs (app check).
85
+ const fleet = found.ok ? found.value : { root: fleetRoot(here.value), servers: [] };
86
+ const args = run(parser(fleet), runOptions(version));
87
+ const short = shortener([
88
+ [kayra, "<kayra>"],
89
+ ...(found.ok ? [[fleet.root, "<fleet>"]] : []),
90
+ [homedir(), "~"],
91
+ ]);
92
+ const context = contextFor({ kayra, fleet: fleet, version, here: here.value, network: network(2_000), tofu: opentofu });
93
+ if (args.command.name === "serve") {
94
+ if (!found.ok)
95
+ fail(found.error);
96
+ // The browser side: web/dist in a checkout, cli/dist/browser in the package.
97
+ const assets = [join(kayra, "web", "dist"), join(kayra, "cli", "dist", "browser")].find((dir) => existsSync(join(dir, "index.html")));
98
+ const { port, noOpen } = args.command;
99
+ const clients = { ui: args.command.ui || !args.command.api, api: args.command.api };
100
+ // The port taken, or the discovery file in the way: kayra says why instead of a stack trace.
101
+ const started = await serve({ kayra, fleet, version, short, network: context.network }, assets, port, clients).then(ok, (error) => err(error instanceof Error ? error.message : String(error)));
102
+ if (!started.ok)
103
+ fail(`could not start: ${started.error}`);
104
+ else {
105
+ const listening = started.value;
106
+ io.err([strong("kayra serve"), muted(` · ${fleet.servers.length.toString()} servers · kayra ${version} · Ctrl-C stops it`)]);
107
+ io.out(listening.url);
108
+ if (listening.discovery !== undefined)
109
+ io.err([muted(`API credentials: ${listening.discovery}`)]);
110
+ if (clients.ui && !noOpen)
111
+ systemBrowser.open(listening.url);
112
+ const stop = () => { void listening.close().then(() => process.exit(0)); };
113
+ process.once("SIGINT", stop);
114
+ process.once("SIGTERM", stop);
115
+ }
116
+ }
94
117
  else {
95
- const args = run(parser(fleet.value), runOptions(version));
96
- if (!found.ok && args.command.name !== "app check")
118
+ const { invocation: call, json } = fromCommand(args.command);
119
+ const operation = describe(call.name);
120
+ if (!found.ok && operation.scope !== "repo")
97
121
  fail(found.error);
98
- const short = shortener([
99
- [kayra, "<kayra>"],
100
- ...(found.ok ? [[fleet.value.root, "<fleet>"]] : []),
101
- [homedir(), "~"],
102
- ]);
103
- if (args.command.name === "app check") {
104
- const root = absolutePath(resolve(here.value, args.command.dir ?? "."));
105
- const manifestPath = root.ok ? join(root.value, "app.yml") : "";
106
- const steps = flatMap(root, (dir) => appCheck(kayra, dir, existsSync(manifestPath) ? readFileSync(manifestPath, "utf8") : undefined));
122
+ const target = serverOf(context, call);
123
+ if (hasPlan(call)) {
124
+ const steps = map(planOf(context, call), (each) => (args.verbose ? verbose(each) : each));
125
+ // An operation whose output is its answer (ssh, the deployer's) gets nothing drawn around it.
107
126
  if (!steps.ok)
108
127
  fail(steps.error);
109
128
  else if (args.dryRun)
110
- show(steps.value, invocation(undefined), short);
129
+ show(steps.value, invocation(target), short);
111
130
  else
112
- await execute(steps.value, invocation(undefined), true);
131
+ await execute(steps.value, invocation(target), operation.bare !== true);
113
132
  }
114
- else if (args.command.name === "status") {
115
- const { json, offline } = args.command;
116
- const { initial, updates } = look(fleet.value, opentofu, offline ? undefined : network(2_000));
133
+ else if (call.name === "status") {
134
+ const { offline } = call.input;
135
+ const { initial, updates } = stream(context, "status", call.input);
117
136
  // On a terminal the table is there at once, its cells filled in as the answers arrive; the report itself goes to stdout.
118
- const draw = (looks, frame) => statusView(looks, { frame, room: screens.err.columns - 1, offline }).map((line) => paint(truncate(line, screens.err.columns - 1), screens.err.colors));
137
+ const draw = (looks, frame) => Object.freeze(statusView(looks, { frame, room: screens.err.columns - 1, offline }).map((line) => paint(truncate(line, screens.err.columns - 1), screens.err.colors)));
119
138
  const looks = !json && screens.out.live && screens.err.live
120
139
  ? await watch((raw) => process.stderr.write(raw), initial, updates, draw)
121
140
  : await settle(initial, updates);
@@ -123,38 +142,18 @@ else {
123
142
  ? [JSON.stringify(statusJson(looks), null, 2)]
124
143
  : statusView(looks, { frame: "", room: screens.out.live ? screens.out.columns : Infinity, offline })).forEach(io.out);
125
144
  }
126
- else if (args.command.name === "ui") {
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
- const { port, noOpen } = args.command;
130
- const listening = await serveUi({ kayra, fleet: fleet.value, version, assets, short, network: network(2_000) }, port);
131
- io.err([strong("kayra ui"), muted(` · ${fleet.value.servers.length.toString()} servers · kayra ${version} · Ctrl-C stops it`)]);
132
- io.out(listening.url);
133
- if (!noOpen)
134
- systemBrowser.open(listening.url);
135
- process.once("SIGINT", () => {
136
- void listening.close().then(() => process.exit(0));
137
- });
138
- }
139
- else if (args.command.name === "validate") {
140
- const { server: chosen, json } = args.command;
141
- const servers = fleet.value.servers.filter((each) => chosen === undefined || each.name === chosen);
142
- const reports = await Promise.all(servers.map(async (each) => ({ server: each, findings: findings(await gather(fleet.value.root, each)) })));
143
- (json ? [JSON.stringify(validateJson(reports), null, 2)] : validateView(reports)).forEach(io.out);
144
- // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
145
- process.exitCode = reports.some((each) => overall(each.findings) === "problem") ? 1 : 0;
145
+ else if (call.name === "validate") {
146
+ const reports = await query(context, "validate", call.input);
147
+ if (!reports.ok)
148
+ fail(reports.error);
149
+ else {
150
+ (json ? [JSON.stringify(validateJson(reports.value), null, 2)] : validateView(reports.value)).forEach(io.out);
151
+ // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
152
+ process.exitCode = reports.value.some((each) => overall(each.findings) === "problem") ? 1 : 0;
153
+ }
146
154
  }
147
155
  else {
148
- const { command } = args;
149
- const steps = map(planFor({ kayra, fleet: fleet.value.root }, fleet.value, command), (each) => (args.verbose ? verbose(each) : each));
150
- const target = "server" in command ? fleet.value.servers.find((each) => each.name === command.server) : undefined;
151
- // ssh and the deployer's answers are the output itself: nothing around them.
152
- const framing = command.name !== "ssh" && !isDeployer(command);
153
- if (!steps.ok)
154
- fail(steps.error);
155
- else if (args.dryRun)
156
- show(steps.value, invocation(target), short);
157
- else
158
- await execute(steps.value, invocation(target), framing);
156
+ // version: Optique answers `kayra version` and `--version` itself, before this.
157
+ io.out(version);
159
158
  }
160
159
  }
@@ -2,4 +2,14 @@ export const ok = (value) => ({ ok: true, value });
2
2
  export const err = (error) => ({ ok: false, error });
3
3
  export const map = (result, f) => result.ok ? ok(f(result.value)) : result;
4
4
  export const flatMap = (result, f) => (result.ok ? f(result.value) : result);
5
- export const all = (results) => results.reduce((acc, result) => flatMap(acc, (values) => map(result, (value) => [...values, value])), ok([]));
5
+ export const all = (results) => results.reduce((acc, result) => flatMap(acc, (values) => map(result, (value) => Object.freeze([...values, value]))), ok([]));
6
+ export const mapError = (result, f) => result.ok ? result : err(f(result.error));
7
+ /** What `run` makes, or why it threw: for code that reads the disk, the one place an exception becomes a value. */
8
+ export const attempt = (run, why) => {
9
+ try {
10
+ return run();
11
+ }
12
+ catch (error) {
13
+ return err(why(error instanceof Error ? error.message : String(error)));
14
+ }
15
+ };
@@ -0,0 +1,77 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { within } from "./core/fleet/brand.js";
4
+ import { createApi } from "./clients/api/api.js";
5
+ import { admit, cookieName, tokenIn } from "./clients/api/auth.js";
6
+ import { discover } from "./clients/api/discovery.js";
7
+ import { serveAsset } from "./clients/ui/assets.js";
8
+ import { send } from "./deployer/http/http.js";
9
+ export const serve = (config, assets, port, clients = { ui: true, api: false }) => {
10
+ const token = randomBytes(32).toString("base64url");
11
+ const api = createApi(config);
12
+ return new Promise((resolve, reject) => {
13
+ const server = createServer((request, response) => {
14
+ const at = listening();
15
+ const url = new URL(request.url ?? "/", `http://127.0.0.1:${String(at)}`);
16
+ const admission = admit({ method: request.method ?? "GET", path: url.pathname, host: request.headers.host, origin: request.headers.origin, cookie: request.headers.cookie, authorization: request.headers.authorization }, at, token, clients);
17
+ if (!admission.admitted) {
18
+ send(response, admission.status, `${admission.why}\n`);
19
+ return;
20
+ }
21
+ if (url.pathname === "/login" && clients.ui) {
22
+ if (!tokenIn(url.searchParams, token)) {
23
+ send(response, 401, "not this launch's token: open the URL kayra printed\n");
24
+ return;
25
+ }
26
+ response.writeHead(303, { "Set-Cookie": `${cookieName(at)}=${token}; HttpOnly; SameSite=Strict; Path=/`, Location: "/", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" });
27
+ response.end();
28
+ return;
29
+ }
30
+ if (url.pathname.startsWith("/api/")) {
31
+ api.handle(request, response, url).catch(() => {
32
+ if (!response.headersSent)
33
+ send(response, 500, "kayra could not complete this request\n");
34
+ else
35
+ response.end();
36
+ });
37
+ }
38
+ else if (clients.ui)
39
+ serveAsset(assets, url.pathname, response);
40
+ else
41
+ send(response, 404, "the browser interface is not enabled\n");
42
+ });
43
+ const listening = () => {
44
+ const address = server.address();
45
+ return typeof address === "object" && address !== null ? address.port : port;
46
+ };
47
+ server.once("error", reject);
48
+ server.listen(port, "127.0.0.1", () => {
49
+ const actual = listening();
50
+ const base = `http://127.0.0.1:${String(actual)}`;
51
+ const file = within(config.fleet.root, ".cache", "serve.json");
52
+ try {
53
+ const discovery = clients.api ? discover(file, `${base}/api`, token) : undefined;
54
+ if (discovery !== undefined && !discovery.ok) {
55
+ server.close();
56
+ reject(new Error(discovery.error));
57
+ return;
58
+ }
59
+ resolve({
60
+ url: clients.ui ? `${base}/login?token=${token}` : `${base}/api`, port: actual,
61
+ ...(clients.api ? { discovery: file } : {}),
62
+ close: async () => {
63
+ const stopping = api.stop();
64
+ server.closeAllConnections();
65
+ await Promise.all([stopping, new Promise((done) => { server.close(() => { done(); }); })]);
66
+ if (discovery?.ok === true)
67
+ discovery.value.remove();
68
+ },
69
+ });
70
+ }
71
+ catch (error) {
72
+ server.close();
73
+ reject(error instanceof Error ? error : new Error(String(error)));
74
+ }
75
+ });
76
+ });
77
+ };
@@ -0,0 +1,2 @@
1
+ /** A value as `T`: checked against it, and inferred as it. Where a function's result has a name, it says so here, at the value. */
2
+ export const typed = (value) => value;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunuseon/kayra",
3
- "version": "0.16.1",
3
+ "version": "0.17.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",
@@ -39,7 +39,9 @@
39
39
  "typecheck": "tsc -p cli --noEmit",
40
40
  "lint": "cd cli && eslint --flag unstable_native_nodejs_ts_config .",
41
41
  "test": "node --test 'cli/test/**/*.test.ts'",
42
- "schemas": "node cli/scripts/schemas.ts"
42
+ "schemas": "node cli/scripts/schemas.ts",
43
+ "contract": "node cli/scripts/contract.ts",
44
+ "signatures": "rm -rf .cache/signatures && tsc -p cli/tsconfig.build.json --declaration --emitDeclarationOnly --outDir .cache/signatures"
43
45
  },
44
46
  "dependencies": {
45
47
  "@optique/core": "1.3.3",
@@ -57,8 +57,15 @@ if has "${kayra} +(--[a-z-]+ +)*${verbs}( |$)" && ! has '--dry-run'; then
57
57
  || target="$(sed -n 's/^target: *\([a-z]*\).*/\1/p' "${project}/servers/${server}/server.yml")"
58
58
  [ "$target" = multipass ] || ask "kayra changes ${server:-a server}${target:+ (target ${target})}"
59
59
  fi
60
- # kayra ui runs any command on any server from a browser, where this guard sees none of them.
61
- has "${kayra} +(--[a-z-]+ +)*ui( |$)" && ask "kayra ui runs commands on every server from a browser, out of this guard's sight"
60
+ # kayra serve runs any command on any server from a browser, where this guard sees none of them.
61
+ has "${kayra} +(--[a-z-]+ +)*serve( |$)" && ask "kayra serve runs commands on every server from a browser, out of this guard's sight"
62
+
63
+ # Local API writes can change any server; the guard cannot inspect their JSON safely.
64
+ if has 'https?://(127\.0\.0\.1|localhost)(:[0-9]+)?/api(/|[?" ])' \
65
+ && { has 'curl .*((-X|--request)[ =]*(POST|PUT|PATCH|DELETE)|(-d|--data[a-z-]*|--json|--form)([ =]|$))' \
66
+ || { has 'fetch[ (]' && has '(POST|PUT|PATCH|DELETE)'; }; }; then
67
+ ask "a local kayra API write can change a real server"
68
+ fi
62
69
 
63
70
  # ── Ansible and the vaults ──────────────────────────────────────────────────
64
71
  has '(^|[;&|( ])ansible-vault +(decrypt|view|edit|encrypt|encrypt_string|rekey|create)( |$)' \
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bash
2
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
3
+ # and runs it: its version, its help, and kayra serve answering with its browser
4
4
  # side. Run by release.yml before npm publish, and by hand before a release.
5
5
  # bash scripts/local/packed-runs.sh
6
6
  set -euo pipefail
@@ -19,10 +19,25 @@ expected="$(node -p "require('${here}/package.json').version")"
19
19
  [ "$version" = "$expected" ] || { echo "✗ the packed kayra says ${version}, not ${expected}" >&2; exit 1; }
20
20
  (cd "${work}/fleet" && node "$kayra" --help >/dev/null)
21
21
 
22
- (cd "${work}/fleet" && node "$kayra" ui --no-open --port 0 > "${work}/ui.out" 2>&1) &
22
+ (cd "${work}/fleet" && exec node "$kayra" serve --ui --api --no-open --port 0 > "${work}/ui.out" 2>&1) &
23
23
  ui=$!
24
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; }
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 serve did not start" >&2; exit 1; }
26
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"
27
+ grep -q '<script type="module"' <<< "$page" || { echo "✗ kayra serve serves no built browser side" >&2; exit 1; }
28
+ for asset in "${work}/fleet/node_modules/@yunuseon/kayra/cli/dist/browser/assets/"*; do
29
+ curl -sf -b "${work}/jar" "${url%%/login*}/assets/$(basename "$asset")" > "${work}/asset"
30
+ cmp -s "$asset" "${work}/asset" || { echo "✗ kayra serve did not serve $(basename "$asset")" >&2; exit 1; }
31
+ done
32
+ echo "✓ the packed kayra ${version} runs, and kayra serve serves its browser side"
33
+
34
+ discovery="${work}/fleet/.cache/serve.json"
35
+ [ -f "$discovery" ] || { echo "✗ kayra serve wrote no API discovery file" >&2; exit 1; }
36
+ api_url="$(node -p "JSON.parse(require('node:fs').readFileSync(process.argv[1], 'utf8')).url" "$discovery")"
37
+ token="$(node -p "JSON.parse(require('node:fs').readFileSync(process.argv[1], 'utf8')).token" "$discovery")"
38
+ operations="$(curl -sf -H "Authorization: Bearer ${token}" "${api_url}/operations")"
39
+ node -e 'const operations=JSON.parse(process.argv[1]); if (!operations.some(op=>op.name==="ssh") || !operations.some(op=>op.name==="deploy")) process.exit(1)' "$operations"
40
+ kill "$ui"
41
+ wait "$ui"
42
+ [ ! -f "$discovery" ] || { echo "✗ kayra serve left its API discovery file" >&2; exit 1; }
43
+ echo "✓ the packed API exposes the catalog and removes its discovery file on shutdown"
@@ -6,6 +6,13 @@
6
6
  # Usage: bash scripts/local/setup-hosts.sh <domain> <ip> [subdomain…]
7
7
  set -euo pipefail
8
8
 
9
+ if [ "$EUID" -ne 0 ]; then
10
+ if [ "${KAYRA_SUDO_STDIN:-}" = 1 ]; then
11
+ exec sudo -S -p '' -- bash "$0" "$@"
12
+ fi
13
+ exec sudo -- bash "$0" "$@"
14
+ fi
15
+
9
16
  KAYRA_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
10
17
  DOMAIN="${1:?Usage: setup-hosts.sh <domain> <ip>}"
11
18
  IP="${2:?Usage: setup-hosts.sh <domain> <ip> [subdomain…]}"
@@ -15,7 +22,7 @@ echo "==> Updating /etc/hosts for ${DOMAIN} -> ${IP}..."
15
22
 
16
23
  if grep -q "${DOMAIN}" /etc/hosts 2>/dev/null; then
17
24
  echo " Removing old entries..."
18
- sudo sed -i.bak "/${DOMAIN}/d" /etc/hosts
25
+ sed -i.bak "/${DOMAIN}/d" /etc/hosts
19
26
  fi
20
27
 
21
28
  HOSTS=""
@@ -23,7 +30,7 @@ for sub in $(awk '!/^[[:space:]]*(#|$)/ {print $1}' "${KAYRA_ROOT}"/hosts.conf)
23
30
  HOSTS="${HOSTS} ${sub}.${DOMAIN}"
24
31
  done
25
32
 
26
- echo "${IP} ${DOMAIN}${HOSTS}" | sudo tee -a /etc/hosts > /dev/null
33
+ echo "${IP} ${DOMAIN}${HOSTS}" | tee -a /etc/hosts > /dev/null
27
34
 
28
35
  echo ""
29
36
  echo "Done — /etc/hosts updated:"