@rocket.chat/houston 0.27.0-next.2 → 2.1.8

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 (291) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +108 -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 +669 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/troubleshooting.md +193 -0
  12. package/data/docs/upgrading.md +84 -0
  13. package/data/docs/voice.md +253 -0
  14. package/data/iam/engineer-policy.json +11 -0
  15. package/data/iam/engineer-rbac.yaml +42 -0
  16. package/data/iam/operator-policy.json +211 -0
  17. package/data/loadtest/badbot.js +22 -0
  18. package/data/loadtest/common.js +168 -0
  19. package/data/loadtest/custom.js +20 -0
  20. package/data/loadtest/journey.js +58 -0
  21. package/data/loadtest/login.js +18 -0
  22. package/data/loadtest/messages.js +13 -0
  23. package/data/loadtest/mixed.js +39 -0
  24. package/data/loadtest/read.js +12 -0
  25. package/data/loadtest/webhook.js +20 -0
  26. package/data/monitoring/houston-logs.json +98 -0
  27. package/data/monitoring/k6-loadtest.json +610 -0
  28. package/data/monitoring/mongodb-exporter.json +3007 -0
  29. package/data/monitoring/node-exporter-full.json +16114 -0
  30. package/data/monitoring/rocketchat-metrics.json +6471 -0
  31. package/data/presets/airgapped.yaml +16 -0
  32. package/data/presets/default.yaml +9 -0
  33. package/data/seed/avatar-0.png +0 -0
  34. package/data/seed/avatar-1.png +0 -0
  35. package/data/seed/avatar-2.png +0 -0
  36. package/data/seed/avatar-3.png +0 -0
  37. package/data/seed/avatar-4.png +0 -0
  38. package/data/seed/avatar-5.png +0 -0
  39. package/data/seed/avatar-6.png +0 -0
  40. package/data/seed/avatar-7.png +0 -0
  41. package/data/seed/seed-metrics.csv +3 -0
  42. package/data/seed/seed-preview.png +0 -0
  43. package/data/seed/seed-report.pdf +32 -0
  44. package/data/seed/seed-runbook.txt +3 -0
  45. package/data/skill/SKILL.md +399 -0
  46. package/data/versions.yaml +55 -0
  47. package/data/voice/freeswitch/drachtio.xml +52 -0
  48. package/data/voice/freeswitch/public.xml +87 -0
  49. package/data/webui/app.css +2003 -0
  50. package/data/webui/index.html +678 -0
  51. package/data/webui/js/api.js +561 -0
  52. package/data/webui/js/boot.js +44 -0
  53. package/data/webui/js/clusters-tail.js +1377 -0
  54. package/data/webui/js/clusters.js +896 -0
  55. package/data/webui/js/create.js +276 -0
  56. package/data/webui/js/detail.js +507 -0
  57. package/data/webui/js/jobs.js +636 -0
  58. package/data/webui/js/logs.js +634 -0
  59. package/data/webui/js/main.js +14 -0
  60. package/data/webui/js/options.js +408 -0
  61. package/data/webui/js/people.js +438 -0
  62. package/data/webui/js/perf.js +303 -0
  63. package/data/webui/js/render.js +438 -0
  64. package/data/webui/js/shared.js +3 -0
  65. package/data/webui/js/state.js +583 -0
  66. package/data/webui/js/theme.js +123 -0
  67. package/data/webui/js/util.js +584 -0
  68. package/dist/cli/app.js +593 -0
  69. package/dist/cli/capabilities.js +76 -0
  70. package/dist/cli/cell-widths.js +495 -0
  71. package/dist/cli/entry.js +10 -0
  72. package/dist/cli/error-panel.js +492 -0
  73. package/dist/cli/handlers/actor.js +84 -0
  74. package/dist/cli/handlers/https.js +614 -0
  75. package/dist/cli/handlers/prompt.js +299 -0
  76. package/dist/cli/handlers/users.js +226 -0
  77. package/dist/cli/handlers.js +3678 -0
  78. package/dist/cli/help.js +183 -0
  79. package/dist/cli/index.js +15 -0
  80. package/dist/cli/perf.js +810 -0
  81. package/dist/cli/render.js +254 -0
  82. package/dist/cli/serve.js +858 -0
  83. package/dist/cli/spec-data.js +2593 -0
  84. package/dist/cli/spec-types.js +8 -0
  85. package/dist/cli/usage-error.js +520 -0
  86. package/dist/cli/wire.js +70 -0
  87. package/dist/core/audit.js +346 -0
  88. package/dist/core/backup-compat.js +85 -0
  89. package/dist/core/backup.js +1639 -0
  90. package/dist/core/cluster.js +1398 -0
  91. package/dist/core/configimport.js +344 -0
  92. package/dist/core/data.js +267 -0
  93. package/dist/core/database-of.js +82 -0
  94. package/dist/core/diagnose.js +159 -0
  95. package/dist/core/doctor.js +1518 -0
  96. package/dist/core/edge/acme.js +338 -0
  97. package/dist/core/edge/engine.js +500 -0
  98. package/dist/core/edge/networks.js +174 -0
  99. package/dist/core/edge/paths.js +107 -0
  100. package/dist/core/edge/routes.js +251 -0
  101. package/dist/core/edge/routeyml.js +195 -0
  102. package/dist/core/edge/runtime.js +493 -0
  103. package/dist/core/edge/spec.js +305 -0
  104. package/dist/core/edge/types.js +202 -0
  105. package/dist/core/eks-docs.js +135 -0
  106. package/dist/core/eks.js +2240 -0
  107. package/dist/core/envvars.js +562 -0
  108. package/dist/core/eventlog.js +541 -0
  109. package/dist/core/firstrun.js +153 -0
  110. package/dist/core/journal.js +691 -0
  111. package/dist/core/kube/ask.js +231 -0
  112. package/dist/core/kube/capabilities.js +269 -0
  113. package/dist/core/kube/certmanager.js +452 -0
  114. package/dist/core/kube/chart.js +413 -0
  115. package/dist/core/kube/cluster.js +196 -0
  116. package/dist/core/kube/context.js +545 -0
  117. package/dist/core/kube/endpoints.js +448 -0
  118. package/dist/core/kube/exec.js +195 -0
  119. package/dist/core/kube/forward.js +732 -0
  120. package/dist/core/kube/grafana-ingress.js +110 -0
  121. package/dist/core/kube/ingress.js +218 -0
  122. package/dist/core/kube/manifests.js +361 -0
  123. package/dist/core/kube/monitoring.js +768 -0
  124. package/dist/core/kube/names.js +237 -0
  125. package/dist/core/kube/namespace.js +678 -0
  126. package/dist/core/kube/operator.js +941 -0
  127. package/dist/core/kube/probe.js +202 -0
  128. package/dist/core/kube/reachability.js +163 -0
  129. package/dist/core/kube/release.js +439 -0
  130. package/dist/core/kube/replicaset.js +180 -0
  131. package/dist/core/kube/scale.js +398 -0
  132. package/dist/core/kube/status.js +633 -0
  133. package/dist/core/kube/tools.js +238 -0
  134. package/dist/core/kube/transfer.js +173 -0
  135. package/dist/core/kube/workspace.js +423 -0
  136. package/dist/core/lifecycle/admin.js +64 -0
  137. package/dist/core/lifecycle/create-docker.js +1533 -0
  138. package/dist/core/lifecycle/create-k8s.js +939 -0
  139. package/dist/core/lifecycle/destroy.js +339 -0
  140. package/dist/core/lifecycle/inspect.js +635 -0
  141. package/dist/core/lifecycle/naming.js +298 -0
  142. package/dist/core/lifecycle/notes.js +726 -0
  143. package/dist/core/lifecycle/ownership.js +313 -0
  144. package/dist/core/lifecycle/payload.js +401 -0
  145. package/dist/core/lifecycle/ports.js +388 -0
  146. package/dist/core/lifecycle/preconditions.js +367 -0
  147. package/dist/core/lifecycle/pruning.js +551 -0
  148. package/dist/core/lifecycle/ready.js +753 -0
  149. package/dist/core/lifecycle/request.js +525 -0
  150. package/dist/core/lifecycle/seeding.js +281 -0
  151. package/dist/core/lifecycle/sizing.js +392 -0
  152. package/dist/core/lifecycle/state.js +286 -0
  153. package/dist/core/lifecycle/tlsplan.js +704 -0
  154. package/dist/core/lifecycle/types.js +232 -0
  155. package/dist/core/loadtest.js +995 -0
  156. package/dist/core/migrate.js +612 -0
  157. package/dist/core/monitor.js +494 -0
  158. package/dist/core/postready.js +969 -0
  159. package/dist/core/promote.js +804 -0
  160. package/dist/core/rcapi.js +1285 -0
  161. package/dist/core/recovery.js +75 -0
  162. package/dist/core/runner/engine.js +394 -0
  163. package/dist/core/runner/host.js +298 -0
  164. package/dist/core/runner/locks.js +129 -0
  165. package/dist/core/runner/paths.js +173 -0
  166. package/dist/core/runner/ports.js +172 -0
  167. package/dist/core/runner/queries.js +612 -0
  168. package/dist/core/runner/record.js +563 -0
  169. package/dist/core/scaleseed.js +271 -0
  170. package/dist/core/seed-db.js +208 -0
  171. package/dist/core/sessions.js +472 -0
  172. package/dist/core/skill.js +326 -0
  173. package/dist/core/sso-identities.js +172 -0
  174. package/dist/core/sso.js +703 -0
  175. package/dist/core/tls-local.js +311 -0
  176. package/dist/core/tls.js +878 -0
  177. package/dist/core/topology.js +482 -0
  178. package/dist/core/upgrade.js +868 -0
  179. package/dist/core/users.js +739 -0
  180. package/dist/lib/audit.js +100 -0
  181. package/dist/lib/close-matches.js +238 -0
  182. package/dist/lib/compose.js +672 -0
  183. package/dist/lib/config.js +1398 -0
  184. package/dist/lib/context.js +18 -0
  185. package/dist/lib/errors.js +305 -0
  186. package/dist/lib/events.js +208 -0
  187. package/dist/lib/float-text.js +126 -0
  188. package/dist/lib/format.js +1320 -0
  189. package/dist/lib/home.js +325 -0
  190. package/dist/lib/journal.js +122 -0
  191. package/dist/lib/json-text.js +733 -0
  192. package/dist/lib/jsonout.js +382 -0
  193. package/dist/lib/lock.js +516 -0
  194. package/dist/lib/login-name.js +202 -0
  195. package/dist/lib/map-limit.js +29 -0
  196. package/dist/lib/mkdir-parents.js +90 -0
  197. package/dist/lib/mongo-kernel.js +67 -0
  198. package/dist/lib/monitoring.js +492 -0
  199. package/dist/lib/platform-name.js +59 -0
  200. package/dist/lib/presets/common.js +390 -0
  201. package/dist/lib/presets/composite.js +326 -0
  202. package/dist/lib/presets/e2ee.js +143 -0
  203. package/dist/lib/presets/email.js +172 -0
  204. package/dist/lib/presets/guides.js +27 -0
  205. package/dist/lib/presets/index.js +490 -0
  206. package/dist/lib/presets/keycloak.js +369 -0
  207. package/dist/lib/presets/ldap.js +1285 -0
  208. package/dist/lib/presets/livechat.js +220 -0
  209. package/dist/lib/presets/multi-instance.js +124 -0
  210. package/dist/lib/presets/oidc.js +161 -0
  211. package/dist/lib/presets/public.js +496 -0
  212. package/dist/lib/presets/registry.js +64 -0
  213. package/dist/lib/presets/s3-minio.js +300 -0
  214. package/dist/lib/presets/saml.js +149 -0
  215. package/dist/lib/presets/scenario.js +51 -0
  216. package/dist/lib/presets/types.js +86 -0
  217. package/dist/lib/presets/voice-pbx.js +320 -0
  218. package/dist/lib/presets/voice.js +345 -0
  219. package/dist/lib/presets/webhooks.js +182 -0
  220. package/dist/lib/redact.js +106 -0
  221. package/dist/lib/seed-options.js +68 -0
  222. package/dist/lib/seed-profiles.js +59 -0
  223. package/dist/lib/targz.js +1383 -0
  224. package/dist/lib/teammode.js +25 -0
  225. package/dist/lib/tempdir.js +162 -0
  226. package/dist/lib/unicode-tables.js +2335 -0
  227. package/dist/lib/version-spec.js +357 -0
  228. package/dist/lib/versions.js +463 -0
  229. package/dist/lib/yaml-dump.js +1361 -0
  230. package/dist/perf/baseline.js +168 -0
  231. package/dist/perf/constrain.js +296 -0
  232. package/dist/perf/k6.js +235 -0
  233. package/dist/perf/mongoprof.js +171 -0
  234. package/dist/perf/rcmetrics.js +178 -0
  235. package/dist/perf/report.js +386 -0
  236. package/dist/perf/resources.js +224 -0
  237. package/dist/perf/slo.js +111 -0
  238. package/dist/perf/timeline.js +187 -0
  239. package/dist/perf/timings.js +85 -0
  240. package/dist/perf/verdict.js +201 -0
  241. package/dist/seams/aws-cli.js +126 -0
  242. package/dist/seams/docker-cli.js +280 -0
  243. package/dist/seams/exec.js +861 -0
  244. package/dist/seams/fs/lock.js +528 -0
  245. package/dist/seams/kubectl.js +83 -0
  246. package/dist/seams/rc-http.js +921 -0
  247. package/dist/seed/apply.js +190 -0
  248. package/dist/seed/assets.js +76 -0
  249. package/dist/seed/check.js +391 -0
  250. package/dist/seed/client.js +172 -0
  251. package/dist/seed/executor.js +726 -0
  252. package/dist/seed/history.js +281 -0
  253. package/dist/seed/kinds.js +91 -0
  254. package/dist/seed/plan.js +432 -0
  255. package/dist/seed/receipt.js +339 -0
  256. package/dist/seed/repairs.js +75 -0
  257. package/dist/seed/verification.js +363 -0
  258. package/dist/seed/wording.js +248 -0
  259. package/dist/web/app.js +326 -0
  260. package/dist/web/jobs.js +510 -0
  261. package/dist/web/route-deps.js +211 -0
  262. package/dist/web/route-table.js +213 -0
  263. package/dist/web/routes/backup.js +244 -0
  264. package/dist/web/routes/clusters.js +303 -0
  265. package/dist/web/routes/data.js +187 -0
  266. package/dist/web/routes/edge.js +82 -0
  267. package/dist/web/routes/index.js +63 -0
  268. package/dist/web/routes/jobs.js +95 -0
  269. package/dist/web/routes/logs.js +297 -0
  270. package/dist/web/routes/meta.js +191 -0
  271. package/dist/web/routes/people.js +151 -0
  272. package/dist/web/routes/perf.js +95 -0
  273. package/dist/web/routes/repros.js +550 -0
  274. package/dist/web/routes/session.js +361 -0
  275. package/dist/web/routes/spa.js +198 -0
  276. package/dist/web/security.js +475 -0
  277. package/dist/web/signin.js +246 -0
  278. package/package.json +67 -32
  279. package/.eslintrc +0 -94
  280. package/.swcrc +0 -18
  281. package/dist/bin.js +0 -3
  282. package/dist/cli.js +0 -184
  283. package/dist/commands/createBranch.js +0 -192
  284. package/src/bin.js +0 -4
  285. package/src/cli.ts +0 -25
  286. package/src/commands/createBranch.ts +0 -25
  287. package/src-old/logs.js +0 -323
  288. package/src-old/md.js +0 -191
  289. package/src-old/release-table.js +0 -60
  290. package/src-old/set-version.js +0 -614
  291. package/src-old/utils.js +0 -15
@@ -0,0 +1,878 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CLOUDFLARE_HINT_NETS = exports.MODE_ACME = exports.MODE_LOCAL = exports.ISSUED_FILE = exports.CERT_WARN_AT = exports.CERT_LIMIT_PER_WEEK = exports.LEGO_PROVIDER_DOCS = exports.DNS_ENV_FILE = exports.ACME_FILE_STAGING = exports.ACME_FILE = exports.ACME_DIR_NAME = exports.CA_CRT = exports.CA_KEY = exports.CA_DIR_NAME = exports.LOCAL_SUFFIX = exports.SERVICE = exports.TRAEFIK_TAG = void 0;
37
+ exports.tlsSpec = tlsSpec;
38
+ exports.rootUrl = rootUrl;
39
+ exports.caDir = caDir;
40
+ exports.acmeDir = acmeDir;
41
+ exports.localHostFor = localHostFor;
42
+ exports.normalizeAllowHost = normalizeAllowHost;
43
+ exports.normalizeDomain = normalizeDomain;
44
+ exports.acmeStorageName = acmeStorageName;
45
+ exports.registrableDomain = registrableDomain;
46
+ exports.issuedPath = issuedPath;
47
+ exports.readIssued = readIssued;
48
+ exports.recordIssuance = recordIssuance;
49
+ exports.recentIssuances = recentIssuances;
50
+ exports.budgetWarning = budgetWarning;
51
+ exports.dnsEnvPath = dnsEnvPath;
52
+ exports.dnsEnvVars = dnsEnvVars;
53
+ exports.inferDnsProvider = inferDnsProvider;
54
+ exports.dnsCredentials = dnsCredentials;
55
+ exports.acmeArgs = acmeArgs;
56
+ exports.certNames = certNames;
57
+ exports.certificateDetails = certificateDetails;
58
+ exports.originCertificate = originCertificate;
59
+ exports.verify = verify;
60
+ exports.probeServed = probeServed;
61
+ exports.notes = notes;
62
+ /**
63
+ * HTTPS: terminate TLS in front of Rocket.Chat with Traefik.
64
+ *
65
+ * Layered onto ANY repro via `up --https` rather than being its own preset -- `--preset` is
66
+ * single-valued, so a `tls` preset would be mutually exclusive with
67
+ * oidc/saml/livechat/multi-instance, which are exactly the ones that need HTTPS.
68
+ *
69
+ * Two ways to get the certificate, and only two inputs for the common one:
70
+ *
71
+ * acme `--domain X --email Y` Let's Encrypt via Traefik's own ACME resolver, the same
72
+ * DOMAIN + LETSENCRYPT_EMAIL pair the official
73
+ * compose.traefik.yml takes.
74
+ * local `--https` a CA made here with openssl (see `tls-local.ts`).
75
+ * Offline, no domain, no rate limits.
76
+ *
77
+ * The ACME CHALLENGE is not a user-facing choice. TLS-ALPN-01 is the default and what the
78
+ * official compose uses; dns-01 is selected automatically when provider credentials exist
79
+ * in `~/.houston/acme/dns.env`, because that is the only way to issue when Let's Encrypt
80
+ * cannot connect inbound -- behind NAT, behind a tunnel, or behind a proxy that terminates
81
+ * TLS in front of you. Neither appears as a flag.
82
+ *
83
+ * ## `node:tls` is used directly, and that is not a seam bypass
84
+ *
85
+ * `verify()` opens a TLS socket and reads what is actually served. That is a socket and a
86
+ * TLS handshake, and it is not HTTP: no request is made, no body is read, and the
87
+ * whole point is to inspect the handshake rather than what comes after it. Routing it
88
+ * through `seams/rc-http.ts` would mean asking an HTTP client a question about a
89
+ * certificate, which it cannot answer -- `fetch` gives no access to the peer chain. The
90
+ * certificate FIELDS still go through openssl via the process seam, as they always have,
91
+ * so the strings this reports are the same strings on both sides.
92
+ */
93
+ const fs = __importStar(require("node:fs"));
94
+ const net = __importStar(require("node:net"));
95
+ const path = __importStar(require("node:path"));
96
+ const tlsSocket = __importStar(require("node:tls"));
97
+ const node_crypto_1 = require("node:crypto");
98
+ const config = __importStar(require("../lib/config"));
99
+ const errors_1 = require("../lib/errors");
100
+ const home_1 = require("../lib/home");
101
+ const format_1 = require("../lib/format");
102
+ const exec_1 = require("../seams/exec");
103
+ /** The edge's Traefik, which is the multi-instance preset's too (`config.TRAEFIK_TAG`). */
104
+ exports.TRAEFIK_TAG = config.TRAEFIK_TAG;
105
+ exports.SERVICE = 'traefik';
106
+ exports.LOCAL_SUFFIX = 'houston.localhost';
107
+ exports.CA_DIR_NAME = 'ca';
108
+ exports.CA_KEY = 'ca.key';
109
+ exports.CA_CRT = 'ca.crt';
110
+ exports.ACME_DIR_NAME = 'acme';
111
+ exports.ACME_FILE = 'acme.json';
112
+ exports.ACME_FILE_STAGING = 'acme-staging.json';
113
+ /**
114
+ * Credentials for a dns-01 provider. A file, never argv: `ps` shows command lines to every
115
+ * user on the box.
116
+ */
117
+ exports.DNS_ENV_FILE = 'dns.env';
118
+ exports.LEGO_PROVIDER_DOCS = 'https://go-acme.github.io/lego/dns/';
119
+ /**
120
+ * Let's Encrypt: 50 certificates per registered domain per 7 days. Only NEW names cost --
121
+ * an existing certificate is reused -- so this is only reachable by a team creating many
122
+ * differently-named workspaces in a week. Counted and warned about rather than pre-empted:
123
+ * refusing to create a workspace over houston's own tally, which cannot see certificates
124
+ * issued by anything else on the domain, would be wrong far more often than right.
125
+ */
126
+ exports.CERT_LIMIT_PER_WEEK = 50;
127
+ /**
128
+ * Warn from here. Deliberately well below the limit: the useful moment to hear "a wildcard
129
+ * would remove this" is while there is still room to act.
130
+ */
131
+ exports.CERT_WARN_AT = 25;
132
+ /**
133
+ * Names houston has caused a certificate request for, and when. Traefik's acme.json holds
134
+ * the certificates themselves but no issuance dates, and parsing X.509 out of it would
135
+ * need a crypto dependency this project does not have.
136
+ */
137
+ exports.ISSUED_FILE = 'issued.json';
138
+ exports.MODE_LOCAL = 'local';
139
+ exports.MODE_ACME = 'acme';
140
+ /**
141
+ * Subject Traefik puts on the self-signed certificate it serves when a resolver has
142
+ * produced nothing yet -- how `tls-status` tells "ACME has not issued" apart from "ACME
143
+ * issued something wrong".
144
+ */
145
+ const TRAEFIK_FALLBACK = 'TRAEFIK DEFAULT CERT';
146
+ function tlsSpec(values = {}) {
147
+ return {
148
+ mode: exports.MODE_LOCAL,
149
+ host: '',
150
+ port: 0,
151
+ acmeEmail: '',
152
+ acmeStaging: false,
153
+ acmeChallenge: 'tlsalpn',
154
+ acmeDnsProvider: '',
155
+ ...values,
156
+ };
157
+ }
158
+ /**
159
+ * The URL a workspace advertises.
160
+ *
161
+ * 443 is implicit in an https URL; anything else has to be spelled out or Rocket.Chat
162
+ * advertises a URL that does not answer.
163
+ */
164
+ function rootUrl(spec) {
165
+ return `https://${spec.host}${spec.port === 443 ? '' : `:${String(spec.port)}`}`;
166
+ }
167
+ function caDir() {
168
+ return (0, home_1.joinPath)(config.home(), exports.CA_DIR_NAME);
169
+ }
170
+ function acmeDir() {
171
+ return (0, home_1.joinPath)(config.home(), exports.ACME_DIR_NAME);
172
+ }
173
+ function localHostFor(name) {
174
+ return `${name}.${exports.LOCAL_SUFFIX}`;
175
+ }
176
+ /**
177
+ * A hostname label: alphanumeric with internal hyphens. Deliberately not a full RFC 1123
178
+ * implementation -- this only has to reject the shapes that break us.
179
+ */
180
+ const LABEL_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/u;
181
+ /**
182
+ * Shared cleanup for a user-supplied hostname: scheme, trailing slash, dot, case.
183
+ *
184
+ * ONE implementation, because `--domain` and `--allow-host` are mistyped in exactly the
185
+ * same ways -- a pasted URL, a trailing slash, a capitalised name -- and diverging on
186
+ * which of those is forgiven is how one flag ends up accepting what the other refuses.
187
+ * They differ only on a PORT, which each decides for itself.
188
+ */
189
+ function cleanHost(value) {
190
+ let raw = value.trim();
191
+ const fixes = raw !== value ? ['trimmed whitespace'] : [];
192
+ for (const scheme of ['https://', 'http://']) {
193
+ if (raw.toLowerCase().startsWith(scheme)) {
194
+ raw = raw.slice(scheme.length);
195
+ fixes.push(`dropped '${scheme}'`);
196
+ break;
197
+ }
198
+ }
199
+ if (raw.endsWith('/')) {
200
+ raw = raw.replace(/\/+$/u, '');
201
+ fixes.push('dropped the trailing slash');
202
+ }
203
+ if (raw.endsWith('.')) {
204
+ // A trailing dot is a legal FQDN but does not match SNI or a URL host.
205
+ raw = raw.replace(/\.+$/u, '');
206
+ fixes.push('dropped the trailing dot');
207
+ }
208
+ if (raw !== raw.toLowerCase()) {
209
+ raw = raw.toLowerCase();
210
+ fixes.push('lower-cased it');
211
+ }
212
+ return [raw, fixes];
213
+ }
214
+ /**
215
+ * Turn a user-supplied `--allow-host` into a bare hostname. Returns `[host, note]`.
216
+ *
217
+ * The same cleanup as `--domain`, with one deliberate difference: a port is DROPPED and
218
+ * reported rather than refused. The Host guard compares hostnames with the port already
219
+ * stripped off the incoming header, so `--allow-host lab.example.com:9944` names exactly
220
+ * the right host -- and keeping the port, which is what used to happen, made it match
221
+ * nothing at all.
222
+ *
223
+ * Not hypothetical. Measured on a lab box, three of the five forms somebody typed in a row
224
+ * -- `https://h/`, `h/`, `h:9944` -- were each unmatchable, and `serve` started and
225
+ * reported itself healthy every time before 403ing every request.
226
+ *
227
+ * `*` is the documented "any Host" wildcard and passes through untouched.
228
+ */
229
+ function normalizeAllowHost(value) {
230
+ if (value.trim() === '*')
231
+ return ['*', ''];
232
+ let [raw, fixes] = cleanHost(value);
233
+ if (raw.startsWith('[')) {
234
+ // `[::1]:9944` / `[::1]` -- the guard unwraps the brackets too, so match it.
235
+ const inner = raw.slice(1).split(']')[0] ?? '';
236
+ if (inner !== '') {
237
+ raw = inner;
238
+ fixes = [...fixes, 'unwrapped the IPv6 brackets'];
239
+ }
240
+ }
241
+ else if ((raw.match(/:/gu) ?? []).length === 1) {
242
+ // host:port. More than one colon and no brackets is a bare IPv6 literal (`::1`),
243
+ // which has no port to drop and must survive untouched.
244
+ const [head, port] = raw.split(':');
245
+ raw = head;
246
+ fixes = [...fixes, `dropped the port '${port}' — a Host header's port is not matched`];
247
+ }
248
+ if (raw === '') {
249
+ throw new errors_1.ValidationError(`--allow-host '${value}' has no hostname in it. Pass the name you will type in the ` +
250
+ "address bar — e.g. --allow-host lab.example.com, or '*' for any host.");
251
+ }
252
+ if (raw.includes('/')) {
253
+ throw new errors_1.ValidationError(`--allow-host '${value}' contains a path. Pass the hostname only ` +
254
+ `(${raw.split('/')[0] ?? ''}) — the guard matches the Host header, and a Host ` +
255
+ 'header has no path in it.');
256
+ }
257
+ return [raw, fixes.join('; ')];
258
+ }
259
+ /**
260
+ * Turn a user-supplied `--domain` into a bare hostname. Returns `[host, note]`.
261
+ *
262
+ * The official Rocket.Chat compose docs spell out that DOMAIN must be set "without
263
+ * https:// or trailing slashes", which is a strong hint that people get it wrong -- and
264
+ * unguarded it produced `ROOT_URL="https://https://host"` plus a bogus ACME `domains`
265
+ * entry that Let's Encrypt rejects.
266
+ *
267
+ * Forms with one obvious meaning are corrected and reported. Forms that would change what
268
+ * gets served (a port, a path) are refused, because silently dropping them would not do
269
+ * what the user asked.
270
+ */
271
+ function normalizeDomain(value) {
272
+ const [raw, fixes] = cleanHost(value);
273
+ if (raw === '')
274
+ throw new errors_1.ValidationError('--domain is empty');
275
+ if (raw.includes('/')) {
276
+ throw new errors_1.ValidationError(`--domain '${value}' contains a path. Pass the hostname only ` +
277
+ `(${raw.split('/')[0] ?? ''}); serving a workspace under a sub-path is not supported.`);
278
+ }
279
+ if (raw.includes(':')) {
280
+ throw new errors_1.ValidationError(`--domain '${value}' contains a port. Pass the hostname only ` +
281
+ `(${raw.split(':')[0] ?? ''}) — a workspace on a real domain is served on 443, so the ` +
282
+ 'URL carries no port.');
283
+ }
284
+ if (raw.startsWith('*.')) {
285
+ throw new errors_1.ValidationError(`--domain '${value}' is a wildcard. --domain has to be the concrete host the ` +
286
+ 'workspace is reached at, because it becomes ROOT_URL.');
287
+ }
288
+ if (raw.split('.').some((label) => !LABEL_RE.test(label))) {
289
+ throw new errors_1.ValidationError(`--domain '${value}' is not a valid hostname (letters, digits and hyphens per ` +
290
+ 'label, separated by dots).');
291
+ }
292
+ return [raw, fixes.join('; ')];
293
+ }
294
+ function acmeStorageName(staging) {
295
+ return staging ? exports.ACME_FILE_STAGING : exports.ACME_FILE;
296
+ }
297
+ /**
298
+ * The domain Let's Encrypt counts against, approximately.
299
+ *
300
+ * The real rule is the eTLD+1 from the Public Suffix List, which this project does not
301
+ * carry -- so the last two labels are used instead. That is right for
302
+ * `t1.support.xyz.com` -> `xyz.com` and WRONG for multi-part suffixes like `co.uk`, where
303
+ * it groups a whole suffix as one domain and so over-counts.
304
+ *
305
+ * Acceptable only because this drives a warning and never a refusal: the worst case is
306
+ * mentioning a wildcard slightly too early.
307
+ */
308
+ function registrableDomain(host) {
309
+ const labels = (host || '')
310
+ .replace(/^\.+|\.+$/gu, '')
311
+ .split('.')
312
+ .filter((label) => label !== '');
313
+ if (labels.length >= 2)
314
+ return labels.slice(-2).join('.');
315
+ return labels[0] ?? '';
316
+ }
317
+ function issuedPath() {
318
+ return (0, home_1.joinPath)(acmeDir(), exports.ISSUED_FILE);
319
+ }
320
+ /**
321
+ * Exported so a check can read the real file through the real parser rather than
322
+ * re-parsing it; `recordIssuance` is its writer counterpart.
323
+ */
324
+ function readIssued() {
325
+ try {
326
+ const parsed = JSON.parse(fs.readFileSync(issuedPath(), 'utf8'));
327
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
328
+ ? parsed
329
+ : {};
330
+ }
331
+ catch {
332
+ return {};
333
+ }
334
+ }
335
+ const todayIso = () => new Date().toISOString().slice(0, 10);
336
+ /**
337
+ * Note that `host` needed a certificate of its own.
338
+ *
339
+ * Keyed by host and optional certificate identity, written ONCE per certificate:
340
+ * Kubernetes issues separate workspace and Grafana certificates on the same host.
341
+ * Re-registering an existing name
342
+ * reuses its certificate and costs nothing, so overwriting the date would make a
343
+ * long-lived workspace look like a fresh request every time it is recreated. Best-effort
344
+ * -- a tally must never stop the work.
345
+ */
346
+ function recordIssuance(host, when = '', certificate = '') {
347
+ if (host === '')
348
+ return;
349
+ try {
350
+ const issued = readIssued();
351
+ const key = certificate ? `${host}#${certificate}` : host;
352
+ if (key in issued)
353
+ return;
354
+ issued[key] = when || todayIso();
355
+ fs.mkdirSync(acmeDir(), { recursive: true });
356
+ const temporary = `${issuedPath()}.tmp`;
357
+ const ordered = Object.fromEntries(Object.keys(issued)
358
+ .sort()
359
+ .map((key) => [key, issued[key]]));
360
+ fs.writeFileSync(temporary, `${JSON.stringify(ordered, null, 2)}`, 'utf8');
361
+ fs.renameSync(temporary, issuedPath());
362
+ }
363
+ catch {
364
+ // A tally must never stop the work.
365
+ }
366
+ }
367
+ /** How many distinct certificates under `domain` were first seen in the last `days`. */
368
+ function recentIssuances(domain, days = 7) {
369
+ const cutoff = Date.now() - days * 86400000;
370
+ let count = 0;
371
+ for (const [host, day] of Object.entries(readIssued())) {
372
+ if (registrableDomain(host.split('#')[0] ?? host) !== domain)
373
+ continue;
374
+ const when = Date.parse(`${String(day)}T00:00:00Z`);
375
+ if (Number.isNaN(when))
376
+ continue;
377
+ // Strictly newer than the cutoff, as it always was.
378
+ if (when > cutoff - 0) {
379
+ const cutoffDay = new Date(cutoff).toISOString().slice(0, 10);
380
+ if (String(day) > cutoffDay)
381
+ count += 1;
382
+ }
383
+ }
384
+ return count;
385
+ }
386
+ /** The certificate-budget message, or '' while there is nothing worth saying. */
387
+ function budgetWarning(host) {
388
+ const domain = registrableDomain(host);
389
+ if (domain === '')
390
+ return '';
391
+ const used = recentIssuances(domain);
392
+ if (used < exports.CERT_WARN_AT)
393
+ return '';
394
+ return (`${String(used)} certificates issued for ${domain} in the last 7 days (limit ` +
395
+ `${String(exports.CERT_LIMIT_PER_WEEK)}). A wildcard certificate would remove this — it needs ` +
396
+ `a DNS API token in ${dnsEnvPath()}.`);
397
+ }
398
+ function dnsEnvPath() {
399
+ return (0, home_1.joinPath)(acmeDir(), exports.DNS_ENV_FILE);
400
+ }
401
+ /**
402
+ * Which lego provider a credentials variable belongs to.
403
+ *
404
+ * The variables ARE provider-specific, so the file already says which provider it is --
405
+ * asking the user to repeat that on every `up` was ceremony. Longest prefix wins, so
406
+ * `CLOUDFLARE_*` is not mistaken for anything shorter. Not exhaustive: an unrecognised
407
+ * file just means `--acme-dns-provider` is required, which is the old behaviour rather
408
+ * than a failure.
409
+ */
410
+ const DNS_VAR_PROVIDERS = Object.freeze({
411
+ CF_: 'cloudflare',
412
+ CLOUDFLARE_: 'cloudflare',
413
+ AWS_: 'route53',
414
+ DO_AUTH_TOKEN: 'digitalocean',
415
+ GCE_: 'gcloud',
416
+ AZURE_: 'azuredns',
417
+ LINODE_: 'linode',
418
+ HETZNER_: 'hetzner',
419
+ VULTR_: 'vultr',
420
+ OVH_: 'ovh',
421
+ GODADDY_: 'godaddy',
422
+ NAMECHEAP_: 'namecheap',
423
+ DNSIMPLE_: 'dnsimple',
424
+ NS1_: 'ns1',
425
+ DIGITALOCEAN_: 'digitalocean',
426
+ });
427
+ /** The KEY names in a credentials file, never the values. */
428
+ function keyNames(text) {
429
+ const names = [];
430
+ for (const raw of text.split('\n')) {
431
+ const line = raw.trim();
432
+ if (line !== '' && !line.startsWith('#') && line.includes('=')) {
433
+ names.push(line.split('=')[0].trim());
434
+ }
435
+ }
436
+ return names;
437
+ }
438
+ /** Variable NAMES in the credentials file (never values), or `[]` if absent. */
439
+ function dnsEnvVars() {
440
+ try {
441
+ if (!fs.statSync(dnsEnvPath()).isFile())
442
+ return [];
443
+ }
444
+ catch {
445
+ return [];
446
+ }
447
+ return keyNames(fs.readFileSync(dnsEnvPath(), 'utf8'));
448
+ }
449
+ /**
450
+ * Work out the lego provider from the credentials file. Returns `[provider, why]`.
451
+ *
452
+ * `['', reason]` when the file is missing, unrecognised, or names more than one provider
453
+ * -- in which case `--acme-dns-provider` has to be given explicitly.
454
+ */
455
+ function inferDnsProvider() {
456
+ const names = dnsEnvVars();
457
+ if (names.length === 0) {
458
+ return ['', `${dnsEnvPath()} does not exist or has no KEY=VALUE lines`];
459
+ }
460
+ const found = new Map();
461
+ // Longest prefix first so CLOUDFLARE_ beats CF_ and DIGITALOCEAN_ beats DO_.
462
+ const prefixes = Object.keys(DNS_VAR_PROVIDERS).sort((left, right) => right.length - left.length);
463
+ for (const name of names) {
464
+ const upper = name.toUpperCase();
465
+ for (const prefix of prefixes) {
466
+ if (upper.startsWith(prefix)) {
467
+ found.set(DNS_VAR_PROVIDERS[prefix], name);
468
+ break;
469
+ }
470
+ }
471
+ }
472
+ if (found.size === 0) {
473
+ return ['', `none of ${names.join(', ')} matches a known provider`];
474
+ }
475
+ if (found.size > 1) {
476
+ return [
477
+ '',
478
+ `${names.join(', ')} look like more than one provider (${[...found.keys()].sort().join(', ')})`,
479
+ ];
480
+ }
481
+ const [provider, via] = [...found.entries()][0];
482
+ return [provider, `${via} in ${path.basename(dnsEnvPath())}`];
483
+ }
484
+ /**
485
+ * Check the dns-01 credentials file, returning `[ok, message]`.
486
+ *
487
+ * Each lego provider reads its OWN environment variables (CF_DNS_API_TOKEN,
488
+ * AWS_ACCESS_KEY_ID, DO_AUTH_TOKEN, GCE_PROJECT, ...), so this cannot verify the right
489
+ * ones are present -- but it can catch the file being missing or empty, which otherwise
490
+ * surfaces only as an opaque Traefik failure minutes later.
491
+ */
492
+ function dnsCredentials(provider) {
493
+ const target = dnsEnvPath();
494
+ let text;
495
+ try {
496
+ if (!fs.statSync(target).isFile())
497
+ throw new Error('not a file');
498
+ text = fs.readFileSync(target, 'utf8');
499
+ }
500
+ catch {
501
+ return [
502
+ false,
503
+ `--acme-challenge dns needs provider credentials, and ${target} does not exist.\n` +
504
+ ` Create it with the variables '${provider}' expects (see ` +
505
+ `${exports.LEGO_PROVIDER_DOCS}${provider}/), e.g. for cloudflare:\n` +
506
+ ` mkdir -p ${path.dirname(target)} && chmod 700 ${path.dirname(target)}\n` +
507
+ ` printf 'CF_DNS_API_TOKEN=%s\\n' "$TOKEN" > ${target}\n` +
508
+ ` chmod 600 ${target}`,
509
+ ];
510
+ }
511
+ const names = keyNames(text);
512
+ if (names.length === 0) {
513
+ return [
514
+ false,
515
+ `${target} has no KEY=VALUE lines. Add the variables '${provider}' expects — see ` +
516
+ `${exports.LEGO_PROVIDER_DOCS}${provider}/`,
517
+ ];
518
+ }
519
+ // Names only. Never echo the values.
520
+ return [true, `${path.basename(target)}: ${names.join(', ')}`];
521
+ }
522
+ /**
523
+ * Traefik's ACME flags.
524
+ *
525
+ * Public because the front door (`core/edge`) issues certificates the same way a workspace
526
+ * does; two copies of this would drift, and the challenge choice is the part that decides
527
+ * whether issuance works at all.
528
+ */
529
+ function acmeArgs(spec) {
530
+ const args = [
531
+ `--certificatesresolvers.le.acme.email=${spec.acmeEmail}`,
532
+ `--certificatesresolvers.le.acme.storage=/etc/traefik/acme/${acmeStorageName(spec.acmeStaging)}`,
533
+ ];
534
+ if (spec.acmeStaging) {
535
+ args.push('--certificatesresolvers.le.acme.caserver=' +
536
+ 'https://acme-staging-v02.api.letsencrypt.org/directory');
537
+ }
538
+ if (spec.acmeChallenge === 'dns') {
539
+ // dns-01: validated by a TXT record the provider API writes, so Let's Encrypt never
540
+ // connects here. The only option behind NAT, a tunnel, or a proxy that terminates TLS
541
+ // in front of the origin.
542
+ args.push('--certificatesresolvers.le.acme.dnschallenge=true');
543
+ if (spec.acmeDnsProvider !== '') {
544
+ args.push(`--certificatesresolvers.le.acme.dnschallenge.provider=${spec.acmeDnsProvider}`);
545
+ }
546
+ }
547
+ else if (spec.acmeChallenge === 'http') {
548
+ // http-01, and it exists because the other two can both be unavailable at once.
549
+ // Reported from an EC2 box where TLS-ALPN validation failed every time with `remote
550
+ // error: tls: unrecognized name` -- Let's Encrypt reached :443 and the challenge was
551
+ // not being answered -- and where dns-01 was impossible because the operator had the
552
+ // machine and not the DNS zone.
553
+ args.push('--certificatesresolvers.le.acme.httpchallenge=true');
554
+ args.push('--certificatesresolvers.le.acme.httpchallenge.entrypoint=web');
555
+ }
556
+ else {
557
+ // TLS-ALPN-01, the same challenge the official compose.traefik.yml uses. It validates
558
+ // on 443, which is already published, so no second port has to be opened for it.
559
+ args.push('--certificatesresolvers.le.acme.tlschallenge=true');
560
+ }
561
+ return args;
562
+ }
563
+ async function certField(pem, ...args) {
564
+ try {
565
+ const proc = await (0, exec_1.capture)(['openssl', 'x509', '-noout', ...args], {
566
+ input: pem,
567
+ encoding: 'utf8',
568
+ timeoutMs: 15000,
569
+ });
570
+ return String(proc.stdout ?? '').trim();
571
+ }
572
+ catch {
573
+ return '';
574
+ }
575
+ }
576
+ /**
577
+ * The DNS names a certificate is valid for, from its subjectAltName.
578
+ *
579
+ * NEEDED because a certificate can have no subject at all. cert-manager issues exactly
580
+ * that shape -- the name lives only in the SANs -- so every Kubernetes workspace's
581
+ * certificate reported `Subject: ?`, which reads as a parse failure rather than as a
582
+ * perfectly good certificate. `tls-local.ts` already says why the SANs are the field that
583
+ * matters: browsers have ignored commonName since Chrome 58.
584
+ */
585
+ async function certNames(pem) {
586
+ const raw = await certField(pem, '-ext', 'subjectAltName');
587
+ const out = [];
588
+ for (const chunk of raw.split('\n').join(',').split(',')) {
589
+ const part = chunk.trim();
590
+ if (part.startsWith('DNS:'))
591
+ out.push(part.slice(4).trim());
592
+ }
593
+ return out;
594
+ }
595
+ /** Extract identity and provenance fields from the served certificate. */
596
+ async function certificateDetails(pem) {
597
+ const issuer = (await certField(pem, '-issuer')).replace(/^issuer=/u, '').trim();
598
+ const subject = (await certField(pem, '-subject')).replace(/^subject=/u, '').trim();
599
+ return {
600
+ issuer,
601
+ subject,
602
+ // The names, always, because the subject can legitimately be empty. A caller that
603
+ // shows one field should be able to fall back.
604
+ names: await certNames(pem),
605
+ dates: (await certField(pem, '-enddate')).split('\n').join(' '),
606
+ fallback: `${issuer}${subject}`.toLowerCase().includes(TRAEFIK_FALLBACK.toLowerCase()),
607
+ // WHY an untrusted certificate is untrusted, which is three different situations and
608
+ // had one message. `--acme-staging` was treated as the only explanation, so a
609
+ // workspace on Kubernetes whose cert-manager had not finished yet was reported as "a
610
+ // real Let's Encrypt-issued certificate ... normal for --acme-staging" -- wrong twice.
611
+ //
612
+ // self_signed - issuer is the subject: nothing has issued this, it is a
613
+ // placeholder. On a cluster that means "not issued YET".
614
+ // staging - Let's Encrypt's staging root says so in its own name.
615
+ self_signed: issuer !== '' && issuer === subject,
616
+ staging: issuer.toLowerCase().includes('staging'),
617
+ };
618
+ }
619
+ /** One TLS handshake, with verification off, returning the peer certificate as PEM. */
620
+ async function handshake(host, port, timeout, servername) {
621
+ return await new Promise((resolve) => {
622
+ const socket = tlsSocket.connect({
623
+ host,
624
+ port,
625
+ servername: net.isIP(servername) === 0 ? servername : undefined,
626
+ rejectUnauthorized: false,
627
+ timeout: Math.round(timeout * 1000),
628
+ });
629
+ const finish = (pem, error) => {
630
+ clearTimeout(deadline);
631
+ socket.removeAllListeners();
632
+ socket.destroy();
633
+ resolve({ pem, error });
634
+ };
635
+ // A socket idle timeout alone can be extended by handshake traffic indefinitely.
636
+ const deadline = setTimeout(() => finish('', 'TimeoutError: timed out'), timeout * 1000);
637
+ socket.once('secureConnect', () => {
638
+ // `getPeerCertificate` is TYPED as always returning a certificate and does not:
639
+ // for a peer that offered none it returns an empty object, so `raw` is absent at
640
+ // runtime while the type says Buffer. `Buffer.isBuffer` is the check the type
641
+ // system cannot see through, and an empty certificate is no certificate -- the case
642
+ // is real, an anonymous-cipher or aborted handshake reaches it.
643
+ const der = socket.getPeerCertificate(false).raw;
644
+ if (!Buffer.isBuffer(der) || der.length === 0) {
645
+ finish('', 'the server offered no certificate');
646
+ return;
647
+ }
648
+ const body = (der.toString('base64').match(/.{1,64}/gu) ?? []).join('\n');
649
+ finish(`-----BEGIN CERTIFICATE-----\n${body}\n-----END CERTIFICATE-----\n`, '');
650
+ });
651
+ // A timeout, reported in the established words: TimeoutError, "timed out".
652
+ socket.once('timeout', () => finish('', 'TimeoutError: timed out'));
653
+ socket.once('error', (error) => finish('', (0, format_1.socketErrorText)(error)));
654
+ });
655
+ }
656
+ /**
657
+ * The exact peer currently offered by an owned loopback edge for this SNI. This is
658
+ * observation for a credential-free route probe, not an issuer or public-trust verdict.
659
+ */
660
+ async function originCertificate(servername, { port = 443, timeout = 5 } = {}) {
661
+ const observed = await handshake('127.0.0.1', port, timeout, servername);
662
+ const fallback = observed.pem !== '' && new node_crypto_1.X509Certificate(observed.pem).subject === `CN=${TRAEFIK_FALLBACK}`;
663
+ return { ...observed, fallback };
664
+ }
665
+ /** Whether the endpoint validates under the requested trust store. */
666
+ /**
667
+ * What THIS MACHINE trusts: Node's bundled roots plus the operating system's store.
668
+ *
669
+ * Without a `ca` option Node checks only the roots it ships with, so a CA `trust-ca` had
670
+ * put into the system store never counted, and `tls-status` said "Not trusted by this
671
+ * machine yet" straight after it ran. The bundled roots stay, so a public certificate is
672
+ * judged as it always was. Read on every check, not cached: `serve` outlives a `trust-ca`.
673
+ */
674
+ function machineRoots() {
675
+ try {
676
+ return [...tlsSocket.getCACertificates('bundled'), ...tlsSocket.getCACertificates('system')];
677
+ }
678
+ catch {
679
+ return [...tlsSocket.rootCertificates];
680
+ }
681
+ }
682
+ async function certificateAccepted(host, port, timeout, servername, cafile) {
683
+ // THE CA IS READ INSIDE THE TRY, and that is not style. A CA file that does not exist
684
+ // made the trust setup throw ENOENT -- a filesystem error, but thrown one line ABOVE
685
+ // the handler that caught filesystem errors -- so this reporting function
686
+ // crashed its caller instead of reporting. Hit live: a fresh HOUSTON_HOME going straight
687
+ // to `--domain` has never minted a local certificate, so `ca/ca.crt` is simply not
688
+ // there, and `up` ended in a stack trace after the workspace had been built.
689
+ let ca;
690
+ try {
691
+ ca = cafile !== '' ? fs.readFileSync(cafile) : machineRoots();
692
+ }
693
+ catch {
694
+ return false;
695
+ }
696
+ return await new Promise((resolve) => {
697
+ const socket = tlsSocket.connect({
698
+ host,
699
+ port,
700
+ servername: net.isIP(servername) === 0 ? servername : undefined,
701
+ ca,
702
+ rejectUnauthorized: true,
703
+ timeout: Math.round(timeout * 1000),
704
+ });
705
+ const finish = (ok) => {
706
+ socket.removeAllListeners();
707
+ socket.destroy();
708
+ resolve(ok);
709
+ };
710
+ socket.once('secureConnect', () => finish(socket.authorized));
711
+ socket.once('timeout', () => finish(false));
712
+ socket.once('error', () => finish(false));
713
+ });
714
+ }
715
+ /**
716
+ * Connect over TLS and report what is ACTUALLY being served.
717
+ *
718
+ * Deliberately connects with verification off first: a staging or local-CA certificate is
719
+ * untrusted by design, and refusing to look at it would report "broken" for a setup that
720
+ * is working exactly as intended. Trust is then a separate, second question.
721
+ */
722
+ async function verify(host, { port = 443, timeout = 10, cafile = '', sni = '', } = {}) {
723
+ const out = {
724
+ host,
725
+ port,
726
+ serving: false,
727
+ trusted: false,
728
+ trusted_via_ca: false,
729
+ issuer: '',
730
+ subject: '',
731
+ dates: '',
732
+ names: [],
733
+ fallback: false,
734
+ self_signed: false,
735
+ staging: false,
736
+ error: '',
737
+ };
738
+ // `sni` lets the caller connect to an ADDRESS while presenting a different server name
739
+ // -- how you check what this host serves for a domain without letting a proxy in front
740
+ // answer instead.
741
+ const servername = sni || host;
742
+ const { pem, error } = await handshake(host, port, timeout, servername);
743
+ if (error !== '') {
744
+ out.error = error;
745
+ return out;
746
+ }
747
+ out.serving = true;
748
+ Object.assign(out, await certificateDetails(pem));
749
+ // Two DIFFERENT questions, kept apart on purpose:
750
+ // trusted - would a browser accept this, using only the SYSTEM store?
751
+ // trusted_via_ca - does it chain to the CA we were given?
752
+ // Collapsing them made local mode always report "trusted", because passing houston's
753
+ // own CA guarantees success and hides whether `trust-ca` has run.
754
+ out.trusted = await certificateAccepted(host, port, timeout, servername, '');
755
+ out.trusted_via_ca =
756
+ cafile !== ''
757
+ ? await certificateAccepted(host, port, timeout, servername, cafile)
758
+ : out.trusted;
759
+ return out;
760
+ }
761
+ /**
762
+ * What THIS host really serves for a workspace's name, asked where its bytes actually go.
763
+ *
764
+ * ONE PROBE FOR BOTH FRONT-ENDS. `tls-status` learnt both rules below in 2.1.1 and the GUI's
765
+ * Check TLS, which asked on its own, learnt neither: it reported a CDN's certificate as a
766
+ * Kubernetes workspace's, and the cluster's placeholder as a Docker workspace's.
767
+ */
768
+ async function probeServed(host, port, extra,
769
+ // `ask` is `verify` as the caller reaches it, so a stand-in for this module's `verify` is
770
+ // the one asked: a call from in here would bypass it.
771
+ { cafile = '', ask = verify } = {}) {
772
+ const withCa = cafile === '' ? {} : { cafile };
773
+ // On a Kubernetes workspace this box is not in the path at all: the certificate is a
774
+ // Secret in the cluster and the cluster's ingress holds :443. Probing loopback there
775
+ // reaches whatever else is listening here, which reported a healthy EKS workspace as
776
+ // broken. So the NAME is what gets probed when TLS terminates elsewhere.
777
+ if (String(extra.tls_terminates ?? '') === 'cluster') {
778
+ // THE ORIGIN, when this box's edge passes the name through to the cluster: the name
779
+ // itself may be answered by a CDN in front, and behind Cloudflare this reported its
780
+ // certificate (Google Trust Services WE1) as the workspace's, exit 0, while the cluster
781
+ // served its ingress default -- which hid a certificate that never issued. The recorded
782
+ // ingress endpoint, asked with the name as SNI, is what the edge hands the bytes to.
783
+ const origin = /^(.+):(\d+)$/u.exec(String(extra.ingress_endpoint ?? ''));
784
+ if ((0, format_1.isTruthy)(extra.edge) && origin !== null) {
785
+ const served = await ask(String(origin[1]), {
786
+ port: Number(origin[2]),
787
+ sni: host,
788
+ ...withCa,
789
+ });
790
+ if (!served.serving)
791
+ return served;
792
+ // THE ORIGIN ANSWERING IS NOT THE NAME ANSWERING: with the edge down this said
793
+ // "✓ serving" for a URL that refused every connection. Any certificate at the name
794
+ // will do here -- a CDN's included -- the one reported stays the origin's.
795
+ const front = await ask(host, { port, ...withCa });
796
+ return front.serving
797
+ ? served
798
+ : {
799
+ ...served,
800
+ serving: false,
801
+ error: `${host}:${String(port)} answers nothing from this machine (${front.error}); ` +
802
+ 'the cluster does, so the edge in front of it is likely down — ' +
803
+ '`houston edge status`',
804
+ };
805
+ }
806
+ return await ask(host, { port, ...withCa });
807
+ }
808
+ // BOTH LOOPBACK FAMILIES, because one of them may not be ours: k3s's ServiceLB DNATs
809
+ // IPv4 :443 into the cluster, so 127.0.0.1 answered `CN = TRAEFIK DEFAULT CERT` while
810
+ // [::1] -- the houston edge -- served the real one. The first answer that is not a
811
+ // fallback wins; if every family answers with a placeholder, that IS the finding -- and a
812
+ // family that refuses does not replace it: with IPv6 off, [::1]'s refusal read as
813
+ // "nothing serving" over the placeholder IPv4 had found.
814
+ let report = null;
815
+ for (const probe of ['127.0.0.1', '::1']) {
816
+ const answer = await ask(probe, { port, sni: host, ...withCa });
817
+ if (report === null || !report.serving || (answer.serving && !answer.fallback)) {
818
+ report = answer;
819
+ }
820
+ if (report.serving && !report.fallback)
821
+ break;
822
+ }
823
+ return report;
824
+ }
825
+ /**
826
+ * A few of Cloudflare's published edge ranges. Used ONLY to explain a failure more
827
+ * precisely, never to block: the list drifts, and being wrong here must not stop a working
828
+ * setup.
829
+ */
830
+ exports.CLOUDFLARE_HINT_NETS = [
831
+ '104.16.0.0/13',
832
+ '104.24.0.0/14',
833
+ '172.64.0.0/13',
834
+ '173.245.48.0/20',
835
+ '162.158.0.0/15',
836
+ '108.162.192.0/18',
837
+ '190.93.240.0/20',
838
+ '188.114.96.0/20',
839
+ '197.234.240.0/22',
840
+ '198.41.128.0/17',
841
+ '131.0.72.0/22',
842
+ '141.101.64.0/18',
843
+ '103.21.244.0/22',
844
+ '103.22.200.0/22',
845
+ '103.31.4.0/22',
846
+ ];
847
+ function notes(spec, name = '<name>') {
848
+ if (spec.mode === exports.MODE_LOCAL) {
849
+ return [
850
+ `HTTPS (local certificate): ${rootUrl(spec)}`,
851
+ "Signed by houston's own CA, so a browser warns until you run `houston trust-ca` " +
852
+ 'once (then no warnings, and curl needs no -k).',
853
+ 'A phone cannot use this: the cert is untrusted there and .localhost resolves to ' +
854
+ 'the phone itself. Use --domain for mobile.',
855
+ ];
856
+ }
857
+ if (spec.acmeStaging) {
858
+ // Staging roots are NOT in any trust store -- that is the whole point of staging.
859
+ // Claiming otherwise sent people looking for a broken workspace when the browser
860
+ // warning was the expected, correct outcome.
861
+ return [
862
+ `HTTPS (Let's Encrypt STAGING): ${rootUrl(spec)}`,
863
+ 'A staging certificate is deliberately NOT trusted - a browser warning here is the ' +
864
+ "SUCCESS signal, because TLS terminated with a real Let's Encrypt-issued cert.",
865
+ `Confirm what is served: houston tls-status --name ${name}`,
866
+ 'Then `houston config unset acme.staging` and re-run with --force.',
867
+ ];
868
+ }
869
+ return [
870
+ `HTTPS (Let's Encrypt): ${rootUrl(spec)}`,
871
+ 'Publicly trusted, so the Rocket.Chat mobile app accepts it with nothing to install - ' +
872
+ `just add ${rootUrl(spec)} in the app.`,
873
+ 'Traefik requests the certificate in the background. Confirm it issued: houston ' +
874
+ `tls-status --name ${name}`,
875
+ 'Certificate state lives in ~/.houston/acme/ and survives `down`, so re-creating this ' +
876
+ 'workspace reuses the cert instead of re-issuing it.',
877
+ ];
878
+ }