@yunuseon/kayra 0.17.0 → 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 (101) hide show
  1. package/ansible/roles/platform/tasks/main.yml +31 -0
  2. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  3. package/cli/dist/browser/index.html +1 -1
  4. package/cli/dist/clients/api/api.js +138 -218
  5. package/cli/dist/clients/api/auth.js +8 -7
  6. package/cli/dist/clients/api/commands.js +50 -14
  7. package/cli/dist/clients/api/contract.js +8 -6
  8. package/cli/dist/clients/api/discovery.js +7 -2
  9. package/cli/dist/clients/api/live.js +40 -0
  10. package/cli/dist/clients/api/protocol.js +17 -10
  11. package/cli/dist/clients/api/queries.js +3 -3
  12. package/cli/dist/clients/api/runs.js +10 -9
  13. package/cli/dist/clients/api/start.js +97 -0
  14. package/cli/dist/clients/api/status.js +29 -0
  15. package/cli/dist/clients/api/validate.js +13 -0
  16. package/cli/dist/clients/cli/explain.js +12 -10
  17. package/cli/dist/clients/cli/framed.js +12 -9
  18. package/cli/dist/clients/cli/invocation.js +4 -3
  19. package/cli/dist/clients/cli/paint.js +1 -1
  20. package/cli/dist/clients/cli/parser.js +8 -8
  21. package/cli/dist/clients/cli/questions.js +11 -10
  22. package/cli/dist/clients/cli/status.js +75 -0
  23. package/cli/dist/clients/cli/terminal.js +4 -2
  24. package/cli/dist/{core/present → clients/cli}/text.js +15 -24
  25. package/cli/dist/clients/cli/validate.js +32 -0
  26. package/cli/dist/clients/cli/values.js +19 -0
  27. package/cli/dist/{core/present → clients/cli}/views.js +28 -60
  28. package/cli/dist/core/adapters/fs.js +18 -0
  29. package/cli/dist/core/{net.js → adapters/network.js} +20 -5
  30. package/cli/dist/core/adapters/opentofu.js +24 -0
  31. package/cli/dist/core/ctl/answers.js +32 -0
  32. package/cli/dist/core/fleet/brand.js +45 -0
  33. package/cli/dist/core/{schemas.js → fleet/docs.js} +4 -3
  34. package/cli/dist/core/fleet/load.js +44 -0
  35. package/cli/dist/core/fleet/model.js +1 -0
  36. package/cli/dist/core/{fleet.js → fleet/parse.js} +61 -41
  37. package/cli/dist/core/{settings.js → fleet/settings.js} +10 -3
  38. package/cli/dist/core/{validate.js → fleet/shape.js} +6 -5
  39. package/cli/dist/core/{present/progress.js → interpreter/events.js} +27 -31
  40. package/cli/dist/core/interpreter/io.js +18 -0
  41. package/cli/dist/core/interpreter/loop.js +101 -0
  42. package/cli/dist/core/interpreter/needs.js +47 -0
  43. package/cli/dist/core/interpreter/process.js +107 -0
  44. package/cli/dist/core/interpreter/progress.js +15 -0
  45. package/cli/dist/core/interpreter/pty.js +8 -0
  46. package/cli/dist/core/operations/catalog.js +35 -18
  47. package/cli/dist/core/operations/{run.js → dispatch.js} +49 -46
  48. package/cli/dist/core/{plan.js → plan/describe.js} +4 -14
  49. package/cli/dist/core/plan/model.js +14 -0
  50. package/cli/dist/core/{commands → recipes}/app-check.js +11 -16
  51. package/cli/dist/core/recipes/apps.js +63 -0
  52. package/cli/dist/core/recipes/backup.js +34 -0
  53. package/cli/dist/core/recipes/certs.js +4 -0
  54. package/cli/dist/core/{commands → recipes}/doctor.js +20 -35
  55. package/cli/dist/core/recipes/host.js +104 -0
  56. package/cli/dist/core/recipes/ssh.js +20 -0
  57. package/cli/dist/core/recipes/steps.js +82 -0
  58. package/cli/dist/core/status/look.js +55 -0
  59. package/cli/dist/core/status/model.js +6 -0
  60. package/cli/dist/core/status/ports.js +1 -0
  61. package/cli/dist/core/text/plural.js +2 -0
  62. package/cli/dist/core/text/spans.js +22 -0
  63. package/cli/dist/core/text/time.js +12 -0
  64. package/cli/dist/core/validation/facts.js +49 -0
  65. package/cli/dist/core/{commands/validate.js → validation/findings.js} +31 -66
  66. package/cli/dist/deployer/app.js +2 -1
  67. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  68. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  69. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  70. package/cli/dist/deployer/cron.js +2 -2
  71. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  72. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  73. package/cli/dist/deployer/deployer.js +23 -22
  74. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  75. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  76. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  77. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  78. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  79. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  80. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  81. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  82. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  83. package/cli/dist/deployer/main.js +2 -2
  84. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  85. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  86. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  87. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  88. package/cli/dist/main.js +89 -89
  89. package/cli/dist/result.js +11 -1
  90. package/cli/dist/serve.js +2 -2
  91. package/cli/dist/typed.js +2 -0
  92. package/package.json +3 -2
  93. package/cli/dist/browser/assets/index-9a-SE2rU.js +0 -7
  94. package/cli/dist/core/brand.js +0 -39
  95. package/cli/dist/core/commands/server.js +0 -298
  96. package/cli/dist/core/commands/status.js +0 -194
  97. package/cli/dist/core/gather.js +0 -61
  98. package/cli/dist/core/interpret.js +0 -276
  99. package/cli/dist/core/load.js +0 -64
  100. package/cli/dist/core/present/line.js +0 -17
  101. /package/cli/dist/core/{updates.js → status/updates.js} +0 -0
@@ -1,4 +1,6 @@
1
- import { within } from "../brand.js";
1
+ import { within } from "../fleet/brand.js";
2
+ import { homeReach, onPath } from "./steps.js";
3
+ import { typed } from "../../typed.js";
2
4
  const everyServer = () => true;
3
5
  const tools = [
4
6
  { program: "git", install: "brew install git", neededBy: everyServer },
@@ -8,7 +10,7 @@ const tools = [
8
10
  { program: "ansible-playbook", install: "brew install ansible", neededBy: everyServer },
9
11
  { program: "ansible-galaxy", install: "brew install ansible", neededBy: everyServer },
10
12
  { program: "ansible-vault", install: "brew install ansible", neededBy: (server) => server.vault.kind !== "none" },
11
- { program: "tofu", install: "brew install opentofu", neededBy: (server) => server.terraform },
13
+ { program: "tofu", install: "brew install opentofu", neededBy: (server) => server.hasTerraform },
12
14
  {
13
15
  program: "mkcert",
14
16
  install: "brew install mkcert && mkcert -install",
@@ -19,25 +21,19 @@ const tools = [
19
21
  install: "brew install --cask multipass",
20
22
  neededBy: (server) => server.target === "multipass",
21
23
  },
22
- { program: "qemu-img", install: "brew install qemu", neededBy: (server) => server.vm },
24
+ { program: "qemu-img", install: "brew install qemu", neededBy: (server) => server.buildsVm },
23
25
  ];
24
- const toolChecks = (fleet) => tools.flatMap((tool) => {
26
+ const toolChecks = (fleet) => Object.freeze(tools.flatMap((tool) => {
25
27
  const users = fleet.servers.filter(tool.neededBy).map((server) => server.name);
26
28
  return users.length === 0
27
- ? []
28
- : [
29
- {
30
- kind: "check",
31
- label: `${tool.program} (${users.length === fleet.servers.length ? "every server" : users.join(", ")})`,
32
- probe: { kind: "on-path", program: tool.program },
33
- hint: tool.install,
34
- onFailure: "continue",
35
- },
36
- ];
37
- });
29
+ ? Object.freeze([])
30
+ : Object.freeze([
31
+ onPath(`${tool.program} (${users.length === fleet.servers.length ? "every server" : users.join(", ")})`, tool.program, tool.install, "continue"),
32
+ ]);
33
+ }));
38
34
  // ansible-vault opens whole-file vaults only; values vaulted inline are opened by setup.
39
- const vaultChecks = (fleet) => fleet.servers.flatMap((server) => server.vault.kind === "file" && server.secretsVaulted
40
- ? [
35
+ const vaultChecks = (fleet) => Object.freeze(fleet.servers.flatMap((server) => server.vault.kind === "file" && server.hasVaultedSecrets
36
+ ? Object.freeze([
41
37
  {
42
38
  kind: "check",
43
39
  label: `vault password opens ${server.name}'s secrets.yml`,
@@ -48,32 +44,21 @@ const vaultChecks = (fleet) => fleet.servers.flatMap((server) => server.vault.ki
48
44
  hint: `the password file is ${server.vault.file}`,
49
45
  onFailure: "continue",
50
46
  },
51
- ]
52
- : []);
47
+ ])
48
+ : Object.freeze([])));
53
49
  /** The apps' repositories are cloned on this Mac with the operator's own git credentials. */
54
- const repoChecks = (fleet) => [...new Set(fleet.servers.flatMap((server) => server.apps.map((app) => app.repo)))].map((repo) => ({
50
+ const repoChecks = (fleet) => Object.freeze([...new Set(fleet.servers.flatMap((server) => Object.freeze(server.apps.map((app) => app.repo))))].map((repo) => ({
55
51
  kind: "check",
56
52
  label: `git can read ${repo}`,
57
53
  probe: { kind: "exits-zero", argv: ["sh", "-c", 'GIT_TERMINAL_PROMPT=0 git ls-remote "$1" HEAD', "sh", repo] },
58
54
  hint: "gh auth login && gh auth setup-git (or git credentials of your own for that host)",
59
55
  onFailure: "continue",
60
- }));
61
- const reachChecks = (fleet, kayra) => fleet.servers
62
- .filter((server) => server.target === "home")
63
- .map((server) => ({
64
- kind: "check",
65
- label: `${server.name} answers over SSH`,
66
- probe: {
67
- kind: "exits-zero",
68
- argv: ["bash", within(kayra, "scripts", "local", "home-reach.sh"), server.name, server.kind],
69
- env: { FLEET_ROOT: fleet.root },
70
- },
71
- onFailure: "continue",
72
- }));
56
+ })));
57
+ const reachChecks = (fleet, kayra) => Object.freeze(fleet.servers.filter((server) => server.target === "home").map((server) => homeReach({ kayra, fleet: fleet.root }, server, "continue")));
73
58
  /** Is this Mac ready to run every command on every server? Each check reports; none stops the others. */
74
- export const doctor = (fleet, kayra) => [
59
+ export const doctor = (fleet, kayra) => typed([
75
60
  ...toolChecks(fleet),
76
61
  ...vaultChecks(fleet),
77
62
  ...repoChecks(fleet),
78
63
  ...reachChecks(fleet, kayra),
79
- ];
64
+ ]);
@@ -0,0 +1,104 @@
1
+ import { partOf, run } from "../plan/model.js";
2
+ import { err, map, ok } from "../../result.js";
3
+ import { ansibleEnv, ansiblePath, appSubdomains, certs, collections, fleetEnv, fromMain, inventory, latestState, needing, reachable, script, sequence, terraform, vault, vaulted } from "./steps.js";
4
+ import { apps } from "./apps.js";
5
+ import { typed } from "../../typed.js";
6
+ export const provision = (engine, server) => ok(partOf("provision", [
7
+ fromMain(engine, server),
8
+ ...(server.buildsVm ? [run("VM image and seed ISO", ["bash", script(engine, "home-image.sh"), server.name], fleetEnv(engine))] : []),
9
+ ...(server.hasTerraform
10
+ ? [
11
+ latestState(engine, server),
12
+ run("OpenTofu init", ["tofu", terraform(server), "init", "-input=false"]),
13
+ run("OpenTofu apply", ["tofu", terraform(server), "apply", "-auto-approve"]),
14
+ ]
15
+ : []),
16
+ ]));
17
+ /** The playbook for the server's kind, as setup runs it; plan adds check mode. */
18
+ const hostPlaybook = (engine, server, extra = []) => vaulted(run(`Host layer · ${server.kind}.yml${extra.includes("--check") ? ", check mode" : ""}`, [
19
+ "ansible-playbook",
20
+ "-i",
21
+ inventory(server),
22
+ ansiblePath(engine, "playbooks", `${server.kind}.yml`),
23
+ "-e",
24
+ `server=${server.name}`,
25
+ "-e",
26
+ `server_dir=${server.dir}`,
27
+ "-e",
28
+ `domain=${server.domain}`,
29
+ "-e",
30
+ `target=${server.target}`,
31
+ ...extra,
32
+ ], ansibleEnv(engine, {})), server);
33
+ /** The host layer: the playbook for the server's kind. */
34
+ export const setup = (engine, server) => ok(partOf("setup", [
35
+ fromMain(engine, server),
36
+ // mkcert where Let's Encrypt cannot reach: test VMs, and home servers without DNS-01.
37
+ ...(server.kind === "platform" && server.target !== "hetzner" && !server.usesAcmeDns
38
+ ? [certs(engine, server.domain, [appSubdomains(engine, server), ...server.stackHosts])]
39
+ : []),
40
+ ...reachable(engine, server),
41
+ collections(engine, vault(server).env),
42
+ hostPlaybook(engine, server),
43
+ ]));
44
+ /**
45
+ * What provision and setup would change, changing nothing: OpenTofu's plan and
46
+ * the playbook in check mode, with diffs (files holding secrets say only that
47
+ * they would change). From any checkout: it previews a branch against a server.
48
+ */
49
+ export const preview = (engine, server) => ok([
50
+ ...reachable(engine, server),
51
+ ...(server.hasTerraform
52
+ ? [
53
+ latestState(engine, server),
54
+ run("OpenTofu init", ["tofu", terraform(server), "init", "-input=false"]),
55
+ run("OpenTofu plan", ["tofu", terraform(server), "plan", "-input=false", "-lock=false"]),
56
+ ]
57
+ : []),
58
+ collections(engine, vault(server).env),
59
+ hostPlaybook(engine, server, ["--check", "--diff"]),
60
+ { kind: "note", text: `kayra plan changed nothing on ${server.name}: the changed tasks above are what kayra setup would do.` },
61
+ ]);
62
+ export const hosts = (engine, server) => ok(partOf("hosts", server.target === "multipass"
63
+ ? [
64
+ needing(run("/etc/hosts", [
65
+ "bash",
66
+ script(engine, "setup-hosts.sh"),
67
+ server.domain,
68
+ { kind: "substitution", argv: ["tofu", terraform(server), "output", "-raw", "server_ip"], words: "one" },
69
+ appSubdomains(engine, server),
70
+ ]), [{ kind: "sudo" }])
71
+ ]
72
+ : [{ kind: "note", text: `hosts: ${server.target} uses real DNS, nothing to do.` }]));
73
+ /** Whether a platform server works as its users see it (scripts/local/verify.sh); other kinds have nothing to check yet. */
74
+ const verifyStep = (engine, server) => typed({
75
+ ...run("Verify", ["bash", script(engine, "verify.sh"), server.name], fleetEnv(engine)),
76
+ part: "verify",
77
+ });
78
+ export const verify = (engine, server) => server.kind === "platform"
79
+ ? ok([verifyStep(engine, server)])
80
+ : err(`'${server.name}' is of kind ${server.kind}: kayra verify checks platform servers only.`);
81
+ /** Host setup, then the apps; a platform server is verified at the end, so a deploy that leaves it broken fails. */
82
+ export const deploy = (engine, server) => map(sequence([setup(engine, server), apps(engine, server)]), (plan) => server.kind === "platform" ? typed([...plan, verifyStep(engine, server)]) : plan);
83
+ export const up = (engine, server) => sequence([provision(engine, server), deploy(engine, server), hosts(engine, server)]);
84
+ export const down = (engine, server) => server.hasTerraform
85
+ ? ok([
86
+ latestState(engine, server),
87
+ ...(server.target === "hetzner"
88
+ ? [
89
+ {
90
+ kind: "confirm",
91
+ warning: `This destroys the Hetzner server '${server.name}' (${server.domain}) and everything on it.`,
92
+ expect: server.name,
93
+ },
94
+ ]
95
+ : []),
96
+ run("OpenTofu destroy", ["tofu", terraform(server), "destroy", "-auto-approve"]),
97
+ ])
98
+ : err(`${server.name} has no terraform/: nothing here creates it, so nothing destroys it`);
99
+ /** Once, for a server we did not create: the deploy user, added as root. */
100
+ export const adopt = (engine, server) => ok([
101
+ fromMain(engine, server),
102
+ collections(engine, {}),
103
+ run("Deploy user, added as root", ["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", "adopt.yml")], ansibleEnv(engine, {})),
104
+ ]);
@@ -0,0 +1,20 @@
1
+ import { run } from "../plan/model.js";
2
+ import { err, map, ok } from "../../result.js";
3
+ import { typed } from "../../typed.js";
4
+ /** ssh to a server as its inventory says, its host key trusted as `hostKeys` say. */
5
+ export const sshArgv = (inventory, hostKeys, remote) => typed([
6
+ "ssh",
7
+ "-p",
8
+ inventory.port,
9
+ "-i",
10
+ inventory.key ?? "",
11
+ ...hostKeys,
12
+ `${inventory.user ?? ""}@${inventory.host ?? ""}`,
13
+ ...remote,
14
+ ]);
15
+ /** Rebuilt servers come back with new host keys: none is remembered. */
16
+ export const sshTo = (server, remote) => server.inventory === undefined
17
+ ? err(`no inventory for '${server.name}' — provision it first.`)
18
+ : ok(sshArgv(server.inventory, ["-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null"], remote));
19
+ /** An interactive shell, or the remote command as ssh runs it (the remote shell reads it). */
20
+ export const ssh = (server, remote) => map(sshTo(server, remote), (argv) => typed([remote.length === 0 ? { ...run("SSH", argv), kind: "session" } : run("SSH", argv)]));
@@ -0,0 +1,82 @@
1
+ import { within } from "../fleet/brand.js";
2
+ import { run } from "../plan/model.js";
3
+ import { all, map } from "../../result.js";
4
+ import { typed } from "../../typed.js";
5
+ /** The local scripts that read the fleet's files find them here, not beside themselves. */
6
+ export const fleetEnv = ({ fleet }) => typed({ FLEET_ROOT: fleet });
7
+ export const script = ({ kayra }, name) => within(kayra, "scripts", "local", name);
8
+ export const ansiblePath = ({ kayra }, ...segments) => within(kayra, "ansible", ...segments);
9
+ export const inventory = (server) => within(server.dir, "inventory.ini");
10
+ export const terraform = (server) => `-chdir=${within(server.dir, "terraform")}`;
11
+ /**
12
+ * How Ansible gets the vault password: from the server's password file, or
13
+ * from kayra, which asks the operator once per run (Need "vault").
14
+ */
15
+ export const vault = (server) => {
16
+ switch (server.vault.kind) {
17
+ case "file":
18
+ return typed({ env: { ANSIBLE_VAULT_PASSWORD_FILE: server.vault.file }, needs: [] });
19
+ case "ask":
20
+ return typed({ env: {}, needs: [{ kind: "vault", server: server.name }] });
21
+ case "none":
22
+ return typed({ env: {}, needs: [] });
23
+ }
24
+ };
25
+ export const needing = (step, needs) => typed({ ...step, needs });
26
+ /** The vault's environment, and its need where kayra must ask for the password. */
27
+ export const vaulted = (step, server) => {
28
+ const { env, needs } = vault(server);
29
+ return typed({ ...step, env: { ...env, ...step.env }, ...(needs.length === 0 ? {} : { needs }) });
30
+ };
31
+ export const ansibleEnv = (engine, env) => typed({ ...env, ANSIBLE_CONFIG: ansiblePath(engine, "ansible.cfg") });
32
+ /** --verbose: every playbook prints Ansible's own output, with -v, instead of kayra's summary of it (ansible.cfg's stdout_callback). */
33
+ export const verbose = (plan) => typed(plan.map((step) => step.kind === "run" && step.argv[0] === "ansible-playbook"
34
+ ? typed({ ...step, argv: ["ansible-playbook", "-v", ...step.argv.slice(1)], env: { ...step.env, ANSIBLE_STDOUT_CALLBACK: "default" } })
35
+ : step));
36
+ /** Real servers change only from main as merged; a multipass one from anything. */
37
+ export const fromMain = (engine, server) => typed({
38
+ kind: "check",
39
+ label: `${server.name} may be changed from this checkout`,
40
+ probe: { kind: "exits-zero", argv: ["bash", script(engine, "require-main.sh"), server.name], env: fleetEnv(engine) },
41
+ onFailure: "stop",
42
+ });
43
+ /** OpenTofu only on the newest committed state: none waiting on an unmerged branch. */
44
+ export const latestState = (engine, server) => typed({
45
+ kind: "check",
46
+ label: `${server.name}'s OpenTofu state is the newest`,
47
+ probe: { kind: "exits-zero", argv: ["bash", script(engine, "require-latest-state.sh"), within(server.dir, "terraform")] },
48
+ onFailure: "stop",
49
+ });
50
+ /** Before Ansible's UNREACHABLE: why a home machine cannot be reached. */
51
+ export const reachable = (engine, server) => typed(server.target === "home" ? [homeReach(engine, server, "stop")] : []);
52
+ /** Whether a home machine answers over SSH, and if not, why (scripts/local/home-reach.sh). */
53
+ export const homeReach = (engine, server, onFailure) => typed({
54
+ kind: "check",
55
+ label: `${server.name} answers over SSH`,
56
+ probe: { kind: "exits-zero", argv: ["bash", script(engine, "home-reach.sh"), server.name, server.kind], env: fleetEnv(engine) },
57
+ onFailure,
58
+ });
59
+ /** Whether a program is on PATH, and how to install it where it is not. */
60
+ export const onPath = (label, program, hint, onFailure) => typed({
61
+ kind: "check",
62
+ label,
63
+ probe: { kind: "on-path", program },
64
+ hint,
65
+ onFailure,
66
+ });
67
+ /** The pinned Ansible collections; a no-op once installed. */
68
+ export const collections = (engine, env) => typed({
69
+ kind: "run",
70
+ title: "Ansible collections",
71
+ argv: ["ansible-galaxy", "collection", "install", "-r", ansiblePath(engine, "requirements.yml")],
72
+ env,
73
+ stdout: "discard",
74
+ });
75
+ export const appSubdomains = (engine, server) => typed({
76
+ kind: "substitution",
77
+ argv: ["bash", script(engine, "app-manifests.sh"), "--subdomains", server.name],
78
+ words: "many",
79
+ env: fleetEnv(engine),
80
+ });
81
+ export const certs = (engine, domain, subdomains) => run("mkcert certificates", ["bash", script(engine, "certs.sh"), domain, within(engine.fleet, ".cache", "certs"), ...subdomains]);
82
+ export const sequence = (plans) => map(all(plans), (each) => Object.freeze(each.flat()));
@@ -0,0 +1,55 @@
1
+ import { host, sshDefaultPort, within } from "../fleet/brand.js";
2
+ import { isMachine } from "./model.js";
3
+ import { typed } from "../../typed.js";
4
+ /** The inventory names the address: hand-written at home, written by provision elsewhere. */
5
+ export const listed = (server) => server.inventory === undefined
6
+ ? undefined
7
+ : typed({ kind: "found", address: server.inventory.host, from: "inventory" });
8
+ const provisioned = async (server, tofu) => {
9
+ const dir = within(server.dir, "terraform");
10
+ const state = await tofu.state(dir);
11
+ if (!state.ok)
12
+ return typed({ kind: "unreadable", reason: state.error });
13
+ if (state.value.length === 0)
14
+ return typed({ kind: "not-provisioned" });
15
+ if (!state.value.some(isMachine))
16
+ return typed({ kind: "no-machine" });
17
+ const output = await tofu.output(dir, "server_ip");
18
+ const address = output === undefined ? undefined : host(output);
19
+ return typed({ kind: "found", address: address?.ok === true ? address.value : undefined, from: "opentofu" });
20
+ };
21
+ export const sshPort = (server) => server.inventory?.port ?? sshDefaultPort;
22
+ export const authUrl = (server) => `https://auth.${server.domain}/`;
23
+ const pending = { kind: "pending" };
24
+ const skipped = { kind: "skipped" };
25
+ const at = (index, change) => (looks) => typed(looks.map((look, each) => (each === index ? { ...look, ...change } : look)));
26
+ /**
27
+ * Every server as far as the fleet's files tell, and the answers still to
28
+ * come, each an update to it: OpenTofu's state where no inventory names the
29
+ * address, then a TCP connect to SSH, and on platform servers HTTPS on
30
+ * auth.<domain> (Authelia's health), all at once. Without a network
31
+ * (--offline), only OpenTofu.
32
+ */
33
+ export const look = (fleet, tofu, network) => fleet.servers.reduce((so, server, index) => {
34
+ const known = listed(server);
35
+ const machine = known === undefined ? provisioned(server, tofu) : Promise.resolve(known);
36
+ const platform = server.kind === "platform";
37
+ const updates = [
38
+ ...(known === undefined ? [machine.then((answer) => at(index, { machine: answer }))] : []),
39
+ ...(network === undefined
40
+ ? []
41
+ : [
42
+ machine
43
+ .then((found) => found.kind === "found" && found.address !== undefined ? network.connect(found.address, sshPort(server)) : skipped)
44
+ .then((answer) => at(index, { ssh: answer })),
45
+ ...(platform ? [network.get(`${authUrl(server)}api/health`).then((answer) => at(index, { https: answer }))] : []),
46
+ ]),
47
+ ];
48
+ const first = {
49
+ server,
50
+ machine: known ?? pending,
51
+ ssh: network === undefined ? skipped : pending,
52
+ https: platform ? (network === undefined ? skipped : pending) : undefined,
53
+ };
54
+ return { initial: [...so.initial, first], updates: [...so.updates, ...updates] };
55
+ }, { initial: [], updates: [] });
@@ -0,0 +1,6 @@
1
+ /** Every state a probe's cell can be in, as the API names them. */
2
+ export const reachStates = ["pending", "open", "answered", "refused", "no-answer", "unreachable", "unknown-host", "bad-certificate", "failed", "skipped"];
3
+ /** Every state a machine's cell can be in. */
4
+ export const machineStates = ["pending", "found", "not-provisioned", "no-machine", "unreadable"];
5
+ /** A machine kayra's modules create, by its resource type; a data source is none. */
6
+ export const isMachine = (resource) => /(?:^|\.)(?<!data\.)(?:hcloud_server|multipass_instance)\.[^.]+$/.test(resource);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ /** "1 server", "3 servers": a count with its noun. */
2
+ export const count = (n, noun) => `${String(n)} ${noun}${n === 1 ? "" : "s"}`;
@@ -0,0 +1,22 @@
1
+ /** What a piece of text means, not how it looks: each client gives it a look (a terminal colour, a CSS class), or none. */
2
+ export const tones = ["ok", "bad", "warn", "active", "muted", "strong", "accent"];
3
+ import { typed } from "../../typed.js";
4
+ const toned = (tone) => (text) => typed({ tone, text });
5
+ export const ok = toned("ok");
6
+ export const bad = toned("bad");
7
+ export const warn = toned("warn");
8
+ export const active = toned("active");
9
+ export const muted = toned("muted");
10
+ export const strong = toned("strong");
11
+ export const accent = toned("accent");
12
+ export const link = (text, href, tone) => typed({ text, href, ...(tone === undefined ? {} : { tone }) });
13
+ export const spans = (text) => (typeof text === "string" ? typed([text]) : text);
14
+ const textOf = (span) => (typeof span === "string" ? span : span.text);
15
+ export const flat = (text) => spans(text).map(textOf).join("");
16
+ const graphemes = new Intl.Segmenter();
17
+ /** A string's characters as a reader counts them. */
18
+ export const characters = (text) => Object.freeze(Array.from(graphemes.segment(text), (each) => each.segment));
19
+ /** Columns it takes: one per character, which holds for everything kayra writes itself. */
20
+ export const width = (text) => characters(flat(text)).length;
21
+ /** What to do about it, under what it is about: an arrow, then the advice. */
22
+ export const pointing = (indent, ...said) => typed([indent, active("→"), " ", ...said]);
@@ -0,0 +1,12 @@
1
+ /** 0.4s, 12s, 2m03s, 1h04m: never more precise than it is worth reading. */
2
+ export const duration = (ms) => {
3
+ const seconds = Math.max(0, ms) / 1000;
4
+ if (seconds < 10)
5
+ return `${(Math.floor(seconds * 10) / 10).toFixed(1)}s`;
6
+ if (seconds < 60)
7
+ return `${String(Math.floor(seconds))}s`;
8
+ const minutes = Math.floor(seconds / 60);
9
+ if (minutes < 60)
10
+ return `${String(minutes)}m${String(Math.floor(seconds % 60)).padStart(2, "0")}s`;
11
+ return `${String(Math.floor(minutes / 60))}h${String(minutes % 60).padStart(2, "0")}m`;
12
+ };
@@ -0,0 +1,49 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { textAt } from "../adapters/fs.js";
5
+ import { fields, isVaulted } from "../fleet/parse.js";
6
+ import { capture } from "../interpreter/process.js";
7
+ import { typed } from "../../typed.js";
8
+ /** YAML as validate reads it: what it cannot read holds no values. */
9
+ const valuesOf = (text) => {
10
+ const parsed = text === undefined ? undefined : fields(text);
11
+ return parsed?.ok === true ? parsed.value : typed({});
12
+ };
13
+ /** A secrets file's values: plaintext as is, a vault only with the server's password file; a missing file has none. */
14
+ const secretsOf = async (server, file, text) => {
15
+ if (text === undefined)
16
+ return typed({ kind: "readable", values: {} });
17
+ if (!isVaulted(text))
18
+ return typed({ kind: "readable", values: valuesOf(text) });
19
+ if (server.vault.kind !== "file")
20
+ return typed({ kind: "locked", reason: "vaulted, and server.yml names no vault_password_file", hint: "vault_password_file in server.yml lets kayra open it" });
21
+ const password = server.vault.file.replace(homedir(), "~");
22
+ if (!existsSync(server.vault.file))
23
+ return typed({ kind: "locked", reason: `vaulted, and there is no ${password} here`, hint: "put the vault's password there" });
24
+ const opened = await capture(["ansible-vault", "view", "--vault-password-file", server.vault.file, join(server.dir, file)], "capture");
25
+ return typed(opened.code === 0 ? { kind: "readable", values: valuesOf(opened.stdout) } : { kind: "locked", reason: `${password} does not open it`, hint: "is it this vault's password?" });
26
+ };
27
+ /**
28
+ * What validate needs of a server: its files as the fleet loaded them, its
29
+ * vaults opened, and each app's app.yml from the fleet's clone (.cache/apps).
30
+ */
31
+ export const gather = async (root, server) => {
32
+ const appText = (file) => server.files.appValues.find((each) => each.file === file)?.text;
33
+ const appSecrets = await Promise.all(server.apps.map(async (app) => [app.name, await secretsOf(server, join("apps", `${app.name}.secrets.yml`), appText(`${app.name}.secrets.yml`))]));
34
+ return typed({
35
+ server,
36
+ vars: server.vars,
37
+ varsText: server.files.vars,
38
+ secrets: await secretsOf(server, "secrets.yml", server.files.secrets),
39
+ stackDirs: server.files.stacks,
40
+ appConfig: Object.fromEntries(server.apps.map((app) => [app.name, valuesOf(appText(`${app.name}.yml`))])),
41
+ appSecrets: Object.fromEntries(appSecrets),
42
+ manifests: Object.fromEntries(
43
+ // eslint-disable-next-line functional/prefer-immutable-types -- an app.yml's values are unknown, read only
44
+ server.apps.flatMap((app) => {
45
+ const manifest = textAt(join(root, ".cache", "apps", app.name, app.path, "app.yml"));
46
+ return manifest === undefined ? Object.freeze([]) : Object.freeze([[app.name, valuesOf(manifest)]]);
47
+ })),
48
+ });
49
+ };
@@ -1,25 +1,29 @@
1
- import { appManifestSchema, secretsSchema, settings } from "../settings.js";
2
- import { active, bad, muted, ok, strong } from "../present/line.js";
3
- import { closest } from "../validate.js";
4
- const finding = (result, text, hint) => ({ result, text, ...(hint === undefined ? {} : { hint }) });
1
+ import { appManifestSchema, secretsSchema, settings } from "../fleet/settings.js";
2
+ import { closest } from "../fleet/shape.js";
3
+ import { count } from "../text/plural.js";
4
+ import { mapping as fields } from "../fleet/parse.js";
5
+ import { subdomain } from "../fleet/brand.js";
6
+ import { typed } from "../../typed.js";
7
+ /** How a check went: it found a problem, could not look, or holds. */
8
+ export const verdicts = ["problem", "unchecked", "passed"];
9
+ const finding = (result, text, hint) => typed({ result, text, ...(hint === undefined ? {} : { hint }) });
5
10
  const problem = (text, hint) => finding("problem", text, hint);
6
11
  const unchecked = (text, hint) => finding("unchecked", text, hint);
7
12
  const passed = (text) => finding("passed", text);
8
13
  /** A check's findings, or one line saying it holds when it found nothing to say. */
9
- const holds = (found, text) => (found.length === 0 ? [passed(text)] : found);
10
- const count = (n, noun) => `${String(n)} ${noun}${n === 1 ? "" : "s"}`;
11
- const mapping = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : {};
12
- const strings = (value) => Array.isArray(value) ? value.filter((each) => typeof each === "string") : [];
13
- const secretSettingNames = (kind) => settings.filter((each) => each.secret && each.kinds.includes(kind)).map((each) => each.name);
14
+ const holds = (found, text) => (found.length === 0 ? typed([passed(text)]) : found);
15
+ const mapping = (value) => fields(value) ?? {};
16
+ const strings = (value) => Array.isArray(value) ? value.filter((each) => typeof each === "string") : typed([]);
17
+ const secretSettingNames = (kind) => Object.freeze(settings.filter((each) => each.secret && each.kinds.includes(kind)).map((each) => each.name));
14
18
  /** secrets.yml: known secrets typed; anything else must be a helper vars.yml uses. */
15
19
  const secretsFindings = (facts) => {
16
20
  if (facts.secrets.kind === "locked")
17
- return [unchecked(`secrets.yml not checked: ${facts.secrets.reason}`, facts.secrets.hint)];
21
+ return typed([unchecked(`secrets.yml not checked: ${facts.secrets.reason}`, facts.secrets.hint)]);
18
22
  const values = facts.secrets.values;
19
- const typed = secretsSchema(facts.server.kind).safeParse(values);
20
- const typeProblems = typed.success
23
+ const checked = secretsSchema(facts.server.kind).safeParse(values);
24
+ const typeProblems = checked.success
21
25
  ? []
22
- : typed.error.issues.slice(0, 1).map((issue) => problem(`secrets.yml: ${issue.path.join(".")}: ${issue.message}`));
26
+ : checked.error.issues.slice(0, 1).map((issue) => problem(`secrets.yml: ${issue.path.join(".")}: ${issue.message}`));
23
27
  const known = secretSettingNames(facts.server.kind);
24
28
  const unused = Object.keys(values)
25
29
  .filter((key) => !known.includes(key) && !key.startsWith("ansible_"))
@@ -34,7 +38,7 @@ const secretsFindings = (facts) => {
34
38
  const stackFindings = (facts) => {
35
39
  const listed = strings(mapping(facts.vars["compose_stacks"])["stacks"]);
36
40
  if (listed.length === 0 && facts.stackDirs.length === 0)
37
- return [];
41
+ return typed([]);
38
42
  return holds([
39
43
  ...listed
40
44
  .filter((name) => !facts.stackDirs.includes(name))
@@ -48,30 +52,30 @@ const stackFindings = (facts) => {
48
52
  const routeFindings = (facts) => {
49
53
  const routes = Array.isArray(facts.vars["edge_routes"]) ? facts.vars["edge_routes"] : [];
50
54
  if (routes.length === 0)
51
- return [];
55
+ return typed([]);
52
56
  return holds(routes.flatMap((route, index) => {
53
57
  const fields = mapping(route);
54
58
  const upstream = fields["upstream"];
55
- return [
59
+ return Object.freeze([
56
60
  ...strings(fields["subdomains"])
57
- .filter((sub) => !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(sub))
61
+ .filter((sub) => !subdomain(sub).ok)
58
62
  .map((sub) => problem(`edge_routes[${String(index)}]: '${sub}' is not a subdomain`, "lowercase letters, digits and dashes")),
59
63
  ...(typeof upstream === "string" && /^[^\s:]+:\d+$/.test(upstream)
60
64
  ? []
61
65
  : [problem(`edge_routes[${String(index)}]: upstream must be host:port`, "a host and its port, e.g. 192.168.1.10:8080")]),
62
- ];
66
+ ]);
63
67
  }), `edge_routes: ${count(routes.length, "route")}, each with subdomains and a host:port upstream`);
64
68
  };
65
69
  /** Each app's contract against the fleet's values for it. */
66
- const appFindings = (facts) => facts.server.apps.flatMap((app) => {
70
+ const appFindings = (facts) => Object.freeze(facts.server.apps.flatMap((app) => {
67
71
  const manifest = facts.manifests[app.name];
68
72
  if (manifest === undefined)
69
- return [unchecked(`app ${app.name} not checked: not cloned yet`, `kayra apps ${facts.server.name} clones it`)];
73
+ return typed([unchecked(`app ${app.name} not checked: not cloned yet`, `kayra apps ${facts.server.name} clones it`)]);
70
74
  const parsed = appManifestSchema.safeParse(manifest);
71
75
  if (!parsed.success)
72
- return [problem(`app ${app.name}: its app.yml: ${parsed.error.issues.at(0)?.message ?? "invalid"}`)];
76
+ return typed([problem(`app ${app.name}: its app.yml: ${parsed.error.issues.at(0)?.message ?? "invalid"}`)]);
73
77
  if (parsed.data.name !== app.name)
74
- return [problem(`app ${app.name}: its app.yml says name ${parsed.data.name}`, "server.yml and app.yml must name it alike")];
78
+ return typed([problem(`app ${app.name}: its app.yml says name ${parsed.data.name}`, "server.yml and app.yml must name it alike")]);
75
79
  const configKeys = parsed.data.config ?? [];
76
80
  const secretKeys = parsed.data.secrets ?? [];
77
81
  const config = facts.appConfig[app.name] ?? {};
@@ -90,56 +94,17 @@ const appFindings = (facts) => facts.server.apps.flatMap((app) => {
90
94
  .filter((key) => !(key in secrets.values))
91
95
  .map((key) => problem(`${secretsFile}: no value for ${key}, which app.yml asks for`, `${edit} servers/${facts.server.name}/${secretsFile}`));
92
96
  return holds([...missingConfig, ...missingSecrets], `app ${app.name}: ${count(configKeys.length, "config value")} and ${count(secretKeys.length, "secret")}, as its app.yml asks`);
93
- });
97
+ }));
94
98
  const rank = { problem: 0, unchecked: 1, passed: 2 };
95
99
  /** Everything validate finds for one server: problems first, then what it could not check, then what holds. */
96
- export const findings = (facts) => [...secretsFindings(facts), ...stackFindings(facts), ...routeFindings(facts), ...appFindings(facts)].toSorted((a, b) => rank[a.result] - rank[b.result]);
100
+ export const findings = (facts) => Object.freeze([...secretsFindings(facts), ...stackFindings(facts), ...routeFindings(facts), ...appFindings(facts)].toSorted((a, b) => rank[a.result] - rank[b.result]));
97
101
  /** How a set of findings went as a whole: its worst. */
98
- export const overall = (found) => found.some((each) => each.result === "problem") ? "problem" : found.some((each) => each.result === "unchecked") ? "unchecked" : "passed";
99
- const marks = { problem: bad("✗"), unchecked: muted("·"), passed: ok("✓") };
100
- const tally = (reports) => {
102
+ export const overall = (found) => verdicts.find((verdict) => found.some((each) => each.result === verdict)) ?? "passed";
103
+ /** How many problems, and how many checks could not look, across reports. */
104
+ export const tally = (reports) => {
101
105
  const all = reports.flatMap((report) => report.findings);
102
106
  return {
103
107
  problems: all.filter((each) => each.result === "problem").length,
104
108
  unchecked: all.filter((each) => each.result === "unchecked").length,
105
109
  };
106
110
  };
107
- /** "✗ 3 servers · 1 problem · 2 not checked" */
108
- export const summary = (reports) => {
109
- const { problems, unchecked: notChecked } = tally(reports);
110
- return [
111
- marks[overall(reports.flatMap((report) => report.findings))],
112
- " ",
113
- count(reports.length, "server"),
114
- muted(" · "),
115
- problems === 0 ? ok("no problems") : bad(count(problems, "problem")),
116
- ...(notChecked === 0 ? [] : [muted(" · "), `${String(notChecked)} not checked`]),
117
- ];
118
- };
119
- /** Each server with its mark, its findings under it with what to do about them, then the summary. */
120
- export const validateView = (reports) => {
121
- const names = Math.max(0, ...reports.map((report) => report.server.name.length));
122
- return [
123
- ...reports.flatMap((report) => [
124
- [marks[overall(report.findings)], " ", strong(report.server.name.padEnd(names)), muted(` ${report.server.kind} on ${report.server.target}`)],
125
- ...report.findings.flatMap((each) => [
126
- [" ", marks[each.result], " ", each.result === "passed" ? muted(each.text) : each.text],
127
- ...(each.hint === undefined ? [] : [[" ", active("→"), " ", each.hint]]),
128
- ]),
129
- [],
130
- ]),
131
- summary(reports),
132
- ];
133
- };
134
- /** `kayra validate --json`: the shape cli.md documents. */
135
- export const validateJson = (reports) => ({
136
- result: overall(reports.flatMap((report) => report.findings)),
137
- ...tally(reports),
138
- servers: reports.map((report) => ({
139
- name: report.server.name,
140
- kind: report.server.kind,
141
- target: report.server.target,
142
- result: overall(report.findings),
143
- findings: report.findings.map((each) => ({ result: each.result, text: each.text, hint: each.hint ?? null })),
144
- })),
145
- });
@@ -1,9 +1,10 @@
1
+ import { typed } from "../typed.js";
1
2
  import { existsSync, readFileSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { err, ok } from "../result.js";
4
5
  import { appName } from "./brand.js";
5
6
  const strings = (value, pattern) => Array.isArray(value) && value.every((item) => typeof item === "string" && pattern.test(item))
6
- ? value
7
+ ? typed(value)
7
8
  : undefined;
8
9
  export const field = (record, key) => {
9
10
  const value = Reflect.get(record, key);