@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,25 +1,29 @@
1
- import { appManifestSchema, secretsSchema, settings } from "../settings.js";
2
- import { active, bad, muted, ok, strong } from "../ui/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);
@@ -1,28 +1,29 @@
1
1
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
2
  import { createServer } from "node:http";
3
3
  import { join } from "node:path";
4
- import { err, ok } from "../result.js";
5
- import { field, registered } from "./app.js";
6
- import { owner, runId, sha } from "./brand.js";
7
- import { body, json, send } from "./http.js";
8
- import { page, runPage } from "./page.js";
9
- import { spawnLines } from "./process.js";
10
- import { forgeRepo, signed } from "./forge.js";
11
- import { pushedRef } from "./webhook.js";
4
+ import { err, ok } from "../../result.js";
5
+ import { field, registered } from "../app.js";
6
+ import { owner, runId, sha } from "../brand.js";
7
+ import { body, json, send } from "../http/http.js";
8
+ import { page, runPage } from "../http/page.js";
9
+ import { spawnLines } from "../process.js";
10
+ import { forgeRepo, signed } from "../forges/forge.js";
11
+ import { pushedRef } from "../http/webhook.js";
12
+ import { typed } from "../../typed.js";
12
13
  const fromFile = (path) => () => (existsSync(path) ? readFileSync(path, "utf8").trim() : "");
13
14
  const settings = (env) => {
14
15
  const platformDir = env["PLATFORM_DIR"] ?? "/opt/platform";
15
- return {
16
+ return typed({
16
17
  platformDir,
17
18
  work: env["WORK_DIR"] ?? "/work",
18
19
  deployer: env["DEPLOYER_URL"] ?? "http://deployer:8090",
19
20
  resolveImages: env["RESOLVE_IMAGES"] ?? "/opt/kayra/scripts/platform/resolve-images.sh",
20
21
  webhookSecret: () => env["WEBHOOK_SECRET"] ?? "",
21
22
  gitToken: fromFile("/run/platform-secrets/GIT_TOKEN"),
22
- };
23
+ });
23
24
  };
24
25
  /** git with the platform's token as a header: neither in the clone's config nor in the process list. */
25
- const gitEnv = (token) => ({
26
+ const gitEnv = (token) => typed({
26
27
  GIT_TERMINAL_PROMPT: "0",
27
28
  GIT_CONFIG_COUNT: "1",
28
29
  GIT_CONFIG_KEY_0: "http.extraHeader",
@@ -38,7 +39,7 @@ export const resolveRef = async (app, ref, token) => {
38
39
  return err(`git ls-remote ${app.repo} failed (exit ${String(exit.code)})`);
39
40
  const refs = new Map(exit.stdout.split("\n").flatMap((line) => {
40
41
  const [commit, name] = line.split("\t");
41
- return commit === undefined || name === undefined ? [] : [[name, commit]];
42
+ return typed(commit === undefined || name === undefined ? [] : [[name, commit]]);
42
43
  }));
43
44
  const found = refs.get(`refs/tags/${ref}^{}`) ?? refs.get(`refs/heads/${ref}`) ?? refs.get(`refs/tags/${ref}`);
44
45
  return found === undefined ? err(`${ref} is no branch or tag of ${app.repo}`) : sha(found);
@@ -83,7 +84,7 @@ export const prepare = async (app, commit, s, line) => {
83
84
  const artifacts = planned.value
84
85
  .split("\n")
85
86
  .filter((row) => row !== "")
86
- .map((row) => row.split("\t"));
87
+ .map((row) => Object.freeze(row.split("\t")));
87
88
  const built = await sequence(artifacts.map(([name]) => () => {
88
89
  line(`── Image ${name ?? "?"}`);
89
90
  return run(["bash", s.resolveImages, app.name, root, "--ensure", name ?? ""], { env: buildEnv }, line);
@@ -1,6 +1,7 @@
1
- import { err, ok } from "../result.js";
2
- import { field } from "./app.js";
3
- import { sha } from "./brand.js";
1
+ import { err, ok } from "../../result.js";
2
+ import { field } from "../app.js";
3
+ import { sha } from "../brand.js";
4
+ import { typed } from "../../typed.js";
4
5
  const relative = (path) => path !== "" && !path.startsWith("/") && !path.split("/").some((segment) => segment === ".." || segment === "");
5
6
  export const parseBundle = (app, expected, json) => {
6
7
  if (typeof json !== "object" || json === null)
@@ -16,25 +17,25 @@ export const parseBundle = (app, expected, json) => {
16
17
  const own = new RegExp(`^localhost:5000/${app}/[a-z0-9._/-]+:[0-9a-f]{12}$`);
17
18
  const parsedImages = images.map((image) => {
18
19
  if (typeof image !== "object" || image === null)
19
- return "an image is not an object";
20
+ return typed("an image is not an object");
20
21
  const variable = field(image, "variable");
21
22
  const ref = field(image, "ref");
22
23
  if (typeof variable !== "string" || !/^[A-Z][A-Z0-9_]*_IMAGE$/.test(variable))
23
24
  return `image variable ${String(variable)}`;
24
25
  if (typeof ref !== "string" || !own.test(ref))
25
26
  return `image ${String(ref)} is outside ${app}/`;
26
- return { variable, ref };
27
+ return typed({ variable, ref });
27
28
  });
28
29
  const parsedCompose = compose.map((file) => {
29
30
  if (typeof file !== "object" || file === null)
30
- return "a compose file is not an object";
31
+ return typed("a compose file is not an object");
31
32
  const path = field(file, "path");
32
33
  const content = field(file, "content");
33
34
  if (typeof path !== "string" || !relative(path))
34
35
  return `compose file ${String(path)}`;
35
36
  if (typeof content !== "string")
36
37
  return `compose file ${path} has no content`;
37
- return { path, content };
38
+ return typed({ path, content });
38
39
  });
39
40
  const problem = [...parsedImages, ...parsedCompose].find((item) => typeof item === "string");
40
41
  if (problem !== undefined)
@@ -1,3 +1,4 @@
1
+ import { typed } from "../../typed.js";
1
2
  /**
2
3
  * The app's compose project, run in the run's directory: its .env from the
3
4
  * platform (operator config), the image refs from this run, the compose files
@@ -6,21 +7,21 @@
6
7
  */
7
8
  const project = (app, appsDir, bundle) => {
8
9
  const dir = `${appsDir}/${app.name}`;
9
- return [
10
+ return typed([
10
11
  "compose", "-p", app.name, "--project-directory", dir, "--env-file", `${dir}/.env`, "--env-file", "images.env",
11
12
  ...bundle.compose.flatMap((file) => ["-f", file.path]),
12
- ];
13
+ ]);
13
14
  };
14
15
  /**
15
16
  * What admission checks. --no-env-resolution: otherwise compose reads every
16
17
  * env_file here, from any path (another app's secrets included), and bakes it
17
18
  * into the config; unresolved, the allow-list sees env_file and refuses it.
18
19
  */
19
- export const config = (app, appsDir, bundle) => [
20
+ export const config = (app, appsDir, bundle) => typed([
20
21
  "docker", ...project(app, appsDir, bundle), "config", "--no-env-resolution", "--format", "json",
21
- ];
22
- export const policy = (app, script) => ["bash", script, app.name, ...app.hosts];
22
+ ]);
23
+ export const policy = (app, script) => typed(["bash", script, app.name, ...app.hosts]);
23
24
  /** --remove-orphans: a service the app dropped from its compose files must not keep running. */
24
- export const up = (app, appsDir, bundle) => [
25
+ export const up = (app, appsDir, bundle) => typed([
25
26
  "docker", ...project(app, appsDir, bundle), "up", "-d", "--wait", "--wait-timeout", "180", "--remove-orphans",
26
- ];
27
+ ]);
@@ -1,5 +1,5 @@
1
1
  import { all, err, map, ok } from "../result.js";
2
- const range = (from, to, step) => Array.from({ length: Math.floor((to - from) / step) + 1 }, (_, i) => from + i * step);
2
+ const range = (from, to, step) => Object.freeze(Array.from({ length: Math.floor((to - from) / step) + 1 }, (_, i) => from + i * step));
3
3
  const part = (text, min, max) => {
4
4
  const match = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(text);
5
5
  if (match === null)
@@ -10,7 +10,7 @@ const part = (text, min, max) => {
10
10
  const to = whole === "*" ? max : high === undefined ? (every === undefined ? from : max) : Number(high);
11
11
  return from < min || to > max || from > to || step < 1 ? err(`'${text}' (${String(min)}-${String(max)})`) : ok(range(from, to, step));
12
12
  };
13
- const values = (text, min, max) => map(all(text.split(",").map((piece) => part(piece, min, max))), (parts) => new Set(parts.flat()));
13
+ const values = (text, min, max) => map(all(text.split(",").map((piece) => part(piece, min, max))), (parts) => Object.freeze(new Set(parts.flat())));
14
14
  export const parseCron = (spec) => {
15
15
  const fields = spec.trim().split(/\s+/);
16
16
  const [minute, hour, day, month, weekday] = fields;
@@ -1,7 +1,8 @@
1
+ import { typed } from "../../typed.js";
1
2
  /** A release record's compact UTC time, 20261018T101500Z, as ISO 8601. */
2
3
  const iso = (compact) => compact.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/, "$1-$2-$3T$4:$5:$6Z");
3
- const deployed = (release) => ({ sha: release.sha, time: iso(release.time) });
4
- const answer = (run) => ({
4
+ const deployed = (release) => typed({ sha: release.sha, time: iso(release.time) });
5
+ const answer = (run) => typed({
5
6
  id: run.id,
6
7
  state: run.state,
7
8
  why: run.why,
@@ -10,12 +11,12 @@ const answer = (run) => ({
10
11
  started: run.started,
11
12
  ...(run.finished === undefined ? {} : { finished: run.finished }),
12
13
  });
13
- export const runsAnswer = (app, runs, live) => ({
14
+ export const runsAnswer = (app, runs, live) => typed({
14
15
  app,
15
16
  ...(live === undefined ? {} : { live: deployed(live) }),
16
17
  runs: runs.map(answer),
17
18
  });
18
- export const releasesAnswer = (app, releases) => ({
19
+ export const releasesAnswer = (app, releases) => typed({
19
20
  app,
20
21
  releases: releases.map((release, index) => ({ ...deployed(release), live: index === 0 })),
21
22
  });
@@ -1,9 +1,9 @@
1
1
  import { existsSync, readdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { releasesAnswer, runsAnswer } from "./answers.js";
4
- import { appOwner, appName, owner as mintOwner, runId } from "./brand.js";
5
- import { releases } from "./records.js";
6
- import { log, runsOf } from "./store.js";
4
+ import { appOwner, appName, owner as mintOwner, runId } from "../brand.js";
5
+ import { releases } from "../runs/records.js";
6
+ import { log, runsOf } from "../runs/store.js";
7
7
  /**
8
8
  * The operator's side, run inside the deployer container by `kayra app …` and
9
9
  * `kayra job …` over SSH. Reads runs/ and releases/ directly; anything that
@@ -9,15 +9,16 @@ import { all, err, ok } from "../result.js";
9
9
  import { field, registered } from "./app.js";
10
10
  import { appName, appOwner, jobOwner, newRunId, sha } from "./brand.js";
11
11
  import { matches, parseCron } from "./cron.js";
12
- import { forge, forgeRepo } from "./forge.js";
13
- import { json, send } from "./http.js";
12
+ import { forge, forgeRepo } from "./forges/forge.js";
13
+ import { json, send } from "./http/http.js";
14
14
  import { spawnLines } from "./process.js";
15
- import { empty, enqueue, finish } from "./queue.js";
16
- import { expired, moved, releaseName, releases } from "./records.js";
17
- import { githubIssues } from "./github-issues.js";
18
- import { decide, parseNotify, silent } from "./notify.js";
19
- import { deploy, renovate } from "./run.js";
20
- import { runsOf } from "./store.js";
15
+ import { empty, enqueue, finish } from "./runs/queue.js";
16
+ import { expired, moved, releaseName, releases } from "./runs/records.js";
17
+ import { githubIssues } from "./forges/issues.js";
18
+ import { decide, parseNotify, silent } from "./forges/notify.js";
19
+ import { deploy, renovate } from "./runs/run.js";
20
+ import { runsOf } from "./runs/store.js";
21
+ import { typed } from "../typed.js";
21
22
  const token = (name) => {
22
23
  const path = `/run/platform-secrets/${name}`;
23
24
  return existsSync(path) ? readFileSync(path, "utf8").trim() : "";
@@ -29,8 +30,8 @@ const must = (result) => {
29
30
  };
30
31
  const settings = (env) => {
31
32
  const scripts = env["PLATFORM_SCRIPTS"] ?? "/opt/kayra/scripts/platform";
32
- const strings = Object.fromEntries(Object.entries(env).flatMap(([key, value]) => (value === undefined ? [] : [[key, value]])));
33
- return {
33
+ const strings = Object.fromEntries(Object.entries(env).flatMap(([key, value]) => typed(value === undefined ? [] : [[key, value]])));
34
+ return typed({
34
35
  platformDir: env["PLATFORM_DIR"] ?? "/opt/platform",
35
36
  appsDir: env["APPS_DIR"] ?? "/opt/apps",
36
37
  builder: env["BUILDER_URL"] ?? "http://builder:8081",
@@ -44,7 +45,7 @@ const settings = (env) => {
44
45
  env: strings,
45
46
  server: env["SERVER"] ?? env["DOMAIN"] ?? "this server",
46
47
  notifier: notifierFor(must(parseNotify(env["NOTIFIER"])), env["PLATFORM_DIR"] ?? "/opt/platform"),
47
- };
48
+ });
48
49
  };
49
50
  /** The configured notifier; its open alerts are kept in <platformDir>/alerts/<key>. */
50
51
  const notifierFor = (config, platformDir) => {
@@ -88,11 +89,11 @@ const runsDir = (s) => join(s.platformDir, "runs");
88
89
  const keepRuns = 50;
89
90
  const registeredApps = (s) => {
90
91
  const dir = join(s.platformDir, "apps");
91
- return (existsSync(dir) ? readdirSync(dir) : []).flatMap((file) => {
92
+ return Object.freeze((existsSync(dir) ? readdirSync(dir) : []).flatMap((file) => {
92
93
  const name = /^(.+)\.json$/.exec(file)?.[1];
93
94
  const app = name === undefined ? undefined : registered(s.platformDir, name);
94
- return app?.ok === true ? [app.value] : [];
95
- });
95
+ return app?.ok === true ? Object.freeze([app.value]) : Object.freeze([]);
96
+ }));
96
97
  };
97
98
  const builderResolve = async (s, app, ref) => {
98
99
  const response = await fetch(`${s.builder}/resolve`, { method: "POST", body: JSON.stringify({ app: app.name, ref }) }).catch(() => undefined);
@@ -139,7 +140,7 @@ const appSecrets = (app) => {
139
140
  return read.ok ? ok(Object.fromEntries(read.value)) : read;
140
141
  };
141
142
  const target = (s, who, id) => `https://deploy.${s.domain}/runs/${who}/${id}`;
142
- const effects = (s, who, id, log) => ({
143
+ const effects = (s, who, id, log) => typed({
143
144
  log,
144
145
  resolve: (app, ref) => builderResolve(s, app, ref),
145
146
  prepare: (app, commit) => builderPrepare(s, app, commit, log),
@@ -172,21 +173,21 @@ const effects = (s, who, id, log) => ({
172
173
  },
173
174
  });
174
175
  const describe = (request) => request.work.kind === "deploy"
175
- ? { what: `deploy ${request.work.ref}`, why: request.work.why }
176
- : { what: `${request.work.job}${request.work.dryRun ? " (dry run)" : ""}`, why: "schedule" };
176
+ ? typed({ what: `deploy ${request.work.ref}`, why: request.work.why })
177
+ : typed({ what: `${request.work.job}${request.work.dryRun ? " (dry run)" : ""}`, why: "schedule" });
177
178
  const work = async (s, request, fx) => {
178
179
  if (request.work.kind === "deploy") {
179
180
  const app = registered(s.platformDir, request.work.app);
180
181
  if (!app.ok) {
181
182
  fx.log(app.error);
182
- return { ok: false };
183
+ return typed({ ok: false });
183
184
  }
184
185
  return deploy(app.value, request.work.ref, { appsDir: s.appsDir, policyScript: s.policyScript }, fx);
185
186
  }
186
187
  const argv = request.work.job === "gc" ? ["bash", s.gcScript] : renovate(s.env, request.work.dryRun, s.renovateImage);
187
188
  const env = request.work.job === "renovate" ? { RENOVATE_TOKEN: token("RENOVATE_TOKEN") } : {};
188
189
  const exit = await fx.exec(argv, { cwd: s.platformDir, env });
189
- return { ok: exit.code === 0 };
190
+ return typed({ ok: exit.code === 0 });
190
191
  };
191
192
  /** The daemon's one mutable cell: the queue, swapped whole on every change. */
192
193
  // eslint-disable-next-line functional/prefer-immutable-types -- the daemon's state lives here, nowhere else
@@ -213,7 +214,7 @@ const start = async (s, request) => {
213
214
  };
214
215
  const outcome = await work(s, request, effects(s, request.owner, id, log)).catch((error) => {
215
216
  log(`deployer: ${String(error)}`);
216
- return { ok: false };
217
+ return typed({ ok: false });
217
218
  });
218
219
  const ended = {
219
220
  ...begun,
@@ -233,11 +234,11 @@ const start = async (s, request) => {
233
234
  });
234
235
  swap(s, (queue) => finish(queue, request.owner));
235
236
  };
236
- const deployRequest = (app, ref, why) => ({
237
+ const deployRequest = (app, ref, why) => typed({
237
238
  owner: appOwner(app.name),
238
239
  work: { kind: "deploy", app: app.name, ref, why },
239
240
  });
240
- const jobRequest = (job, dryRun) => ({ owner: jobOwner(job), work: { kind: "job", job, dryRun } });
241
+ const jobRequest = (job, dryRun) => typed({ owner: jobOwner(job), work: { kind: "job", job, dryRun } });
241
242
  /** The webhook's fallback: an app whose ref moved to a commit no run has tried yet and no release runs (one migrated from Jenkins has releases but no runs). */
242
243
  const poll = async (s) => {
243
244
  await Promise.all(registeredApps(s).map(async (app) => {
@@ -1,6 +1,7 @@
1
1
  import { forgejo } from "./forgejo.js";
2
2
  import { github } from "./github.js";
3
3
  import { gitlab } from "./gitlab.js";
4
+ import { typed } from "../../typed.js";
4
5
  const adapters = { github, forgejo, gitlab };
5
6
  const kinds = { "https://github.com": "github", "https://gitlab.com": "gitlab" };
6
7
  /** GitHub for https://github.com, GitLab for https://gitlab.com, a Forgejo for any other host; undefined for a URL none understands. */
@@ -11,7 +12,7 @@ export const forgeRepo = (repo) => {
11
12
  const [, origin, owner, name] = match;
12
13
  if (origin === undefined || owner === undefined || name === undefined)
13
14
  return undefined;
14
- return { kind: kinds[origin] ?? "forgejo", origin, owner, name };
15
+ return typed({ kind: kinds[origin] ?? "forgejo", origin, owner, name });
15
16
  };
16
17
  export const forge = (repo, token, fetch) => adapters[repo.kind].api(repo, token, fetch);
17
18
  export const signed = (repo, secret, body, headers) => adapters[repo.kind].signed(secret, body, headers);
@@ -1,5 +1,5 @@
1
- import { err, ok } from "../result.js";
2
- import { header, hmacMatches } from "./webhook.js";
1
+ import { err, ok } from "../../result.js";
2
+ import { header, hmacMatches } from "../http/webhook.js";
3
3
  /** A Forgejo's API (Gitea's statuses endpoint); webhooks signed `X-Forgejo-Signature: <hex>` (or Gitea's, or GitHub's, which it sends too). */
4
4
  export const forgejo = {
5
5
  api: (repo, token, fetch) => ({
@@ -1,5 +1,5 @@
1
- import { err, ok } from "../result.js";
2
- import { header, hmacMatches } from "./webhook.js";
1
+ import { err, ok } from "../../result.js";
2
+ import { header, hmacMatches } from "../http/webhook.js";
3
3
  /** GitHub's REST API; webhooks signed `X-Hub-Signature-256: sha256=<hex>`. */
4
4
  export const github = {
5
5
  api: (repo, token, fetch) => ({
@@ -1,5 +1,5 @@
1
- import { err, ok } from "../result.js";
2
- import { header, secretMatches } from "./webhook.js";
1
+ import { err, ok } from "../../result.js";
2
+ import { header, secretMatches } from "../http/webhook.js";
3
3
  /** GitLab knows no "failure" or "error", only "failed". */
4
4
  const states = { pending: "pending", success: "success", failure: "failed", error: "failed" };
5
5
  /**
@@ -1,6 +1,7 @@
1
1
  import { createSign } from "node:crypto";
2
- import { err, ok } from "../result.js";
3
- import { field } from "./app.js";
2
+ import { err, ok } from "../../result.js";
3
+ import { field } from "../app.js";
4
+ import { typed } from "../../typed.js";
4
5
  const base64url = (data) => Buffer.from(data).toString("base64url");
5
6
  /** The app's own token: a JWT signed with its private key, valid nine minutes. */
6
7
  export const appJwt = (appId, privateKey, nowSeconds) => {
@@ -10,7 +11,7 @@ export const appJwt = (appId, privateKey, nowSeconds) => {
10
11
  return `${header}.${payload}.${base64url(signature)}`;
11
12
  };
12
13
  const api = "https://api.github.com";
13
- const headers = (token) => ({
14
+ const headers = (token) => typed({
14
15
  Authorization: `Bearer ${token}`,
15
16
  Accept: "application/vnd.github+json",
16
17
  "Content-Type": "application/json",
@@ -67,5 +68,5 @@ export const githubIssues = (repository, appId, world) => {
67
68
  world.remember(key, undefined);
68
69
  return ok(undefined);
69
70
  };
70
- return { raise, resolve };
71
+ return typed({ raise, resolve });
71
72
  };
@@ -1,5 +1,6 @@
1
- import { err, ok } from "../result.js";
2
- import { field } from "./app.js";
1
+ import { err, ok } from "../../result.js";
2
+ import { field } from "../app.js";
3
+ import { typed } from "../../typed.js";
3
4
  export const silent = {
4
5
  raise: () => Promise.resolve(ok(undefined)),
5
6
  resolve: () => Promise.resolve(ok(undefined)),
@@ -37,25 +38,25 @@ export const decide = (end) => {
37
38
  const key = request.owner;
38
39
  const commit = end.sha === undefined ? "" : ` at ${end.sha.slice(0, 12)}`;
39
40
  if (end.ok)
40
- return { kind: "resolve", key, note: `Recovered: ${end.page}` };
41
+ return typed({ kind: "resolve", key, note: `Recovered: ${end.page}` });
41
42
  if (request.work.kind === "deploy") {
42
43
  if (request.work.why !== "push" && request.work.why !== "poll")
43
- return { kind: "none" };
44
- return {
44
+ return typed({ kind: "none" });
45
+ return typed({
45
46
  kind: "raise",
46
47
  alert: {
47
48
  key,
48
49
  title: `${server}: ${request.work.app} did not deploy${commit}`,
49
50
  body: `${request.work.app}'s ${request.work.ref} failed to build or deploy on ${server}${commit}, after a ${request.work.why}.\n\nThe run: ${end.page}\n\nIt stays open until a deploy of ${request.work.app} on ${server} succeeds.`,
50
51
  },
51
- };
52
+ });
52
53
  }
53
- return {
54
+ return typed({
54
55
  kind: "raise",
55
56
  alert: {
56
57
  key,
57
58
  title: `${server}: the ${request.work.job} job failed`,
58
59
  body: `The platform's ${request.work.job} job failed on ${server}.\n\nThe run: ${end.page}\n\nIt stays open until the job succeeds on ${server}.`,
59
60
  },
60
- };
61
+ });
61
62
  };
@@ -1,5 +1,6 @@
1
1
  /** The request body, refused past `limit` bytes. */
2
2
  export const body = async (request, limit = 1 << 20) => {
3
+ // eslint-disable-next-line functional/prefer-immutable-types -- Node's Buffer: bytes, never changed here
3
4
  const chunks = await Array.fromAsync(request, (chunk) => chunk);
4
5
  const all = Buffer.concat(chunks);
5
6
  return all.length > limit ? undefined : all;
@@ -1,4 +1,4 @@
1
- import { log, meta, owners, runsOf } from "./store.js";
1
+ import { log, meta, owners, runsOf } from "../runs/store.js";
2
2
  /** The read-only runs pages at deploy.<domain>, behind Authelia: what Jenkins' job pages were for. */
3
3
  const escape = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
4
4
  const shell = (title, content) => `<!doctype html>
@@ -1,5 +1,5 @@
1
1
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
- import { field } from "./app.js";
2
+ import { field } from "../app.js";
3
3
  /** A header's single value; undefined when it is missing or repeated. */
4
4
  export const header = (headers, name) => {
5
5
  const value = headers[name];
@@ -16,6 +16,7 @@ export const hmacMatches = (secret, body, given) => {
16
16
  export const secretMatches = (secret, given) => {
17
17
  if (secret === "" || given === undefined)
18
18
  return false;
19
+ // eslint-disable-next-line functional/prefer-immutable-types -- Node's Buffer: bytes, never changed here
19
20
  const digest = (text) => createHash("sha256").update(text).digest();
20
21
  return timingSafeEqual(digest(secret), digest(given));
21
22
  };
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { serveBuilder } from "./builder.js";
3
- import { ctl } from "./ctl.js";
2
+ import { serveBuilder } from "./build/builder.js";
3
+ import { ctl } from "./ctl/ctl.js";
4
4
  import { serveDeployer } from "./deployer.js";
5
5
  /** One program, three roles: `builder`, `deployer` (the two daemons) and `ctl` (the operator, inside the deployer). */
6
6
  const [role, ...args] = process.argv.slice(2);