@rocket.chat/houston 0.27.0-next.3 → 2.1.9

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 (294) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +109 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +642 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/loadtest.md +264 -0
  12. package/data/docs/troubleshooting.md +203 -0
  13. package/data/docs/upgrading.md +84 -0
  14. package/data/docs/voice.md +253 -0
  15. package/data/iam/engineer-policy.json +11 -0
  16. package/data/iam/engineer-rbac.yaml +42 -0
  17. package/data/iam/operator-policy.json +211 -0
  18. package/data/loadtest/badbot.js +22 -0
  19. package/data/loadtest/common.js +170 -0
  20. package/data/loadtest/custom.js +20 -0
  21. package/data/loadtest/journey.js +58 -0
  22. package/data/loadtest/login.js +18 -0
  23. package/data/loadtest/messages.js +13 -0
  24. package/data/loadtest/mixed.js +57 -0
  25. package/data/loadtest/read.js +12 -0
  26. package/data/loadtest/webhook.js +20 -0
  27. package/data/monitoring/houston-logs.json +98 -0
  28. package/data/monitoring/k6-loadtest.json +610 -0
  29. package/data/monitoring/mongodb-exporter.json +3007 -0
  30. package/data/monitoring/node-exporter-full.json +16114 -0
  31. package/data/monitoring/rocketchat-metrics.json +6471 -0
  32. package/data/presets/airgapped.yaml +16 -0
  33. package/data/presets/default.yaml +9 -0
  34. package/data/seed/avatar-0.png +0 -0
  35. package/data/seed/avatar-1.png +0 -0
  36. package/data/seed/avatar-2.png +0 -0
  37. package/data/seed/avatar-3.png +0 -0
  38. package/data/seed/avatar-4.png +0 -0
  39. package/data/seed/avatar-5.png +0 -0
  40. package/data/seed/avatar-6.png +0 -0
  41. package/data/seed/avatar-7.png +0 -0
  42. package/data/seed/seed-metrics.csv +3 -0
  43. package/data/seed/seed-preview.png +0 -0
  44. package/data/seed/seed-report.pdf +32 -0
  45. package/data/seed/seed-runbook.txt +3 -0
  46. package/data/skill/SKILL.md +399 -0
  47. package/data/versions.yaml +55 -0
  48. package/data/voice/freeswitch/drachtio.xml +52 -0
  49. package/data/voice/freeswitch/public.xml +87 -0
  50. package/data/webui/app.css +2003 -0
  51. package/data/webui/index.html +678 -0
  52. package/data/webui/js/api.js +561 -0
  53. package/data/webui/js/boot.js +44 -0
  54. package/data/webui/js/clusters-tail.js +1377 -0
  55. package/data/webui/js/clusters.js +896 -0
  56. package/data/webui/js/create.js +276 -0
  57. package/data/webui/js/detail.js +507 -0
  58. package/data/webui/js/jobs.js +636 -0
  59. package/data/webui/js/logs.js +634 -0
  60. package/data/webui/js/main.js +14 -0
  61. package/data/webui/js/options.js +408 -0
  62. package/data/webui/js/people.js +438 -0
  63. package/data/webui/js/perf.js +303 -0
  64. package/data/webui/js/render.js +438 -0
  65. package/data/webui/js/shared.js +3 -0
  66. package/data/webui/js/state.js +583 -0
  67. package/data/webui/js/theme.js +123 -0
  68. package/data/webui/js/util.js +584 -0
  69. package/dist/cli/app.js +593 -0
  70. package/dist/cli/capabilities.js +76 -0
  71. package/dist/cli/cell-widths.js +495 -0
  72. package/dist/cli/entry.js +10 -0
  73. package/dist/cli/error-panel.js +492 -0
  74. package/dist/cli/handlers/actor.js +84 -0
  75. package/dist/cli/handlers/https.js +614 -0
  76. package/dist/cli/handlers/prompt.js +299 -0
  77. package/dist/cli/handlers/users.js +226 -0
  78. package/dist/cli/handlers.js +3694 -0
  79. package/dist/cli/help.js +183 -0
  80. package/dist/cli/index.js +15 -0
  81. package/dist/cli/perf.js +814 -0
  82. package/dist/cli/render.js +254 -0
  83. package/dist/cli/serve.js +858 -0
  84. package/dist/cli/spec-data.js +2599 -0
  85. package/dist/cli/spec-types.js +8 -0
  86. package/dist/cli/usage-error.js +520 -0
  87. package/dist/cli/wire.js +70 -0
  88. package/dist/core/audit.js +346 -0
  89. package/dist/core/backup-compat.js +85 -0
  90. package/dist/core/backup.js +1639 -0
  91. package/dist/core/cluster.js +1398 -0
  92. package/dist/core/configimport.js +345 -0
  93. package/dist/core/data.js +267 -0
  94. package/dist/core/database-of.js +82 -0
  95. package/dist/core/diagnose.js +159 -0
  96. package/dist/core/doctor.js +1518 -0
  97. package/dist/core/edge/acme.js +338 -0
  98. package/dist/core/edge/engine.js +500 -0
  99. package/dist/core/edge/networks.js +174 -0
  100. package/dist/core/edge/paths.js +107 -0
  101. package/dist/core/edge/routes.js +251 -0
  102. package/dist/core/edge/routeyml.js +195 -0
  103. package/dist/core/edge/runtime.js +493 -0
  104. package/dist/core/edge/spec.js +305 -0
  105. package/dist/core/edge/types.js +202 -0
  106. package/dist/core/eks-docs.js +135 -0
  107. package/dist/core/eks.js +2240 -0
  108. package/dist/core/envvars.js +562 -0
  109. package/dist/core/eventlog.js +541 -0
  110. package/dist/core/firstrun.js +153 -0
  111. package/dist/core/journal.js +694 -0
  112. package/dist/core/kube/ask.js +231 -0
  113. package/dist/core/kube/capabilities.js +269 -0
  114. package/dist/core/kube/certmanager.js +452 -0
  115. package/dist/core/kube/chart.js +413 -0
  116. package/dist/core/kube/cluster.js +196 -0
  117. package/dist/core/kube/context.js +545 -0
  118. package/dist/core/kube/endpoints.js +448 -0
  119. package/dist/core/kube/exec.js +195 -0
  120. package/dist/core/kube/forward.js +732 -0
  121. package/dist/core/kube/grafana-ingress.js +110 -0
  122. package/dist/core/kube/ingress.js +218 -0
  123. package/dist/core/kube/manifests.js +361 -0
  124. package/dist/core/kube/monitoring.js +768 -0
  125. package/dist/core/kube/names.js +237 -0
  126. package/dist/core/kube/namespace.js +678 -0
  127. package/dist/core/kube/operator.js +941 -0
  128. package/dist/core/kube/probe.js +202 -0
  129. package/dist/core/kube/reachability.js +163 -0
  130. package/dist/core/kube/release.js +439 -0
  131. package/dist/core/kube/replicaset.js +180 -0
  132. package/dist/core/kube/scale.js +398 -0
  133. package/dist/core/kube/status.js +633 -0
  134. package/dist/core/kube/tools.js +238 -0
  135. package/dist/core/kube/transfer.js +173 -0
  136. package/dist/core/kube/workspace.js +423 -0
  137. package/dist/core/lifecycle/admin.js +64 -0
  138. package/dist/core/lifecycle/create-docker.js +1549 -0
  139. package/dist/core/lifecycle/create-k8s.js +960 -0
  140. package/dist/core/lifecycle/destroy.js +339 -0
  141. package/dist/core/lifecycle/inspect.js +636 -0
  142. package/dist/core/lifecycle/naming.js +298 -0
  143. package/dist/core/lifecycle/notes.js +862 -0
  144. package/dist/core/lifecycle/ownership.js +313 -0
  145. package/dist/core/lifecycle/payload.js +401 -0
  146. package/dist/core/lifecycle/ports.js +388 -0
  147. package/dist/core/lifecycle/preconditions.js +367 -0
  148. package/dist/core/lifecycle/pruning.js +551 -0
  149. package/dist/core/lifecycle/ready.js +818 -0
  150. package/dist/core/lifecycle/request.js +510 -0
  151. package/dist/core/lifecycle/seeding.js +281 -0
  152. package/dist/core/lifecycle/sizing.js +392 -0
  153. package/dist/core/lifecycle/state.js +286 -0
  154. package/dist/core/lifecycle/tlsplan.js +704 -0
  155. package/dist/core/lifecycle/types.js +232 -0
  156. package/dist/core/loadtest.js +1051 -0
  157. package/dist/core/migrate.js +612 -0
  158. package/dist/core/monitor.js +494 -0
  159. package/dist/core/postready.js +976 -0
  160. package/dist/core/promote.js +804 -0
  161. package/dist/core/rcapi.js +1336 -0
  162. package/dist/core/recovery.js +75 -0
  163. package/dist/core/runner/engine.js +394 -0
  164. package/dist/core/runner/host.js +298 -0
  165. package/dist/core/runner/locks.js +129 -0
  166. package/dist/core/runner/paths.js +173 -0
  167. package/dist/core/runner/ports.js +172 -0
  168. package/dist/core/runner/queries.js +612 -0
  169. package/dist/core/runner/record.js +563 -0
  170. package/dist/core/scaleseed.js +271 -0
  171. package/dist/core/seed-db.js +208 -0
  172. package/dist/core/sessions.js +472 -0
  173. package/dist/core/skill.js +326 -0
  174. package/dist/core/sso-identities.js +172 -0
  175. package/dist/core/sso.js +703 -0
  176. package/dist/core/tls-local.js +311 -0
  177. package/dist/core/tls.js +878 -0
  178. package/dist/core/topology.js +482 -0
  179. package/dist/core/upgrade.js +877 -0
  180. package/dist/core/users.js +739 -0
  181. package/dist/lib/audit.js +100 -0
  182. package/dist/lib/close-matches.js +238 -0
  183. package/dist/lib/compose.js +672 -0
  184. package/dist/lib/config.js +1398 -0
  185. package/dist/lib/context.js +18 -0
  186. package/dist/lib/errors.js +305 -0
  187. package/dist/lib/events.js +208 -0
  188. package/dist/lib/float-text.js +126 -0
  189. package/dist/lib/format.js +1320 -0
  190. package/dist/lib/home.js +325 -0
  191. package/dist/lib/journal.js +122 -0
  192. package/dist/lib/json-text.js +733 -0
  193. package/dist/lib/jsonout.js +382 -0
  194. package/dist/lib/lock.js +516 -0
  195. package/dist/lib/login-name.js +202 -0
  196. package/dist/lib/map-limit.js +29 -0
  197. package/dist/lib/mkdir-parents.js +90 -0
  198. package/dist/lib/mongo-kernel.js +67 -0
  199. package/dist/lib/monitoring.js +492 -0
  200. package/dist/lib/platform-name.js +59 -0
  201. package/dist/lib/presets/common.js +390 -0
  202. package/dist/lib/presets/composite.js +326 -0
  203. package/dist/lib/presets/e2ee.js +143 -0
  204. package/dist/lib/presets/email.js +172 -0
  205. package/dist/lib/presets/guides.js +27 -0
  206. package/dist/lib/presets/index.js +490 -0
  207. package/dist/lib/presets/keycloak.js +371 -0
  208. package/dist/lib/presets/ldap.js +1285 -0
  209. package/dist/lib/presets/livechat.js +220 -0
  210. package/dist/lib/presets/multi-instance.js +124 -0
  211. package/dist/lib/presets/oidc.js +161 -0
  212. package/dist/lib/presets/public.js +496 -0
  213. package/dist/lib/presets/registry.js +64 -0
  214. package/dist/lib/presets/s3-minio.js +300 -0
  215. package/dist/lib/presets/saml.js +149 -0
  216. package/dist/lib/presets/scenario.js +51 -0
  217. package/dist/lib/presets/types.js +86 -0
  218. package/dist/lib/presets/voice-pbx.js +320 -0
  219. package/dist/lib/presets/voice.js +345 -0
  220. package/dist/lib/presets/webhooks.js +182 -0
  221. package/dist/lib/redact.js +106 -0
  222. package/dist/lib/seed-options.js +68 -0
  223. package/dist/lib/seed-profiles.js +59 -0
  224. package/dist/lib/targz.js +1383 -0
  225. package/dist/lib/teammode.js +25 -0
  226. package/dist/lib/tempdir.js +162 -0
  227. package/dist/lib/unicode-tables.js +2335 -0
  228. package/dist/lib/version-spec.js +357 -0
  229. package/dist/lib/versions.js +463 -0
  230. package/dist/lib/yaml-dump.js +1361 -0
  231. package/dist/perf/baseline.js +168 -0
  232. package/dist/perf/constrain.js +299 -0
  233. package/dist/perf/k6.js +235 -0
  234. package/dist/perf/mongoprof.js +171 -0
  235. package/dist/perf/rcmetrics.js +191 -0
  236. package/dist/perf/report.js +386 -0
  237. package/dist/perf/resources.js +236 -0
  238. package/dist/perf/slo.js +111 -0
  239. package/dist/perf/timeline.js +187 -0
  240. package/dist/perf/timings.js +85 -0
  241. package/dist/perf/verdict.js +201 -0
  242. package/dist/seams/aws-cli.js +126 -0
  243. package/dist/seams/docker-cli.js +280 -0
  244. package/dist/seams/exec.js +861 -0
  245. package/dist/seams/fs/lock.js +528 -0
  246. package/dist/seams/kubectl.js +83 -0
  247. package/dist/seams/rc-http.js +921 -0
  248. package/dist/seed/apply.js +190 -0
  249. package/dist/seed/assets.js +76 -0
  250. package/dist/seed/check.js +391 -0
  251. package/dist/seed/client.js +172 -0
  252. package/dist/seed/executor.js +726 -0
  253. package/dist/seed/history.js +281 -0
  254. package/dist/seed/kinds.js +91 -0
  255. package/dist/seed/plan.js +432 -0
  256. package/dist/seed/receipt.js +339 -0
  257. package/dist/seed/repairs.js +75 -0
  258. package/dist/seed/verification.js +363 -0
  259. package/dist/seed/wording.js +248 -0
  260. package/dist/web/app.js +326 -0
  261. package/dist/web/jobs.js +510 -0
  262. package/dist/web/route-deps.js +211 -0
  263. package/dist/web/route-table.js +213 -0
  264. package/dist/web/routes/backup.js +244 -0
  265. package/dist/web/routes/clusters.js +303 -0
  266. package/dist/web/routes/data.js +187 -0
  267. package/dist/web/routes/edge.js +82 -0
  268. package/dist/web/routes/index.js +63 -0
  269. package/dist/web/routes/jobs.js +95 -0
  270. package/dist/web/routes/logs.js +297 -0
  271. package/dist/web/routes/meta.js +191 -0
  272. package/dist/web/routes/people.js +151 -0
  273. package/dist/web/routes/perf.js +95 -0
  274. package/dist/web/routes/repros.js +550 -0
  275. package/dist/web/routes/session.js +361 -0
  276. package/dist/web/routes/spa.js +198 -0
  277. package/dist/web/security.js +475 -0
  278. package/dist/web/signin.js +246 -0
  279. package/package.json +70 -32
  280. package/.eslintrc +0 -94
  281. package/.swcrc +0 -18
  282. package/dist/bin.js +0 -3
  283. package/dist/cli.js +0 -184
  284. package/dist/commands/createBranch.js +0 -194
  285. package/dist/outputCI.js +0 -59
  286. package/src/bin.js +0 -4
  287. package/src/cli.ts +0 -25
  288. package/src/commands/createBranch.ts +0 -28
  289. package/src/outputCI.ts +0 -12
  290. package/src-old/logs.js +0 -323
  291. package/src-old/md.js +0 -191
  292. package/src-old/release-table.js +0 -60
  293. package/src-old/set-version.js +0 -614
  294. package/src-old/utils.js +0 -15
@@ -0,0 +1,858 @@
1
+ "use strict";
2
+ /** The `serve` command's security and lifetime policy around the shared Fastify app. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.serve = serve;
5
+ exports.portClaimNote = portClaimNote;
6
+ exports.reportGuiTls = reportGuiTls;
7
+ const errors_1 = require("../lib/errors");
8
+ const home_1 = require("../lib/home");
9
+ const format_1 = require("../lib/format");
10
+ const mkdir_parents_1 = require("../lib/mkdir-parents");
11
+ const events_1 = require("../lib/events");
12
+ const DEFAULT_PORT = 7070;
13
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1']);
14
+ const WILDCARD = new Set(['0.0.0.0', '::', '[::]']);
15
+ function optionsWithDefaults(options) {
16
+ const port = options.port ?? DEFAULT_PORT;
17
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
18
+ throw new errors_1.ValidationError('--port must be an integer between 0 and 65535');
19
+ }
20
+ return {
21
+ port,
22
+ domain: options.domain ?? '',
23
+ email: options.email ?? '',
24
+ noDomain: options.noDomain ?? false,
25
+ bind: options.bind ?? '',
26
+ allowHost: [...(options.allowHost ?? [])],
27
+ noOpen: options.noOpen ?? false,
28
+ printService: options.printService ?? false,
29
+ insecure: options.insecure ?? false,
30
+ trustProxy: [...(options.trustProxy ?? [])],
31
+ };
32
+ }
33
+ function defaultIo() {
34
+ return {
35
+ writeOut: (text) => process.stdout.write(text),
36
+ writeErr: (text) => process.stderr.write(text),
37
+ };
38
+ }
39
+ function waitForSignal(_app) {
40
+ return new Promise((resolve) => {
41
+ const done = () => {
42
+ process.off('SIGINT', done);
43
+ process.off('SIGTERM', done);
44
+ // Closing Fastify does not prove that a log-follow child or another handle
45
+ // has gone. Keep the process bound after close returns, even with no jobs.
46
+ // An unreferenced timer lets a fully drained server exit naturally.
47
+ setTimeout(() => {
48
+ process.stderr.write(' ⚠ serve shutdown exceeded 38 seconds; ending the process\n');
49
+ process.exit();
50
+ }, 38000).unref();
51
+ resolve();
52
+ };
53
+ process.once('SIGINT', done);
54
+ process.once('SIGTERM', done);
55
+ });
56
+ }
57
+ function openBrowser(url) {
58
+ const exec = require('../seams/exec');
59
+ const argv = process.platform === 'darwin'
60
+ ? ['open', url]
61
+ : process.platform === 'win32'
62
+ ? ['cmd.exe', '/c', 'start', '', url]
63
+ : ['xdg-open', url];
64
+ return exec.startDetached(argv).then(() => undefined);
65
+ }
66
+ /**
67
+ * Home to 0700 and the users, sessions and audit files to 0600, each only when its mode lets
68
+ * the group or others in, and SAID -- the reassurance a shared-box admin reads before the
69
+ * URL. A mode already private is left alone and not mentioned; a filesystem error anywhere is
70
+ * silent, and one on home skips the files too.
71
+ */
72
+ function tightenPrivateState(say) {
73
+ const fs = require('node:fs');
74
+ const path = require('node:path');
75
+ const config = require('../lib/config');
76
+ const users = require('../core/users');
77
+ const sessions = require('../core/sessions');
78
+ const audit = require('../core/audit');
79
+ const ssoIdentities = require('../core/sso-identities');
80
+ const home = config.home();
81
+ try {
82
+ // The home made with its parents and NO mode, then the chmod: a recursive mkdir at
83
+ // 0700 also made every missing parent 0700.
84
+ fs.mkdirSync(home, { recursive: true });
85
+ if ((fs.statSync(home).mode & 0o077) !== 0) {
86
+ fs.chmodSync(home, 0o700);
87
+ say(` tightened ${home} to 0700 (it holds accounts, sessions and the audit log)`);
88
+ }
89
+ }
90
+ catch {
91
+ return;
92
+ }
93
+ for (const target of [
94
+ users.usersFile(),
95
+ sessions.sessionsFile(),
96
+ audit.auditPath(),
97
+ ssoIdentities.identitiesFile(),
98
+ ]) {
99
+ try {
100
+ if (fs.existsSync(target) && (fs.statSync(target).mode & 0o077) !== 0) {
101
+ fs.chmodSync(target, 0o600);
102
+ say(` tightened ${path.basename(target)} to 0600`);
103
+ }
104
+ }
105
+ catch {
106
+ // Best effort: failure to repair an old mode must not make the GUI unavailable.
107
+ }
108
+ }
109
+ }
110
+ function writePid(target, pid) {
111
+ const fs = require('node:fs');
112
+ const path = require('node:path');
113
+ const temporary = `${target}.${String(pid)}.tmp`;
114
+ try {
115
+ // The pid file's directory made with its parents, 0700 on the leaf only.
116
+ (0, mkdir_parents_1.mkdirParents)(path.dirname(target), 0o700);
117
+ fs.writeFileSync(temporary, `${String(pid)}\n`, { encoding: 'utf8', mode: 0o600 });
118
+ fs.renameSync(temporary, target);
119
+ return true;
120
+ }
121
+ catch {
122
+ return false;
123
+ }
124
+ finally {
125
+ try {
126
+ fs.rmSync(temporary, { force: true });
127
+ }
128
+ catch {
129
+ // Already renamed or the directory is unwritable.
130
+ }
131
+ }
132
+ }
133
+ function livePid(target) {
134
+ const fs = require('node:fs');
135
+ let pid;
136
+ try {
137
+ pid = Number.parseInt(fs.readFileSync(target, 'utf8').trim(), 10);
138
+ }
139
+ catch {
140
+ return null;
141
+ }
142
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid)
143
+ return null;
144
+ try {
145
+ process.kill(pid, 0);
146
+ return pid;
147
+ }
148
+ catch (error) {
149
+ // Alive, and somebody else's to signal.
150
+ return error.code === 'EPERM' ? pid : null;
151
+ }
152
+ }
153
+ function removeOwnedPid(target, pid) {
154
+ const fs = require('node:fs');
155
+ try {
156
+ if (fs.readFileSync(target, 'utf8').trim() === String(pid))
157
+ fs.rmSync(target, { force: true });
158
+ }
159
+ catch {
160
+ // Best effort on shutdown, matching the writer.
161
+ }
162
+ }
163
+ /**
164
+ * Set by `bin/houston`, this build's entry, to its own absolute path with its symlinks
165
+ * resolved: the command the owner installed.
166
+ */
167
+ const DISPATCHER_ENV = 'HOUSTON_DISPATCHER';
168
+ /**
169
+ * What a unit's ExecStart runs: the `bin/houston` that ran this, else this build. It named
170
+ * THIS build -- `node <checkout>/tools/cli.js` -- so a unit went stale the moment the build
171
+ * behind the command moved. So a unit names `bin/houston`, this build's entry, whenever that
172
+ * is what started the process. Run directly, not through it, this build still names itself.
173
+ * systemd refuses a relative ExecStart, so a `bin/houston` path that is not absolute is not
174
+ * used.
175
+ */
176
+ function defaultExecutable() {
177
+ const path = require('node:path');
178
+ const dispatcher = process.env[DISPATCHER_ENV] ?? '';
179
+ if (path.isAbsolute(dispatcher))
180
+ return [dispatcher];
181
+ const script = process.argv[1];
182
+ return script === undefined || script === ''
183
+ ? ['houston']
184
+ : [process.execPath, path.resolve(script)];
185
+ }
186
+ function defaultDependencies() {
187
+ const config = require('../lib/config');
188
+ const tls = require('../core/tls');
189
+ const edgeSpec = require('../core/edge/spec');
190
+ const edgeEngine = require('../core/edge/engine');
191
+ const edgeTypes = require('../core/edge/types');
192
+ const edgeRuntime = require('../core/edge/runtime');
193
+ const edgeNetworks = require('../core/edge/networks');
194
+ const edgePaths = require('../core/edge/paths');
195
+ const users = require('../core/users');
196
+ const firstrun = require('../core/firstrun');
197
+ const promote = require('../core/promote');
198
+ const preconditions = require('../core/lifecycle/preconditions');
199
+ const web = require('../web/app');
200
+ const recovery = require('../core/recovery');
201
+ const admin = require('../core/lifecycle/admin');
202
+ const host = require('../core/runner/host');
203
+ return {
204
+ home: config.home,
205
+ loadConfig: () => config.loadConfig(false),
206
+ saveConfig: config.saveConfig,
207
+ normalizeAllowHost: tls.normalizeAllowHost,
208
+ normalizeDomain: tls.normalizeDomain,
209
+ servedDomain: edgeSpec.servedDomain,
210
+ bridgeAddress: edgeEngine.bridgeAddress,
211
+ engineKind: async () => (await host.engine())?.kind ?? '',
212
+ resolveEdge: edgeTypes.resolveEdge,
213
+ requireDocker: preconditions.requireDocker,
214
+ writeEdge: edgeSpec.write,
215
+ ensureEdge: edgeRuntime.ensureRunning,
216
+ edgePortHolder: edgeEngine.portHolder,
217
+ edgeDirectory: edgePaths.edgeDir,
218
+ edgeProject: edgePaths.PROJECT,
219
+ edgeAddresses: edgeNetworks.containerAddresses,
220
+ anyUsers: users.anyUsers,
221
+ listUsers: users.listUsers,
222
+ roleOf: users.roleOf,
223
+ implicitAdmins: users.implicitAdmins,
224
+ mintFirstRun: firstrun.mint,
225
+ createApp: web.createApp,
226
+ recoverInterrupted: () => recovery.recover(events_1.nullEmit, { login: admin.login }),
227
+ reportGuiTls: async (io, domain) => {
228
+ await reportGuiTls(io, domain);
229
+ },
230
+ dnsEnvPath: tls.dnsEnvPath,
231
+ waitForShutdown: waitForSignal,
232
+ openBrowser,
233
+ executable: defaultExecutable(),
234
+ user: () => process.env.USER || 'houston',
235
+ systemdUnit: edgeRuntime.systemdUnit,
236
+ servePidPath: promote.servePidPath,
237
+ tightenPrivateState,
238
+ writePid,
239
+ removeOwnedPid,
240
+ livePid,
241
+ };
242
+ }
243
+ function isZeroAddress(address, family) {
244
+ if (family === 4)
245
+ return address.split('.').every((part) => Number(part) === 0);
246
+ return address
247
+ .split(':')
248
+ .filter((part) => part !== '')
249
+ .every((part) => /^0+$/u.test(part));
250
+ }
251
+ function proxySet(entries) {
252
+ const net = require('node:net');
253
+ const networks = [];
254
+ const usable = [];
255
+ const problems = [];
256
+ for (const raw of entries) {
257
+ for (const value of raw.split(',')) {
258
+ const part = value.trim();
259
+ if (part === '')
260
+ continue;
261
+ const pieces = part.split('/');
262
+ const address = pieces[0] ?? '';
263
+ const family = net.isIP(address);
264
+ const maximum = family === 6 ? 128 : 32;
265
+ const prefix = pieces.length === 1 ? maximum : Number(pieces[1]);
266
+ if (pieces.length > 2 ||
267
+ family === 0 ||
268
+ !Number.isInteger(prefix) ||
269
+ prefix < 0 ||
270
+ prefix > maximum) {
271
+ problems.push(`--trust-proxy ${(0, format_1.quotedText)(part)} is not an address or CIDR, so it was ignored — no proxy is trusted by it.`);
272
+ continue;
273
+ }
274
+ const block = new net.BlockList();
275
+ const type = family === 6 ? 'ipv6' : 'ipv4';
276
+ if (pieces.length === 1)
277
+ block.addAddress(address, type);
278
+ else
279
+ block.addSubnet(address, prefix, type);
280
+ const matchesNothing = prefix === maximum && isZeroAddress(address, family);
281
+ if (prefix === 0) {
282
+ problems.push(`--trust-proxy ${part} trusts X-Forwarded-* from ANY client, not just a proxy: ` +
283
+ 'anyone can then claim X-Forwarded-Proto: https to get a Secure cookie and ' +
284
+ 'silence the unencrypted warning, and set X-Forwarded-For to dodge the sign-in ' +
285
+ "throttle. Name the proxy's own address instead.");
286
+ }
287
+ else if (matchesNothing) {
288
+ const every = family === 4 ? '0.0.0.0/0' : '::/0';
289
+ const single = `${family === 4 ? '0.0.0.0' : '::'}/${String(maximum)}`;
290
+ problems.push(`--trust-proxy ${part} means the single address ${single}, which no proxy has — ` +
291
+ `did you mean ${every}? As it stands nothing is trusted and the session cookie ` +
292
+ 'will not be marked Secure.');
293
+ }
294
+ networks.push({ contains: (candidate) => block.check(candidate, type) });
295
+ if (!matchesNothing)
296
+ usable.push(part);
297
+ }
298
+ }
299
+ return { networks, usable, problems };
300
+ }
301
+ function shellQuote(value) {
302
+ if (/^[A-Za-z0-9_@%+=:,./-]+$/u.test(value))
303
+ return value;
304
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
305
+ }
306
+ function serveCommand(options, executable, resolved, service) {
307
+ const parts = [...executable, 'serve'];
308
+ if (resolved.domain !== '') {
309
+ parts.push('--domain', resolved.domain, '--email', resolved.email);
310
+ }
311
+ else {
312
+ parts.push('--bind', resolved.bind);
313
+ if (options.insecure)
314
+ parts.push('--insecure');
315
+ for (const proxy of options.trustProxy)
316
+ parts.push('--trust-proxy', proxy);
317
+ }
318
+ if (options.port !== DEFAULT_PORT)
319
+ parts.push('--port', String(options.port));
320
+ for (const host of resolved.allowHost)
321
+ parts.push('--allow-host', host);
322
+ if (service)
323
+ parts.push('--no-open');
324
+ return parts.map(shellQuote).join(' ');
325
+ }
326
+ function serviceText(command, dependencies) {
327
+ return ('\n# systemd — survives logout, restarts on crash, starts on boot.\n' +
328
+ `# Write this to /etc/systemd/system/houston.service:\n\n` +
329
+ // The unit already ends in a newline, and one more follows it.
330
+ `${dependencies.systemdUnit(command, dependencies.user())}\n` +
331
+ '# Then:\n' +
332
+ ' sudo tee /etc/systemd/system/houston.service > /dev/null # paste the above\n' +
333
+ ' sudo systemctl daemon-reload\n' +
334
+ ' sudo systemctl enable --now houston\n' +
335
+ ' systemctl status houston && journalctl -u houston -f\n' +
336
+ '\n# No systemd? nohup survives logout — and nothing else:\n' +
337
+ // `config.home() / 'serve.log'`: `path.join` folded a `..` in the home.
338
+ ` nohup ${command} > ${(0, home_1.joinPath)(dependencies.home(), 'serve.log')} 2>&1 &\n` +
339
+ '# It will NOT restart on crash, NOT come back after a reboot,\n' +
340
+ '# NOT rotate that log, and there is no `status` to ask.\n');
341
+ }
342
+ /** The lowercased reason for each bind failure the refusal names. */
343
+ const BIND_STRERROR = {
344
+ EADDRINUSE: 'address already in use',
345
+ EACCES: 'permission denied',
346
+ EADDRNOTAVAIL: 'address not available',
347
+ };
348
+ /**
349
+ * The line logged when the listener cannot bind, or null for a failure that is not one.
350
+ *
351
+ * The line is `cannot listen on <host>:<port>: <reason, lowercased>` -- `address already in
352
+ * use` for a port another process holds, `address not available` for an address this box
353
+ * does not have -- with an IPv6 host in brackets, `[::1]:80`.
354
+ */
355
+ function bindRefusal(error, bind, port) {
356
+ // Read by shape, not `instanceof Error`: a Node core error need not come from this realm.
357
+ if (typeof error !== 'object' || error === null)
358
+ return null;
359
+ const failure = error;
360
+ if (failure.syscall !== 'listen' && failure.syscall !== 'bind')
361
+ return null;
362
+ const net = require('node:net');
363
+ const host = typeof failure.address === 'string' ? failure.address : bind;
364
+ const at = typeof failure.port === 'number' ? failure.port : port;
365
+ const where = net.isIP(host) === 6 ? `[${host}]:${String(at)}` : `${host}:${String(at)}`;
366
+ const code = typeof failure.code === 'string' ? failure.code : '';
367
+ const strerror = BIND_STRERROR[code];
368
+ if (strerror === undefined)
369
+ return null;
370
+ return `cannot listen on ${where}: ${strerror}`;
371
+ }
372
+ /**
373
+ * What to do about a port in use. Commonly the holder is an earlier `houston serve` -- one
374
+ * left running under nohup, a service unit, or a 1.x serve -- and the bare "address already
375
+ * in use" did not say so. Named exactly when this home's pid file records a live serve.
376
+ */
377
+ function inUseHint(earlier, port) {
378
+ if (earlier !== null) {
379
+ return (`an earlier houston serve from this home is still running (pid ${String(earlier)}): ` +
380
+ `stop it (\`kill ${String(earlier)}\`, or \`sudo systemctl stop houston\` if it runs ` +
381
+ 'as the service), or choose another --port');
382
+ }
383
+ const { holderCommand } = require('../core/kube/forward');
384
+ return (`an older houston serve may still hold it: \`${holderCommand(port)}\` names what does; ` +
385
+ 'stop that, or choose another --port');
386
+ }
387
+ function actualPort(app, fallback) {
388
+ const address = app.server.address();
389
+ return address !== null && typeof address !== 'string' ? address.port : fallback;
390
+ }
391
+ function localUrl(bind, port, allowHost, setupKey) {
392
+ const loopback = LOOPBACK.has(bind);
393
+ const host = loopback
394
+ ? 'localhost'
395
+ : (allowHost.find((value) => value !== '*') ?? (WILDCARD.has(bind) ? '<this-box>' : bind));
396
+ const path = setupKey === '' ? '/' : `/setup#k=${setupKey}`;
397
+ return `http://${host}:${String(port)}${path}`;
398
+ }
399
+ /** The URL, then how people sign in. */
400
+ function announce(io, dependencies, values) {
401
+ const say = (line) => io.writeOut(`${line}\n`);
402
+ say(`houston GUI: ${values.url}`);
403
+ // localhost is the machine running serve, which is often not the reader's: say how in.
404
+ const local = values.loopback && values.domain === '' && !values.localProxy;
405
+ const port = local ? new URL(values.url).port : '';
406
+ const tunnel = `From your computer: ssh -L ${port}:localhost:${port} <you>@<this server>, ` +
407
+ 'then open the same URL.';
408
+ if (values.door !== null) {
409
+ if (values.door.wildcard) {
410
+ say(` one *.${values.domain} certificate (a certificate, not a DNS record) covers every ` +
411
+ 'workspace — no per-name issuance, no weekly limit to hit.');
412
+ }
413
+ else {
414
+ say(' each workspace name gets its own certificate. A DNS API token in ' +
415
+ `${dependencies.dnsEnvPath()} would make it one wildcard.`);
416
+ }
417
+ say(` ${values.domain} and every <ticket>.${values.domain} must resolve to this server, or ` +
418
+ `no certificate can be issued: a DNS record for ${values.domain}, and one wildcard ` +
419
+ `record (*.${values.domain}) for every workspace.`);
420
+ say(" the first request may take a few seconds while Let's Encrypt issues it.");
421
+ say(' workspaces published under this name: houston up -v <X.Y.Z> --domain ' +
422
+ `<ticket>.${values.domain}`);
423
+ }
424
+ if (values.accounts) {
425
+ // One line naming the posture, so an operator can read how people sign in and whether
426
+ // the transport is believed, without inferring it from flags.
427
+ const how = values.domain !== ''
428
+ ? 'https, arranged by houston'
429
+ : values.trusted.length > 0
430
+ ? `https when the proxy says so, trusted from ${values.trusted.join(', ')}`
431
+ : values.localProxy
432
+ ? 'a proxy on this machine, NOT marked Secure (see the note above)'
433
+ : values.loopback
434
+ ? 'loopback, so nothing crosses a network'
435
+ : 'PLAIN HTTP on a reachable interface';
436
+ say(` auth: named accounts over ${how}`);
437
+ if (local) {
438
+ say(' reachable only from a browser on the machine running houston.');
439
+ say(` ${tunnel}`);
440
+ say(' To share it:');
441
+ say(' houston serve --domain <name.example.com> --email you@example.com');
442
+ say(' …or, behind a lab/proxy already doing TLS: --bind 0.0.0.0 --allow-host ' +
443
+ '<name>\n --trust-proxy <its address>');
444
+ }
445
+ if (values.domain === '' && values.trusted.length === 0 && !values.loopback) {
446
+ say(' ⚠ the session cookie will NOT be marked Secure, and the sign-in page will warn\n' +
447
+ ' about an unencrypted connection. If TLS terminates at a proxy in front,\n' +
448
+ ' tell houston which one: --trust-proxy <its address>');
449
+ }
450
+ const names = dependencies
451
+ .listUsers()
452
+ .map((user) => `${user.name} (${dependencies.roleOf(user.name)})`)
453
+ .join(', ');
454
+ say(` sign in as: ${names}`);
455
+ const implicit = dependencies.implicitAdmins();
456
+ if (implicit.length > 0) {
457
+ say(` ⚠ admin by default (blank role): ${implicit.join(', ')}`);
458
+ say(` narrow one with: houston users role ${implicit[0] ?? ''} member`);
459
+ }
460
+ say(' every action is recorded against the account that took it.');
461
+ // Said, never fatal: a provider that is misconfigured or down must not take the GUI
462
+ // with it, and password sign-in is the way back in.
463
+ const okta = require('../core/sso').readiness();
464
+ if (okta.state === 'ready') {
465
+ say(` Okta sign-in: on, from ${okta.settings.issuer}, back at ${okta.settings.publicUrl}`);
466
+ }
467
+ else if (okta.state === 'broken') {
468
+ say(` ⚠ Okta sign-in is set up but off: ${okta.why}`);
469
+ }
470
+ }
471
+ else if (values.setupKey !== '') {
472
+ say(' this link creates the first account. It is single-use and expires in 15 minutes.');
473
+ if (local) {
474
+ say(' it opens only in a browser on the machine running houston (localhost is that one).');
475
+ say(` ${tunnel}`);
476
+ }
477
+ say(' the part after # never reaches the server, so it cannot appear in a log.');
478
+ say(' prefer a terminal? `houston users add <name>`, then start this again.');
479
+ }
480
+ }
481
+ /**
482
+ * STARTUP RECOVERY: what the last process was killed in the middle of is still true.
483
+ *
484
+ * Recovery runs before the server accepts a request, and an earlier version of this module
485
+ * MISSED it: no front door called `core/recovery` at all, although that module's own
486
+ * docstring says the front doors are its only callers. The shutdown drain is bounded and a
487
+ * SIGKILL or an OOM skips it
488
+ * entirely, so a previous run can have left Rocket.Chat stopped after an interrupted backup,
489
+ * the API rate limiter off, or CPU caps applied after an interrupted load test -- with
490
+ * nothing in memory recording it. `journal.recover` acts only on notes whose owning process
491
+ * is provably gone, so a CLI operation running right now is left alone.
492
+ *
493
+ * Before the listener. And NEVER fatal: a box that cannot be repaired must still serve, or
494
+ * one stuck workspace becomes an outage of the whole GUI. The three lines are the
495
+ * established ones, word for word.
496
+ */
497
+ async function recoverInterruptedWork(io, dependencies) {
498
+ try {
499
+ for (const row of await dependencies.recoverInterrupted()) {
500
+ io.writeErr(`houston: ${row.repaired ? 'repaired' : 'STILL BROKEN'}: ${row.what}\n`);
501
+ }
502
+ }
503
+ catch (error) {
504
+ io.writeErr(`houston: could not check for interrupted work: ${(0, errors_1.errorText)(error)}\n`);
505
+ }
506
+ }
507
+ /**
508
+ * Resolve, secure, start and own the TypeScript GUI listener.
509
+ *
510
+ * The CLI handler supplies already-parsed values, but this boundary still validates them.
511
+ * Stateful modules are loaded at call time and every one is injectable so tests can prove
512
+ * ordering without starting Docker, a browser, or a real listener.
513
+ */
514
+ async function serve(supplied, overrides = {}, suppliedIo) {
515
+ const options = optionsWithDefaults(supplied);
516
+ const dependencies = { ...defaultDependencies(), ...overrides };
517
+ const io = suppliedIo ?? defaultIo();
518
+ // Warnings, notes and hints off a terminal: every line on stdout.
519
+ const say = (line) => io.writeOut(`${line}\n`);
520
+ // The allowed hosts, normalised.
521
+ const allowed = [];
522
+ for (const given of options.allowHost) {
523
+ const [host, fixed] = dependencies.normalizeAllowHost(given);
524
+ allowed.push(host);
525
+ if (fixed !== '')
526
+ say(` using --allow-host ${host} (${fixed})`);
527
+ }
528
+ const allowHost = [...allowed];
529
+ const hasAccounts = dependencies.anyUsers();
530
+ // The front door: the domain, its contact email, the bind and the edge they imply.
531
+ let domain = options.domain;
532
+ let email = options.email;
533
+ let bind = options.bind;
534
+ let door = null;
535
+ if (domain === '' && !options.noDomain) {
536
+ domain = dependencies.servedDomain();
537
+ if (domain !== '')
538
+ say(` serving ${domain} (set up earlier; --no-domain for a local session)`);
539
+ }
540
+ if (domain !== '') {
541
+ const normalized = dependencies.normalizeDomain(domain);
542
+ domain = normalized[0];
543
+ if (normalized[1] !== '')
544
+ say(` using --domain ${domain} (${normalized[1]})`);
545
+ const config = dependencies.loadConfig();
546
+ const remembered = String(config.acme_email ?? '');
547
+ email = email || remembered;
548
+ if (email === '') {
549
+ throw new errors_1.ValidationError("a Let's Encrypt certificate needs a contact email:\n" +
550
+ ` houston serve --domain ${domain} --email you@example.com\n` +
551
+ 'It is remembered after the first use, or set it once with:\n' +
552
+ ' houston config set acme.email you@example.com');
553
+ }
554
+ if (options.email !== '' && options.email !== remembered) {
555
+ dependencies.saveConfig({ ...config, acme_email: email });
556
+ }
557
+ if (options.port === 0) {
558
+ // TypeScript-only: `--port 0` exists here for tests and has no stable backend port.
559
+ throw new errors_1.ValidationError('--port 0 cannot be used with --domain because the edge needs a stable backend port');
560
+ }
561
+ // Podman's containers reach the host by a different road from Docker's, rootless most
562
+ // of all, so the bridge gateway is a guess there: refuse rather than publish the GUI
563
+ // where the edge cannot see it.
564
+ if (bind === '' && (await dependencies.engineKind()) === 'podman') {
565
+ throw new errors_1.ValidationError('`serve --domain` on Podman needs --bind <an address of this host the HTTPS edge can ' +
566
+ "reach>, such as the host's own IP: Podman's containers reach the host differently " +
567
+ 'from Docker’s, and the gateway houston would guess may be unreachable.');
568
+ }
569
+ bind = bind || (await dependencies.bridgeAddress());
570
+ if (bind === '') {
571
+ throw new errors_1.ReproError('could not read the Docker bridge address, which is how the front door reaches the GUI.\n' +
572
+ ' Is Docker running? `houston doctor` checks.');
573
+ }
574
+ allowed.push(domain);
575
+ door = dependencies.resolveEdge(domain, email, { guiHost: bind, guiPort: options.port });
576
+ }
577
+ else {
578
+ bind = bind || '127.0.0.1';
579
+ }
580
+ const loopback = LOOPBACK.has(bind);
581
+ const resolved = { domain, email, bind, allowHost };
582
+ // The first-run key: no accounts starts only on loopback with no domain. The refusal is
583
+ // amber and two steps, NOT a red `error:` -- it is the documented first-run sequence -- but
584
+ // it still exits 3, because `serve` did not serve. Whole block on stderr.
585
+ let setupKey = '';
586
+ if (!hasAccounts) {
587
+ if (loopback && domain === '') {
588
+ setupKey = dependencies.mintFirstRun();
589
+ }
590
+ else {
591
+ io.writeErr('houston needs an account before it will serve on an interface other than loopback.\n' +
592
+ '\n 1. create one — the password is generated and shown once:\n' +
593
+ ' houston users add <name>\n' +
594
+ ' 2. start it again:\n' +
595
+ ` ${serveCommand(options, ['houston'], resolved, false)}\n\n`);
596
+ return { printed: false, refused: true, exitCode: 3 };
597
+ }
598
+ }
599
+ // No password in the clear. `--trust-proxy` counts as SAID even when it matches nothing --
600
+ // the list given is what is tested -- and its problems are warned below instead.
601
+ const tlsUpstream = domain !== '' || options.insecure || options.trustProxy.length > 0;
602
+ if (hasAccounts && !loopback && !tlsUpstream) {
603
+ // A plain error with exit 3, as the no-accounts stop above, but a plain ReproError --
604
+ // REPRO_ERROR in the event log, not PREFLIGHT_FAILED.
605
+ throw new errors_1.ReproError(`signing in over plain http on ${bind} puts the password on the wire once, and the\n` +
606
+ ' session cookie on every request after it — both readable by anyone on the path.\n' +
607
+ ' Refused by default.\n' +
608
+ ' Have a hostname pointing here? Let houston do the TLS:\n' +
609
+ ' houston serve --domain <your-domain> --email you@example.com\n' +
610
+ ' TLS proxy on THIS box? Keep the GUI on loopback and point the proxy at it:\n' +
611
+ ` houston serve --bind 127.0.0.1 --port ${String(options.port)} --allow-host <your-domain>\n` +
612
+ ' TLS terminating upstream (remote proxy, lab, load balancer)?\n' +
613
+ ' name the peer, so the cookie is marked Secure too:\n' +
614
+ " --trust-proxy <the proxy's address>\n" +
615
+ ' Nothing doing TLS at all, on a network you trust?\n' +
616
+ ' add --insecure to the command you just ran\n' +
617
+ ' --trust-proxy and --insecure answer different questions: the first says who is\n' +
618
+ ' encrypting it, the second says nobody is and you accept that. If there is a\n' +
619
+ ' proxy, name it — it is the better answer and --insecure is then not needed.', { exitCode: 3 });
620
+ }
621
+ // A warning when the bind is reachable from elsewhere.
622
+ const parsedProxies = proxySet(options.trustProxy);
623
+ if (!loopback && door === null) {
624
+ say(` ⚠ binding ${bind} exposes docker control (create/delete workspaces + volumes) to ` +
625
+ 'your network — use only if you mean to.');
626
+ }
627
+ if (allowed.includes('*')) {
628
+ say(" ⚠ --allow-host '*' accepts ANY Host header — only on a trusted/ephemeral network.");
629
+ }
630
+ for (const problem of parsedProxies.problems)
631
+ say(` ⚠ ${problem}`);
632
+ // A name allowed on a loopback bind is a proxy on this machine (nginx, cloudflared) that
633
+ // people reach from elsewhere: it needs trusting for the cookie to be Secure, not a wider bind.
634
+ const localProxy = allowHost.length > 0 && loopback && domain === '';
635
+ if (localProxy && parsedProxies.usable.length === 0) {
636
+ say(` note: --allow-host ${allowHost[0] ?? ''} on a loopback bind is for a proxy on this\n` +
637
+ ' machine. If it terminates TLS, add --trust-proxy 127.0.0.1 so the session\n' +
638
+ ' cookie is marked Secure.');
639
+ }
640
+ if (!loopback && door === null && allowHost.length === 0) {
641
+ say(' ⚠ nothing is in --allow-host, so only localhost is accepted — a request by any\n' +
642
+ " other name will be a 403. Add --allow-host <the name you will type>, or '*'.");
643
+ }
644
+ // The service unit is printed after every check, never before.
645
+ const command = serveCommand(options, dependencies.executable, resolved, true);
646
+ if (options.printService) {
647
+ io.writeOut(serviceText(command, dependencies));
648
+ if (!hasAccounts) {
649
+ io.writeOut('\n# Note: no accounts exist, so this would refuse to start on a\n' +
650
+ '# reachable interface. `houston users add <name>` first.\n');
651
+ }
652
+ return { printed: true, command };
653
+ }
654
+ // Opening the front door: the edge, when a domain asks for one.
655
+ let edgeAddresses = [];
656
+ if (door !== null) {
657
+ await dependencies.requireDocker();
658
+ say('starting the edge (one Traefik, :80 and :443 for every name)…');
659
+ await dependencies.writeEdge(door);
660
+ const started = await dependencies.ensureEdge({
661
+ acmeEmail: email,
662
+ acmeStaging: door.acmeStaging,
663
+ });
664
+ if (!started.ok) {
665
+ const holder = await dependencies.edgePortHolder(443);
666
+ throw new errors_1.ReproError('the edge did not start' +
667
+ (holder !== '' ? ` — ${holder} is holding :443.` : '.') +
668
+ (started.why !== '' ? `\n docker said: ${started.why}` : '') +
669
+ `\n Its compose project is \`${dependencies.edgeProject}\` in ` +
670
+ `${dependencies.edgeDirectory()}; \`houston edge status\` reports it.` +
671
+ `\n Full output: cd ${dependencies.edgeDirectory()} && docker compose -p ` +
672
+ `${dependencies.edgeProject} up`);
673
+ }
674
+ await dependencies.reportGuiTls(io, domain);
675
+ edgeAddresses = await dependencies.edgeAddresses();
676
+ }
677
+ const edgeProxies = proxySet(edgeAddresses);
678
+ const trustedProxies = [...parsedProxies.networks, ...edgeProxies.networks];
679
+ const trustedNames = [...parsedProxies.usable, ...edgeProxies.usable];
680
+ // The announcement, the app, the browser and the pid file, and only then the recovery and
681
+ // the bind. The announcement comes BEFORE the listener, so a port in use is refused after
682
+ // it, and its URL names the port that was ASKED for: `--port 0` announces
683
+ // http://localhost:0/, as it always has, useless as that is -- the port it binds is not
684
+ // known when it speaks.
685
+ dependencies.tightenPrivateState(say);
686
+ const url = domain !== '' ? `https://${domain}/` : localUrl(bind, options.port, allowed, setupKey);
687
+ announce(io, dependencies, {
688
+ url,
689
+ domain,
690
+ door,
691
+ loopback,
692
+ localProxy,
693
+ setupKey,
694
+ trusted: trustedNames,
695
+ accounts: hasAccounts,
696
+ });
697
+ const app = await dependencies.createApp({
698
+ allowHosts: allowed,
699
+ accounts: true,
700
+ publicHttps: domain !== '',
701
+ firstRun: setupKey !== '',
702
+ trustedProxies,
703
+ onShutdownStop: (jobIds) => io.writeErr(` ⚠ ${String(jobIds.length)} job(s) still running at shutdown — stopping them, as ` +
704
+ 'Stop does; what they had done stays done\n'),
705
+ });
706
+ if (!options.noOpen && loopback) {
707
+ try {
708
+ await dependencies.openBrowser(url);
709
+ }
710
+ catch {
711
+ // Headless hosts are normal; the printed URL remains the interface.
712
+ }
713
+ }
714
+ const pidPath = dependencies.servePidPath(dependencies.home());
715
+ // Read before this serve writes its own over it, to name in a refusal.
716
+ const earlier = dependencies.livePid(pidPath);
717
+ const pidWritten = dependencies.writePid(pidPath, process.pid);
718
+ try {
719
+ await recoverInterruptedWork(io, dependencies);
720
+ try {
721
+ await app.listen({ host: bind, port: options.port });
722
+ }
723
+ catch (error) {
724
+ const refusal = bindRefusal(error, bind, options.port);
725
+ if (refusal === null)
726
+ throw error;
727
+ // The startup failure: ONE `error:` line on stderr and exit 3, the preflight code --
728
+ // the server refusing to start, said once -- and for a port in use, what to do.
729
+ io.writeErr(`error: ${refusal}\n`);
730
+ if (error.code === 'EADDRINUSE')
731
+ io.writeErr(` ${inUseHint(earlier, options.port)}\n`);
732
+ // The earlier serve's record, put back: this one wrote over it and removes its own.
733
+ if (earlier !== null)
734
+ dependencies.writePid(pidPath, earlier);
735
+ return { printed: false, refused: true, exitCode: 3 };
736
+ }
737
+ await dependencies.waitForShutdown(app);
738
+ return { printed: false, bind, port: actualPort(app, options.port), domain, url };
739
+ }
740
+ finally {
741
+ if (pidWritten)
742
+ dependencies.removeOwnedPid(pidPath, process.pid);
743
+ // Arm the bound before close: active HTTP streams can keep Fastify's close
744
+ // pending. The job hook has 25s to drain and 10s to unwind a stop request.
745
+ const shutdownDeadline = setTimeout(() => {
746
+ io.writeErr(' ⚠ serve shutdown exceeded 38 seconds; ending the process\n');
747
+ process.exit();
748
+ }, 38000);
749
+ shutdownDeadline.unref();
750
+ try {
751
+ await app.close();
752
+ }
753
+ finally {
754
+ clearTimeout(shutdownDeadline);
755
+ }
756
+ // BOUNDED. A job that would not stop kept this process alive with its listener closed --
757
+ // neither serving nor gone, for as long as a capacity search runs -- after the event log
758
+ // had already written `end`. The timer is unref'd: it ends only a process something
759
+ // abandoned is still holding, and lets one that is done exit by itself.
760
+ const left = app.jobs?.active?.() ?? 0;
761
+ if (left > 0) {
762
+ io.writeErr(` ⚠ ${String(left)} job(s) did not finish and could not be stopped — ` +
763
+ 'serve ends without them; what they had done stays done\n');
764
+ setTimeout(() => process.exit(), 2000).unref();
765
+ }
766
+ }
767
+ }
768
+ function realSleep(seconds) {
769
+ return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
770
+ }
771
+ /** `value` with every trailing character that is in `chars` removed. */
772
+ function rstrip(value, chars) {
773
+ let end = value.length;
774
+ while (end > 0 && chars.includes(value[end - 1]))
775
+ end -= 1;
776
+ return value.slice(0, end);
777
+ }
778
+ function writeLine(io, line) {
779
+ io.writeOut(`${line}\n`);
780
+ }
781
+ /**
782
+ * A cluster holding this host's :80/:443, as a sentence, or "".
783
+ *
784
+ * THE EDGE STARTING IS NOT THE EDGE WORKING. A k3s ServiceLB claims host ports by DNAT
785
+ * rather than by binding, so the edge binds both ports, compose reports success, and the
786
+ * start path said "every registered name is served again" about a box where no name was
787
+ * served at all -- for two days, with `edge status` agreeing the edge was running.
788
+ */
789
+ async function portClaimNote() {
790
+ const endpoints = require('../core/kube/endpoints');
791
+ let claim;
792
+ try {
793
+ // 3s, not the probe default: this is a warning on the way to starting a proxy.
794
+ claim = await endpoints.portClaimingCluster({ timeout: 3 });
795
+ }
796
+ catch {
797
+ // a warning must never break a start
798
+ return '';
799
+ }
800
+ if (claim === null)
801
+ return '';
802
+ const took = claim.ports
803
+ .filter((port) => port === 80 || port === 443)
804
+ .map((port) => `:${String(port)}`)
805
+ .join(', ');
806
+ return (`cluster ${(0, format_1.quotedText)(claim.context)} holds this host's ${took} at ${claim.address} ` +
807
+ `(${claim.service}), so the edge is bound but cannot receive: names answer ` +
808
+ 'from the cluster, not from houston.\n' +
809
+ ' Give the ports back: kubectl -n kube-system patch svc ' +
810
+ `${claim.service.split('/').at(-1) ?? ''} -p ` +
811
+ `'{"spec":{"type":"NodePort"}}'\n` +
812
+ ' A k3s reinstall undoes that patch. Permanently: install with ' +
813
+ '`--disable traefik --disable servicelb`, or put those two under ' +
814
+ '`disable:` in /etc/rancher/k3s/config.yaml.');
815
+ }
816
+ /**
817
+ * Whether `domain` is really being served over TLS yet, and why not. Never fatal.
818
+ *
819
+ * Polled rather than asked once: ACME takes a few seconds on a good day, so a single probe
820
+ * would report "not yet" for every healthy start and teach people to ignore it.
821
+ */
822
+ async function reportGuiTls(io, domain, { tries = 10, pause = 2.0, sleep = realSleep, } = {}) {
823
+ const tls = require('../core/tls');
824
+ const acme = require('../core/edge/acme');
825
+ // BEFORE the wait: with a cluster holding the ports no challenge of any kind can
826
+ // complete, so twenty seconds of "waiting for the certificate…" taught the reader that
827
+ // this message means nothing.
828
+ const claim = await portClaimNote();
829
+ if (claim !== '') {
830
+ writeLine(io, ` ⚠ https://${domain} cannot get a certificate — ${claim}`);
831
+ return;
832
+ }
833
+ for (let attempt = 0; attempt < tries; attempt += 1) {
834
+ const got = await tls.verify('127.0.0.1', { port: 443, sni: domain, timeout: 5.0 });
835
+ if (got.serving && !got.fallback) {
836
+ writeLine(io, rstrip(`https://${domain} is serving a real certificate (${got.issuer})`, ' ()'));
837
+ return;
838
+ }
839
+ const why = await acme.acmeFailure({ domain });
840
+ if (why !== '') {
841
+ // Conclusive: Let's Encrypt has answered and said no. Stop waiting.
842
+ writeLine(io, ` ⚠ https://${domain} has NO certificate yet, and Let's Encrypt refused:\n ${why}`);
843
+ writeLine(io, ` The GUI itself is fine — this is the name, not the server. Check that ${domain} ` +
844
+ "resolves to this host's public address and that :443 is reachable from the " +
845
+ 'internet (houston validates over TLS-ALPN on 443, not :80), then `houston edge restart`.');
846
+ writeLine(io, ' Full detail: `houston edge logs --tail 50`');
847
+ return;
848
+ }
849
+ if (attempt < tries - 1) {
850
+ if (attempt === 0)
851
+ writeLine(io, ` waiting for the certificate for ${domain}…`);
852
+ await sleep(pause);
853
+ }
854
+ }
855
+ writeLine(io, ` ⚠ https://${domain} is not serving a real certificate yet. Traefik requests it in ` +
856
+ 'the background, so this may still complete.');
857
+ writeLine(io, ' Watch it: `houston edge logs -f` · check it: `houston tls-status`');
858
+ }