@yunuseon/kayra 0.18.0 → 0.20.0

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 (164) hide show
  1. package/agent/skills/kayra-release/SKILL.md +1 -4
  2. package/agent/skills/kayra-rollout/SKILL.md +4 -6
  3. package/ansible/playbooks/edge.yml +5 -0
  4. package/ansible/playbooks/nas.yml +9 -1
  5. package/ansible/playbooks/platform.yml +8 -2
  6. package/ansible/roles/app/tasks/main.yml +33 -3
  7. package/ansible/roles/kayra-version/defaults/main.yml +5 -0
  8. package/ansible/roles/kayra-version/tasks/main.yml +18 -0
  9. package/ansible/roles/platform/defaults/main.yml +3 -0
  10. package/ansible/roles/platform/tasks/main.yml +6 -84
  11. package/ansible/roles/platform/templates/platform.env.j2 +2 -0
  12. package/bin/kayra-app-hook.js +6 -0
  13. package/bin/kayra-app-init.js +6 -0
  14. package/bin/kayra-app-launch.js +6 -0
  15. package/bin/kayra-app-values.js +6 -0
  16. package/cli/dist/app-hook.js +75 -0
  17. package/cli/dist/app-init.js +65 -0
  18. package/cli/dist/app-launch.js +89 -0
  19. package/cli/dist/app-values.js +37 -0
  20. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-400-normal-BTotfTJu.woff +0 -0
  21. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-400-normal-DZqxrq2p.woff2 +0 -0
  22. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-600-normal-71GNu3SW.woff2 +0 -0
  23. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-600-normal-BGq0mW3O.woff +0 -0
  24. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-400-normal-Dsrv2Tcn.woff +0 -0
  25. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-400-normal-g30qAdWV.woff2 +0 -0
  26. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-600-normal-Bz0x94Yp.woff +0 -0
  27. package/cli/dist/browser/assets/ibm-plex-sans-cyrillic-ext-600-normal-DUMzJB7m.woff2 +0 -0
  28. package/cli/dist/browser/assets/ibm-plex-sans-greek-400-normal-D9ESIMu3.woff +0 -0
  29. package/cli/dist/browser/assets/ibm-plex-sans-greek-400-normal-_efipK4i.woff2 +0 -0
  30. package/cli/dist/browser/assets/ibm-plex-sans-greek-600-normal-D-CqTdkO.woff +0 -0
  31. package/cli/dist/browser/assets/ibm-plex-sans-greek-600-normal-DzTrcv_p.woff2 +0 -0
  32. package/cli/dist/browser/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
  33. package/cli/dist/browser/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
  34. package/cli/dist/browser/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
  35. package/cli/dist/browser/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
  36. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-400-normal-C5H60-Va.woff2 +0 -0
  37. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-400-normal-RBey6euL.woff +0 -0
  38. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-600-normal-DIrixKbi.woff +0 -0
  39. package/cli/dist/browser/assets/ibm-plex-sans-latin-ext-600-normal-DOrvGEcy.woff2 +0 -0
  40. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-400-normal-DG4YqDda.woff2 +0 -0
  41. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-400-normal-fK1oJ5dG.woff +0 -0
  42. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-600-normal-DgdngZtN.woff +0 -0
  43. package/cli/dist/browser/assets/ibm-plex-sans-vietnamese-600-normal-DpPYBSTl.woff2 +0 -0
  44. package/cli/dist/browser/assets/index-DzIVPXyL.css +1 -0
  45. package/cli/dist/browser/assets/index-SP8bCDrl.js +7 -0
  46. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  47. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  48. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
  49. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
  50. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-600-normal-8K4wrrwR.woff +0 -0
  51. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  52. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
  53. package/cli/dist/browser/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
  54. package/cli/dist/browser/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  55. package/cli/dist/browser/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  56. package/cli/dist/browser/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
  57. package/cli/dist/browser/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
  58. package/cli/dist/browser/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  59. package/cli/dist/browser/assets/jetbrains-mono-greek-600-normal-mc2nkWzM.woff +0 -0
  60. package/cli/dist/browser/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
  61. package/cli/dist/browser/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
  62. package/cli/dist/browser/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  63. package/cli/dist/browser/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  64. package/cli/dist/browser/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  65. package/cli/dist/browser/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  66. package/cli/dist/browser/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
  67. package/cli/dist/browser/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  68. package/cli/dist/browser/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
  69. package/cli/dist/browser/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
  70. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  71. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  72. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  73. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
  74. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  75. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-600-normal-DObL3zCW.woff +0 -0
  76. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
  77. package/cli/dist/browser/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
  78. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  79. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
  80. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-600-normal-OWROknRo.woff +0 -0
  81. package/cli/dist/browser/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
  82. package/cli/dist/browser/index.html +10 -3
  83. package/cli/dist/clients/api/start.js +1 -1
  84. package/cli/dist/clients/cli/invocation.js +25 -0
  85. package/cli/dist/clients/cli/parser.js +24 -7
  86. package/cli/dist/clients/cli/status.js +28 -7
  87. package/cli/dist/clients/cli/text.js +3 -3
  88. package/cli/dist/clients/cli/values.js +0 -1
  89. package/cli/dist/clients/cli/views.js +9 -2
  90. package/cli/dist/clients/mcp/tools.js +8 -1
  91. package/cli/dist/clients/ui/assets.js +1 -0
  92. package/cli/dist/clients/wire/contract.js +2 -2
  93. package/cli/dist/clients/wire/queries.js +1 -0
  94. package/cli/dist/clients/wire/schemas.js +6 -2
  95. package/cli/dist/clients/wire/status.js +7 -1
  96. package/cli/dist/clients/wire/words.js +14 -0
  97. package/cli/dist/core/adapters/network.js +20 -1
  98. package/cli/dist/core/adapters/opentofu.js +1 -1
  99. package/cli/dist/core/app-hook/hooks.js +90 -0
  100. package/cli/dist/core/app-hook/token.js +49 -0
  101. package/cli/dist/core/app-init/plan.js +208 -0
  102. package/cli/dist/core/app-values/model.js +45 -0
  103. package/cli/dist/core/app-values/store.js +124 -0
  104. package/cli/dist/core/ctl/answers.js +14 -9
  105. package/cli/dist/core/fleet/brand.js +10 -7
  106. package/cli/dist/core/fleet/parse.js +10 -1
  107. package/cli/dist/core/fleet/settings.js +32 -12
  108. package/cli/dist/core/operations/catalog.js +46 -1
  109. package/cli/dist/core/operations/dispatch.js +40 -9
  110. package/cli/dist/core/recipes/app-check.js +14 -1
  111. package/cli/dist/core/recipes/app-hook.js +26 -0
  112. package/cli/dist/core/recipes/app-values.js +21 -0
  113. package/cli/dist/core/recipes/doctor.js +5 -5
  114. package/cli/dist/core/recipes/host.js +8 -3
  115. package/cli/dist/core/recipes/launch.js +51 -0
  116. package/cli/dist/core/status/look.js +33 -13
  117. package/cli/dist/core/status/model.js +2 -0
  118. package/cli/dist/core/validation/facts.js +1 -3
  119. package/cli/dist/deployer/brand.js +9 -1
  120. package/cli/dist/deployer/build/builder.js +15 -4
  121. package/cli/dist/deployer/build/bundle.js +5 -0
  122. package/cli/dist/deployer/build/client.js +44 -0
  123. package/cli/dist/deployer/build/compose.js +21 -8
  124. package/cli/dist/deployer/build/routes.js +149 -0
  125. package/cli/dist/deployer/ctl/answers.js +6 -2
  126. package/cli/dist/deployer/ctl/ctl.js +66 -9
  127. package/cli/dist/deployer/deployer.js +114 -191
  128. package/cli/dist/deployer/forges/forge.js +0 -12
  129. package/cli/dist/deployer/forges/notify.js +3 -3
  130. package/cli/dist/deployer/http/http.js +0 -1
  131. package/cli/dist/deployer/http/page.js +4 -2
  132. package/cli/dist/deployer/http/webhook.js +0 -1
  133. package/cli/dist/deployer/runs/effects.js +70 -0
  134. package/cli/dist/deployer/runs/queue.js +5 -4
  135. package/cli/dist/deployer/runs/records.js +22 -3
  136. package/cli/dist/deployer/runs/restore.js +6 -0
  137. package/cli/dist/deployer/runs/run.js +64 -11
  138. package/cli/dist/deployer/runs/store.js +19 -3
  139. package/cli/dist/deployer/settings.js +69 -0
  140. package/cli/dist/lib/forge-repo.js +15 -0
  141. package/cli/dist/lib/names.js +13 -0
  142. package/cli/dist/main.js +46 -25
  143. package/compose/docker-compose.ci.yml +2 -0
  144. package/package.json +2 -2
  145. package/schema/app.json +69 -8
  146. package/schema/defaults.json +8 -0
  147. package/schema/vars-platform.json +8 -0
  148. package/scripts/local/app-check.sh +12 -9
  149. package/scripts/local/app-manifests.sh +11 -6
  150. package/scripts/local/verify.sh +30 -12
  151. package/scripts/platform/compose-policy.sh +37 -40
  152. package/terraform/modules/platform-dns/main.tf +66 -0
  153. package/terraform/modules/platform-dns/outputs.tf +9 -0
  154. package/terraform/modules/platform-dns/tests/fleet/.cache/apps/blog/site/app.yml +3 -0
  155. package/terraform/modules/platform-dns/tests/fleet/.cache/apps/shop/app.yml +6 -0
  156. package/terraform/modules/platform-dns/tests/fleet/servers/nested/server.yml +6 -0
  157. package/terraform/modules/platform-dns/tests/fleet/servers/shop/server.yml +7 -0
  158. package/terraform/modules/platform-dns/tests/fleet/servers/uncloned/server.yml +6 -0
  159. package/terraform/modules/platform-dns/tests/platform-dns.tftest.hcl +64 -0
  160. package/terraform/modules/platform-dns/variables.tf +25 -0
  161. package/cli/dist/browser/assets/index-Ct0Eudk4.css +0 -1
  162. package/cli/dist/browser/assets/index-hcyM6f6T.js +0 -7
  163. package/compose/traefik/dynamic/ratelimit.yml +0 -21
  164. package/scripts/agent/guard.sh +0 -125
@@ -0,0 +1,208 @@
1
+ import { isAbsolute, relative } from "node:path";
2
+ import { Document } from "yaml";
3
+ import { names } from "../../lib/names.js";
4
+ import { typed } from "../../lib/typed.js";
5
+ export const overlayFile = "kayra/compose.yml";
6
+ const defaultMemory = "512m";
7
+ const defaultPort = 8080;
8
+ /** What compose-policy.sh allows on a service. */
9
+ const allowed = new Set(["image", "command", "entrypoint", "environment", "labels", "networks", "volumes", "tmpfs", "healthcheck",
10
+ "depends_on", "restart", "user", "working_dir", "init", "read_only", "expose", "stop_grace_period", "stop_signal", "mem_limit",
11
+ "mem_reservation", "cpus", "deploy"]);
12
+ /** Refused by the policy, and safe to drop: the platform builds, routes and names instead. */
13
+ const dropped = ["build", "ports", "env_file", "container_name", "pull_policy", "platform", "hostname"];
14
+ const droppedKeys = new Set(dropped);
15
+ const reserved = new Set(["deploy", "auth", "traefik"]);
16
+ const secretish = /PASSWORD|SECRET|TOKEN|KEY|PRIVATE|CREDENTIAL/i;
17
+ /** Variables a compose file needs and gives no default for: `${X}`, `${X:?…}`, `${X?…}`. */
18
+ const required = (text) => Object.freeze([...text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?\?[^}]*)?\}/g)].flatMap((match) => (match[1] === undefined ? Object.freeze([]) : Object.freeze([match[1]]))));
19
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : undefined;
20
+ const list = (value) => (Array.isArray(value) ? typed(value) : typed([]));
21
+ const text = (value) => (typeof value === "string" ? value : undefined);
22
+ const imageVariable = (service) => `${service.toUpperCase().replace(/-/g, "_")}_IMAGE`;
23
+ const inside = (root, path) => {
24
+ const rel = relative(root, path);
25
+ return rel === "" ? "." : rel.startsWith("..") || isAbsolute(rel) ? undefined : rel;
26
+ };
27
+ const artifact = (app, root, service, build) => {
28
+ const spec = record(build);
29
+ const context = text(spec?.["context"]) ?? ".";
30
+ const at = inside(root, isAbsolute(context) ? context : `${root}/${context}`);
31
+ if (at === undefined)
32
+ return { written: [], todo: [`service ${service}: its build context ${context} is outside the app; the build sees only the app's checkout`] };
33
+ const dockerfile = text(spec?.["dockerfile"]) ?? "Dockerfile";
34
+ const extra = ["args", "target", "secrets", "ssh", "additional_contexts"].filter((key) => spec?.[key] !== undefined);
35
+ const manifest = { image: `${app}/${service}`, dockerfile: at === "." ? dockerfile : `${at}/${dockerfile}`, context: at, inputs: [at] };
36
+ return {
37
+ written: [typed({ path: `kayra/${service}/docker/image.json`, content: `${JSON.stringify(manifest, null, 2)}\n` })],
38
+ todo: extra.map((key) => `service ${service}: build.${key} is not passed to the platform's build; bake it into the Dockerfile`),
39
+ };
40
+ };
41
+ const routeOf = (service, ports) => {
42
+ const tcp = ports.map(record).find((port) => port !== undefined && (text(port["protocol"]) ?? "tcp") === "tcp");
43
+ const target = typeof tcp?.["target"] === "number" ? tcp["target"] : undefined;
44
+ if (target === undefined)
45
+ return { route: undefined, todo: [] };
46
+ const host = service.toLowerCase();
47
+ return names.subdomain.pattern.test(host) && !reserved.has(host)
48
+ ? { route: { host, service, port: target }, todo: [] }
49
+ : { route: undefined, todo: [`service ${service} publishes ${String(target)}, but ${host} is no host it may have: add its route to app.yml by hand`] };
50
+ };
51
+ const volumesOf = (root, service, volumes, isFile) => {
52
+ const mounts = volumes.map(record).flatMap((volume) => (volume === undefined ? Object.freeze([]) : Object.freeze([volume])));
53
+ const binds = mounts.filter((volume) => volume["type"] === "bind");
54
+ if (binds.length === 0)
55
+ return { volumes: undefined, named: [], did: [], todo: [] };
56
+ const named = (volume) => `${service}-${(text(volume["source"]) ?? "data").split("/").filter((part) => part !== "").at(-1) ?? "data"}`.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
57
+ const fileBinds = binds.filter((volume) => isFile(text(volume["source"]) ?? ""));
58
+ const directoryBinds = binds.filter((volume) => !fileBinds.includes(volume));
59
+ const where = (volume) => `${relative(root, text(volume["source"]) ?? "")} → ${text(volume["target"]) ?? ""}`;
60
+ return {
61
+ volumes: mounts
62
+ .filter((volume) => !fileBinds.includes(volume))
63
+ .map((volume) => (volume["type"] === "bind"
64
+ ? { type: "volume", source: named(volume), target: volume["target"], ...(volume["read_only"] === true ? { read_only: true } : {}) }
65
+ : volume)),
66
+ named: directoryBinds.map(named),
67
+ did: directoryBinds.map((volume) => `service ${service}: bind mount ${where(volume)} as the named volume ${named(volume)}; its data starts empty on the server`),
68
+ todo: fileBinds.map((volume) => `service ${service}: bind mount of the file ${where(volume)}; COPY it into the image instead`),
69
+ };
70
+ };
71
+ const serviceOf = (app, root, name, value, envKeys, isFile) => {
72
+ const builds = value["build"] !== undefined;
73
+ const valid = /^[a-z0-9][a-z0-9-]*$/.test(name);
74
+ const built = builds && valid ? artifact(app, root, name, value["build"]) : { written: [], todo: builds ? [`service ${name}: an image name needs lowercase letters, digits and dashes; rename the service`] : [] };
75
+ const fromFiles = list(value["env_file"]).map((entry) => text(record(entry)?.["path"]) ?? text(entry) ?? "");
76
+ const keys = fromFiles.map((path) => ({ path, keys: envKeys(path) }));
77
+ const envTodo = keys.filter((each) => each.keys === undefined).map((each) => `service ${name}: env_file ${relative(root, each.path)} could not be read; declare its keys in app.yml`);
78
+ const envFromFiles = keys.flatMap((each) => each.keys ?? []);
79
+ const { route, todo: routeTodo } = routeOf(name, list(value["ports"]));
80
+ const deploy = record(value["deploy"]);
81
+ const limited = value["mem_limit"] !== undefined || record(record(deploy?.["resources"])?.["limits"])?.["memory"] !== undefined;
82
+ const mounts = volumesOf(root, name, list(value["volumes"]), isFile);
83
+ const refused = Object.keys(value).filter((key) => !allowed.has(key) && !droppedKeys.has(key));
84
+ const resets = dropped.filter((key) => value[key] !== undefined);
85
+ const builtImage = built.written.length > 0;
86
+ return typed({
87
+ overlay: {
88
+ ...(builtImage ? { image: `\${${imageVariable(name)}:?}` } : {}),
89
+ ...(envFromFiles.length === 0 ? {} : { environment: Object.fromEntries(envFromFiles.map((key) => [key, `\${${key}:?}`])) }),
90
+ ...(limited ? {} : { mem_limit: defaultMemory }),
91
+ },
92
+ volumes: mounts.volumes,
93
+ named: mounts.named,
94
+ resets,
95
+ artifacts: built.written,
96
+ route,
97
+ declared: envFromFiles,
98
+ did: [
99
+ ...(builtImage ? [`service ${name}: built by the platform from ${built.written[0]?.path ?? ""}, deployed as \${${imageVariable(name)}}`] : []),
100
+ ...(route === undefined ? [] : [`service ${name}: route ${route.host} → ${String(route.port)} instead of its published port`]),
101
+ ...(envFromFiles.length === 0 ? [] : [`service ${name}: ${String(envFromFiles.length)} key(s) from env_file declared in app.yml, its values never read`]),
102
+ ...(limited ? [] : [`service ${name}: mem_limit ${defaultMemory}, since it had none`]),
103
+ ...mounts.did,
104
+ ...resets.filter((key) => key !== "build" && key !== "ports" && key !== "env_file").map((key) => `service ${name}: ${key} dropped`),
105
+ ],
106
+ todo: [
107
+ ...built.todo,
108
+ ...envTodo,
109
+ ...routeTodo,
110
+ ...mounts.todo,
111
+ ...refused.map((key) => `service ${name}: ${key} is not allowed by the compose policy`),
112
+ ...(route !== undefined && value["healthcheck"] === undefined ? [`service ${name}: no healthcheck; a deploy then waits only for it to start`] : []),
113
+ ],
114
+ });
115
+ };
116
+ const overlay = (services) => {
117
+ const named = services.flatMap(([, service]) => service.named);
118
+ const document = new Document({
119
+ services: Object.fromEntries(services.map(([name, service]) => [name, service.overlay])),
120
+ ...(named.length === 0 ? {} : { volumes: Object.fromEntries(named.map((volume) => [volume, {}])) }),
121
+ });
122
+ services.forEach(([name, service]) => {
123
+ if (service.volumes !== undefined) {
124
+ const node = document.createNode(service.volumes);
125
+ // eslint-disable-next-line functional/immutable-data -- the yaml library tags a node by assignment
126
+ node.tag = "!override";
127
+ document.setIn(["services", name, "volumes"], node);
128
+ }
129
+ service.resets.forEach((key) => {
130
+ const node = document.createNode(key === "ports" || key === "env_file" ? [] : null);
131
+ // eslint-disable-next-line functional/immutable-data -- the yaml library tags a node by assignment
132
+ node.tag = "!reset";
133
+ document.setIn(["services", name, key], node);
134
+ });
135
+ });
136
+ return `# Written by kayra app init: what the platform deploys on top of the project's own compose file.\n${document.toString()}`;
137
+ };
138
+ const manifest = (app, compose, routes, keys) => {
139
+ const secrets = keys.filter((key) => secretish.test(key));
140
+ const config = keys.filter((key) => !secretish.test(key));
141
+ const document = new Document({
142
+ name: app,
143
+ compose,
144
+ ...(routes.length === 0 ? {} : { routes: routes.flatMap((route) => (route === undefined ? Object.freeze([]) : Object.freeze([route]))) }),
145
+ ...(secrets.length === 0 ? {} : { secrets }),
146
+ ...(config.length === 0 ? {} : { config }),
147
+ });
148
+ return `# Written by kayra app init. Review it, then: kayra app check\n${document.toString()}`;
149
+ };
150
+ /** What `app init` writes for a compose project; `root` is the app's root, absolute. */
151
+ const fromCompose = (app, root, file, config, envKeys, isFile) => {
152
+ const services = Object.entries(record(record(config)?.["services"]) ?? {}).flatMap(([name, value]) => {
153
+ const service = record(value);
154
+ return service === undefined ? Object.freeze([]) : Object.freeze([[name, serviceOf(app, root, name, service, envKeys, isFile)]]);
155
+ });
156
+ const variables = new Set(services.map(([name]) => imageVariable(name)));
157
+ const interpolated = required(JSON.stringify(config)).filter((key) => !variables.has(key) && key !== "DOMAIN");
158
+ const keys = [...new Set([...interpolated, ...services.flatMap(([, service]) => service.declared)])].toSorted();
159
+ const routes = services.map(([, service]) => service.route).filter((route) => route !== undefined);
160
+ return typed({
161
+ files: [
162
+ { path: "app.yml", content: manifest(app, [file, overlayFile], routes, keys) },
163
+ { path: overlayFile, content: overlay(services) },
164
+ ...services.flatMap(([, service]) => service.artifacts),
165
+ ],
166
+ did: [
167
+ ...services.flatMap(([, service]) => service.did),
168
+ ...(keys.length === 0 ? [] : [`declared ${keys.join(", ")}: set them with kayra app config set / app secret import|generate`]),
169
+ ],
170
+ todo: [
171
+ ...services.flatMap(([, service]) => service.todo),
172
+ ...(routes.length === 0 ? ["no service publishes a port: add a route to app.yml for the one people reach"] : []),
173
+ ],
174
+ });
175
+ };
176
+ /** What `app init` writes for a project with a Dockerfile and no compose file: one service, `web`. */
177
+ const fromDockerfile = (app, expose) => {
178
+ const port = expose ?? defaultPort;
179
+ const overlayText = new Document({ services: { web: { image: `\${${imageVariable("web")}:?}`, mem_limit: defaultMemory } } }).toString();
180
+ return typed({
181
+ files: [
182
+ { path: "app.yml", content: manifest(app, [overlayFile], [{ host: "www", service: "web", port }], []) },
183
+ { path: overlayFile, content: `# Written by kayra app init: the project's one service, built from its Dockerfile.\n${overlayText}` },
184
+ { path: "kayra/web/docker/image.json", content: `${JSON.stringify({ image: `${app}/web`, dockerfile: "Dockerfile", context: ".", inputs: ["."] }, null, 2)}\n` },
185
+ ],
186
+ did: [`service web: built from ./Dockerfile, route www → ${String(port)}, mem_limit ${defaultMemory}`],
187
+ todo: [
188
+ ...(expose === undefined ? [`the Dockerfile EXPOSEs no port; assumed ${String(defaultPort)}, correct the route in app.yml if it listens elsewhere`] : []),
189
+ "service web: no healthcheck; a deploy then waits only for it to start",
190
+ ],
191
+ });
192
+ };
193
+ export const planInit = (app, root, source) => source.kind === "compose" ? fromCompose(app, root, source.file, source.config, source.envKeys, source.isFile) : fromDockerfile(app, source.expose);
194
+ /** The first port a Dockerfile EXPOSEs. */
195
+ export const exposed = (dockerfile) => {
196
+ const match = /^\s*EXPOSE\s+(\d+)/im.exec(dockerfile);
197
+ return match?.[1] === undefined ? undefined : Number.parseInt(match[1], 10);
198
+ };
199
+ /** The keys of an env file, never its values. */
200
+ export const envFileKeys = (content) => Object.freeze(content.split(/\r?\n/).flatMap((line) => {
201
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
202
+ return match?.[1] === undefined ? Object.freeze([]) : Object.freeze([match[1]]);
203
+ }));
204
+ /** An app name from a directory's: lowercase, dashes for anything else. */
205
+ export const nameFrom = (directory) => {
206
+ const name = directory.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "");
207
+ return names.app.pattern.test(name) ? name : undefined;
208
+ };
@@ -0,0 +1,45 @@
1
+ import { z } from "zod";
2
+ import { appManifestSchema } from "../fleet/settings.js";
3
+ import { err, flatMap, ok } from "../../lib/result.js";
4
+ import { fields } from "../../lib/yaml.js";
5
+ import { within } from "../fleet/brand.js";
6
+ export const valueKeySchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, "expected an environment variable name");
7
+ export const valueStateSchema = z.enum(["set", "missing", "locked"]);
8
+ export const valuesReportSchema = z.object({
9
+ server: z.string(),
10
+ app: z.string(),
11
+ manifest: z.string(),
12
+ config: z.array(z.object({ key: z.string(), state: valueStateSchema })),
13
+ secrets: z.array(z.object({ key: z.string(), state: valueStateSchema })),
14
+ hint: z.string().nullable(),
15
+ });
16
+ export const editSchema = z.discriminatedUnion("kind", [
17
+ z.strictObject({ kind: z.literal("config"), key: valueKeySchema, value: z.string().refine((value) => !value.includes("\0"), "NUL is not an environment value") }),
18
+ z.strictObject({ kind: z.literal("import"), key: valueKeySchema, file: z.string().min(1) }),
19
+ z.strictObject({ kind: z.literal("generate"), key: valueKeySchema }),
20
+ ]);
21
+ export const requirements = (root, server, name, read, dir) => {
22
+ if (server.kind !== "platform")
23
+ return err("only platform servers have app values");
24
+ const app = server.apps.find((each) => each.name === name);
25
+ if (app === undefined)
26
+ return err(`app '${name}' is not registered in ${server.name}'s server.yml`);
27
+ const manifest = dir === undefined ? within(root, ".cache", "apps", app.name, app.path, "app.yml") : within(dir, "app.yml");
28
+ const source = read(manifest);
29
+ if (source === undefined)
30
+ return err(`no app.yml for ${name}; provide the local app directory with --dir`);
31
+ const parsed = flatMap(fields(source), (value) => {
32
+ const checked = appManifestSchema.safeParse(value);
33
+ return checked.success ? ok({ name: checked.data.name, config: Object.freeze(checked.data.config ?? []), secrets: Object.freeze(checked.data.secrets ?? []) }) : err("app.yml does not match the app contract");
34
+ });
35
+ if (!parsed.ok)
36
+ return err(`app.yml for ${name} is invalid`);
37
+ if (parsed.value.name !== name)
38
+ return err(`app.yml names another app, not ${name}`);
39
+ const { config, secrets } = parsed.value;
40
+ if ([...config, ...secrets].some((key) => !valueKeySchema.safeParse(key).success))
41
+ return err("app.yml contains an invalid configuration or secret name");
42
+ if (config.some((key) => secrets.includes(key)))
43
+ return err("app.yml declares a key as both configuration and secret");
44
+ return ok({ manifest, config: Object.freeze(config), secrets: Object.freeze(secrets) });
45
+ };
@@ -0,0 +1,124 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { parseDocument } from "yaml";
5
+ import { appValuesSchema } from "../fleet/settings.js";
6
+ import { isVaulted } from "../fleet/parse.js";
7
+ import { within } from "../fleet/brand.js";
8
+ import { textAt } from "../adapters/fs.js";
9
+ import { spawned } from "../interpreter/process.js";
10
+ import { vault } from "../recipes/steps.js";
11
+ import { attempt, err, ok } from "../../lib/result.js";
12
+ import { fields } from "../../lib/yaml.js";
13
+ import { requirements } from "./model.js";
14
+ const parsedValues = (text) => {
15
+ const parsed = fields(text);
16
+ if (!parsed.ok)
17
+ return err("values file is not a valid YAML mapping");
18
+ const checked = appValuesSchema.safeParse(parsed.value);
19
+ return checked.success ? ok(checked.data) : err("values must be strings, numbers, or booleans");
20
+ };
21
+ const present = (values, key) => Object.hasOwn(values, key) && values[key] !== "";
22
+ const fileOf = (server, name, secret) => within(server.dir, "apps", `${name}${secret ? ".secrets" : ""}.yml`);
23
+ const opened = async (server, file, source) => {
24
+ if (source === undefined)
25
+ return ok("");
26
+ if (!isVaulted(source)) {
27
+ if (server.vault.kind !== "none")
28
+ return err("secrets must be Ansible Vault encrypted for this server");
29
+ return ok(source);
30
+ }
31
+ const result = await spawned(["ansible-vault", "view", file], { stdout: "capture", stderr: "capture", stdin: { kind: "none" } }, vault(server).env);
32
+ return result.code === 0 ? ok(result.stdout) : err("cannot open app secrets; configure vault_password_file or provide the vault password through the client");
33
+ };
34
+ export const inspectValues = async (root, server, name, dir) => {
35
+ const required = requirements(root, server, name, textAt, dir);
36
+ if (!required.ok)
37
+ return required;
38
+ const config = parsedValues(textAt(fileOf(server, name, false)) ?? "");
39
+ if (!config.ok)
40
+ return config;
41
+ const file = fileOf(server, name, true);
42
+ const source = textAt(file);
43
+ const secret = source !== undefined && isVaulted(source) && server.vault.kind === "ask"
44
+ ? err("configure vault_password_file to inspect encrypted secret presence without prompting")
45
+ : await opened(server, file, source);
46
+ const values = secret.ok ? parsedValues(secret.value) : secret;
47
+ if (secret.ok && !values.ok)
48
+ return values;
49
+ return ok({
50
+ server: server.name, app: name, manifest: required.value.manifest,
51
+ config: required.value.config.map((key) => ({ key, state: present(config.value, key) ? "set" : "missing" })),
52
+ secrets: required.value.secrets.map((key) => ({ key, state: values.ok ? (present(values.value, key) ? "set" : "missing") : "locked" })),
53
+ hint: values.ok ? null : values.error,
54
+ });
55
+ };
56
+ const store = (file, original, content) => {
57
+ const temporary = `${file}.${randomUUID()}.tmp`;
58
+ try {
59
+ if (textAt(file) !== original)
60
+ return err("values changed during this operation; retry with the latest file");
61
+ writeFileSync(temporary, content, { mode: 0o600, flag: "wx" });
62
+ renameSync(temporary, file);
63
+ return ok("saved");
64
+ }
65
+ finally {
66
+ rmSync(temporary, { force: true });
67
+ }
68
+ };
69
+ const editFile = async (server, name, edit) => {
70
+ const file = fileOf(server, name, edit.kind !== "config");
71
+ if (existsSync(file) && lstatSync(file).isSymbolicLink())
72
+ return err("refusing to replace a symlinked values file");
73
+ const original = textAt(file);
74
+ if (edit.kind === "config" && original !== undefined && isVaulted(original))
75
+ return err("configuration belongs in plaintext, not a vault");
76
+ const source = edit.kind === "config" ? ok(original ?? "") : await opened(server, file, original);
77
+ if (!source.ok)
78
+ return source;
79
+ const existing = parsedValues(source.value);
80
+ if (!existing.ok)
81
+ return existing;
82
+ if (edit.kind === "generate" && present(existing.value, edit.key))
83
+ return ok(`${edit.key} already exists; kept it`);
84
+ const value = edit.kind === "config" ? edit.value : edit.kind === "generate" ? randomBytes(32).toString("hex") : readFileSync(edit.file, "utf8").replace(/\r?\n$/, "");
85
+ if (value.includes("\0") || (edit.kind !== "config" && value === ""))
86
+ return err("secret input must be nonempty text without NUL bytes");
87
+ if (existing.value[edit.key] === value)
88
+ return ok(`${edit.key} is unchanged`);
89
+ const document = parseDocument(source.value || "{}\n");
90
+ document.set(edit.key, value);
91
+ const plaintext = document.toString();
92
+ if (edit.kind === "config" || (server.vault.kind === "none" && (original === undefined || !isVaulted(original)))) {
93
+ const saved = store(file, original, plaintext);
94
+ return saved.ok ? ok(`${edit.key} saved in the fleet; apply with kayra apps ${server.name} after reviewing the change`) : saved;
95
+ }
96
+ // Vault receives plaintext over stdin; only ciphertext reaches a temporary file.
97
+ const encrypted = await spawned(["ansible-vault", "encrypt", "--output", "-"], { stdout: "capture", stderr: "capture", stdin: { kind: "given", text: plaintext } }, vault(server).env);
98
+ if (encrypted.code !== 0 || !isVaulted(encrypted.stdout))
99
+ return err("could not encrypt app secrets; the existing file was not changed");
100
+ const saved = store(file, original, encrypted.stdout);
101
+ return saved.ok ? ok(`${edit.key} saved in the fleet; apply with kayra apps ${server.name} after reviewing the change`) : saved;
102
+ };
103
+ export const editValues = async (root, server, name, edit, dir) => {
104
+ const required = requirements(root, server, name, textAt, dir);
105
+ if (!required.ok)
106
+ return required;
107
+ const keys = edit.kind === "config" ? required.value.config : required.value.secrets;
108
+ if (!keys.includes(edit.key))
109
+ return err(`${edit.key} is not a declared ${edit.kind === "config" ? "configuration" : "secret"} key`);
110
+ const directory = dirname(fileOf(server, name, edit.kind !== "config"));
111
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
112
+ if (lstatSync(directory).isSymbolicLink())
113
+ return err("refusing a symlinked apps directory");
114
+ const lock = join(directory, ".kayra-values.lock");
115
+ const acquired = attempt(() => { mkdirSync(lock, { mode: 0o700 }); return ok(true); }, () => "app values are being edited; retry, or remove apps/.kayra-values.lock if its writer was interrupted");
116
+ if (!acquired.ok)
117
+ return acquired;
118
+ try {
119
+ return await editFile(server, name, edit);
120
+ }
121
+ finally {
122
+ rmSync(lock, { recursive: true, force: true });
123
+ }
124
+ };
@@ -1,18 +1,23 @@
1
1
  import { z } from "zod";
2
2
  const deployed = z.object({ sha: z.string(), time: z.iso.datetime() });
3
+ /** One run, as `ctl runs --json` lists it and `ctl deploy --json` ends with it. */
4
+ export const runSchema = z.object({
5
+ id: z.string(),
6
+ state: z.enum(["queued", "running", "success", "failure", "superseded"]),
7
+ why: z.string(),
8
+ what: z.string(),
9
+ sha: z.string().exactOptional(),
10
+ started: z.iso.datetime(),
11
+ finished: z.iso.datetime().exactOptional(),
12
+ error: z.string().exactOptional(),
13
+ urls: z.array(z.string()).exactOptional(),
14
+ checks: z.array(z.object({ url: z.string(), status: z.number().int(), ok: z.boolean() })).exactOptional(),
15
+ });
3
16
  /** `ctl runs <app> --json`, as this kayra reads it. */
4
17
  export const runsSchema = z.object({
5
18
  app: z.string(),
6
19
  live: deployed.exactOptional(),
7
- runs: z.array(z.object({
8
- id: z.string(),
9
- state: z.enum(["running", "success", "failure"]),
10
- why: z.string(),
11
- what: z.string(),
12
- sha: z.string().exactOptional(),
13
- started: z.iso.datetime(),
14
- finished: z.iso.datetime().exactOptional(),
15
- })),
20
+ runs: z.array(runSchema),
16
21
  });
17
22
  /** `ctl rollback <app> --json`, as this kayra reads it. */
18
23
  export const releasesSchema = z.object({
@@ -4,13 +4,17 @@ import { z } from "zod";
4
4
  import { branded } from "../../lib/brand.js";
5
5
  import { err, ok } from "../../lib/result.js";
6
6
  import { minting } from "../../lib/schema.js";
7
- /** A string matching `regex`: brand it, and it is the schema the fleet's files are parsed with and the constructor everything else mints with. */
7
+ import { names } from "../../lib/names.js";
8
+ /** A string matching a name's pattern: brand it, and it is the schema the fleet's files are parsed with and the constructor everything else mints with. */
8
9
  // eslint-disable-next-line functional/prefer-immutable-types -- a RegExp, and a Zod schema: immutable once built, but classes the rule cannot see into
9
- const pattern = (regex, what) => z.string().regex(regex, { error: (issue) => `'${String(issue.input)}' is not ${what}` });
10
- export const serverNameSchema = pattern(/^[a-z0-9][a-z0-9-]*$/, "a server name (lowercase letters, digits, dashes)").transform(branded());
11
- export const appNameSchema = pattern(/^[a-z][a-z0-9-]*$/, "an app name (lowercase letters, digits, dashes)").transform(branded());
12
- export const subdomainSchema = pattern(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/, "a subdomain").transform(branded());
13
- export const domainSchema = pattern(/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*$/, "a domain").transform(branded());
10
+ const pattern = ({ pattern: regex, what }) => z.string().regex(regex, { error: (issue) => `'${String(issue.input)}' is not ${what}` });
11
+ export const serverNameSchema = pattern({ pattern: /^[a-z0-9][a-z0-9-]*$/, what: "a server name (lowercase letters, digits, dashes)" }).transform(branded());
12
+ export const appNameSchema = pattern(names.app).transform(branded());
13
+ export const subdomainSchema = pattern(names.subdomain).transform(branded());
14
+ export const routePathSchema = pattern(names.routePath).transform(branded());
15
+ export const serviceNameSchema = pattern(names.serviceName).transform(branded());
16
+ export const periodSchema = pattern(names.period).transform(branded());
17
+ export const domainSchema = pattern({ pattern: /^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*$/, what: "a domain" }).transform(branded());
14
18
  /** A path inside a repository, never above it. */
15
19
  export const repoPathSchema = z
16
20
  .string()
@@ -22,7 +26,6 @@ export const serverName = minting(serverNameSchema);
22
26
  export const appName = minting(appNameSchema);
23
27
  export const subdomain = minting(subdomainSchema);
24
28
  export const domain = minting(domainSchema);
25
- export const repoPath = minting(repoPathSchema);
26
29
  /** `~/…` is the operator's home, as Ansible reads it in vault_password_file. */
27
30
  export const absolutePath = (value) => {
28
31
  const expanded = value === "~" || value.startsWith("~/") ? join(homedir(), value.slice(1)) : value;
@@ -1,5 +1,5 @@
1
1
  import { absolutePath, host, sshDefaultPort, keyFile, port, remotePath, sshUser, vaultPasswordFile } from "./brand.js";
2
- import { err, map, ok } from "../../lib/result.js";
2
+ import { err, flatMap, map, ok } from "../../lib/result.js";
3
3
  import { serverSchema, varsSchema } from "./settings.js";
4
4
  import { checkSettings, knownSettings } from "./shape.js";
5
5
  import { typed } from "../../lib/typed.js";
@@ -118,6 +118,14 @@ export const parseServer = (files) => {
118
118
  const backupDir = typeof backup === "string" ? remotePath(backup) : ok(undefined);
119
119
  if (!backupDir.ok)
120
120
  return err(`vars.yml: restic_backup.dir ${backupDir.error}`);
121
+ const nasRoot = vars.value["nas_root"];
122
+ const versionFile = kind !== "nas"
123
+ ? remotePath("/opt/kayra/version")
124
+ : typeof nasRoot === "string"
125
+ ? flatMap(remotePath(nasRoot), (dir) => remotePath(`${dir}/.kayra/version`))
126
+ : ok(undefined);
127
+ if (!versionFile.ok)
128
+ return err(`vars.yml: nas_root ${versionFile.error}`);
121
129
  const inventory = files.inventory === undefined ? ok(undefined) : inventoryOf(files.inventory);
122
130
  if (!inventory.ok)
123
131
  return inventory;
@@ -137,6 +145,7 @@ export const parseServer = (files) => {
137
145
  usesAcmeDns: typeof vars.value["acme_dns"] === "string" && vars.value["acme_dns"] !== "",
138
146
  inventory: inventory.value,
139
147
  backupDir: backupDir.value,
148
+ versionFile: versionFile.value,
140
149
  stackHosts: stackHosts(files.stacks.flatMap((stack) => Object.freeze(stack.compose ?? [])), domain),
141
150
  vars: vars.value,
142
151
  files: { vars: files.vars, secrets: files.secrets, stacks: files.stacks.map((stack) => stack.name), appValues: files.appValues },
@@ -1,12 +1,10 @@
1
1
  import { z } from "zod";
2
2
  import { typed } from "../../lib/typed.js";
3
- import { appNameSchema, domainSchema, repoPathSchema, repoUrlSchema, subdomainSchema } from "./brand.js";
3
+ import { appNameSchema, domainSchema, periodSchema, repoPathSchema, repoUrlSchema, routePathSchema, serviceNameSchema, subdomainSchema } from "./brand.js";
4
4
  import { serverTargets } from "./model.js";
5
5
  /** The server kinds, each with its playbook; settings say which kinds read them. */
6
6
  export const serverKinds = ["platform", "edge", "nas"];
7
- // eslint-disable-next-line functional/prefer-immutable-types -- holds a Zod schema: immutable once built, but a class the rule cannot see into
8
7
  const setting = (name, kinds, schema, description) => typed({ name, kinds, secret: false, schema: schema.describe(description), description });
9
- // eslint-disable-next-line functional/prefer-immutable-types -- holds a Zod schema: immutable once built, but a class the rule cannot see into
10
8
  const secret = (name, kinds, schema, description) => typed({ name, kinds, secret: true, schema: schema.describe(description), description });
11
9
  const text = z.string();
12
10
  const texts = z.array(z.string());
@@ -26,6 +24,8 @@ export const settings = [
26
24
  setting("authelia_smtp_username", platform, text, "SMTP user for Authelia."),
27
25
  setting("authelia_smtp_sender", platform, text, "Sender address of Authelia's mails."),
28
26
  setting("acme_dns", platform, z.enum(["", "hetzner"]), "Certificates by DNS-01 instead of HTTP-01, for a server the internet never reaches: the DNS provider (hetzner)."),
27
+ setting("webhooks", platform, z.boolean(), "Whether a push webhook may start a deploy at once: true (default) serves deploy.<domain>/hook/<app>; false serves no such endpoint, and pushes deploy by deploy_poll."),
28
+ setting("deploy_poll", platform, text, "When the deployer looks for pushes no webhook brought, as a five-field cron spec in the server's time (default hourly: 17 * * * *)."),
29
29
  setting("renovate_repositories", platform, texts, "owner/repo of the repos this server's Renovate job keeps up to date; the job runs only where the list is not empty."),
30
30
  setting("renovate_schedule", platform, text, "When the Renovate job runs, as a five-field cron spec in the server's time (default weekly: 0 4 * * 1)."),
31
31
  setting("renovate_platform", platform, z.enum(["github", "forgejo", "gitlab"]), "Where the repos live: github (default), forgejo or gitlab."),
@@ -106,7 +106,7 @@ export const settings = [
106
106
  ];
107
107
  /** Ansible's own variables (connection, privilege escalation) are always allowed. */
108
108
  export const isAnsibleVariable = (key) => key.startsWith("ansible_");
109
- export const settingsFor = (kind, secrets) => Object.freeze(settings.filter((each) => each.secret === secrets && each.kinds.includes(kind)));
109
+ const settingsFor = (kind, secrets) => Object.freeze(settings.filter((each) => each.secret === secrets && each.kinds.includes(kind)));
110
110
  // eslint-disable-next-line functional/prefer-immutable-types -- Zod schemas: immutable once built, but classes the rule cannot see into
111
111
  const shape = (chosen) => Object.fromEntries(chosen.map((each) => [each.name, each.schema.optional()]));
112
112
  /** vars.yml for a kind: its settings and nothing else (Ansible's own variables apart). */
@@ -123,6 +123,13 @@ export const secretsSchema = (kind) => z.looseObject(shape(settingsFor(kind, tru
123
123
  */
124
124
  const schemes = (target) => typed(target === "multipass" ? ["https://", "http://"] : ["https://"]);
125
125
  /** server.yml: topology only. What it says is checked here, once: the parser, the editors' schema and the docs read it. */
126
+ /** One app in server.yml: where its code is and which branch deploys. */
127
+ export const appEntrySchema = z.strictObject({
128
+ name: appNameSchema,
129
+ repo: repoUrlSchema.describe("The app's repository, https://."),
130
+ ref: z.string().optional().describe("The branch to build and deploy (default main)."),
131
+ path: repoPathSchema.prefault(".").describe("The app's root inside the repository (default .)."),
132
+ });
126
133
  export const serverSchema = z
127
134
  .strictObject({
128
135
  kind: z
@@ -136,12 +143,7 @@ export const serverSchema = z
136
143
  vault: z.boolean().default(false).describe("secrets.yml is vault-encrypted (required outside multipass)."),
137
144
  vault_password_file: z.string().optional().describe("The vault password file; without it, Ansible asks."),
138
145
  apps: z
139
- .array(z.strictObject({
140
- name: appNameSchema,
141
- repo: repoUrlSchema.describe("The app's repository, https://."),
142
- ref: z.string().optional().describe("The branch to build and deploy (default main)."),
143
- path: repoPathSchema.prefault(".").describe("The app's root inside the repository (default .)."),
144
- }))
146
+ .array(appEntrySchema)
145
147
  .default([])
146
148
  .describe("The apps this server runs (platform only)."),
147
149
  })
@@ -157,11 +159,29 @@ export const serverSchema = z
157
159
  });
158
160
  });
159
161
  });
162
+ /** One of an app's public routes: the platform writes its Traefik router, the app no label. */
163
+ const routeSchema = z.strictObject({
164
+ host: subdomainSchema.describe("Its hostname, <host>.<domain>. The app's hosts are its routes' hosts."),
165
+ path: routePathSchema.optional().describe("A path prefix: the route answers below it, and beats its host's route without one."),
166
+ service: serviceNameSchema.describe("The compose service that answers it."),
167
+ port: z.number().int().min(1).max(65535).describe("The port that service listens on, inside its container."),
168
+ rate_limit: z
169
+ .strictObject({
170
+ average: z.number().int().positive().describe("Requests a client may send per period, on average."),
171
+ period: periodSchema.describe("The period, such as 10s, 10m or 1h."),
172
+ burst: z.number().int().positive().describe("Requests a client may send at once beyond the average."),
173
+ })
174
+ .optional()
175
+ .describe("A rate limit on this route, per client address (Traefik's rateLimit)."),
176
+ check: routePathSchema
177
+ .optional()
178
+ .describe("A path that answers 2xx or 3xx once the app is ready; a deploy waits for it. Without one, the route's own path must answer below 500."),
179
+ });
160
180
  /** app.yml, at the root of an app's repository: the app contract. */
161
181
  export const appManifestSchema = z.strictObject({
162
182
  name: appNameSchema.describe("The app's name, as in the server.yml entry."),
163
- compose: z.array(z.string()).describe("Compose files, relative to the app root, in order."),
164
- subdomains: z.array(subdomainSchema).describe("Hostnames the app claims: <sub>.<domain>."),
183
+ compose: z.array(z.string()).describe("Compose files, relative to the app root, in order. No Traefik label, no platform network: routes say how the app is reached."),
184
+ routes: z.array(routeSchema).optional().describe("How the app is reached: each route a host (and path) to a service's port. Read at the commit being deployed; a new host needs kayra apps."),
165
185
  secrets: z.array(z.string()).optional().describe("Secret keys; their values come from the fleet's apps/<app>.secrets.yml."),
166
186
  config: z.array(z.string()).optional().describe("Config keys; their values come from the fleet's apps/<app>.yml."),
167
187
  });