@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
@@ -21,8 +21,26 @@ export const fromCommand = (command) => {
21
21
  return plainly({ name: "backup.test", input: { server: command.server } });
22
22
  case "ssh":
23
23
  return plainly(command.remote.length === 0 ? { name: "ssh", input: { server: command.server } } : { name: "ssh.exec", input: { server: command.server, command: command.remote } });
24
+ case "app init":
25
+ return plainly({ name: "app.init", input: { dir: command.dir ?? ".", ...(command.appName === undefined ? {} : { name: command.appName }) } });
24
26
  case "app check":
25
27
  return plainly({ name: "app.check", input: { dir: command.dir ?? "." } });
28
+ case "app hook":
29
+ return plainly({ name: "app.hook", input: { server: command.server, app: command.app } });
30
+ case "app launch":
31
+ return plainly({ name: "app.launch", input: {
32
+ server: command.server, app: command.app,
33
+ ...(command.repo === undefined ? {} : { repo: command.repo }), ...(command.ref === undefined ? {} : { ref: command.ref }),
34
+ ...(command.path === undefined ? {} : { path: command.path }), ...(command.dir === undefined ? {} : { dir: command.dir }),
35
+ } });
36
+ case "app values":
37
+ return typed({ invocation: { name: "app.values", input: { server: command.server, app: command.app, ...(command.dir === undefined ? {} : { dir: command.dir }) } }, json: command.json });
38
+ case "app config set":
39
+ return plainly({ name: "app.config.set", input: { server: command.server, app: command.app, ...(command.dir === undefined ? {} : { dir: command.dir }), key: command.key, value: command.value } });
40
+ case "app secret import":
41
+ return plainly({ name: "app.secret.import", input: { server: command.server, app: command.app, ...(command.dir === undefined ? {} : { dir: command.dir }), key: command.key, file: command.file } });
42
+ case "app secret generate":
43
+ return plainly({ name: "app.secret.generate", input: { server: command.server, app: command.app, ...(command.dir === undefined ? {} : { dir: command.dir }), key: command.key } });
26
44
  case "app purge":
27
45
  return plainly({ name: "app.purge", input: { server: command.server, app: command.app } });
28
46
  case "app runs":
@@ -67,7 +85,14 @@ export const reaches = {
67
85
  down: ["down", "SERVER"],
68
86
  adopt: ["adopt", "SERVER"],
69
87
  "backup.test": ["backup", "test", "SERVER"],
88
+ "app.init": ["app", "init", ".", "--name", "shop"],
70
89
  "app.check": ["app", "check", "."],
90
+ "app.hook": ["app", "hook", "SERVER", "APP"],
91
+ "app.launch": ["app", "launch", "SERVER", "APP", "--repo", "https://github.com/OWNER/APP.git", "--dir", "."],
92
+ "app.values": ["app", "values", "SERVER", "APP"],
93
+ "app.config.set": ["app", "config", "set", "SERVER", "APP", "PUBLIC_URL", "https://example.com"],
94
+ "app.secret.import": ["app", "secret", "import", "SERVER", "APP", "API_KEY", "/tmp/credential"],
95
+ "app.secret.generate": ["app", "secret", "generate", "SERVER", "APP", "DATABASE_PASSWORD"],
71
96
  "app.purge": ["app", "purge", "SERVER", "APP"],
72
97
  "app.runs": ["app", "runs", "SERVER", "APP"],
73
98
  "app.log": ["app", "logs", "SERVER", "APP"],
@@ -5,7 +5,6 @@ import { choice, integer, string } from "@optique/core/valueparser";
5
5
  import { appNameParser, domainParser, serverNameParser, subdomainParser } from "./values.js";
6
6
  import { operation } from "../../core/operations/catalog.js";
7
7
  /** A command's one line, as the catalog says it: the same words in every client. */
8
- // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message is readonly only at the top
9
8
  const summary = (name) => message `${text(operation(name).summary)}`;
10
9
  /** Command lines, each with what it is for, aligned. Plain text: Optique folds an indent that stands alone before a command line. */
11
10
  const examples = (indent, rows) => {
@@ -40,7 +39,7 @@ export const runOptions = (version) => Object.freeze(({
40
39
  // The option form's ARG cannot be hidden from the help page; completion scripts call the command.
41
40
  completion: { command: { group: "Help" } },
42
41
  brief: message `kayra ${text(version)}: a fleet's servers, from the machine to the apps on it.`,
43
- description: message `Run it anywhere inside a fleet (the directory holding servers/); app check also outside one. Server names are the fleet's and complete in the shell.`,
42
+ description: message `Run it anywhere inside a fleet (the directory holding servers/); app init and app check also outside one. Server names are the fleet's and complete in the shell.`,
44
43
  examples: examples("", [
45
44
  ["kayra status", "every server, and whether it answers"],
46
45
  ["kayra up shop-test", "a server from nothing"],
@@ -64,10 +63,10 @@ export const parser = (fleet) => {
64
63
  // Outside a fleet there is no name to offer; main refuses every server command there.
65
64
  // Help adds the fleet's servers to its description (showChoices): kept short so they fit beside it.
66
65
  const server = argument(first === undefined ? serverNameParser : choice([first, ...rest], { metavar: "SERVER", suggest: "nearest" }), { description: message `A server` });
66
+ const valuesDir = optional(option("--dir", string({ metavar: "DIR" }), { description: message `Local app directory; otherwise use the fleet cache.` }));
67
67
  const app = argument(appNameParser, { description: message `An app in the server's server.yml.` });
68
- // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message is readonly only at the top
69
68
  const onServer = (name, brief, more = {}) => command(name, object({ name: constant(name), server }), { brief, ...more });
70
- return Object.freeze(merge(group("Options", object({
69
+ return merge(group("Options", object({
71
70
  dryRun: option("--dry-run", { description: message `Print the plan instead of running it.` }),
72
71
  verbose: option("-v", "--verbose", {
73
72
  description: message `Ansible's own output (with -v) instead of kayra's summary.`,
@@ -99,13 +98,31 @@ export const parser = (fleet) => {
99
98
  }), onServer("adopt", summary("adopt")), command("backup", command("test", object({ name: constant("backup test"), server })), {
100
99
  brief: summary("backup.test"),
101
100
  footer: footer(["kayra backup test nas", "started on the server, followed over SSH"]),
102
- }))), group("Apps on a server", or(command("app", or(group("In an app's repository", command("check", object({
101
+ }))), group("Apps on a server", or(command("app", or(group("In an app's repository", or(command("init", object({
102
+ name: constant("app init"),
103
+ dir: optional(argument(string({ metavar: "DIR" }), { description: message `The project's repository; the current directory by default.` })),
104
+ appName: optional(option("--name", string({ metavar: "NAME" }), { description: message `The app's name; the directory's by default.` })),
105
+ }), {
106
+ brief: summary("app.init"),
107
+ footer: footer(["kayra app init", "in a project with a compose file or a Dockerfile, once"]),
108
+ }), command("check", object({
103
109
  name: constant("app check"),
104
110
  dir: optional(argument(string({ metavar: "DIR" }), { description: message `The app's repository; the current directory by default.` })),
105
111
  }), {
106
112
  brief: summary("app.check"),
107
113
  footer: footer(["kayra app check", "in the app's repository, before a push"]),
108
- })), group("On a server", or(command("purge", object({ name: constant("app purge"), server, app }), {
114
+ }))), group("On a server", or(command("hook", object({ name: constant("app hook"), server, app }), { brief: summary("app.hook") }), command("launch", object({
115
+ name: constant("app launch"), server, app, dir: valuesDir,
116
+ repo: optional(option("--repo", string({ metavar: "URL" }), { description: message `The app's repository, https://; needed until server.yml registers it.` })),
117
+ ref: optional(option("--ref", string({ metavar: "REF" }), { description: message `The branch that deploys; main by default.` })),
118
+ path: optional(option("--path", string({ metavar: "PATH" }), { description: message `The app's root inside the repository; . by default.` })),
119
+ }), { brief: summary("app.launch"), footer: footer(["kayra app launch shop-prod shop --repo https://github.com/OWNER/shop.git --dir .", "register, check values, apply, deploy; again after a stop"]) }), command("values", object({ name: constant("app values"), server, app, dir: valuesDir, json: option("--json") }), { brief: summary("app.values") }), command("config", command("set", object({
120
+ name: constant("app config set"), server, app, dir: valuesDir,
121
+ key: argument(string({ metavar: "KEY" })), value: argument(string({ metavar: "VALUE" })),
122
+ }), { brief: summary("app.config.set") })), command("secret", or(command("import", object({
123
+ name: constant("app secret import"), server, app, dir: valuesDir,
124
+ key: argument(string({ metavar: "KEY" })), file: argument(string({ metavar: "FILE" })),
125
+ }), { brief: summary("app.secret.import") }), command("generate", object({ name: constant("app secret generate"), server, app, dir: valuesDir, key: argument(string({ metavar: "KEY" })) }), { brief: summary("app.secret.generate") }))), command("purge", object({ name: constant("app purge"), server, app }), {
109
126
  brief: summary("app.purge"),
110
127
  }), command("runs", object({ name: constant("app runs"), server, app }), {
111
128
  brief: summary("app.runs"),
@@ -180,5 +197,5 @@ export const parser = (fleet) => {
180
197
  }), {
181
198
  brief: summary("certs"),
182
199
  footer: footer(["kayra certs shop.test www api", "into the fleet's .cache/certs"]),
183
- })))), (chosen) => ({ command: chosen }))));
200
+ })))), (chosen) => ({ command: chosen })));
184
201
  };
@@ -46,8 +46,23 @@ const said = (reach, frame) => {
46
46
  };
47
47
  const sshCell = (reach, frame) => (reach.kind === "refused" ? typed([warn("off")]) : said(reach, frame));
48
48
  const httpsCell = (reach, frame, url) => Object.freeze(said(reach, frame).map((span, index) => (index === 0 && typeof span !== "string" ? link(span.text, url, span.tone) : span)));
49
- const headings = ["SERVER", "KIND", "TARGET", "DOMAIN", "ADDRESS", "SSH", "HTTPS", "APPS"];
50
- const probed = ["SSH", "HTTPS"];
49
+ /** The kayra that set the server up; where it is not the pin, the pin after it: what a setup would make it. */
50
+ const kayraCell = (running, pin, frame) => {
51
+ switch (running.kind) {
52
+ case "pending":
53
+ return waiting(frame, pin.length);
54
+ case "skipped":
55
+ return typed([muted("–")]);
56
+ case "recorded":
57
+ return running.version === pin ? typed([fine(running.version)]) : typed([warn(running.version), muted(` → ${pin}`)]);
58
+ case "unrecorded":
59
+ return typed([warn("unrecorded"), muted(` → ${pin}`)]);
60
+ case "unreadable":
61
+ return typed([bad("unreadable")]);
62
+ }
63
+ };
64
+ const headings = ["SERVER", "KIND", "TARGET", "DOMAIN", "ADDRESS", "SSH", "HTTPS", "KAYRA", "APPS"];
65
+ const probed = ["SSH", "HTTPS", "KAYRA"];
51
66
  const row = (look, frame) => {
52
67
  const { server } = look;
53
68
  return typed([
@@ -58,6 +73,7 @@ const row = (look, frame) => {
58
73
  machineCell(look.machine, frame),
59
74
  sshCell(look.ssh, frame),
60
75
  look.https === undefined ? [] : httpsCell(look.https, frame, authUrl(server)),
76
+ kayraCell(look.kayra, look.pin, frame),
61
77
  [server.apps.map((app) => app.name).join(", ")],
62
78
  ]);
63
79
  };
@@ -65,11 +81,16 @@ const row = (look, frame) => {
65
81
  export const statusView = (looks, drawing) => {
66
82
  const shown = headings.flatMap((heading, index) => (drawing.offline && probed.includes(heading) ? Object.freeze([]) : Object.freeze([index])));
67
83
  const rows = [headings.map((heading) => Object.freeze([muted(heading)])), ...looks.map((look) => row(look, drawing.frame))].map((cells) => Object.freeze(shown.map((index) => cells[index] ?? [])));
68
- const notes = looks.flatMap((look) => typed(look.machine.kind === "unreadable" ? [
69
- [" ", bad("✗"), " ", strong(look.server.name), `: OpenTofu's state could not be read: ${look.machine.reason}`],
70
- ...(look.machine.reason === "tofu init needed"
71
- ? [pointing(" ", `tofu -chdir=servers/${look.server.name}/terraform init`)]
84
+ const notes = looks.flatMap((look) => typed([
85
+ ...(look.machine.kind === "unreadable" ? [
86
+ typed([" ", bad("✗"), " ", strong(look.server.name), `: OpenTofu's state could not be read: ${look.machine.reason}`]),
87
+ ...(look.machine.reason === "tofu init needed"
88
+ ? [pointing(" ", `tofu -chdir=servers/${look.server.name}/terraform init`)]
89
+ : []),
90
+ ] : []),
91
+ ...(look.kayra.kind === "unreadable"
92
+ ? [typed([" ", bad("✗"), " ", strong(look.server.name), `: which kayra set it up could not be read: ${look.kayra.reason}`])]
72
93
  : []),
73
- ] : []));
94
+ ]));
74
95
  return typed([...table(fit(rows, drawing.room, [shown.length - 1, shown.indexOf(3)])), ...(notes.length === 0 ? [] : [[], ...notes])]);
75
96
  };
@@ -37,13 +37,13 @@ export const ago = (ms) => {
37
37
  const hours = Math.floor(minutes / 60);
38
38
  return hours < 48 ? `${String(hours)}h ago` : `${String(Math.floor(hours / 24))}d ago`;
39
39
  };
40
- /** Rows of cells in columns as wide as their widest cell, two spaces apart; nothing trails a row's last cell. */
41
40
  /** Each column as wide as its widest cell. */
42
41
  const columnWidths = (rows) => rows.reduce((most, row) => Object.freeze(Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? [])))), []);
42
+ /** Rows of cells in columns as wide as their widest cell, two spaces apart; nothing trails a row's last cell. */
43
43
  export const table = (rows) => {
44
44
  const filled = rows.map((row) => Object.freeze(row.slice(0, row.findLastIndex((cell) => width(cell) > 0) + 1)));
45
45
  const widths = columnWidths(filled);
46
- return Object.freeze(filled.map((row) => Object.freeze(row.flatMap((cell, at) => (at === row.length - 1 ? cell : typed([...cell, " ".repeat((widths[at] ?? 0) - width(cell) + 2)]))))));
46
+ return typed(filled.map((row) => Object.freeze(row.flatMap((cell, at) => (at === row.length - 1 ? cell : typed([...cell, " ".repeat((widths[at] ?? 0) - width(cell) + 2)]))))));
47
47
  };
48
48
  /**
49
49
  * Rows for table() that fit `room` columns: the cells of the columns in
@@ -58,7 +58,7 @@ export const fit = (rows, room, shrink) => {
58
58
  const less = Math.min(Math.max(0, so.over), Math.max(0, now - width(rows[0]?.[at] ?? [])));
59
59
  return { widths: Object.freeze(so.widths.with(at, now - less)), over: so.over - less };
60
60
  }, { widths, over }).widths;
61
- return Object.freeze(rows.map((row) => Object.freeze(row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))))));
61
+ return typed(rows.map((row) => Object.freeze(row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))))));
62
62
  };
63
63
  /** Paths by the root they are under, the longest first: the engine may live inside the fleet. */
64
64
  export const shortener = (roots) => (text) => roots.toSorted(([a], [b]) => b.length - a.length).reduce((short, [path, name]) => short.replaceAll(path, name), text);
@@ -6,7 +6,6 @@ const minting = (metavar, mint, placeholder) => typed({
6
6
  mode: "sync",
7
7
  metavar,
8
8
  placeholder,
9
- // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message: readonly by contract, but a type the rule cannot see into
10
9
  parse: (input) => {
11
10
  const minted = mint(input);
12
11
  return minted.ok ? { success: true, value: minted.value } : { success: false, error: [text(minted.error)] };
@@ -16,6 +16,13 @@ const states = {
16
16
  success: [ok("✓ success")],
17
17
  failure: [bad("✗ failure")],
18
18
  running: [active("◆ running")],
19
+ queued: [muted("… queued")],
20
+ superseded: [muted("↷ superseded")],
21
+ };
22
+ /** Why the newest run failed, under the table: the first thing to know after a failed deploy. */
23
+ const newestError = (answer) => {
24
+ const [newest] = answer.runs;
25
+ return typed(newest?.state === "failure" && newest.error !== undefined ? [[" ", bad(`✗ ${newest.error}`)], []] : []);
19
26
  };
20
27
  const took = (run, now) => typed(run.finished === undefined ? [active(`${duration(milliseconds(now - Date.parse(run.started)))}…`)] : [duration(milliseconds(Date.parse(run.finished) - Date.parse(run.started)))]);
21
28
  const commit = (run, release) => {
@@ -34,7 +41,7 @@ export const runsView = (view, answer, now) => {
34
41
  [],
35
42
  ...(answer.runs.length === 0
36
43
  ? [[" ", muted("no runs yet")]]
37
- : [...rows.map((row) => typed([" ", ...row])), [], hint(`kayra app logs ${view.server} ${view.app} [RUN]`, "shows a run's log, the newest by default")]),
44
+ : [...rows.map((row) => typed([" ", ...row])), [], ...newestError(answer), hint(`kayra app logs ${view.server} ${view.app} [RUN]`, "shows a run's log, the newest by default")]),
38
45
  ]);
39
46
  };
40
47
  /** `kayra app rollback` without a commit: every release, the live one marked, and how to go back to one. */
@@ -42,7 +49,7 @@ export const releasesView = (view, answer, now) => {
42
49
  const earlier = answer.releases.find((release) => !release.live);
43
50
  const rows = table([
44
51
  [[muted(" COMMIT")], [muted("DEPLOYED")]],
45
- ...answer.releases.map((release) => Object.freeze([
52
+ ...answer.releases.map((release) => typed([
46
53
  release.live ? [ok("●"), " ", accent(short(release.sha))] : [" ", short(release.sha)],
47
54
  [since(release.time, now)],
48
55
  release.live ? [ok("live")] : [],
@@ -21,7 +21,14 @@ export const reaches = {
21
21
  down: { tool: "down" },
22
22
  adopt: { tool: "adopt" },
23
23
  "backup.test": { tool: "backup_test" },
24
+ "app.init": { tool: "app_init" },
24
25
  "app.check": { tool: "app_check" },
26
+ "app.values": { tool: "app_values" },
27
+ "app.launch": { tool: "app_launch" },
28
+ "app.hook": { tool: "app_hook" },
29
+ "app.config.set": { tool: "app_config_set" },
30
+ "app.secret.import": { tool: "app_secret_import" },
31
+ "app.secret.generate": { tool: "app_secret_generate" },
25
32
  "app.purge": { tool: "app_purge" },
26
33
  "app.runs": { tool: "app_runs" },
27
34
  "app.log": { tool: "app_log" },
@@ -51,7 +58,7 @@ const effectSaid = (each) => {
51
58
  return "Changes nothing.";
52
59
  if (each.effect === "destroys")
53
60
  return "Irreversible: the operator approves every call, and types the server's name before it runs.";
54
- return each.scope === "fleet" || each.scope === "repo"
61
+ return each.local === true || each.scope === "fleet" || each.scope === "repo"
55
62
  ? "Changes files on this machine."
56
63
  : "Changes the server: on one that is not multipass, the operator approves it first.";
57
64
  };
@@ -8,6 +8,7 @@ const types = {
8
8
  ".png": "image/png",
9
9
  ".ico": "image/x-icon",
10
10
  ".woff2": "font/woff2",
11
+ ".woff": "font/woff",
11
12
  ".json": "application/json; charset=utf-8",
12
13
  };
13
14
  const unbuilt = `<!doctype html><meta charset="utf-8"><title>kayra</title>
@@ -1,10 +1,10 @@
1
1
  import { z } from "zod";
2
- import { operations, operationNames } from "../../core/operations/catalog.js";
2
+ import { operations, operationNames, operation } from "../../core/operations/catalog.js";
3
3
  import { options, schemas } from "./schemas.js";
4
4
  import { typed } from "../../lib/typed.js";
5
5
  export const catalog = () => Object.freeze(operationNames.map((name) => {
6
6
  const { summary, scope, effect, kind, input } = operations[name];
7
- return { name, summary, scope, effect, kind, input: z.toJSONSchema(input, { io: "input" }) };
7
+ return { name, summary, scope, effect, kind, local: operation(name).local === true, input: z.toJSONSchema(input, { io: "input" }) };
8
8
  }));
9
9
  const isObject = (value) => typeof value === "object" && value !== null;
10
10
  const object = (value) => isObject(value) ? value : typed({});
@@ -11,6 +11,7 @@ const data = (schema, text) => {
11
11
  return value === undefined ? err("the deployer returned an unreadable answer") : ok(value);
12
12
  };
13
13
  const queries = {
14
+ "app.values": (context, input) => query(context, "app.values", input),
14
15
  validate: async (context, input) => map(await query(context, "validate", input), validateJson),
15
16
  version: (context, input) => query(context, "version", input),
16
17
  "app.runs": async (context, input) => data(runsSchema, await query(context, "app.runs", input)),
@@ -1,10 +1,11 @@
1
1
  import { z } from "zod";
2
+ import { valuesReportSchema } from "../../core/app-values/model.js";
2
3
  import { effects, kinds, operationNames, scopes } from "../../core/operations/catalog.js";
3
4
  import { serverKinds } from "../../core/fleet/settings.js";
4
5
  import { serverTargets } from "../../core/fleet/model.js";
5
6
  import { parts } from "../../core/plan/model.js";
6
7
  import { stopReasons } from "../../core/interpreter/progress.js";
7
- import { machineStates, reachStates } from "../../core/status/model.js";
8
+ import { machineStates, reachStates, runningStates } from "../../core/status/model.js";
8
9
  import { tones } from "../../core/text/spans.js";
9
10
  import { verdicts } from "../../core/validation/findings.js";
10
11
  import { releasesSchema, runsSchema } from "../../core/ctl/answers.js";
@@ -57,11 +58,14 @@ export const schemas = {
57
58
  machine: z.object({ state: z.enum(machineStates), address: z.string().nullable(), from: z.enum(["inventory", "opentofu"]).nullable(), reason: z.string().nullable() }),
58
59
  ssh: z.object({ port: z.number(), state: reach, ms: z.number().nullable(), error: z.string().nullable() }),
59
60
  https: z.object({ url: z.string(), state: reach, status: z.number().nullable(), ms: z.number().nullable(), error: z.string().nullable() }).nullable(),
61
+ kayra: z.object({ pin: z.string(), state: z.enum(runningStates), version: z.string().nullable(), error: z.string().nullable() }),
60
62
  })) }),
61
63
  Validation: z.object({ result: verdict, servers: z.array(z.object({ name: z.string(), kind: z.string(), target: z.string(), result: verdict, findings: z.array(z.object({ result: verdict, text: z.string(), hint: z.string().nullable() })) })) }),
64
+ AppValues: valuesReportSchema,
62
65
  AppRuns: runsSchema, AppReleases: releasesSchema,
63
- OperationInfo: z.object({ name: z.enum(operationNames), summary: z.string(), scope: z.enum(scopes), effect: z.enum(effects), kind: z.enum(kinds), input: z.record(z.string(), z.unknown()) }),
66
+ OperationInfo: z.object({ name: z.enum(operationNames), summary: z.string(), scope: z.enum(scopes), effect: z.enum(effects), kind: z.enum(kinds), local: z.boolean(), input: z.record(z.string(), z.unknown()) }),
64
67
  };
65
68
  export const querySchemas = {
69
+ "app.values": schemas.AppValues,
66
70
  validate: schemas.Validation, version: z.string(), "app.runs": schemas.AppRuns, "app.releases": schemas.AppReleases, "app.log": z.string(),
67
71
  };
@@ -3,7 +3,7 @@ export const ms = (reach) => ("ms" in reach ? reach.ms : null);
3
3
  const error = (reach) => ("code" in reach ? reach.code : null);
4
4
  /** `kayra status --json`: the shape cli.md documents. */
5
5
  export const statusJson = (looks) => ({
6
- servers: looks.map(({ server, machine, ssh, https }) => ({
6
+ servers: looks.map(({ server, machine, ssh, https, kayra, pin }) => ({
7
7
  name: server.name,
8
8
  kind: server.kind,
9
9
  target: server.target,
@@ -25,5 +25,11 @@ export const statusJson = (looks) => ({
25
25
  ms: ms(https),
26
26
  error: error(https),
27
27
  },
28
+ kayra: {
29
+ pin,
30
+ state: kayra.kind,
31
+ version: kayra.kind === "recorded" ? kayra.version : null,
32
+ error: kayra.kind === "unreadable" ? kayra.reason : null,
33
+ },
28
34
  })),
29
35
  });
@@ -1,6 +1,18 @@
1
1
  /** What follows the server and the app on the command line, by operation. */
2
2
  const extra = (call) => {
3
3
  switch (call.name) {
4
+ case "app.config.set":
5
+ return [call.input.key, call.input.value, ...(call.input.dir === undefined ? [] : ["--dir", call.input.dir])];
6
+ case "app.secret.import":
7
+ return [call.input.key, call.input.file, ...(call.input.dir === undefined ? [] : ["--dir", call.input.dir])];
8
+ case "app.secret.generate":
9
+ return [call.input.key, ...(call.input.dir === undefined ? [] : ["--dir", call.input.dir])];
10
+ case "app.values":
11
+ return call.input.dir === undefined ? [] : ["--dir", call.input.dir];
12
+ case "app.hook":
13
+ return [];
14
+ case "app.launch":
15
+ return ["repo", "ref", "path", "dir"].flatMap((key) => (call.input[key] === undefined ? [] : [`--${key}`, call.input[key]]));
4
16
  case "ssh.exec":
5
17
  return ["--", ...call.input.command];
6
18
  case "job":
@@ -13,6 +25,8 @@ const extra = (call) => {
13
25
  return call.input.run === undefined ? [] : [call.input.run];
14
26
  case "app.check":
15
27
  return [call.input.dir];
28
+ case "app.init":
29
+ return [call.input.dir, ...(call.input.name === undefined ? [] : ["--name", call.input.name])];
16
30
  case "certs":
17
31
  return [call.input.domain, ...call.input.subdomains];
18
32
  case "up":
@@ -1,7 +1,11 @@
1
+ import { execFile } from "node:child_process";
1
2
  import { Agent, request } from "node:https";
2
3
  import { connect } from "node:net";
3
4
  import { getCACertificates } from "node:tls";
4
5
  import { milliseconds } from "../fleet/brand.js";
6
+ import { quote } from "../plan/describe.js";
7
+ import { sshArgv } from "../recipes/ssh.js";
8
+ import { err, ok } from "../../lib/result.js";
5
9
  import { typed } from "../../lib/typed.js";
6
10
  /** Why a connection failed, by Node's error code. */
7
11
  export const failure = (code) => {
@@ -19,7 +23,12 @@ export const failure = (code) => {
19
23
  };
20
24
  const codeOf = (error) => typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "ERROR";
21
25
  const since = (started) => milliseconds(Math.round(performance.now() - started));
22
- /** The network, as status asks it: a TCP connect, an HTTPS GET, each given up after `ms`; every answer a Reach, never an exception. */
26
+ /**
27
+ * The network, as status asks it: a TCP connect, an HTTPS GET, each given up
28
+ * after `ms`, every answer a Reach, never an exception; and a file read over
29
+ * SSH, which never asks (no password, no host key to confirm: rebuilt servers
30
+ * come back with new ones) and is given up after three times `ms`.
31
+ */
23
32
  export const network = (ms) => {
24
33
  // A multipass server's certificates are mkcert's, whose root is in the system's store, not Node's.
25
34
  // Reading it takes a while: after the first frame, not before.
@@ -63,5 +72,15 @@ export const network = (ms) => {
63
72
  asked.end();
64
73
  });
65
74
  },
75
+ read: (inventory, path) => new Promise((resolve) => {
76
+ const [program, ...args] = sshArgv(inventory, ["-o", "BatchMode=yes", "-o", `ConnectTimeout=${String(Math.ceil(ms / 1000))}`, "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "LogLevel=ERROR"], [`cat ${quote(path)} 2>/dev/null || true`]);
77
+ execFile(program, args, { timeout: ms * 3, killSignal: "SIGKILL" }, (error, stdout, stderr) => {
78
+ const said = stderr.trim().split("\n").at(-1) ?? "";
79
+ if (error === null)
80
+ resolve(ok(stdout));
81
+ else
82
+ resolve(err(error.killed ? "no answer" : said === "" ? `ssh exited ${String(error.code ?? "")}` : said));
83
+ });
84
+ }),
66
85
  });
67
86
  };
@@ -14,7 +14,7 @@ export const unreadable = (stderr) => {
14
14
  export const opentofu = {
15
15
  state: async (dir) => {
16
16
  const listed = await capture(["tofu", `-chdir=${dir}`, "state", "list", "-no-color"], "capture");
17
- return listed.code === 0 ? ok(listed.stdout.split("\n").filter((line) => line.trim() !== "")) : err(unreadable(listed.stderr));
17
+ return listed.code === 0 ? ok(Object.freeze(listed.stdout.split("\n").filter((line) => line.trim() !== ""))) : err(unreadable(listed.stderr));
18
18
  },
19
19
  output: async (dir, name) => {
20
20
  const value = await capture(["tofu", `-chdir=${dir}`, "output", "-raw", name], "capture");
@@ -0,0 +1,90 @@
1
+ import { err, ok } from "../../lib/result.js";
2
+ import { typed } from "../../lib/typed.js";
3
+ export const hookUrl = (domain, app) => `https://deploy.${domain}/hook/${app}`;
4
+ const field = (value, key) => typeof value === "object" && value !== null ? Object.entries(value).find(([name]) => name === key)?.[1] : undefined;
5
+ const hookOf = (url) => (value) => {
6
+ const id = field(value, "id");
7
+ const to = url(value);
8
+ return typeof id === "number" && typeof to === "string" ? typed({ id, url: to }) : undefined;
9
+ };
10
+ const listed = (answer, of) => Array.isArray(answer.json) ? Object.freeze(answer.json.flatMap((each) => { const hook = of(each); return hook === undefined ? Object.freeze([]) : Object.freeze([hook]); })) : typed([]);
11
+ const failed = (what, answer) => err(`${what}: HTTP ${String(answer.status)}${answer.status === 401 || answer.status === 403 || answer.status === 404 ? " (does the token have admin rights on the repository?)" : ""}`);
12
+ /**
13
+ * The three forges kayra knows, the same that the deployer verifies webhooks
14
+ * for: GitHub's X-Hub-Signature-256, Forgejo's (or Gitea's) signature, GitLab's
15
+ * secret token. Each hook is a JSON push hook to the deployer.
16
+ */
17
+ export const hookApi = (repo, http) => {
18
+ const json = { "Content-Type": "application/json" };
19
+ switch (repo.kind) {
20
+ case "github": {
21
+ const base = `https://api.github.com/repos/${repo.owner}/${repo.name}`;
22
+ const auth = (token) => typed({ Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" });
23
+ const of = hookOf((value) => field(field(value, "config"), "url"));
24
+ return {
25
+ readable: async (token) => { const answer = await http(base, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(true) : failed("the platform's git_token cannot read the repository", answer); },
26
+ hooks: async (token) => { const answer = await http(`${base}/hooks`, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(listed(answer, of)) : failed("listing the hooks", answer); },
27
+ save: async (token, url, secret, id) => {
28
+ const body = JSON.stringify({ active: true, events: ["push"], config: { url, content_type: "json", secret, insecure_ssl: "0" } });
29
+ const answer = await http(id === undefined ? `${base}/hooks` : `${base}/hooks/${String(id)}`, { method: id === undefined ? "POST" : "PATCH", headers: { ...auth(token), ...json }, body });
30
+ const hook = of(answer.json);
31
+ return answer.status < 300 && hook !== undefined ? ok(hook) : failed("saving the hook", answer);
32
+ },
33
+ };
34
+ }
35
+ case "forgejo": {
36
+ const base = `${repo.origin}/api/v1/repos/${repo.owner}/${repo.name}`;
37
+ const auth = (token) => typed({ Authorization: `token ${token}` });
38
+ const of = hookOf((value) => field(field(value, "config"), "url"));
39
+ return {
40
+ readable: async (token) => { const answer = await http(base, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(true) : failed("the platform's git_token cannot read the repository", answer); },
41
+ hooks: async (token) => { const answer = await http(`${base}/hooks`, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(listed(answer, of)) : failed("listing the hooks", answer); },
42
+ save: async (token, url, secret, id) => {
43
+ const config = { url, content_type: "json", secret };
44
+ const body = JSON.stringify(id === undefined ? { type: "gitea", active: true, events: ["push"], config } : { active: true, events: ["push"], config });
45
+ const answer = await http(id === undefined ? `${base}/hooks` : `${base}/hooks/${String(id)}`, { method: id === undefined ? "POST" : "PATCH", headers: { ...auth(token), ...json }, body });
46
+ const hook = of(answer.json);
47
+ return answer.status < 300 && hook !== undefined ? ok(hook) : failed("saving the hook", answer);
48
+ },
49
+ };
50
+ }
51
+ case "gitlab": {
52
+ const base = `${repo.origin}/api/v4/projects/${encodeURIComponent(`${repo.owner}/${repo.name}`)}`;
53
+ const auth = (token) => typed({ Authorization: `Bearer ${token}` });
54
+ const of = hookOf((value) => field(value, "url"));
55
+ return {
56
+ readable: async (token) => { const answer = await http(base, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(true) : failed("the platform's git_token cannot read the repository", answer); },
57
+ hooks: async (token) => { const answer = await http(`${base}/hooks`, { method: "GET", headers: auth(token) }); return answer.status === 200 ? ok(listed(answer, of)) : failed("listing the hooks", answer); },
58
+ save: async (token, url, secret, id) => {
59
+ const body = JSON.stringify({ url, token: secret, push_events: true, enable_ssl_verification: true });
60
+ const answer = await http(id === undefined ? `${base}/hooks` : `${base}/hooks/${String(id)}`, { method: id === undefined ? "POST" : "PUT", headers: { ...auth(token), ...json }, body });
61
+ const hook = of(answer.json);
62
+ return answer.status < 300 && hook !== undefined ? ok(hook) : failed("saving the hook", answer);
63
+ },
64
+ };
65
+ }
66
+ }
67
+ };
68
+ /**
69
+ * The repository readable by the platform's token, and exactly one push hook
70
+ * to its deployer: an existing one is updated, so its secret is the platform's
71
+ * now, never a second added.
72
+ */
73
+ export const ensureHook = async (api, url, tokens, secret) => {
74
+ const readable = await api.readable(tokens.platform);
75
+ if (!readable.ok)
76
+ return readable;
77
+ const existing = await api.hooks(tokens.operator);
78
+ if (!existing.ok)
79
+ return existing;
80
+ const same = existing.value.filter((hook) => hook.url === url);
81
+ if (same.length > 1)
82
+ return err(`there are ${String(same.length)} hooks to ${url}; delete all but one`);
83
+ const saved = await api.save(tokens.operator, url, secret, same[0]?.id);
84
+ if (!saved.ok)
85
+ return err(saved.error.replaceAll(secret, "…"));
86
+ return ok(typed([
87
+ "✓ the platform's token reads the repository",
88
+ `✓ push hook ${same[0] === undefined ? "created" : "updated"}: ${url} (id ${String(saved.value.id)})`,
89
+ ]));
90
+ };
@@ -0,0 +1,49 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fields } from "../../lib/yaml.js";
6
+ /** KAYRA_FORGE_TOKEN_<HOST>: github.com → KAYRA_FORGE_TOKEN_GITHUB_COM. */
7
+ export const tokenVariable = (host) => `KAYRA_FORGE_TOKEN_${host.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
8
+ /** A CLI's answer, if that CLI is here at all: its absence is no error, only no answer. */
9
+ const asked = (program, args) => {
10
+ const result = spawnSync(program, args, { encoding: "utf8" });
11
+ const token = result.status === 0 ? result.stdout.trim() : "";
12
+ return token === "" ? undefined : token;
13
+ };
14
+ const field = (value, key) => typeof value === "object" && value !== null ? Object.entries(value).find(([name]) => name === key)?.[1] : undefined;
15
+ const teaToken = (host, home, env) => {
16
+ const files = [
17
+ join(env["XDG_CONFIG_HOME"] ?? join(home, ".config"), "tea", "config.yml"),
18
+ join(home, "Library", "Application Support", "tea", "config.yml"),
19
+ ];
20
+ const file = files.find((each) => existsSync(each));
21
+ if (file === undefined)
22
+ return undefined;
23
+ const parsed = fields(readFileSync(file, "utf8"));
24
+ const logins = parsed.ok ? parsed.value["logins"] : undefined;
25
+ const list = Array.isArray(logins) ? logins : [];
26
+ const login = list.find((each) => {
27
+ const url = field(each, "url");
28
+ return typeof url === "string" && URL.canParse(url) && new URL(url).host === host;
29
+ });
30
+ const token = field(login, "token");
31
+ return typeof token === "string" && token !== "" ? token : undefined;
32
+ };
33
+ /**
34
+ * The operator's token for a forge (hooks need a repository admin, which the
35
+ * platform's token is not): KAYRA_FORGE_TOKEN_<HOST> first; else, only if it
36
+ * happens to be here, the forge CLI's own login (gh, tea, glab). No CLI is
37
+ * ever required.
38
+ */
39
+ export const operatorToken = (repo, env = process.env, home = homedir()) => {
40
+ const host = new URL(repo.origin).host;
41
+ const fromEnv = env[tokenVariable(host)];
42
+ if (fromEnv !== undefined && fromEnv !== "")
43
+ return { token: fromEnv, from: tokenVariable(host) };
44
+ const fallback = repo.kind === "github" ? asked("gh", ["auth", "token", "--hostname", host])
45
+ : repo.kind === "gitlab" ? asked("glab", ["config", "get", "token", "--host", host])
46
+ : teaToken(host, home, env);
47
+ const cli = repo.kind === "github" ? "gh" : repo.kind === "gitlab" ? "glab" : "tea";
48
+ return fallback === undefined ? undefined : { token: fallback, from: `${cli}'s login` };
49
+ };