@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,1285 @@
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.rcapi = exports.RequestFailed = exports.OTP_WAIT_SECONDS = exports.NotReady = void 0;
37
+ exports.releaseInfo = releaseInfo;
38
+ exports.authHeaders = authHeaders;
39
+ exports.apiInfo = apiInfo;
40
+ exports.waitReady = waitReady;
41
+ exports.password2faHeaders = password2faHeaders;
42
+ exports.otpRecipient = otpRecipient;
43
+ exports.login = login;
44
+ exports.loginUser = loginUser;
45
+ exports.releasesReachable = releasesReachable;
46
+ exports.extractOtp = extractOtp;
47
+ exports.addressedTo = addressedTo;
48
+ exports.newestMailStamp = newestMailStamp;
49
+ exports.fetchEmailOtp = fetchEmailOtp;
50
+ exports.completeSetupWizard = completeSetupWizard;
51
+ exports.generatePat = generatePat;
52
+ exports.listIntegrations = listIntegrations;
53
+ exports.findIntegration = findIntegration;
54
+ exports.createIncomingWebhook = createIncomingWebhook;
55
+ exports.createOutgoingWebhook = createOutgoingWebhook;
56
+ exports.updateOutgoingUrls = updateOutgoingUrls;
57
+ exports.getSetting = getSetting;
58
+ exports.licenseValid = licenseValid;
59
+ exports.settingIds = settingIds;
60
+ exports.setSetting = setSetting;
61
+ exports.samlProviderState = samlProviderState;
62
+ exports.samlProviderReady = samlProviderReady;
63
+ exports.methodSucceeded = methodSucceeded;
64
+ exports.addOauthService = addOauthService;
65
+ exports.createUser = createUser;
66
+ exports.addLivechatAgent = addLivechatAgent;
67
+ exports.setVoiceExtension = setVoiceExtension;
68
+ exports.getUserId = getUserId;
69
+ exports.ensureLivechatDepartment = ensureLivechatDepartment;
70
+ exports.assignLivechatAgents = assignLivechatAgents;
71
+ exports.saveCannedResponse = saveCannedResponse;
72
+ exports.setLivechatAvailable = setLivechatAvailable;
73
+ exports.fetchSamlIdpCert = fetchSamlIdpCert;
74
+ exports.call = call;
75
+ exports.multipart = multipart;
76
+ exports.download = download;
77
+ /**
78
+ * Minimal Rocket.Chat REST client: readiness polling, login, and calls.
79
+ *
80
+ * Every request goes through `seams/rc-http`; nothing here opens a socket, and nothing there
81
+ * knows a Rocket.Chat path. The division is the point: the retry loops, the 2FA dance and the
82
+ * "which of these four failures is this" judgements are domain, and they all live on this
83
+ * side.
84
+ *
85
+ * ONE DEPARTURE FROM THE PREVIOUS IMPLEMENTATION, and it is the runtime's: every function
86
+ * that makes a request is `async`, because service entry points are asynchronous and `Emit`
87
+ * stays synchronous; and the sleeps inside the three polling loops are injectable so their
88
+ * specs do not spend real seconds.
89
+ */
90
+ const config = __importStar(require("../lib/config"));
91
+ const errors_1 = require("../lib/errors");
92
+ const audit_1 = require("../lib/audit");
93
+ const format_1 = require("../lib/format");
94
+ const json_text_1 = require("../lib/json-text");
95
+ const exec_1 = require("../seams/exec");
96
+ const rc_http_1 = require("../seams/rc-http");
97
+ /** Fetch a release document for callers that must prefetch before synchronous resolution. */
98
+ async function releaseInfo(url) {
99
+ try {
100
+ return await get(url, { timeoutMs: 5000 });
101
+ }
102
+ catch (error) {
103
+ if (error instanceof rc_http_1.RequestFailed)
104
+ return null;
105
+ throw error;
106
+ }
107
+ }
108
+ /** Rocket.Chat is not serving yet, or stopped being able to. */
109
+ class NotReady extends Error {
110
+ constructor(message) {
111
+ super(message);
112
+ this.name = 'NotReady';
113
+ }
114
+ }
115
+ exports.NotReady = NotReady;
116
+ function authHeaders(auth) {
117
+ return { 'X-Auth-Token': auth.token, 'X-User-Id': auth.userId };
118
+ }
119
+ /** The real sleep, which a Ctrl-C interrupts. */
120
+ const realSleep = (seconds) => (0, exec_1.sleep)(seconds * 1000);
121
+ const now = () => Date.now() / 1000;
122
+ const trimEnd = (url) => url.replace(/\/+$/u, '');
123
+ /** `resp.json()` or `{}`, for the many places a non-JSON body is just a failure. */
124
+ function body(resp) {
125
+ let parsed;
126
+ try {
127
+ parsed = resp.json();
128
+ }
129
+ catch {
130
+ return {};
131
+ }
132
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
133
+ ? parsed
134
+ : {};
135
+ }
136
+ const map = (value) => value !== null && typeof value === 'object' && !Array.isArray(value)
137
+ ? value
138
+ : {};
139
+ const list = (value) => Array.isArray(value) ? value : [];
140
+ /** The first 200 characters of a body, which is what every message here quotes. */
141
+ const said = (resp, limit = 200) => resp.text.slice(0, limit);
142
+ async function get(url, options = {}) {
143
+ return await rc_http_1.rcHttp.request(url, { ...options, method: 'GET' });
144
+ }
145
+ async function post(url, options = {}) {
146
+ return await rc_http_1.rcHttp.request(url, { ...options, method: 'POST' });
147
+ }
148
+ async function put(url, options = {}) {
149
+ return await rc_http_1.rcHttp.request(url, { ...options, method: 'PUT' });
150
+ }
151
+ /** GET /api/info (public). The JSON, or null if it is not serving. */
152
+ async function apiInfo(rootUrl, { timeoutMs = 5000, requestOptions = {}, } = {}) {
153
+ let resp;
154
+ try {
155
+ resp = await get(`${trimEnd(rootUrl)}/api/info`, { ...requestOptions, timeoutMs });
156
+ }
157
+ catch (error) {
158
+ if (error instanceof rc_http_1.RequestFailed)
159
+ return null;
160
+ throw error;
161
+ }
162
+ if (resp.status !== 200)
163
+ return null;
164
+ try {
165
+ const parsed = resp.json();
166
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
167
+ ? parsed
168
+ : null;
169
+ }
170
+ catch {
171
+ return null;
172
+ }
173
+ }
174
+ /**
175
+ * Block until Rocket.Chat serves /api/info, returning its payload.
176
+ *
177
+ * `isAlive()` is checked each tick, so a crashed container fails fast rather than being
178
+ * polled for the full timeout. `onTick(elapsed)` drives progress display.
179
+ */
180
+ async function waitReady(rootUrl, { timeout = 300, interval = 3, isAlive, onTick, sleep = realSleep, requestOptions = {}, page = false, } = {}) {
181
+ const deadline = now() + timeout;
182
+ for (;;) {
183
+ const remainingMs = () => Math.max(1, Math.min(5000, (deadline - now()) * 1000));
184
+ const options = typeof requestOptions === 'function' ? await requestOptions(remainingMs()) : requestOptions;
185
+ const info = options === null
186
+ ? null
187
+ : await apiInfo(rootUrl, { requestOptions: options, timeoutMs: remainingMs() });
188
+ if (info !== null &&
189
+ options !== null &&
190
+ (!page || (await pageServing(rootUrl, options, remainingMs()))))
191
+ return info;
192
+ if (isAlive !== undefined && !(await isAlive())) {
193
+ throw new NotReady('Rocket.Chat container is not running (check `logs`)');
194
+ }
195
+ if (now() >= deadline) {
196
+ throw new NotReady(`Rocket.Chat did not become ready within ${String(Math.trunc(timeout))}s`);
197
+ }
198
+ // AWAITED, so a tick that decides the boot has already failed can throw out of the
199
+ // poll there and then, before the next sleep. A caller that ignores the return value
200
+ // is unaffected.
201
+ if (onTick !== undefined)
202
+ await onTick(timeout - (deadline - now()));
203
+ await sleep(interval);
204
+ }
205
+ }
206
+ async function pageServing(rootUrl, requestOptions, timeoutMs) {
207
+ try {
208
+ const response = await get(`${trimEnd(rootUrl)}/`, {
209
+ ...requestOptions,
210
+ timeoutMs,
211
+ followRedirects: false,
212
+ });
213
+ return response.status === 200 && response.text.trim() !== '';
214
+ }
215
+ catch (error) {
216
+ if (error instanceof rc_http_1.RequestFailed)
217
+ return false;
218
+ throw error;
219
+ }
220
+ }
221
+ /**
222
+ * The Auth in a login response.
223
+ *
224
+ * A 200 with a non-JSON body -- a proxy's error page -- must fall through to the error
225
+ * below, which carries the body text an operator needs, rather than escaping as a bare
226
+ * JSON parse failure.
227
+ */
228
+ function authFrom(resp) {
229
+ const data = map(body(resp).data);
230
+ const token = String(data.authToken ?? '');
231
+ const userId = String(data.userId ?? '');
232
+ if (token === '' || userId === '') {
233
+ throw new Error(`login did not return a token: ${said(resp)}`);
234
+ }
235
+ return { token, userId };
236
+ }
237
+ /** Headers that satisfy Rocket.Chat's 'password' 2FA method for guarded endpoints. */
238
+ async function password2faHeaders(password) {
239
+ const crypto = await Promise.resolve().then(() => __importStar(require('node:crypto')));
240
+ return {
241
+ 'x-2fa-code': crypto.createHash('sha256').update(password, 'utf8').digest('hex'),
242
+ 'x-2fa-method': 'password',
243
+ };
244
+ }
245
+ /**
246
+ * An `HttpStatusError` for a 4xx or a 5xx status, and nothing otherwise.
247
+ *
248
+ * In the established words, and the words carry behaviour. A refused login used to say
249
+ * `login failed: HTTP 401: <body>` (and `login with the email code failed: ...`), where the
250
+ * established text is `401 Client Error: Unauthorized for url:
251
+ * http://localhost:3100/api/v1/login` -- every caller of `login` prints it. And the REST
252
+ * commands' `notAnswering`, and `seed`, test that text for `429` to tell Rocket.Chat's rate
253
+ * limiter from a broken login, so the URL in it is read too: a workspace on port 3429 (or
254
+ * 4290-4299, 14290, ...) whose login is refused is reported as rate-limited, exit 5, as it
255
+ * always has been. That is an accident, and reproducing it is the point of matching it.
256
+ *
257
+ * Named `HttpStatusError` and NOT a `RequestFailed`: only a connection failure or a timeout is
258
+ * "not answering yet", and `notAnswering` reads a `RequestFailed` as one of those.
259
+ */
260
+ function raiseForStatus(resp) {
261
+ const kind = resp.status >= 400 && resp.status < 500
262
+ ? 'Client Error'
263
+ : resp.status >= 500 && resp.status < 600
264
+ ? 'Server Error'
265
+ : '';
266
+ if (kind === '')
267
+ return;
268
+ const error = new Error(`${String(resp.status)} ${kind}: ${resp.reason ?? ''} for url: ${resp.url}`);
269
+ error.name = 'HttpStatusError';
270
+ throw error;
271
+ }
272
+ /** Plain login, then Rocket.Chat's password-fallback 2FA method. */
273
+ async function tryPasswordLogins(base, creds, password, timeoutMs) {
274
+ const resp = await post(`${base}/login`, { json: creds, timeoutMs });
275
+ if (resp.status === 200)
276
+ return [authFrom(resp), resp];
277
+ if (!resp.text.includes('totp-required')) {
278
+ // `raiseForStatus` is a no-op for 2xx/3xx, so a 204 -- or a reverse proxy's 302 to
279
+ // HTTPS, the case `--allow-host` exists for -- used to fall through into the 2FA
280
+ // branch below and report a missing Mailpit URL for what is really a redirect.
281
+ raiseForStatus(resp);
282
+ throw new Error(`login returned HTTP ${String(resp.status)}, which is neither a success nor a 2FA ` +
283
+ `challenge: ${said(resp)}`);
284
+ }
285
+ const retry = await post(`${base}/login`, {
286
+ json: creds,
287
+ timeoutMs,
288
+ headers: await password2faHeaders(password),
289
+ });
290
+ if (retry.status === 200)
291
+ return [authFrom(retry), resp];
292
+ return [null, resp];
293
+ }
294
+ /**
295
+ * A safe recipient filter for Mailpit's shared inbox.
296
+ *
297
+ * Falling back to no filter disabled it entirely, so this could hand back a DIFFERENT
298
+ * user's code -- the exact thing the filter exists to prevent. It refuses instead.
299
+ */
300
+ function otpRecipient(user) {
301
+ if (user.includes('@'))
302
+ return user;
303
+ if (user === config.ADMIN_USERNAME)
304
+ return config.ADMIN_EMAIL;
305
+ throw new Error(`cannot fetch an email-2FA code for '${user}': its address is unknown, and polling the ` +
306
+ "shared Mailpit inbox unfiltered could return another user's code");
307
+ }
308
+ /** Trigger, fetch, and submit a fresh recipient-filtered email code. */
309
+ async function loginWithEmailCode(base, creds, user, timeoutMs, mailpitUrl, sleep, otpTimeout) {
310
+ // Snapshot the inbox FIRST, so a leftover code from a previous login is not mistaken
311
+ // for the fresh one, and filter by recipient because Mailpit is a catch-all for every
312
+ // address.
313
+ const toEmail = otpRecipient(user);
314
+ const baseline = await newestMailStamp(mailpitUrl, { toEmail });
315
+ let sent = null;
316
+ try {
317
+ sent = await post(`${base}/users.2fa.sendEmailCode`, {
318
+ json: { emailOrUsername: user },
319
+ timeoutMs,
320
+ });
321
+ }
322
+ catch (error) {
323
+ if (!(error instanceof rc_http_1.RequestFailed))
324
+ throw error;
325
+ }
326
+ const code = await fetchEmailOtp(mailpitUrl, {
327
+ toEmail,
328
+ after: baseline,
329
+ sleep,
330
+ timeout: otpTimeout,
331
+ });
332
+ if (code === null) {
333
+ // Surface a failed send instead of blaming the timeout for it.
334
+ const detail = sent !== null && !sent.ok
335
+ ? ` (users.2fa.sendEmailCode returned HTTP ${String(sent.status)}: ${said(sent, 120)})`
336
+ : '';
337
+ throw new Error(`email-2FA code did not arrive in Mailpit within the timeout${detail}`);
338
+ }
339
+ const resp = await post(`${base}/login`, {
340
+ json: creds,
341
+ timeoutMs,
342
+ headers: { 'x-2fa-code': code, 'x-2fa-method': 'email' },
343
+ });
344
+ raiseForStatus(resp);
345
+ return authFrom(resp);
346
+ }
347
+ /**
348
+ * Log in and return an Auth.
349
+ *
350
+ * With email-2FA on (the `email` preset's default) a plain login is rejected with
351
+ * `totp-required`. The password-fallback method is tried first, and if that is not
352
+ * accepted and a Mailpit URL is known, the code email is triggered, read out of Mailpit
353
+ * and submitted -- so houston's own admin calls keep working while OTP stays on for
354
+ * browsers.
355
+ */
356
+ async function login(rootUrl, { user = config.ADMIN_USERNAME, password = config.ADMIN_PASSWORD, timeoutMs = 10000, mailpitUrl = '', sleep = realSleep, otpTimeout = exports.OTP_WAIT_SECONDS, } = {}) {
357
+ const base = `${trimEnd(rootUrl)}/api/v1`;
358
+ const creds = { user, password };
359
+ const [auth, challenge] = await tryPasswordLogins(base, creds, password, timeoutMs);
360
+ if (auth !== null)
361
+ return auth;
362
+ if (mailpitUrl === '') {
363
+ throw new Error('login requires an email-2FA code and no Mailpit URL is configured (is this the ' +
364
+ `\`email\` preset?): ${said(challenge)}`);
365
+ }
366
+ return await loginWithEmailCode(base, creds, user, timeoutMs, mailpitUrl, sleep, otpTimeout);
367
+ }
368
+ /**
369
+ * A seeded user's plain login, for the identities a load test's VUs carry.
370
+ *
371
+ * The load test once posted to `/api/v1/login` directly — one of three bypasses of the REST
372
+ * client. Here it goes through this module: the dependency policy allows exactly one module
373
+ * to speak HTTP, and the endpoint is Rocket.Chat's own, so this is where it belongs.
374
+ * Returns the token pair, or null for any non-200; a transport failure still throws
375
+ * `RequestFailed`, which the caller's loop breaks on.
376
+ */
377
+ async function loginUser(rootUrl, user, { timeoutMs = 10000 } = {}) {
378
+ const resp = await rc_http_1.rcHttp.request(`${trimEnd(rootUrl)}/api/v1/login`, {
379
+ method: 'POST',
380
+ json: { user, password: user },
381
+ timeoutMs,
382
+ });
383
+ if (resp.status !== 200)
384
+ return null;
385
+ const data = body(resp).data;
386
+ if (data === null || data === undefined)
387
+ return null;
388
+ return { authToken: String(data.authToken ?? ''), userId: String(data.userId ?? '') };
389
+ }
390
+ /**
391
+ * Whether releases.rocket.chat answers, for doctor's version-lookup check.
392
+ *
393
+ * doctor's version check once fetched it directly -- the fourth recorded `rcapi` bypass,
394
+ * after `seed`'s three. Here it goes through this module instead: exactly one module speaks
395
+ * HTTP, and the endpoint is houston's own lookup. Returns the status code, or null when the
396
+ * request failed (`RequestFailed`).
397
+ */
398
+ async function releasesReachable(version = '8.5.1') {
399
+ try {
400
+ const resp = await rc_http_1.rcHttp.request(`https://releases.rocket.chat/${version}/info`, {
401
+ timeoutMs: 5000,
402
+ });
403
+ return resp.status;
404
+ }
405
+ catch (error) {
406
+ // `RequestFailed` alone -- the transport-failure type and the only thing the HTTP seam
407
+ // throws. A programmer error propagates rather than being reported as a network
408
+ // problem.
409
+ if (error instanceof rc_http_1.RequestFailed)
410
+ return null;
411
+ throw error;
412
+ }
413
+ }
414
+ /** How long `fetchEmailOtp` waits, and therefore how long a 2FA login can take. */
415
+ exports.OTP_WAIT_SECONDS = 30;
416
+ /**
417
+ * The emailed 2FA code, as the six digits Rocket.Chat stored, or null.
418
+ *
419
+ * Rocket.Chat mails it as `ddd-ddd` (`EmailCheck.send2FAEmail`:
420
+ * `random.replace(/^(\d{3})/, '$1-')`, the same at every tag checked, 3.18.0 to 8.8.0),
421
+ * and its `verify` strips every non-digit before comparing, so the digits alone are what it
422
+ * accepts. Only that shape is read: a bare six-digit run was never the code, and taking one
423
+ * would spend a login attempt on a colour, a year or a ticket number in a custom template.
424
+ */
425
+ function extractOtp(text) {
426
+ const found = /(?<![\d-])(\d{3})-(\d{3})(?![\d-])/u.exec(text || '');
427
+ return found === null ? null : `${found[1]}${found[2]}`;
428
+ }
429
+ /**
430
+ * Whether one Mailpit message is addressed to `toEmail`. An empty filter matches anything,
431
+ * which is why an unresolvable recipient is refused by `otpRecipient` before it ever
432
+ * reaches here.
433
+ *
434
+ * Exported so it can be checked directly:
435
+ * a filter that silently stops matching is how a login reads somebody else's code, and
436
+ * nothing about the caller's behaviour would look different.
437
+ */
438
+ function addressedTo(item, toEmail) {
439
+ if (toEmail === '')
440
+ return true;
441
+ const addresses = list(item.To).map((entry) => String(entry.Address ?? ''));
442
+ return addresses.some((address) => address.toLowerCase() === toEmail.toLowerCase());
443
+ }
444
+ /**
445
+ * The `Created` timestamp of the newest message, or ''.
446
+ *
447
+ * Snapshot this BEFORE triggering a new code so `fetchEmailOtp` can ignore stale codes
448
+ * still sitting in the catch-all inbox.
449
+ */
450
+ async function newestMailStamp(mailpitUrl, { toEmail = '' } = {}) {
451
+ try {
452
+ const resp = await get(`${trimEnd(mailpitUrl)}/api/v1/messages`, {
453
+ params: { limit: 10 },
454
+ timeoutMs: 5000,
455
+ });
456
+ if (resp.status === 200) {
457
+ for (const item of list(body(resp).messages)) {
458
+ // Newest first.
459
+ if (addressedTo(item, toEmail))
460
+ return String(item.Created ?? '');
461
+ }
462
+ }
463
+ }
464
+ catch {
465
+ // A Mailpit that is not answering is not a reason to fail the login that has not
466
+ // been attempted yet; the fetch below reports the real outcome.
467
+ }
468
+ return '';
469
+ }
470
+ /**
471
+ * Poll Mailpit for an emailed 2FA code (`extractOtp`), optionally only in messages addressed
472
+ * to `toEmail`.
473
+ *
474
+ * `after` (a `newestMailStamp` snapshot) skips any message not newer than it, so a code
475
+ * left over from a previous login is never reused. Null if none shows up in time.
476
+ */
477
+ async function fetchEmailOtp(mailpitUrl, { toEmail = '', timeout = 30, interval = 1.5, after = '', sleep = realSleep, } = {}) {
478
+ const base = trimEnd(mailpitUrl);
479
+ const deadline = now() + timeout;
480
+ for (;;) {
481
+ try {
482
+ const listing = await get(`${base}/api/v1/messages`, {
483
+ params: { limit: 10 },
484
+ timeoutMs: 5000,
485
+ });
486
+ if (listing.status === 200) {
487
+ for (const item of list(body(listing).messages)) {
488
+ // Newest first.
489
+ const id = String(item.ID ?? '');
490
+ if (id === '' || !addressedTo(item, toEmail))
491
+ continue;
492
+ // Stale: it predates the code we just requested.
493
+ if (after !== '' && String(item.Created ?? '') <= after)
494
+ continue;
495
+ const message = await get(`${base}/api/v1/message/${id}`, { timeoutMs: 5000 });
496
+ if (message.status !== 200)
497
+ continue;
498
+ const parsed = body(message);
499
+ const code = extractOtp(String(parsed.Text ?? '')) ?? extractOtp(String(parsed.HTML ?? ''));
500
+ if (code !== null)
501
+ return code;
502
+ }
503
+ }
504
+ }
505
+ catch {
506
+ // A transport failure or an unparseable body is a reason to poll again, not to give
507
+ // up: Mailpit comes up alongside Rocket.Chat and may not be answering yet.
508
+ }
509
+ if (now() >= deadline)
510
+ return null;
511
+ await sleep(interval);
512
+ }
513
+ }
514
+ /**
515
+ * Mark the setup wizard completed so the repro is usable immediately.
516
+ *
517
+ * Rocket.Chat leaves the wizard at 'in_progress' (the cloud-registration step) after
518
+ * auto-provisioning the admin, and that beats OVERWRITE_SETTING_Show_Setup_Wizard.
519
+ * Best-effort; never throws.
520
+ */
521
+ async function completeSetupWizard(rootUrl, auth, password, { timeoutMs = 15000 } = {}) {
522
+ return await setSetting(rootUrl, auth, password, 'Show_Setup_Wizard', 'completed', {
523
+ timeoutMs,
524
+ });
525
+ }
526
+ /**
527
+ * Create (or regenerate) a Personal Access Token and return the token string.
528
+ *
529
+ * Mirrors a token created in the UI with "Ignore Two Factor Authentication". Generating a
530
+ * PAT is itself a 2FA-guarded action, satisfied here with the password method.
531
+ */
532
+ async function generatePat(rootUrl, auth, password, { tokenName = 'houston', bypass2fa = true, timeoutMs = 15000, workspace = '', } = {}) {
533
+ // AUDITED HERE, not at the handlers. There were exactly eight non-test call sites, so
534
+ // a record written at one handler would have missed six -- and a bypass-2FA
535
+ // admin token for somebody else's workspace is one of the two most sensitive things
536
+ // this tool can do. `workspace` is passed by every caller; the root URL is the fallback
537
+ // so a ninth site still writes a usable line rather than an anonymous one.
538
+ //
539
+ // `bypass_2fa=True` / `bypass_2fa=False`, capitalised: audit.log is a record both releases
540
+ // append to, so it keeps the stored spelling (`storedText`) it has always had. This wrote
541
+ // `true`/`false`, so every PAT this build minted -- `pat`, `api --pat`, a load test's,
542
+ // the GUI's -- left a line an external `grep bypass_2fa=True` or awk over
543
+ // audit.log does not match, beside the lines earlier releases wrote.
544
+ (0, audit_1.recordAudit)('pat', `${workspace || rootUrl} label=${tokenName} bypass_2fa=${(0, format_1.storedText)(Boolean(bypass2fa))}`);
545
+ const base = `${trimEnd(rootUrl)}/api/v1`;
546
+ const headers = {
547
+ ...authHeaders(auth),
548
+ 'Content-Type': 'application/json',
549
+ ...(await password2faHeaders(password)),
550
+ };
551
+ // The documented contract is "a token, or an Error". A bare transport failure escaping
552
+ // would break it for any caller that narrows its catch.
553
+ const send = async (path, json) => {
554
+ try {
555
+ return await post(`${base}/${path}`, { headers, json, timeoutMs });
556
+ }
557
+ catch (error) {
558
+ throw new Error(`could not reach ${path}: ${String(error.message)}`, {
559
+ cause: error,
560
+ });
561
+ }
562
+ };
563
+ const first = await send('users.generatePersonalAccessToken', {
564
+ tokenName,
565
+ bypassTwoFactor: bypass2fa,
566
+ });
567
+ const created = body(first);
568
+ if (created.success === true && typeof created.token === 'string' && created.token !== '') {
569
+ return created.token;
570
+ }
571
+ // Already exists -> regenerate it (also 2FA-guarded).
572
+ const second = await send('users.regeneratePersonalAccessToken', { tokenName });
573
+ const regenerated = body(second);
574
+ if (regenerated.success === true &&
575
+ typeof regenerated.token === 'string' &&
576
+ regenerated.token !== '') {
577
+ return regenerated.token;
578
+ }
579
+ throw new Error(`could not create PAT: ${said(first)}`);
580
+ }
581
+ /** The headers every integration call sends: the session, JSON, and the password 2FA method. */
582
+ async function integrationHeaders(auth, password) {
583
+ return {
584
+ ...authHeaders(auth),
585
+ 'Content-Type': 'application/json',
586
+ ...(await password2faHeaders(password)),
587
+ };
588
+ }
589
+ /** 48 hex characters, the shape Rocket.Chat's own form gives an outgoing integration. */
590
+ async function newIntegrationToken() {
591
+ const crypto = await Promise.resolve().then(() => __importStar(require('node:crypto')));
592
+ return crypto.randomBytes(24).toString('hex');
593
+ }
594
+ /**
595
+ * Every integration, page by page (`count=100`), optionally of one `type`; null when the
596
+ * list could not be read. Filtered here rather than by the `name`/`type` query params,
597
+ * which older releases ignore.
598
+ */
599
+ async function listIntegrations(rootUrl, auth, password, { type = '', timeoutMs = 15000 } = {}) {
600
+ const headers = await integrationHeaders(auth, password);
601
+ const out = [];
602
+ try {
603
+ // Stepped by what a page HELD: API_Upper_Count_Limit is a setting, and a dump that caps
604
+ // a page at 25 answered 25 to count=100. 50 pages: more than 5,000 is not a repro.
605
+ let offset = 0;
606
+ for (let pages = 0; pages < 50; pages += 1) {
607
+ const resp = await get(`${trimEnd(rootUrl)}/api/v1/integrations.list`, {
608
+ headers,
609
+ params: { count: 100, offset },
610
+ timeoutMs,
611
+ });
612
+ if (resp.status !== 200)
613
+ return null;
614
+ const parsed = body(resp);
615
+ const page = list(parsed.integrations);
616
+ out.push(...page);
617
+ offset += page.length;
618
+ const total = typeof parsed.total === 'number' ? parsed.total : 0;
619
+ if (page.length === 0 || (total > 0 ? out.length >= total : page.length < 100))
620
+ break;
621
+ }
622
+ }
623
+ catch {
624
+ return null;
625
+ }
626
+ return type === '' ? out : out.filter((one) => one.type === type);
627
+ }
628
+ /** The integration of exactly this `name` and `type`, or null (also when the list failed). */
629
+ async function findIntegration(rootUrl, auth, password, { name, type, timeoutMs = 15000 }) {
630
+ const all = await listIntegrations(rootUrl, auth, password, { type, timeoutMs });
631
+ return all?.find((one) => one.name === name) ?? null;
632
+ }
633
+ /**
634
+ * Find, else create, an incoming-webhook integration; returns its POST path
635
+ * (`/hooks/<id>/<token>`) or null. Used by the loadtest `webhook` scenario and the webhooks
636
+ * preset. Looked up FIRST: Rocket.Chat accepts a duplicate name, so creating and looking only
637
+ * on refusal added a hook on every run.
638
+ */
639
+ async function createIncomingWebhook(rootUrl, auth, password, { channel = '#general', name = 'houston-loadtest-hook', alias = 'loadtest', timeoutMs = 15000, } = {}) {
640
+ const hookPath = (integration) => {
641
+ const id = String(integration._id ?? '');
642
+ const token = String(integration.token ?? '');
643
+ return id !== '' && token !== '' ? `/hooks/${id}/${token}` : null;
644
+ };
645
+ try {
646
+ const found = await findIntegration(rootUrl, auth, password, {
647
+ name,
648
+ type: 'webhook-incoming',
649
+ timeoutMs,
650
+ });
651
+ if (found !== null)
652
+ return hookPath(found);
653
+ const created = await post(`${trimEnd(rootUrl)}/api/v1/integrations.create`, {
654
+ headers: await integrationHeaders(auth, password),
655
+ json: {
656
+ type: 'webhook-incoming',
657
+ name,
658
+ enabled: true,
659
+ username: 'rocket.cat',
660
+ channel,
661
+ scriptEnabled: false,
662
+ script: '',
663
+ alias,
664
+ avatar: '',
665
+ emoji: '',
666
+ },
667
+ timeoutMs,
668
+ });
669
+ const madeBody = body(created);
670
+ if (created.status === 200 && madeBody.success === true) {
671
+ return hookPath(map(madeBody.integration));
672
+ }
673
+ }
674
+ catch {
675
+ // Best-effort by contract: the scenario runs without a webhook.
676
+ }
677
+ return null;
678
+ }
679
+ /**
680
+ * Find, else create, an outgoing-webhook integration that posts every message of every
681
+ * public channel to `urls`; returns its id or null. As rocket.cat, the one user with
682
+ * `message-impersonate` on every workspace; with a token, because the update the admin UI
683
+ * saves refuses an empty one.
684
+ */
685
+ async function createOutgoingWebhook(rootUrl, auth, password, { name, urls, channel = 'all_public_channels', event = 'sendMessage', timeoutMs = 15000, }) {
686
+ try {
687
+ const found = await findIntegration(rootUrl, auth, password, {
688
+ name,
689
+ type: 'webhook-outgoing',
690
+ timeoutMs,
691
+ });
692
+ if (found !== null)
693
+ return String(found._id ?? '') || null;
694
+ const created = await post(`${trimEnd(rootUrl)}/api/v1/integrations.create`, {
695
+ headers: await integrationHeaders(auth, password),
696
+ json: {
697
+ type: 'webhook-outgoing',
698
+ name,
699
+ enabled: true,
700
+ username: 'rocket.cat',
701
+ channel,
702
+ event,
703
+ urls: [...urls],
704
+ token: await newIntegrationToken(),
705
+ scriptEnabled: false,
706
+ script: '',
707
+ retryFailedCalls: true,
708
+ retryCount: 4,
709
+ retryDelay: 'powers-of-ten',
710
+ impersonateUser: false,
711
+ runOnEdits: false,
712
+ triggerWordAnywhere: false,
713
+ alias: 'houston',
714
+ avatar: '',
715
+ emoji: '',
716
+ },
717
+ timeoutMs,
718
+ });
719
+ const madeBody = body(created);
720
+ if (created.status === 200 && madeBody.success === true) {
721
+ return String(map(madeBody.integration)._id ?? '') || null;
722
+ }
723
+ }
724
+ catch {
725
+ // Best-effort by contract: the caller says what is missing.
726
+ }
727
+ return null;
728
+ }
729
+ /** The fields `integrations.update` takes for an outgoing webhook, and nothing else. */
730
+ const OUTGOING_UPDATE_FIELDS = [
731
+ 'name',
732
+ 'enabled',
733
+ 'username',
734
+ 'channel',
735
+ 'event',
736
+ 'triggerWords',
737
+ 'triggerWordAnywhere',
738
+ 'token',
739
+ 'scriptEnabled',
740
+ 'script',
741
+ 'runOnEdits',
742
+ 'retryFailedCalls',
743
+ 'retryCount',
744
+ 'retryDelay',
745
+ 'impersonateUser',
746
+ 'targetRoom',
747
+ 'alias',
748
+ 'avatar',
749
+ 'emoji',
750
+ ];
751
+ /**
752
+ * Point an outgoing integration at other `urls`, as stored (`integrations.list`'s document).
753
+ *
754
+ * The update writes EVERY field from its body, so the whole document goes back -- but only
755
+ * the fields the schema names (it refuses unknown keys, and `scriptEngine`/`skipTranspile`
756
+ * exist on some releases only), the channel list as the comma-joined string the form sends,
757
+ * and a token where the stored one is empty, which the update refuses.
758
+ */
759
+ async function updateOutgoingUrls(rootUrl, auth, password, integration, urls, { timeoutMs = 15000 } = {}) {
760
+ const json = {
761
+ type: 'webhook-outgoing',
762
+ integrationId: String(integration._id ?? ''),
763
+ };
764
+ for (const key of OUTGOING_UPDATE_FIELDS) {
765
+ const value = integration[key];
766
+ if (value !== undefined && value !== null)
767
+ json[key] = value;
768
+ }
769
+ if (Array.isArray(integration.channel))
770
+ json.channel = integration.channel.join(',');
771
+ if (String(json.token ?? '').trim() === '')
772
+ json.token = await newIntegrationToken();
773
+ json.urls = [...urls];
774
+ try {
775
+ // A PUT: Rocket.Chat registers integrations.update that way, and a POST is refused.
776
+ const resp = await put(`${trimEnd(rootUrl)}/api/v1/integrations.update`, {
777
+ headers: await integrationHeaders(auth, password),
778
+ json,
779
+ timeoutMs,
780
+ });
781
+ return resp.status === 200 && body(resp).success === true;
782
+ }
783
+ catch {
784
+ return false;
785
+ }
786
+ }
787
+ /** A Rocket.Chat setting's current value, or null if unavailable. */
788
+ async function getSetting(rootUrl, auth, password, settingId, { timeoutMs = 15000 } = {}) {
789
+ const headers = { ...authHeaders(auth), ...(await password2faHeaders(password)) };
790
+ try {
791
+ const resp = await get(`${trimEnd(rootUrl)}/api/v1/settings/${settingId}`, {
792
+ headers,
793
+ timeoutMs,
794
+ });
795
+ const parsed = body(resp);
796
+ if (resp.status === 200 && parsed.success === true)
797
+ return parsed.value;
798
+ }
799
+ catch {
800
+ // Unreachable or unparseable: the caller gets null, which is "unavailable".
801
+ }
802
+ return null;
803
+ }
804
+ /**
805
+ * Whether Rocket.Chat ACCEPTED the license it holds: true, false, or null when it could not
806
+ * be asked (not serving, or a release whose `licenses.info` does not say).
807
+ */
808
+ async function licenseValid(rootUrl, auth, { timeoutMs = 15000 } = {}) {
809
+ try {
810
+ const resp = await get(`${trimEnd(rootUrl)}/api/v1/licenses.info`, {
811
+ headers: authHeaders(auth),
812
+ timeoutMs,
813
+ });
814
+ const valid = map(body(resp).license).hasValidLicense;
815
+ return resp.status === 200 && typeof valid === 'boolean' ? valid : null;
816
+ }
817
+ catch {
818
+ return null;
819
+ }
820
+ }
821
+ /**
822
+ * Every setting id this workspace knows, or null if it could not be asked.
823
+ *
824
+ * Catches a silent mistake: a Rocket.Chat SETTING only takes effect from the environment
825
+ * as `OVERWRITE_SETTING_<id>`. A bare setting id is accepted by docker, changes nothing,
826
+ * and reports no error -- so it is worth asking the workspace itself which names are
827
+ * settings rather than guessing from their shape.
828
+ */
829
+ async function settingIds(rootUrl, auth, password, { timeoutMs = 20000 } = {}) {
830
+ const headers = { ...authHeaders(auth), ...(await password2faHeaders(password)) };
831
+ try {
832
+ // count=0 means "all" to Rocket.Chat's REST pagination.
833
+ const resp = await get(`${trimEnd(rootUrl)}/api/v1/settings?count=0`, { headers, timeoutMs });
834
+ if (resp.status !== 200)
835
+ return null;
836
+ const parsed = body(resp);
837
+ if (parsed.success !== true)
838
+ return null;
839
+ const ids = new Set();
840
+ for (const setting of list(parsed.settings)) {
841
+ const id = String(setting._id ?? '');
842
+ if (id !== '')
843
+ ids.add(id);
844
+ }
845
+ return ids;
846
+ }
847
+ catch {
848
+ return null;
849
+ }
850
+ }
851
+ /** Write a Rocket.Chat setting (2FA-guarded; satisfied via the password method). */
852
+ async function setSetting(rootUrl, auth, password, settingId, value, { timeoutMs = 15000 } = {}) {
853
+ const headers = {
854
+ ...authHeaders(auth),
855
+ 'Content-Type': 'application/json',
856
+ ...(await password2faHeaders(password)),
857
+ };
858
+ try {
859
+ const resp = await post(`${trimEnd(rootUrl)}/api/v1/settings/${settingId}`, {
860
+ headers,
861
+ json: { value },
862
+ timeoutMs,
863
+ });
864
+ return resp.status === 200 && body(resp).success === true;
865
+ }
866
+ catch {
867
+ return false;
868
+ }
869
+ }
870
+ /**
871
+ * This process's loaded SAML provider, without following its missing-provider redirect.
872
+ * A transport failure is unknown, rather than proof that a disable has completed.
873
+ */
874
+ async function samlProviderState(rootUrl, provider, { timeoutMs = 3000, publicUrl = '' } = {}) {
875
+ const exposed = new URL(publicUrl || rootUrl);
876
+ try {
877
+ const metadata = await get(`${trimEnd(rootUrl)}/_saml/metadata/${encodeURIComponent(provider)}`, {
878
+ timeoutMs,
879
+ followRedirects: false,
880
+ headers: {
881
+ Host: exposed.host,
882
+ 'X-Forwarded-Proto': exposed.protocol.slice(0, -1),
883
+ },
884
+ });
885
+ if (metadata.status === 200 && /<(?:[\w.-]+:)?EntityDescriptor\b/u.test(metadata.text))
886
+ return 'loaded';
887
+ if (metadata.status === 404)
888
+ return 'unloaded';
889
+ const location = metadata.headers.location;
890
+ if (metadata.status === 302 &&
891
+ location !== undefined &&
892
+ URL.canParse(location, exposed.href) &&
893
+ new URL(location, exposed).href === new URL('home', `${exposed.origin}/`).href)
894
+ return 'unloaded';
895
+ return 'unknown';
896
+ }
897
+ catch (error) {
898
+ if (error instanceof rc_http_1.RequestFailed || error instanceof TypeError)
899
+ return 'unknown';
900
+ throw error;
901
+ }
902
+ }
903
+ /** A SAML login service exists and this Rocket.Chat process can serve its metadata. */
904
+ async function samlProviderReady(rootUrl, { timeoutMs = 3000, auth, publicUrl = '', } = {}) {
905
+ try {
906
+ // Self-configuration already has an admin session. Anonymous polling consumes the
907
+ // same per-IP provider-list quota the next visitor needs to render the SSO button.
908
+ const resp = await get(`${trimEnd(rootUrl)}/api/v1/service.configurations`, {
909
+ timeoutMs,
910
+ ...(auth === undefined ? {} : { headers: authHeaders(auth) }),
911
+ });
912
+ const parsed = body(resp);
913
+ if (resp.status !== 200 || parsed.success !== true)
914
+ return false;
915
+ const service = list(parsed.configurations).find((entry) => entry.service === 'saml');
916
+ const provider = map(service?.clientConfig).provider;
917
+ if (typeof provider !== 'string' || provider === '')
918
+ return false;
919
+ // The service document is shared in MongoDB; metadata is served by the instance's
920
+ // own loaded providers. Both matter when several processes share that document.
921
+ return (await samlProviderState(rootUrl, provider, { timeoutMs, publicUrl })) === 'loaded';
922
+ }
923
+ catch (error) {
924
+ if (error instanceof rc_http_1.RequestFailed)
925
+ return false;
926
+ throw error;
927
+ }
928
+ }
929
+ /**
930
+ * Whether a `method.call` response reflects a SUCCESSFUL method run.
931
+ *
932
+ * `method.call` returns HTTP 200 with a top-level `success: true` even when the Meteor
933
+ * method itself threw -- the real outcome is a JSON-encoded string in `message`
934
+ * (`{"msg":"result", ..., "error": {...}}` on failure). So the outer flag alone reports
935
+ * false success and the inner envelope has to be opened.
936
+ */
937
+ function methodSucceeded(resp) {
938
+ let inner;
939
+ try {
940
+ const outer = body(resp);
941
+ if (resp.status !== 200 || outer.success !== true)
942
+ return false;
943
+ inner = JSON.parse(String(outer.message ?? '{}'));
944
+ }
945
+ catch {
946
+ return false;
947
+ }
948
+ return !(inner !== null && typeof inner === 'object' && 'error' in inner);
949
+ }
950
+ /** Invoke a Meteor method over REST. True on success. */
951
+ async function methodCall(rootUrl, auth, password, method, params, { timeoutMs = 15000 } = {}) {
952
+ const headers = {
953
+ ...authHeaders(auth),
954
+ 'Content-Type': 'application/json',
955
+ ...(await password2faHeaders(password)),
956
+ };
957
+ // `dumps(...)`, the established string in `message`: `', '` and `': '` between members
958
+ // and `\uXXXX` for anything past ASCII, in the literal's order.
959
+ // `JSON.stringify` wrote it compact, so every `addOAuthService` -- a dump's custom OAuth
960
+ // provider, the oidc and saml presets' post-ready step -- sent Rocket.Chat other bytes.
961
+ const message = (0, json_text_1.dumps)({ msg: 'method', id: '1', method, params });
962
+ try {
963
+ const resp = await post(`${trimEnd(rootUrl)}/api/v1/method.call/${method}`, {
964
+ headers,
965
+ json: { message },
966
+ timeoutMs,
967
+ });
968
+ return methodSucceeded(resp);
969
+ }
970
+ catch {
971
+ return false;
972
+ }
973
+ }
974
+ /**
975
+ * Create a Custom OAuth provider via Rocket.Chat's `addOAuthService` method.
976
+ *
977
+ * A custom provider's `Accounts_OAuth_Custom-<name>-*` settings do not exist until it is
978
+ * created, so OVERWRITE_SETTING env cannot configure it -- this creates the provider (and
979
+ * its settings) so they can then be set via the API.
980
+ */
981
+ async function addOauthService(rootUrl, auth, password, name, { timeoutMs = 15000 } = {}) {
982
+ return await methodCall(rootUrl, auth, password, 'addOAuthService', [name], { timeoutMs });
983
+ }
984
+ /** Create a verified user (idempotent-ish: an existing username just fails). */
985
+ async function createUser(rootUrl, auth, password, username, { timeoutMs = 15000 } = {}) {
986
+ const headers = {
987
+ ...authHeaders(auth),
988
+ 'Content-Type': 'application/json',
989
+ ...(await password2faHeaders(password)),
990
+ };
991
+ try {
992
+ const resp = await post(`${trimEnd(rootUrl)}/api/v1/users.create`, {
993
+ headers,
994
+ json: {
995
+ name: username.charAt(0).toUpperCase() + username.slice(1),
996
+ username,
997
+ email: `${username}@example.com`,
998
+ password: username,
999
+ verified: true,
1000
+ requirePasswordChange: false,
1001
+ },
1002
+ timeoutMs,
1003
+ });
1004
+ return resp.status === 200 && body(resp).success === true;
1005
+ }
1006
+ catch {
1007
+ return false;
1008
+ }
1009
+ }
1010
+ /** Make `username` an Omnichannel agent (assigns the livechat-agent role). */
1011
+ async function addLivechatAgent(rootUrl, auth, password, username, { timeoutMs = 15000 } = {}) {
1012
+ const headers = {
1013
+ ...authHeaders(auth),
1014
+ 'Content-Type': 'application/json',
1015
+ ...(await password2faHeaders(password)),
1016
+ };
1017
+ try {
1018
+ const resp = await post(`${trimEnd(rootUrl)}/api/v1/livechat/users/agent`, {
1019
+ headers,
1020
+ json: { username },
1021
+ timeoutMs,
1022
+ });
1023
+ return resp.ok;
1024
+ }
1025
+ catch {
1026
+ return false;
1027
+ }
1028
+ }
1029
+ /** Give user `id` a voice call extension; false when Rocket.Chat refuses (Voice unlicensed). */
1030
+ async function setVoiceExtension(rootUrl, auth, password, id, extension, { timeoutMs = 15000 } = {}) {
1031
+ const headers = {
1032
+ ...authHeaders(auth),
1033
+ 'Content-Type': 'application/json',
1034
+ ...(await password2faHeaders(password)),
1035
+ };
1036
+ try {
1037
+ const resp = await post(`${trimEnd(rootUrl)}/api/v1/users.update`, {
1038
+ headers,
1039
+ json: { userId: id, data: { freeSwitchExtension: extension } },
1040
+ timeoutMs,
1041
+ });
1042
+ return resp.status === 200 && body(resp).success === true;
1043
+ }
1044
+ catch {
1045
+ return false;
1046
+ }
1047
+ }
1048
+ /** Resolve a username to its `_id` via users.info, or null. */
1049
+ async function getUserId(rootUrl, auth, username, { timeoutMs = 15000 } = {}) {
1050
+ try {
1051
+ const resp = await get(`${trimEnd(rootUrl)}/api/v1/users.info`, {
1052
+ params: { username },
1053
+ headers: authHeaders(auth),
1054
+ timeoutMs,
1055
+ });
1056
+ if (resp.ok) {
1057
+ const id = String(map(body(resp).user)._id ?? '');
1058
+ return id === '' ? null : id;
1059
+ }
1060
+ }
1061
+ catch {
1062
+ // Unreachable: null, and the caller decides.
1063
+ }
1064
+ return null;
1065
+ }
1066
+ /**
1067
+ * Create (or find) an Omnichannel department and return its id.
1068
+ *
1069
+ * The create schema is strict -- only these department fields, no agents, which are
1070
+ * assigned separately by `assignLivechatAgents`.
1071
+ */
1072
+ async function ensureLivechatDepartment(rootUrl, auth, password, name, { timeoutMs = 15000 } = {}) {
1073
+ const base = `${trimEnd(rootUrl)}/api/v1`;
1074
+ const headers = {
1075
+ ...authHeaders(auth),
1076
+ 'Content-Type': 'application/json',
1077
+ ...(await password2faHeaders(password)),
1078
+ };
1079
+ const department = {
1080
+ enabled: true,
1081
+ name,
1082
+ email: `${name}@example.com`,
1083
+ showOnRegistration: true,
1084
+ showOnOfflineForm: true,
1085
+ };
1086
+ try {
1087
+ const created = await post(`${base}/livechat/department`, {
1088
+ headers,
1089
+ json: { department },
1090
+ timeoutMs,
1091
+ });
1092
+ const madeBody = body(created);
1093
+ if (madeBody.success === true) {
1094
+ const id = String(map(madeBody.department)._id ?? '');
1095
+ return id === '' ? null : id;
1096
+ }
1097
+ // Already exists (or a strict-schema reject) -- look it up by name. count=0 means all
1098
+ // departments, so a match past the default page is not missed.
1099
+ const listed = await get(`${base}/livechat/department`, {
1100
+ headers,
1101
+ params: { count: 0 },
1102
+ timeoutMs,
1103
+ });
1104
+ for (const entry of list(body(listed).departments)) {
1105
+ if (entry.name === name) {
1106
+ const id = String(entry._id ?? '');
1107
+ return id === '' ? null : id;
1108
+ }
1109
+ }
1110
+ }
1111
+ catch {
1112
+ // Best-effort: the preset reports what it could not set up.
1113
+ }
1114
+ return null;
1115
+ }
1116
+ /** Assign agents to a department. Idempotent. */
1117
+ async function assignLivechatAgents(rootUrl, auth, password, deptId, agents, { timeoutMs = 15000 } = {}) {
1118
+ const headers = {
1119
+ ...authHeaders(auth),
1120
+ 'Content-Type': 'application/json',
1121
+ ...(await password2faHeaders(password)),
1122
+ };
1123
+ const upsert = agents.map((agent) => ({
1124
+ agentId: agent.agentId,
1125
+ username: agent.username,
1126
+ count: 0,
1127
+ order: 0,
1128
+ }));
1129
+ try {
1130
+ const resp = await post(`${trimEnd(rootUrl)}/api/v1/livechat/department/${deptId}/agents`, {
1131
+ headers,
1132
+ json: { upsert, remove: [] },
1133
+ timeoutMs,
1134
+ });
1135
+ return resp.ok;
1136
+ }
1137
+ catch {
1138
+ return false;
1139
+ }
1140
+ }
1141
+ /**
1142
+ * Save a global canned response. An ENTERPRISE feature, so this returns false on
1143
+ * Community (403) and callers treat it as best-effort.
1144
+ */
1145
+ async function saveCannedResponse(rootUrl, auth, password, shortcut, text, { timeoutMs = 15000 } = {}) {
1146
+ const headers = {
1147
+ ...authHeaders(auth),
1148
+ 'Content-Type': 'application/json',
1149
+ ...(await password2faHeaders(password)),
1150
+ };
1151
+ try {
1152
+ const resp = await post(`${trimEnd(rootUrl)}/api/v1/canned-responses`, {
1153
+ headers,
1154
+ json: { shortcut, text, scope: 'global' },
1155
+ timeoutMs,
1156
+ });
1157
+ return resp.status === 200 && body(resp).success === true;
1158
+ }
1159
+ catch {
1160
+ return false;
1161
+ }
1162
+ }
1163
+ /**
1164
+ * Set the logged-in agent available for Omnichannel.
1165
+ *
1166
+ * The workspace only shows as "online" to visitors once that agent also has a live
1167
+ * presence (is logged into the UI); this flips the availability flag and nothing else.
1168
+ */
1169
+ async function setLivechatAvailable(rootUrl, auth, password, { timeoutMs = 15000 } = {}) {
1170
+ const headers = {
1171
+ ...authHeaders(auth),
1172
+ 'Content-Type': 'application/json',
1173
+ ...(await password2faHeaders(password)),
1174
+ };
1175
+ try {
1176
+ const resp = await post(`${trimEnd(rootUrl)}/api/v1/livechat/agent.status`, {
1177
+ headers,
1178
+ json: { status: 'available' },
1179
+ timeoutMs,
1180
+ });
1181
+ return resp.status === 200 && body(resp).success === true;
1182
+ }
1183
+ catch {
1184
+ return false;
1185
+ }
1186
+ }
1187
+ /**
1188
+ * An IdP's signing certificate from its SAML metadata descriptor.
1189
+ *
1190
+ * Retries until the IdP -- Keycloak, which boots slowly -- is serving. Returns the base64
1191
+ * DER cert body on a single line, which is Rocket.Chat's idp cert format.
1192
+ */
1193
+ async function fetchSamlIdpCert(descriptorUrl, { timeout = 90, interval = 3, sleep = realSleep, } = {}) {
1194
+ const deadline = now() + timeout;
1195
+ for (;;) {
1196
+ try {
1197
+ const resp = await get(descriptorUrl, { timeoutMs: 10000 });
1198
+ if (resp.status === 200) {
1199
+ const found = /<[^>]*X509Certificate>([^<]+)</u.exec(resp.text);
1200
+ if (found !== null)
1201
+ return found[1].split(/\s+/u).join('');
1202
+ }
1203
+ }
1204
+ catch {
1205
+ // Not serving yet. That is what the loop is for.
1206
+ }
1207
+ if (now() >= deadline)
1208
+ return null;
1209
+ await sleep(interval);
1210
+ }
1211
+ }
1212
+ /**
1213
+ * The transport failure, re-exported so a caller can tell one from a 4xx.
1214
+ *
1215
+ * The seam it comes from is fenced to this module by `only-rcapi-speaks-http`, so the class
1216
+ * travels with the call that can raise it. Without this a caller has to catch EVERYTHING to
1217
+ * spot a dropped connection, and a bug in this module would be swallowed as one.
1218
+ */
1219
+ var rc_http_2 = require("../seams/rc-http");
1220
+ Object.defineProperty(exports, "RequestFailed", { enumerable: true, get: function () { return rc_http_2.RequestFailed; } });
1221
+ /**
1222
+ * Make an authed REST call. Returns `[status, bodyText]`.
1223
+ *
1224
+ * `params` is the point: the three modules that once bypassed this seam -- the seed, the
1225
+ * load test and the CLI -- all did so because they needed a query string. Adding the one
1226
+ * keyword they were going around it for is what lets them come back through.
1227
+ */
1228
+ async function call(rootUrl, method, path, { auth, data, extraHeaders, params, responseHeaders, timeoutMs = 30000, } = {}) {
1229
+ const url = `${trimEnd(rootUrl)}/${path.replace(/^\/+/u, '')}`;
1230
+ const headers = { ...(auth === undefined ? {} : authHeaders(auth)), ...extraHeaders };
1231
+ const resp = await rc_http_1.rcHttp.request(url, {
1232
+ method,
1233
+ headers,
1234
+ ...(data === undefined ? {} : { json: data }),
1235
+ ...(params === undefined ? {} : { params }),
1236
+ timeoutMs,
1237
+ });
1238
+ if (responseHeaders !== undefined) {
1239
+ for (const key of Object.keys(responseHeaders))
1240
+ delete responseHeaders[key];
1241
+ Object.assign(responseHeaders, resp.headers);
1242
+ }
1243
+ return [resp.status, resp.text];
1244
+ }
1245
+ async function multipart(rootUrl, path, headers, parts) {
1246
+ const { randomBytes } = await Promise.resolve().then(() => __importStar(require('node:crypto')));
1247
+ const boundary = `houston-${randomBytes(18).toString('hex')}`;
1248
+ const chunks = [];
1249
+ for (const part of parts) {
1250
+ if (/[\r\n"\\]/u.test(part.name) ||
1251
+ (part.filename !== undefined && /[\r\n"\\]/u.test(part.filename))) {
1252
+ throw new Error('invalid multipart field or filename');
1253
+ }
1254
+ chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${part.name}"${part.filename === undefined ? '' : `; filename="${part.filename}"`}\r\n${part.type === undefined ? '' : `Content-Type: ${part.type}\r\n`}\r\n`));
1255
+ chunks.push(Buffer.isBuffer(part.value) ? part.value : Buffer.from(part.value));
1256
+ chunks.push(Buffer.from('\r\n'));
1257
+ }
1258
+ chunks.push(Buffer.from(`--${boundary}--\r\n`));
1259
+ const clean = Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== 'content-type'));
1260
+ const response = await rc_http_1.rcHttp.request(`${trimEnd(rootUrl)}/${path.replace(/^\/+/u, '')}`, {
1261
+ method: 'POST',
1262
+ headers: { ...clean, 'Content-Type': `multipart/form-data; boundary=${boundary}` },
1263
+ body: Buffer.concat(chunks),
1264
+ timeoutMs: 60000,
1265
+ });
1266
+ return [response.status, response.text];
1267
+ }
1268
+ async function download(rootUrl, path, headers) {
1269
+ const base = new URL(`${trimEnd(rootUrl)}/`);
1270
+ const target = new URL(path, base);
1271
+ if (target.origin !== base.origin)
1272
+ throw new Error('file download must stay on the workspace origin');
1273
+ try {
1274
+ return await rc_http_1.rcHttp.request(target.href, {
1275
+ headers,
1276
+ binary: true,
1277
+ sameOriginRedirects: true,
1278
+ timeoutMs: 60000,
1279
+ });
1280
+ }
1281
+ catch {
1282
+ throw new errors_1.CreateFailedError('workspace file download could not be completed');
1283
+ }
1284
+ }
1285
+ exports.rcapi = { call, multipart, download };