@rocket.chat/houston 0.27.0-next.3 → 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 (293) 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 -194
  284. package/dist/outputCI.js +0 -59
  285. package/src/bin.js +0 -4
  286. package/src/cli.ts +0 -25
  287. package/src/commands/createBranch.ts +0 -28
  288. package/src/outputCI.ts +0 -12
  289. package/src-old/logs.js +0 -323
  290. package/src-old/md.js +0 -191
  291. package/src-old/release-table.js +0 -60
  292. package/src-old/set-version.js +0 -614
  293. package/src-old/utils.js +0 -15
@@ -0,0 +1,969 @@
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.POST_READY_ACTIONS = exports.quotedText = exports.IDP_CERT_DEADLINE = void 0;
37
+ exports.execIn = execIn;
38
+ exports.resetActions = resetActions;
39
+ exports.runPostReady = runPostReady;
40
+ /**
41
+ * Post-ready preset self-configuration, moved out of the CLI so both front ends run it
42
+ * identically. Each handler reports via `emit` instead of printing.
43
+ *
44
+ * Behaviour is unchanged from the CLI's former post-ready handlers; only the output
45
+ * mechanism differs (Event objects rather than printed lines and warnings).
46
+ *
47
+ * Every handler returns a BOOLEAN, and `runPostReady` collects the ones that answered
48
+ * false. That is the whole point of the module's shape: a create that printed "could not
49
+ * fetch/apply IdP cert" and then "starting" left the reader to work out for themselves
50
+ * whether SAML actually worked -- the deployment succeeding and the configuration
51
+ * succeeding are different answers to different questions.
52
+ */
53
+ const composite_1 = require("../lib/presets/composite");
54
+ const e2ee_1 = require("../lib/presets/e2ee");
55
+ const voice_1 = require("../lib/presets/voice");
56
+ const config = __importStar(require("../lib/config"));
57
+ const format_1 = require("../lib/format");
58
+ Object.defineProperty(exports, "quotedText", { enumerable: true, get: function () { return format_1.quotedText; } });
59
+ const events_1 = require("../lib/events");
60
+ const exec_1 = require("../seams/exec");
61
+ const exec_2 = require("./kube/exec");
62
+ const names_1 = require("./kube/names");
63
+ const namespace_1 = require("./kube/namespace");
64
+ const rcapi = __importStar(require("./rcapi"));
65
+ const engine_1 = require("./runner/engine");
66
+ const record_1 = require("./runner/record");
67
+ const topology = __importStar(require("./topology"));
68
+ /**
69
+ * How long to wait for Keycloak to serve its SAML descriptor.
70
+ *
71
+ * Passed INTO `fetchSamlIdpCert`, which owns the retrying -- not layered on top of it.
72
+ * Generous because on Kubernetes the image is pulled before the realm is imported.
73
+ */
74
+ exports.IDP_CERT_DEADLINE = 180.0;
75
+ const realSleep = (seconds) => (0, exec_1.sleep)(seconds * 1000);
76
+ /** Truthiness: false for null, undefined, false, 0, '', [] and {}. */
77
+ function truthy(value) {
78
+ if (value === null || value === undefined || value === false)
79
+ return false;
80
+ if (value === true)
81
+ return true;
82
+ if (typeof value === 'number')
83
+ return value !== 0;
84
+ if (typeof value === 'string')
85
+ return value.length > 0;
86
+ if (Array.isArray(value))
87
+ return value.length > 0;
88
+ if (typeof value === 'object')
89
+ return Object.keys(value).length > 0;
90
+ return true;
91
+ }
92
+ /**
93
+ * `meta.extra` when it is a mapping, else `{}`.
94
+ *
95
+ * The declared type says this cannot fail, and the declared type is optimistic: `extra`
96
+ * is copied verbatim out of `repro.json` by `record.fromDocument`, so a hand-edited or
97
+ * half-written record can hold a list, a string or null there and still satisfy the
98
+ * compiler. Routed through `unknown` so the check is against what is on disk rather than
99
+ * against what the annotation claims.
100
+ */
101
+ function bagOf(value) {
102
+ const raw = value;
103
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
104
+ return {};
105
+ return raw;
106
+ }
107
+ /**
108
+ * `action["key"]` -- absent raises, rather than quietly becoming the string "undefined".
109
+ *
110
+ * A preset that names a `post_ready` action without the fields that action needs is a
111
+ * broken preset, and it has always been refused, naming the key. Coercing the missing value
112
+ * instead would PATCH a Rocket.Chat setting to the literal text `undefined` and report
113
+ * success.
114
+ */
115
+ function required(action, key) {
116
+ if (!(key in action))
117
+ throw new Error(`a post_ready action is missing ${JSON.stringify(key)}`);
118
+ return action[key];
119
+ }
120
+ /** The key's value, or `fallback` -- keyed on PRESENCE, so an explicit falsy value survives. */
121
+ function getOr(action, key, fallback) {
122
+ return key in action ? action[key] : fallback;
123
+ }
124
+ /** An integer: a number truncated toward zero, a boolean as 1 or 0, text as signed digits. */
125
+ function toInt(value) {
126
+ if (typeof value === 'boolean')
127
+ return value ? 1 : 0;
128
+ if (typeof value === 'number') {
129
+ if (!Number.isFinite(value))
130
+ throw new RangeError(`${String(value)} is not an integer`);
131
+ return Math.trunc(value);
132
+ }
133
+ const text = String(value ?? '').trim();
134
+ if (!/^[+-]?\d+$/u.test(text)) {
135
+ throw new RangeError(`'${text}' is not an integer`);
136
+ }
137
+ return Number.parseInt(text, 10);
138
+ }
139
+ /**
140
+ * Run a command in a preset's side service, on either runtime.
141
+ *
142
+ * A post_ready action is a preset configuring ITSELF, and presets now exist on both
143
+ * runtimes -- so the one call that reaches into a container had to stop being a Compose
144
+ * call. `composeExec` on a Kubernetes workspace answers "no configuration file provided:
145
+ * not found" -- docker compose's own words for "there is no compose project here" --
146
+ * printed raw, in the middle of a create that then said it succeeded.
147
+ */
148
+ async function execIn(meta, service, argv) {
149
+ if (topology.ofMeta(meta) !== topology.KUBERNETES) {
150
+ return await (0, engine_1.composeExec)(meta.name, service, argv);
151
+ }
152
+ const extra = bagOf(meta.extra);
153
+ const ctxValue = extra[config.EXTRA_CONTEXT];
154
+ const context = String(truthy(ctxValue) ? ctxValue : names_1.CONTEXT);
155
+ const nsValue = extra.namespace;
156
+ // Asked only when none is recorded: asking kubectl to mint the namespace name for a
157
+ // workspace that already recorded one is a subprocess spent on an answer that was
158
+ // already on disk.
159
+ const namespace = String(truthy(nsValue) ? nsValue : await (0, namespace_1.namespaceFor)(meta.name));
160
+ const pod = await exec_2.kube.run([
161
+ 'kubectl',
162
+ '--context',
163
+ context,
164
+ '-n',
165
+ namespace,
166
+ 'get',
167
+ 'pod',
168
+ '-l',
169
+ `app=houston-${service}`,
170
+ '-o',
171
+ 'jsonpath={.items[0].metadata.name}',
172
+ ], { own: (0, names_1.isOurs)(context) });
173
+ const target = (pod.stdout || '').trim();
174
+ if (!target)
175
+ return 1;
176
+ const res = await exec_2.kube.run(['kubectl', '--context', context, '-n', namespace, 'exec', target, '--', ...argv], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
177
+ return res.returncode;
178
+ }
179
+ /** The front door and each independently cached Rocket.Chat instance behind it. */
180
+ function providerRoots(meta) {
181
+ const roots = [meta.rootUrl];
182
+ if (topology.ofMeta(meta) === topology.KUBERNETES)
183
+ return roots;
184
+ const count = Number(bagOf(meta.extra).instances ?? 1);
185
+ for (let i = 1; Number.isInteger(count) && count > 1 && i <= count; i += 1) {
186
+ const own = new URL(meta.rootUrl);
187
+ own.port = String(meta.hostPort + i);
188
+ roots.push(own.origin);
189
+ }
190
+ return roots;
191
+ }
192
+ async function samlProvidersReady(meta, auth, roots, timeoutMs = 3000) {
193
+ const ready = await Promise.all(roots.map(async (root) => await rcapi.samlProviderReady(root, {
194
+ auth,
195
+ publicUrl: meta.publicUrl || meta.rootUrl,
196
+ timeoutMs,
197
+ })));
198
+ return ready.every((ok) => ok);
199
+ }
200
+ async function waitForSamlProviders(meta, auth, roots, sleep, { maxWaitMs } = {}) {
201
+ const deadline = maxWaitMs === undefined ? undefined : Date.now() + maxWaitMs;
202
+ let stable = false;
203
+ for (let attempt = 0; attempt < 12; attempt += 1) {
204
+ const remaining = deadline === undefined ? undefined : deadline - Date.now();
205
+ if (remaining !== undefined && remaining <= 0)
206
+ return false;
207
+ // One probe makes two sequential requests; roots are observed in parallel. Keep
208
+ // their combined request budget inside the pre-mutation observation deadline.
209
+ const timeoutMs = remaining === undefined ? 3000 : Math.min(3000, remaining / 2);
210
+ const all = await samlProvidersReady(meta, auth, roots, timeoutMs);
211
+ if (deadline !== undefined && Date.now() >= deadline)
212
+ return false;
213
+ // HTTP can answer before Rocket.Chat's initial debounced SAML load completes.
214
+ // Observe every process across a reload interval, without changing its settings.
215
+ if (all && stable)
216
+ return true;
217
+ stable = all;
218
+ if (attempt < 11) {
219
+ const pause = deadline === undefined ? 3 : Math.min(3, (deadline - Date.now()) / 1000);
220
+ if (pause <= 0)
221
+ return false;
222
+ await sleep(pause);
223
+ }
224
+ }
225
+ return false;
226
+ }
227
+ async function registerSamlProvider(meta, auth, roots, enable, emit, sleep) {
228
+ const apply = async (value) => {
229
+ const applied = await Promise.all(roots.map(async (root) => await rcapi.setSetting(root, auth, (0, record_1.adminPass)(meta), enable, value)));
230
+ return applied.every((ok) => ok);
231
+ };
232
+ const provider = await rcapi.getSetting(meta.rootUrl, auth, (0, record_1.adminPass)(meta), `${enable}_provider`);
233
+ if (typeof provider !== 'string' || provider === '') {
234
+ (0, events_1.warn)(emit, `could not read ${enable}_provider to refresh the SAML provider`, {
235
+ phase: 'post_ready',
236
+ });
237
+ return false;
238
+ }
239
+ // A disabled reload deletes a shared service before updating this process's provider
240
+ // list. Waiting a fixed debounce interval does not prove slower replicas completed
241
+ // that reload: one could remove the service after another had enabled it again.
242
+ let stable = false;
243
+ let disabled = false;
244
+ let enabled;
245
+ try {
246
+ if (!(await apply(false))) {
247
+ (0, events_1.warn)(emit, `could not disable ${enable} to refresh the SAML provider`, {
248
+ phase: 'post_ready',
249
+ });
250
+ return false;
251
+ }
252
+ for (let attempt = 0; attempt < 12; attempt += 1) {
253
+ const states = await Promise.all(roots.map(async (root) => await rcapi.samlProviderState(root, provider, {
254
+ publicUrl: meta.publicUrl || meta.rootUrl,
255
+ })));
256
+ const all = states.every((state) => state === 'unloaded');
257
+ if (all && stable) {
258
+ disabled = true;
259
+ break;
260
+ }
261
+ stable = all;
262
+ if (attempt < 11)
263
+ await sleep(3);
264
+ }
265
+ }
266
+ finally {
267
+ // Restore after a partial write, observation failure or interruption, as well as a
268
+ // timeout. Cleanup can send this compensating request while cancellation unwinds.
269
+ enabled = await (0, exec_1.cleanup)(async () => await apply(true));
270
+ if (!enabled)
271
+ (0, events_1.warn)(emit, `could not enable ${enable}; the SAML login service is not ready`, {
272
+ phase: 'post_ready',
273
+ });
274
+ }
275
+ if (!enabled)
276
+ return false;
277
+ if (!disabled) {
278
+ (0, events_1.warn)(emit, 'SAML provider reload did not finish disabling on every instance', {
279
+ phase: 'post_ready',
280
+ });
281
+ return false;
282
+ }
283
+ if (await waitForSamlProviders(meta, auth, roots, sleep))
284
+ return true;
285
+ (0, events_1.warn)(emit, 'IdP cert applied, but the SAML login service did not register on every instance', {
286
+ phase: 'post_ready',
287
+ });
288
+ return false;
289
+ }
290
+ async function prSamlIdpCert(meta, auth, action, emit, sleep) {
291
+ (0, events_1.info)(emit, 'fetching IdP cert (Keycloak first boot can take ~30s)...', { phase: 'post_ready' });
292
+ // ONE call. `fetchSamlIdpCert` already retries to its own deadline -- its docstring says
293
+ // "Retries until the IdP (e.g. Keycloak, which boots slowly) is serving" -- and v0.54.1
294
+ // wrapped it in a second 20-attempt loop without reading that. 20 x 90s is thirty
295
+ // minutes of a create that looks hung, which is how the operational audit found it: the
296
+ // SAML workspace sat in "still waiting for the IdP to serve its descriptor" for half an
297
+ // hour.
298
+ //
299
+ // The deadline is raised instead, and only here: Keycloak on Kubernetes has to pull its
300
+ // image before it can boot, which the Compose default did not allow for.
301
+ const cert = await rcapi.fetchSamlIdpCert(String(required(action, 'descriptor_url')), {
302
+ timeout: exports.IDP_CERT_DEADLINE,
303
+ });
304
+ if (!truthy(cert)) {
305
+ (0, events_1.warn)(emit, 'could not fetch/apply IdP cert (is the IdP up?)', { phase: 'post_ready' });
306
+ return false;
307
+ }
308
+ const roots = providerRoots(meta);
309
+ const setting = String(required(action, 'setting'));
310
+ const enable = action.enable_setting;
311
+ // A restarted process can serve HTTP before its initial SAML load finishes. If the
312
+ // certificate is unchanged, let that registration finish before deciding it needs
313
+ // repair: a toggle schedules independent async reloads against a shared service.
314
+ // A provider that stays absent reaches the existing observed reload path below.
315
+ if (truthy(enable) &&
316
+ (await rcapi.getSetting(meta.rootUrl, auth, (0, record_1.adminPass)(meta), setting)) === cert &&
317
+ (await waitForSamlProviders(meta, auth, roots, sleep, { maxWaitMs: 33000 }))) {
318
+ // Nothing was written, so nothing was "applied".
319
+ (0, events_1.info)(emit, 'IdP cert already in place; SAML login button registered.', {
320
+ phase: 'post_ready',
321
+ });
322
+ return true;
323
+ }
324
+ const applied = await Promise.all(roots.map(async (root) => await rcapi.setSetting(root, auth, (0, record_1.adminPass)(meta), setting, cert)));
325
+ if (!applied.every((ok) => ok)) {
326
+ (0, events_1.warn)(emit, 'could not fetch/apply IdP cert (is the IdP up?)', { phase: 'post_ready' });
327
+ return false;
328
+ }
329
+ if (truthy(enable) &&
330
+ !(await registerSamlProvider(meta, auth, roots, String(enable), emit, sleep))) {
331
+ return false;
332
+ }
333
+ (0, events_1.info)(emit, 'IdP cert applied; SAML login button registered.', { phase: 'post_ready' });
334
+ return true;
335
+ }
336
+ async function prKeycloakMasterSslOff(meta, _auth, action, emit, _sleep) {
337
+ const svc = String(getOr(action, 'service', 'keycloak'));
338
+ const port = getOr(action, 'port', 8080);
339
+ // Under the workspace's HTTPS name Keycloak serves from a path (`lib/presets/public.ts`).
340
+ const base = String(getOr(action, 'path', ''));
341
+ const kcadm = '/opt/keycloak/bin/kcadm.sh';
342
+ const script = `${kcadm} config credentials --server http://localhost:${String(port)}${base} ` +
343
+ // Both streams: its "Logging into ... as user admin" goes to stderr, which a Docker exec
344
+ // shares with houston's own -- under `up --json` and on serve's console.
345
+ `--realm master --user admin --password admin >/dev/null 2>&1 && ` +
346
+ `${kcadm} update realms/master -s sslRequired=NONE`;
347
+ // Through whichever runtime owns this workspace -- see `execIn`.
348
+ if ((await execIn(meta, svc, ['bash', '-lc', script])) === 0) {
349
+ (0, events_1.info)(emit, 'Keycloak admin console enabled over HTTP.', { phase: 'post_ready' });
350
+ return true;
351
+ }
352
+ (0, events_1.warn)(emit, 'could not relax Keycloak master-realm sslRequired ' +
353
+ '(is Keycloak up yet?) - the admin console may reject HTTP', { phase: 'post_ready' });
354
+ return false;
355
+ }
356
+ /** Apply each setting; return the ids that did not take. */
357
+ async function applySettings(meta, auth, settings) {
358
+ const failed = [];
359
+ for (const [sid, val] of Object.entries(settings)) {
360
+ if (!(await rcapi.setSetting(meta.rootUrl, auth, (0, record_1.adminPass)(meta), sid, val)))
361
+ failed.push(sid);
362
+ }
363
+ return failed;
364
+ }
365
+ /** Observe the public login service on each independently cached RC process. */
366
+ async function oauthProvidersReady(roots, provider, auth, timeoutMs) {
367
+ const ready = await Promise.all(roots.map(async (root) => {
368
+ try {
369
+ const [status, text] = await rcapi.call(root, 'GET', '/api/v1/service.configurations', {
370
+ auth,
371
+ timeoutMs,
372
+ });
373
+ if (status !== 200)
374
+ return false;
375
+ const parsed = JSON.parse(text);
376
+ if (parsed === null || typeof parsed !== 'object')
377
+ return false;
378
+ const configurations = parsed.configurations;
379
+ return (Array.isArray(configurations) &&
380
+ configurations.some((entry) => entry !== null &&
381
+ typeof entry === 'object' &&
382
+ entry.service === provider));
383
+ }
384
+ catch (error) {
385
+ if (error instanceof SyntaxError || error instanceof rcapi.RequestFailed)
386
+ return false;
387
+ throw error;
388
+ }
389
+ }));
390
+ return ready.every((ok) => ok);
391
+ }
392
+ /** Configure the disabled custom provider before enabling its debounced RC loader. */
393
+ async function prCreateOauthProvider(meta, auth, action, emit, sleep) {
394
+ const name = String(required(action, 'name'));
395
+ if (!(await rcapi.addOauthService(meta.rootUrl, auth, (0, record_1.adminPass)(meta), name))) {
396
+ (0, events_1.warn)(emit, 'could not create the OAuth provider', { phase: 'post_ready' });
397
+ return false;
398
+ }
399
+ const settings = { ...required(action, 'settings') };
400
+ const enable = `Accounts_OAuth_Custom-${name}`;
401
+ const enableValue = settings[enable];
402
+ const hasEnable = enable in settings;
403
+ if (hasEnable)
404
+ delete settings[enable];
405
+ // RC creates a disabled provider. Enabling before its URL exists can make the
406
+ // asynchronous CustomOAuth constructor throw, even though every PATCH answers 200.
407
+ // Keep an existing enabled provider enabled: a healthy ready must not toggle it off.
408
+ let failed = await applySettings(meta, auth, settings);
409
+ for (let attempt = 0; attempt < 3; attempt += 1) {
410
+ if (failed.length === 0)
411
+ break;
412
+ await sleep(2);
413
+ const subset = {};
414
+ for (const key of failed)
415
+ subset[key] = settings[key];
416
+ failed = await applySettings(meta, auth, subset);
417
+ }
418
+ if (failed.length === 0 && hasEnable) {
419
+ if (!(await rcapi.setSetting(meta.rootUrl, auth, (0, record_1.adminPass)(meta), enable, enableValue))) {
420
+ failed.push(enable);
421
+ }
422
+ }
423
+ if (failed.length > 0) {
424
+ const named = [...failed].sort().slice(0, 4).join(', ');
425
+ (0, events_1.warn)(emit, `the OAuth provider exists but ${failed.length} of its ` +
426
+ `${Object.keys(settings).length + (hasEnable ? 1 : 0)} settings did not apply: ` +
427
+ `${named}${failed.length > 4 ? '…' : ''}. Its login button may be absent ` +
428
+ `or lead nowhere.`, { phase: 'post_ready' });
429
+ return false;
430
+ }
431
+ if (enableValue === true) {
432
+ const roots = providerRoots(meta);
433
+ const provider = name.toLowerCase().replace(/[^a-z0-9_]/gu, '');
434
+ const deadline = Date.now() + 33000;
435
+ let registered = false;
436
+ for (let attempt = 0; attempt < 12; attempt += 1) {
437
+ const remaining = deadline - Date.now();
438
+ if (remaining <= 0)
439
+ break;
440
+ const ready = await oauthProvidersReady(roots, provider, auth, Math.min(3000, remaining));
441
+ if (Date.now() > deadline)
442
+ break;
443
+ if (ready) {
444
+ registered = true;
445
+ break;
446
+ }
447
+ if (attempt < 11) {
448
+ const pause = Math.min(3, (deadline - Date.now()) / 1000);
449
+ if (pause <= 0)
450
+ break;
451
+ await sleep(pause);
452
+ }
453
+ }
454
+ if (!registered) {
455
+ (0, events_1.warn)(emit, 'OAuth settings applied, but the login service did not register on every instance', {
456
+ phase: 'post_ready',
457
+ });
458
+ return false;
459
+ }
460
+ }
461
+ (0, events_1.info)(emit, 'OIDC provider created and configured; login button registered.', {
462
+ phase: 'post_ready',
463
+ });
464
+ return true;
465
+ }
466
+ async function prLivechatSetup(meta, auth, action, emit, _sleep) {
467
+ const url = meta.rootUrl;
468
+ const pw = (0, record_1.adminPass)(meta);
469
+ const agents = [
470
+ { agentId: auth.userId, username: config.ADMIN_USERNAME },
471
+ ];
472
+ await rcapi.addLivechatAgent(url, auth, pw, config.ADMIN_USERNAME);
473
+ const wanted = toInt(getOr(action, 'agents', 1));
474
+ for (let i = 2; i <= wanted; i += 1) {
475
+ const u = `agent${String(i)}`;
476
+ await rcapi.createUser(url, auth, pw, u);
477
+ await rcapi.addLivechatAgent(url, auth, pw, u);
478
+ const uid = await rcapi.getUserId(url, auth, u);
479
+ if (truthy(uid))
480
+ agents.push({ agentId: String(uid), username: u });
481
+ }
482
+ const available = await rcapi.setLivechatAvailable(url, auth, pw);
483
+ const dept = action.department;
484
+ let deptOk = false;
485
+ if (truthy(dept)) {
486
+ const deptId = await rcapi.ensureLivechatDepartment(url, auth, pw, String(dept));
487
+ if (truthy(deptId)) {
488
+ deptOk = await rcapi.assignLivechatAgents(url, auth, pw, String(deptId), agents);
489
+ }
490
+ }
491
+ const canned = await rcapi.saveCannedResponse(url, auth, pw, 'hello', 'Hi! Thanks for reaching out - how can I help?');
492
+ if (!canned) {
493
+ (0, events_1.info)(emit, '(canned responses & business hours are Enterprise features - pass ' +
494
+ '--reg-token to enable, else set them up manually)', { phase: 'post_ready' });
495
+ }
496
+ // REPORTED, like every other handler. This returned nothing on both paths, so a livechat
497
+ // workspace whose agent could not be made available printed a warning and was still
498
+ // counted as fully configured -- the same hole the oidc action had. `canned` is
499
+ // deliberately NOT part of the verdict: it fails on a workspace with no licence, which
500
+ // is the normal case and not a fault.
501
+ if (!available) {
502
+ (0, events_1.warn)(emit, 'set up the Omnichannel agent manually (Admin -> Omnichannel -> Agents)', {
503
+ phase: 'post_ready',
504
+ });
505
+ return false;
506
+ }
507
+ let summary = `Omnichannel: ${agents.length} agent(s) available`;
508
+ if (deptOk)
509
+ summary += `, '${String(dept)}' department created + assigned`;
510
+ (0, events_1.info)(emit, `${summary} - log into RC to go online.`, { phase: 'post_ready' });
511
+ return true;
512
+ }
513
+ /**
514
+ * Create test users, each with its username as its password; a user an earlier `ready` made
515
+ * (users.create refuses it) counts. False, with a warning naming who is missing, otherwise.
516
+ */
517
+ async function ensureTestUsers(meta, auth, emit, label, usernames) {
518
+ const url = meta.rootUrl;
519
+ const pw = (0, record_1.adminPass)(meta);
520
+ const missing = [];
521
+ for (const username of usernames) {
522
+ if (await rcapi.createUser(url, auth, pw, username))
523
+ continue;
524
+ if (!truthy(await rcapi.getUserId(url, auth, username)))
525
+ missing.push(username);
526
+ }
527
+ if (missing.length > 0) {
528
+ (0, events_1.warn)(emit, `could not create the ${label} test users ${missing.join(', ')}`, {
529
+ phase: 'post_ready',
530
+ });
531
+ return false;
532
+ }
533
+ return true;
534
+ }
535
+ /**
536
+ * The `e2ee` preset's test users. Nothing about encryption is done here: each user's keys are
537
+ * made in their browser the first time they sign in. Re-run by `ready`, so an existing user
538
+ * is kept, not an error.
539
+ */
540
+ async function prE2eeUsers(meta, auth, _action, emit, _sleep) {
541
+ if (!(await ensureTestUsers(meta, auth, emit, 'E2EE', e2ee_1.E2EE_TEST_USERS)))
542
+ return false;
543
+ (0, events_1.info)(emit, `E2EE test users ready: ${e2ee_1.E2EE_TEST_USERS.join(', ')} (password = username)`, {
544
+ phase: 'post_ready',
545
+ });
546
+ return true;
547
+ }
548
+ /**
549
+ * The Voice test users and, with SIP, their extensions. Rocket.Chat lets an extension be set
550
+ * only while SIP integration is on, which needs a licence with the Voice add-on: a refusal is
551
+ * that missing licence, so it is a warning saying where to set them later, not a failure.
552
+ */
553
+ async function prVoiceUsers(meta, auth, action, emit, _sleep) {
554
+ const users = Object.keys(voice_1.VOICE_TEST_USERS);
555
+ if (!(await ensureTestUsers(meta, auth, emit, 'Voice', users)))
556
+ return false;
557
+ (0, events_1.info)(emit, `Voice test users ready: ${users.join(', ')} (password = username)`, {
558
+ phase: 'post_ready',
559
+ });
560
+ if (!truthy(action.extensions))
561
+ return true;
562
+ const url = meta.rootUrl;
563
+ const pw = (0, record_1.adminPass)(meta);
564
+ const refused = [];
565
+ for (const [username, extension] of Object.entries(voice_1.VOICE_TEST_USERS)) {
566
+ const id = await rcapi.getUserId(url, auth, username);
567
+ if (id === null || !(await rcapi.setVoiceExtension(url, auth, pw, id, extension))) {
568
+ refused.push(username);
569
+ }
570
+ }
571
+ if (refused.length > 0) {
572
+ (0, events_1.warn)(emit, `could not give ${refused.join(', ')} their extensions: Rocket.Chat sets one only while ` +
573
+ 'Voice is licensed. Apply the license in Administration → Subscription, then run ' +
574
+ `houston ready --name ${meta.name}.`, { phase: 'post_ready' });
575
+ return true;
576
+ }
577
+ const given = Object.entries(voice_1.VOICE_TEST_USERS).map(([username, ext], i) => i === 0 ? `${username} has extension ${ext}` : `${username} ${ext}`);
578
+ (0, events_1.info)(emit, `SIP: ${given.join(', ')}`, { phase: 'post_ready' });
579
+ return true;
580
+ }
581
+ /** The Omnichannel webhook's event switches, for a workspace that cannot list its settings. */
582
+ const WEBHOOK_EVENT_SETTINGS = [
583
+ 'start',
584
+ 'close',
585
+ 'chat_taken',
586
+ 'chat_queued',
587
+ 'forward',
588
+ 'offline_msg',
589
+ 'visitor_message',
590
+ 'agent_message',
591
+ ].map((event) => `Livechat_webhook_on_${event}`);
592
+ /** The `?from=` a capture wrote into a repointed URL: where the call was bound. */
593
+ function capturedFrom(url) {
594
+ try {
595
+ return new URL(url).searchParams.get('from') ?? '';
596
+ }
597
+ catch {
598
+ return '';
599
+ }
600
+ }
601
+ /** The JSON the inbox answers: not empty, and without `text`, so Rocket.Chat posts nothing back. */
602
+ const INBOX_ANSWER = '{"captured":true}';
603
+ async function sessionState(api, uuid) {
604
+ try {
605
+ const [status, text] = await rcapi.call(api, 'GET', `/api/session/${encodeURIComponent(uuid)}`, {
606
+ timeoutMs: 5000,
607
+ });
608
+ if (status === 404)
609
+ return 'missing';
610
+ if (status !== 200)
611
+ return 'unreachable';
612
+ const parsed = JSON.parse(text);
613
+ const code = parsed.response?.status_code;
614
+ const body = parsed.response?.response_body_base64;
615
+ if (code !== 200)
616
+ return 'other';
617
+ return typeof body === 'string' && body !== '' ? 'ok' : 'auto';
618
+ }
619
+ catch {
620
+ return 'unreachable';
621
+ }
622
+ }
623
+ async function createSession(api) {
624
+ try {
625
+ const [status, text] = await rcapi.call(api, 'POST', '/api/session', {
626
+ data: {
627
+ status_code: 200,
628
+ headers: [{ name: 'Content-Type', value: 'application/json' }],
629
+ delay: 0,
630
+ response_body_base64: Buffer.from(INBOX_ANSWER).toString('base64'),
631
+ },
632
+ timeoutMs: 5000,
633
+ });
634
+ const uuid = JSON.parse(text).uuid;
635
+ return status < 300 && typeof uuid === 'string' && uuid !== '' ? uuid : null;
636
+ }
637
+ catch {
638
+ return null;
639
+ }
640
+ }
641
+ /** The session segment of a URL at the inbox, `http://webhooks:8080/<uuid>/...`; '' elsewhere. */
642
+ function sessionOf(url, origin) {
643
+ if (!url.startsWith(origin))
644
+ return '';
645
+ try {
646
+ return new URL(url).pathname.split('/')[1] ?? '';
647
+ }
648
+ catch {
649
+ return '';
650
+ }
651
+ }
652
+ function originOf(url, fallback) {
653
+ try {
654
+ return new URL(url).origin;
655
+ }
656
+ catch {
657
+ return fallback;
658
+ }
659
+ }
660
+ /**
661
+ * The inbox's API: the port the preset published, at the address houston reaches the
662
+ * workspace by -- with --bind <ip> nothing answers on localhost.
663
+ */
664
+ function apiOrigin(rootUrl, uiUrl) {
665
+ try {
666
+ const port = new URL(uiUrl).port;
667
+ return port === '' ? '' : `http://${new URL(rootUrl).hostname}:${port}`;
668
+ }
669
+ catch {
670
+ return '';
671
+ }
672
+ }
673
+ /**
674
+ * The webhooks preset: the inbox's session, the two sample integrations, the Omnichannel
675
+ * webhook pointed at the inbox, the inbox on the SSRF allowlist, and -- with capture=all --
676
+ * every other outgoing integration repointed there, the original URL kept in the new one's
677
+ * query string.
678
+ *
679
+ * THE SESSION IS MADE HERE, NOT BY THE FIRST REQUEST: the receiver's auto-created session
680
+ * answers 200 with an empty body, which Rocket.Chat reads as a failed call and retries four
681
+ * times, so every message landed five times and the History tab read too-many-retries. One
682
+ * made through the receiver's API answers JSON. The receiver picks the uuid, so it is
683
+ * recorded, the recorded one is kept while it still answers, and a lost one (an idle month,
684
+ * a removed volume) or the auto-created one is replaced and whatever pointed at it
685
+ * repointed. While the receiver's API cannot be reached nothing is wired: the auto-created
686
+ * session would bring the retries back.
687
+ *
688
+ * Everything is found before it is made, so a ready, an upgrade, a restore and a rebuild
689
+ * re-run it safely; what Rocket.Chat answered is recorded under `extra.webhooks` for `info`
690
+ * and the GUI, as the RELATIVE hook path: the host is composed when it is read.
691
+ *
692
+ * The rule for the Omnichannel webhook is "wire events only to our inbox, never widen a
693
+ * foreign one": a URL a customer's dump brought along is left alone (and named) unless
694
+ * capture=all, because switching more events on would post them to the customer's CRM.
695
+ */
696
+ async function prWebhooksSetup(meta, auth, action, emit, _sleep) {
697
+ // The first build recorded a fixed session in both addresses; the origins are what count.
698
+ const receiverOrigin = originOf(String(required(action, 'receiver')), config.WEBHOOKS_RECEIVER);
699
+ const api = apiOrigin(meta.rootUrl, String(getOr(action, 'ui_url', '')));
700
+ const capture = String(getOr(action, 'capture', 'off')) === 'all';
701
+ const origin = `${receiverOrigin}/`;
702
+ const url = meta.rootUrl;
703
+ const pw = (0, record_1.adminPass)(meta);
704
+ const phase = { phase: 'post_ready' };
705
+ let ok = true;
706
+ const states = new Map();
707
+ const stateOf = async (uuid) => {
708
+ const known = states.get(uuid);
709
+ if (known !== undefined)
710
+ return known;
711
+ const state = await sessionState(api, uuid);
712
+ states.set(uuid, state);
713
+ return state;
714
+ };
715
+ const listed = await rcapi.listIntegrations(url, auth, pw, { type: 'webhook-outgoing' });
716
+ const ours = listed?.find((doc) => doc.name === config.WEBHOOKS_OUTGOING);
717
+ const current = await rcapi.getSetting(url, auth, pw, 'Livechat_webhookUrl');
718
+ const currentUrl = typeof current === 'string' ? current : '';
719
+ // The session a rebuilt record forgot (`up --force` rebuilds `extra`) is the one the
720
+ // sample integration or the Omnichannel webhook still posts to: the first that still
721
+ // answers as the inbox is kept, so a rebuild never splits the inbox in two.
722
+ const recorded = meta.extra.webhooks?.session;
723
+ const oursUrl = Array.isArray(ours?.urls) ? String(ours.urls[0] ?? '') : '';
724
+ const candidates = [
725
+ typeof recorded === 'string' ? recorded : '',
726
+ sessionOf(oursUrl, origin),
727
+ sessionOf(currentUrl, origin),
728
+ ].filter((one) => one !== '');
729
+ let session = '';
730
+ for (const one of candidates) {
731
+ if ((await stateOf(one)) === 'ok') {
732
+ session = one;
733
+ break;
734
+ }
735
+ }
736
+ if (session === '') {
737
+ const made = await createSession(api);
738
+ if (made === null) {
739
+ (0, events_1.warn)(emit, `could not reach the inbox at ${api || 'its port'} to make its session: nothing was wired -- houston ready --name ${meta.name} once the inbox answers`, phase);
740
+ return false;
741
+ }
742
+ session = made;
743
+ states.set(made, 'ok');
744
+ }
745
+ const receiver = `${origin}${session}`;
746
+ /** A URL at the inbox whose session is gone or the receiver's own, moved to this one. */
747
+ const repaired = async (one) => {
748
+ const uuid = sessionOf(one, origin);
749
+ if (uuid === '' || uuid === session)
750
+ return one;
751
+ // An engineer's own session (a 500, a delay) stays; only a lost or empty one moves.
752
+ const state = await stateOf(uuid);
753
+ if (state !== 'missing' && state !== 'auto')
754
+ return one;
755
+ return `${receiver}${one.slice(origin.length + uuid.length)}`;
756
+ };
757
+ const outgoing = ours !== undefined
758
+ ? 'listed'
759
+ : await rcapi.createOutgoingWebhook(url, auth, pw, {
760
+ name: config.WEBHOOKS_OUTGOING,
761
+ urls: [`${receiver}/outgoing`],
762
+ });
763
+ if (outgoing === null) {
764
+ (0, events_1.warn)(emit, `could not create the '${config.WEBHOOKS_OUTGOING}' integration (is rocket.cat present, and does admin hold manage-outgoing-integrations?)`, phase);
765
+ ok = false;
766
+ }
767
+ const incoming = await rcapi.createIncomingWebhook(url, auth, pw, {
768
+ name: config.WEBHOOKS_INCOMING,
769
+ channel: '#general',
770
+ alias: 'houston',
771
+ });
772
+ if (incoming === null) {
773
+ (0, events_1.warn)(emit, `could not create the '${config.WEBHOOKS_INCOMING}' integration (is rocket.cat present, and #general?)`, phase);
774
+ ok = false;
775
+ }
776
+ const failed = [];
777
+ const set = async (id, value) => {
778
+ if (!(await rcapi.setSetting(url, auth, pw, id, value)))
779
+ failed.push(id);
780
+ };
781
+ const atInbox = currentUrl.startsWith(origin);
782
+ let omnichannel = currentUrl;
783
+ if (current === null) {
784
+ // "Could not read" is not "empty": writing over a URL nobody saw could replace a
785
+ // customer's without a word.
786
+ (0, events_1.warn)(emit, 'could not read Livechat_webhookUrl: the Omnichannel webhook is left as it is', phase);
787
+ ok = false;
788
+ }
789
+ else if (currentUrl === '' || atInbox || capture) {
790
+ const replaced = !atInbox && currentUrl !== '';
791
+ if (atInbox) {
792
+ // Ours at a session the receiver lost, or at the auto-created one: moved to this one.
793
+ omnichannel = await repaired(currentUrl);
794
+ if (omnichannel !== currentUrl)
795
+ await set('Livechat_webhookUrl', omnichannel);
796
+ }
797
+ else {
798
+ // The URL it replaced rides along in ?from=, as a captured integration's does, so
799
+ // `info` can say where the webhook was bound after any rebuild of the record.
800
+ omnichannel = replaced
801
+ ? `${receiver}/omnichannel?from=${encodeURIComponent(currentUrl)}`
802
+ : `${receiver}/omnichannel`;
803
+ await set('Livechat_webhookUrl', omnichannel);
804
+ if (replaced)
805
+ (0, events_1.warn)(emit, `Omnichannel webhook was ${currentUrl}: now the inbox (capture=all)`, phase);
806
+ }
807
+ const token = await rcapi.getSetting(url, auth, pw, 'Livechat_secret_token');
808
+ if (token === '' || token === false || replaced) {
809
+ await set('Livechat_secret_token', config.WEBHOOKS_TOKEN);
810
+ }
811
+ // The known switches first, then any the workspace lists beyond them: `settings?count=0`
812
+ // is capped on a workspace without API_Allow_Infinite_Count, and a short list must not
813
+ // read as "this version has none" -- a switch the version lacks answers null below.
814
+ const listed = (await rcapi.settingIds(url, auth, pw)) ?? new Set();
815
+ for (const id of new Set([...WEBHOOK_EVENT_SETTINGS, ...listed])) {
816
+ // `on_capture` needs navigation-as-message and is not an event of a chat.
817
+ if (!id.startsWith('Livechat_webhook_on_') || id === 'Livechat_webhook_on_capture')
818
+ continue;
819
+ if ((await rcapi.getSetting(url, auth, pw, id)) === false)
820
+ await set(id, true);
821
+ }
822
+ }
823
+ else {
824
+ (0, events_1.warn)(emit, `Omnichannel webhook points at ${currentUrl} and would post every chat event there: --set capture=all repoints it at the inbox`, phase);
825
+ }
826
+ const allow = await rcapi.getSetting(url, auth, pw, 'SSRF_Allowlist');
827
+ if (typeof allow === 'string') {
828
+ // Absent (null) before 8.2.0, where nothing it guards reaches a private host anyway.
829
+ const hosts = allow
830
+ .split(/[\r\n,]+/u)
831
+ .map((host) => host.trim())
832
+ .filter((host) => host !== '');
833
+ if (!hosts.includes('webhooks'))
834
+ await set('SSRF_Allowlist', [...hosts, 'webhooks'].join('\n'));
835
+ }
836
+ if (failed.length > 0) {
837
+ (0, events_1.warn)(emit, `these settings did not take: ${failed.join(', ')}`, phase);
838
+ ok = false;
839
+ }
840
+ const captured = [];
841
+ if (listed === null) {
842
+ (0, events_1.warn)(emit, 'could not list the outgoing integrations', phase);
843
+ ok = false;
844
+ }
845
+ else {
846
+ const scripted = [];
847
+ const resave = async (doc, name, target, was) => {
848
+ if (await rcapi.updateOutgoingUrls(url, auth, pw, doc, target)) {
849
+ (0, events_1.info)(emit, `repointed '${name}' at the inbox (was ${was})`, phase);
850
+ if (doc.scriptEnabled === true && String(doc.script ?? '').trim() !== '')
851
+ scripted.push(name);
852
+ return true;
853
+ }
854
+ (0, events_1.warn)(emit, `could not repoint '${name}' (Rocket.Chat refused the update: a deleted user or channel?)`, phase);
855
+ ok = false;
856
+ return false;
857
+ };
858
+ for (const doc of listed) {
859
+ const name = String(doc.name ?? '');
860
+ const urls = Array.isArray(doc.urls) ? doc.urls.map(String) : [];
861
+ if (urls.length === 0)
862
+ continue;
863
+ if (urls.every((one) => one.startsWith(origin))) {
864
+ const fixed = [];
865
+ for (const one of urls)
866
+ fixed.push(await repaired(one));
867
+ if (fixed.some((one, i) => one !== urls[i]))
868
+ await resave(doc, name, fixed, 'a session the inbox no longer has');
869
+ if (name !== config.WEBHOOKS_OUTGOING)
870
+ captured.push({ name, from: fixed.map(capturedFrom).filter((one) => one !== '') });
871
+ continue;
872
+ }
873
+ if (name === config.WEBHOOKS_OUTGOING || !capture)
874
+ continue;
875
+ const target = urls.map((one) => `${receiver}/captured/${encodeURIComponent(name)}?from=${encodeURIComponent(one)}`);
876
+ if (await resave(doc, name, target, urls.join(', ')))
877
+ captured.push({ name, from: urls });
878
+ }
879
+ if (scripted.length > 0) {
880
+ (0, events_1.warn)(emit, `re-saved with a script: ${scripted.join(', ')} -- from Rocket.Chat 9.0.0 a script runs as written, in strict mode (docs.rocket.chat/docs/integrations#script-compatibility)`, phase);
881
+ }
882
+ }
883
+ const hooks = {
884
+ session,
885
+ incoming: incoming ?? '',
886
+ outgoing_name: config.WEBHOOKS_OUTGOING,
887
+ omnichannel,
888
+ captured,
889
+ };
890
+ try {
891
+ await (0, record_1.updateMeta)(meta.name, (recorded) => {
892
+ recorded.extra.webhooks = hooks;
893
+ });
894
+ meta.extra.webhooks = hooks;
895
+ }
896
+ catch {
897
+ (0, events_1.warn)(emit, `could not record the webhook URLs in repro.json: houston ready --name ${meta.name} writes them`, phase);
898
+ ok = false;
899
+ }
900
+ const where = omnichannel.startsWith(origin) ? 'at the inbox' : `left at ${omnichannel}`;
901
+ const count = captured.length > 0 ? `; ${String(captured.length)} integration(s) captured` : '';
902
+ const inbox = `${api}/s/${session}`;
903
+ (0, events_1.info)(emit, `Webhooks: inbox ${inbox} (on the machine running houston); '${config.WEBHOOKS_OUTGOING}' posts every public-channel message there; Omnichannel webhook ${where}${count} -- houston info --name ${meta.name} prints the incoming curl.`, phase);
904
+ return ok;
905
+ }
906
+ /**
907
+ * The action name a preset writes -> the handler that runs it.
908
+ *
909
+ * MUTABLE on purpose: a spec swaps entries in and out to drive `runPostReady` without
910
+ * standing up four RC stubs, and reloads the table afterwards.
911
+ * `resetActions` is the reload.
912
+ */
913
+ exports.POST_READY_ACTIONS = {
914
+ saml_idp_cert: prSamlIdpCert,
915
+ keycloak_master_ssl_off: prKeycloakMasterSslOff,
916
+ create_oauth_provider: prCreateOauthProvider,
917
+ livechat_setup: prLivechatSetup,
918
+ e2ee_users: prE2eeUsers,
919
+ voice_users: prVoiceUsers,
920
+ webhooks_setup: prWebhooksSetup,
921
+ };
922
+ const BUILTIN_ACTIONS = Object.freeze({
923
+ ...exports.POST_READY_ACTIONS,
924
+ });
925
+ /** Put the table back the way it shipped. */
926
+ function resetActions() {
927
+ for (const key of Object.keys(exports.POST_READY_ACTIONS))
928
+ delete exports.POST_READY_ACTIONS[key];
929
+ Object.assign(exports.POST_READY_ACTIONS, BUILTIN_ACTIONS);
930
+ }
931
+ /**
932
+ * Run a workspace's preset self-configuration. Returns the actions that did NOT complete.
933
+ *
934
+ * `null` when there was no admin session to run them with -- nothing ran, which is a
935
+ * different answer from "they all succeeded".
936
+ */
937
+ async function runPostReady(meta, auth, emit, { sleep = realSleep } = {}) {
938
+ const extra = bagOf(meta.extra);
939
+ const raw = extra.post_ready;
940
+ const actions = Array.isArray(raw) ? raw : [];
941
+ if (auth === null || auth === undefined) {
942
+ if (actions.length > 0) {
943
+ (0, events_1.warn)(emit, 'preset self-config skipped - could not log in as admin; ' +
944
+ `re-run once reachable: houston ready --name ${meta.name}`, { phase: 'post_ready' });
945
+ }
946
+ return null;
947
+ }
948
+ // COLLECTED, not just warned past. A create that printed "could not fetch/apply IdP
949
+ // cert" and then "starting" left the reader to work out for themselves whether SAML
950
+ // actually worked -- the deployment succeeded and the CONFIGURATION did not, and those
951
+ // are different answers to different questions.
952
+ const failed = [];
953
+ for (const action of actions) {
954
+ const name = action.action;
955
+ const handler = truthy(name) ? exports.POST_READY_ACTIONS[String(name)] : undefined;
956
+ if (handler === undefined)
957
+ continue;
958
+ if ((await handler(meta, auth, action, emit, sleep)) === false)
959
+ failed.push(String(name));
960
+ }
961
+ if (failed.length > 0) {
962
+ (0, events_1.warn)(emit, `the workspace is RUNNING but its ${(0, format_1.quotedText)(meta.preset)} ` +
963
+ `${(0, composite_1.namesOf)(meta.preset).length > 1 ? 'presets are' : 'preset is'} only ` +
964
+ `partly configured — these did not complete: ${failed.join(', ')}`, { phase: 'post_ready' });
965
+ (0, events_1.warn)(emit, ` Rocket.Chat itself is fine. Re-run the preset's ` +
966
+ `self-configuration with: houston ready --name ${meta.name}`, { phase: 'post_ready' });
967
+ }
968
+ return failed;
969
+ }