@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,739 @@
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.IMPLICIT_ADMIN = exports.ROLES = exports.MIN_PASSWORD = exports.SCRYPT_MAXMEM = exports.SCRYPT_P = exports.SCRYPT_R = exports.SCRYPT_N = exports.USERS_FILE = void 0;
37
+ exports.usersFile = usersFile;
38
+ exports.hashPassword = hashPassword;
39
+ exports.check = check;
40
+ exports.readAll = readAll;
41
+ exports.writeAll = writeAll;
42
+ exports.withUsersLock = withUsersLock;
43
+ exports.normaliseRole = normaliseRole;
44
+ exports.atLeast = atLeast;
45
+ exports.requireValidRole = requireValidRole;
46
+ exports.roleOf = roleOf;
47
+ exports.admins = admins;
48
+ exports.implicitAdmins = implicitAdmins;
49
+ exports.normalizeName = normalizeName;
50
+ exports.requireValidName = requireValidName;
51
+ exports.requireValidPassword = requireValidPassword;
52
+ exports.anyUsers = anyUsers;
53
+ exports.listUsers = listUsers;
54
+ exports.defaultRoleForNewAccount = defaultRoleForNewAccount;
55
+ exports.mintPassword = mintPassword;
56
+ exports.add = add;
57
+ exports.setPassword = setPassword;
58
+ exports.remove = remove;
59
+ exports.setRole = setRole;
60
+ exports.verify = verify;
61
+ exports.installTeamModeAnswer = installTeamModeAnswer;
62
+ /**
63
+ * Named accounts for the web GUI -- shared by the CLI and the web API.
64
+ *
65
+ * A shared deployment needs to answer "who tore down TICKET-1234?", and a session token
66
+ * cannot: it is one secret handed to everybody, regenerated on every restart. Named users
67
+ * give attribution, survive restarts, and let a person be removed without disrupting anyone
68
+ * else.
69
+ *
70
+ * ## scrypt, and the two runtimes that disagree at the boundary
71
+ *
72
+ * Hashing is scrypt from the standard library on both sides -- houston is deliberately
73
+ * dependency-light and has no bcrypt or passlib. The cost parameters live in each line so
74
+ * they can be raised later without invalidating existing entries, and `check` reads
75
+ * `n`/`r`/`p` FROM THE STORED LINE for exactly that reason.
76
+ *
77
+ * `maxmem` is stated explicitly rather than left to the default, for one reason. Node's
78
+ * rule is `128 * N * r > maxmem` -- a strict inequality, so the default 32 MiB ACCEPTS
79
+ * N=32768 at r=8 (which is exactly 32 MiB), while the previous implementation's scrypt --
80
+ * OpenSSL at its own default -- refuses it. The two runtimes disagree at that boundary, and
81
+ * a hash one build could write and the other could not verify locks every account out of
82
+ * one of them. Naming the number here means the agreement is written down rather than
83
+ * inherited.
84
+ *
85
+ * The async `crypto.scrypt` is used rather than `scryptSync`: service entry points are
86
+ * asynchronous so nothing blocks the event loop for ~100 ms per sign-in, and the
87
+ * timing gate pins `UV_THREADPOOL_SIZE` precisely because this form uses the threadpool.
88
+ *
89
+ * ## The dummy hash is a literal, and that is the defect it fixes
90
+ *
91
+ * `DUMMY_HASH` is a well-formed line built from random bytes, NOT `hashPassword('dummy')`.
92
+ * The obvious version derives scrypt TWICE -- once to build the dummy, once to check
93
+ * against it -- so an unknown user cost exactly double a known one, and the timing side
94
+ * channel the line was written to close was instead created by it, twice as loud as the
95
+ * early return it replaced. Measured before that change: 46.6 ms unknown against 23.7 ms
96
+ * known, a ratio of 1.97.
97
+ */
98
+ const node_crypto_1 = require("node:crypto");
99
+ const fs = __importStar(require("node:fs"));
100
+ const path = __importStar(require("node:path"));
101
+ const node_util_1 = require("node:util");
102
+ const config = __importStar(require("../lib/config"));
103
+ const errors_1 = require("../lib/errors");
104
+ const home_1 = require("../lib/home");
105
+ const format_1 = require("../lib/format");
106
+ const teammode_1 = require("../lib/teammode");
107
+ const lock_1 = require("../seams/fs/lock");
108
+ const audit_1 = require("./audit");
109
+ const sessions_1 = require("./sessions");
110
+ const sso_identities_1 = require("./sso-identities");
111
+ const scrypt = (0, node_util_1.promisify)(node_crypto_1.scrypt);
112
+ exports.USERS_FILE = 'users';
113
+ /**
114
+ * scrypt cost. N=16384 lands around 100 ms on a laptop, which is the point: it is the
115
+ * difference between a guessable password being brute-forced in hours and in centuries.
116
+ * Written into every line, so raising it later is a per-user migration rather than a
117
+ * flag day.
118
+ */
119
+ exports.SCRYPT_N = 16384;
120
+ exports.SCRYPT_R = 8;
121
+ exports.SCRYPT_P = 1;
122
+ const DKLEN = 32;
123
+ const SALT_BYTES = 16;
124
+ /** Stated rather than defaulted. See this module's docstring. */
125
+ exports.SCRYPT_MAXMEM = 33554432;
126
+ /**
127
+ * A password below this is refused outright. Short of a policy engine, length is the
128
+ * single control that matters most.
129
+ */
130
+ exports.MIN_PASSWORD = 12;
131
+ /**
132
+ * Usernames become part of a repro name and therefore a DNS label, so they are restricted
133
+ * to what `sanitize()` would leave untouched. Input is NORMALISED to this shape rather
134
+ * than refused -- see `normalizeName`.
135
+ */
136
+ const NAME_RE = /^[a-z0-9][a-z0-9-]{0,30}$/u;
137
+ const NAME_MAX = 31;
138
+ /** Everything `sanitize()` folds to a dash. */
139
+ const NAME_SEPARATORS = /[^a-z0-9-]+/gu;
140
+ function usersFile() {
141
+ return (0, home_1.joinPath)(config.home(), exports.USERS_FILE);
142
+ }
143
+ function lockFile() {
144
+ return (0, home_1.joinPath)(config.home(), 'locks', 'users.lock');
145
+ }
146
+ /** `scrypt$n$r$p$salt$hash`, self-describing so the cost can change later. */
147
+ async function hashPassword(password, salt) {
148
+ const useSalt = salt ?? (0, node_crypto_1.randomBytes)(SALT_BYTES);
149
+ const digest = await scrypt(Buffer.from(password, 'utf8'), useSalt, DKLEN, {
150
+ N: exports.SCRYPT_N,
151
+ r: exports.SCRYPT_R,
152
+ p: exports.SCRYPT_P,
153
+ maxmem: exports.SCRYPT_MAXMEM,
154
+ });
155
+ return [
156
+ 'scrypt',
157
+ exports.SCRYPT_N,
158
+ exports.SCRYPT_R,
159
+ exports.SCRYPT_P,
160
+ useSalt.toString('base64'),
161
+ digest.toString('base64'),
162
+ ].join('$');
163
+ }
164
+ /**
165
+ * What an unknown user is checked against, so a miss costs the same as a hit.
166
+ *
167
+ * A well-formed line with a random salt and a random digest costs nothing to build and
168
+ * makes `check` do exactly ONE derivation, which is what the real path does. The digest
169
+ * is never meant to match; a password deriving to these 32 bytes has the same odds as
170
+ * guessing the salt.
171
+ */
172
+ const DUMMY_HASH = [
173
+ 'scrypt',
174
+ exports.SCRYPT_N,
175
+ exports.SCRYPT_R,
176
+ exports.SCRYPT_P,
177
+ (0, node_crypto_1.randomBytes)(SALT_BYTES).toString('base64'),
178
+ (0, node_crypto_1.randomBytes)(DKLEN).toString('base64'),
179
+ ].join('$');
180
+ /** Constant-time verify against a stored hash. */
181
+ async function check(password, stored) {
182
+ let want;
183
+ let expected;
184
+ try {
185
+ const parts = stored.split('$');
186
+ if (parts.length !== 6)
187
+ return false;
188
+ const [scheme, n, r, p, salt, digest] = parts;
189
+ if (scheme !== 'scrypt')
190
+ return false;
191
+ expected = Buffer.from(digest, 'base64');
192
+ want = await scrypt(Buffer.from(password, 'utf8'), Buffer.from(salt, 'base64'), expected.length, {
193
+ N: Number.parseInt(n, 10),
194
+ r: Number.parseInt(r, 10),
195
+ p: Number.parseInt(p, 10),
196
+ maxmem: exports.SCRYPT_MAXMEM,
197
+ });
198
+ }
199
+ catch {
200
+ // A malformed line is a failed check, not a crash in the sign-in path.
201
+ return false;
202
+ }
203
+ if (want.length !== expected.length)
204
+ return false;
205
+ return (0, node_crypto_1.timingSafeEqual)(want, expected);
206
+ }
207
+ /**
208
+ * `name:hash:created_at[:role]` -> the four fields, or null.
209
+ *
210
+ * The trailing role is optional. `created_at` is a DATE ONLY, because ":" is the field
211
+ * delimiter and an ISO timestamp would split straight into the role column; a legacy line
212
+ * carrying a full timestamp is defensively cut back to its date here.
213
+ *
214
+ * `stripText(line)`, which is not `trim()`: the two whitespace sets disagree in both
215
+ * directions. `trim()` took the BOM a Windows editor leaves on the first line, so
216
+ * `\ufeffalice` -- an account no typed name finds -- was read as `alice`, the only admin,
217
+ * and `users add` rewrote the line without it; and it kept the information separators
218
+ * `\x1c`-`\x1f` that `stripText` strips, and wrote them back.
219
+ */
220
+ function parse(line) {
221
+ const trimmed = (0, format_1.stripText)(line);
222
+ if (!trimmed || trimmed.startsWith('#'))
223
+ return null;
224
+ const parts = trimmed.split(':');
225
+ if (parts.length < 3)
226
+ return null;
227
+ let created = parts[2];
228
+ const role = parts.length > 3 ? parts[3] : '';
229
+ if (created.includes(':'))
230
+ created = created.split(':')[0];
231
+ return [parts[0], parts[1], created, role];
232
+ }
233
+ /** name -> [hash, created_at, role]. A missing file is an empty map, not an error.
234
+ *
235
+ * Exported so a check can read the real file through the real parser rather than
236
+ * re-parsing it; `writeAll` is exported for the same reason.
237
+ */
238
+ function readAll() {
239
+ const target = usersFile();
240
+ let bytes;
241
+ try {
242
+ bytes = fs.readFileSync(target);
243
+ }
244
+ catch (error) {
245
+ if (error.code === 'ENOENT')
246
+ return new Map();
247
+ // The C library's reason. The root callback reads this file on every invocation, so
248
+ // this sentence is what `up --help` answers with when `users` is a directory:
249
+ // `cannot read <path>: Is a directory`, where `String(error)` said
250
+ // `Error: EISDIR: illegal operation on a directory, read`.
251
+ throw new errors_1.ValidationError(`cannot read ${target}: ${(0, format_1.strerrorText)(error, target)}`);
252
+ }
253
+ // STRICT UTF-8 -- and deliberately NOT turned into the ValidationError above. A decode
254
+ // failure is not a failed read, so a `users` holding `al\xffice` escapes `readAll`,
255
+ // the root callback and the app, and `main` reports it as unhandled: the
256
+ // stack trace, `error: <path> is not valid UTF-8 (byte 0xff at position 2: invalid start
257
+ // byte) - this is unhandled, ...`, a REPRO_ERROR envelope under
258
+ // --json, exit 1 -- for `up --help` and `list --json` alike (measured). The lenient
259
+ // `readFileSync(target, 'utf8')` put a U+FFFD in, read the account `al\ufffdice`, and
260
+ // answered both as a sound home does, exit 0.
261
+ const text = (0, format_1.decodeUtf8Strict)(bytes, target);
262
+ const out = new Map();
263
+ // `splitTextLines(text)`, which also breaks at a lone `\r`, `\v`, `\f`, `\x1c`-`\x1e`, NEL and
264
+ // the two Unicode separators. `split('\n')` read a CR-only file as ONE account, alice with
265
+ // the role `admin\rbob`, and the next write rewrote that line, so bob's account was gone.
266
+ for (const line of (0, format_1.splitTextLines)(text)) {
267
+ const parsed = parse(line);
268
+ if (parsed !== null)
269
+ out.set(parsed[0], [parsed[1], parsed[2], parsed[3]]);
270
+ }
271
+ return out;
272
+ }
273
+ /**
274
+ * Rewrite the file atomically, owner-only.
275
+ *
276
+ * Exported so a fixed-salt fixture can write through the real writer, and the HEADER and
277
+ * ROW bytes are what gets compared rather than a transcription.
278
+ *
279
+ * 0600 is set BEFORE the content is in place: creating it world-readable and chmod-ing
280
+ * it afterwards would leave exactly the window this file exists to prevent.
281
+ */
282
+ function writeAll(users) {
283
+ const target = usersFile();
284
+ // No explicit mode, as the directory has always been created. `config.saveConfig`
285
+ // creates the home 0700 and is normally what gets there first; tightening it here would
286
+ // invent a difference from earlier releases in a directory mode. The FILE is 0600
287
+ // either way -- that is the mode that matters, and it
288
+ // is applied at creation below.
289
+ fs.mkdirSync(path.dirname(target), { recursive: true });
290
+ const tmp = (0, home_1.joinPath)(path.dirname(target), `${path.basename(target)}.${process.pid}.tmp`);
291
+ const lines = [
292
+ '# houston GUI accounts. Managed by `houston users`.',
293
+ '# name:hash:created_at[:role]',
294
+ ];
295
+ // The names sorted by code point. `sort()` compares UTF-16 units, which puts an astral name
296
+ // (U+1D400) before a BMP one above the surrogates (U+FF41) in the rewritten file.
297
+ for (const name of [...users.keys()].sort(format_1.compareCodePoints)) {
298
+ const [hashed, created, role] = users.get(name);
299
+ lines.push(`${name}:${hashed}:${created}` + (role ? `:${role}` : ''));
300
+ }
301
+ try {
302
+ const fd = fs.openSync(tmp, 'w', 0o600);
303
+ try {
304
+ fs.writeSync(fd, lines.join('\n') + '\n', null, 'utf8');
305
+ }
306
+ finally {
307
+ fs.closeSync(fd);
308
+ }
309
+ fs.renameSync(tmp, target);
310
+ }
311
+ finally {
312
+ try {
313
+ fs.rmSync(tmp, { force: true });
314
+ }
315
+ catch {
316
+ /* already renamed away */
317
+ }
318
+ }
319
+ }
320
+ /**
321
+ * Exclusive access for a read-modify-write of the users file.
322
+ *
323
+ * Every mutation here is read-whole-file -> change one entry -> rewrite. Without this,
324
+ * two of them interleave and the later write reads a snapshot taken before the earlier one
325
+ * landed, so the earlier change is gone -- with both callers told they succeeded. Measured
326
+ * before it existed: eight concurrent `houston users add` left TWO accounts on disk, and
327
+ * the other six were reported created, complete with a minted password. The sharpest case
328
+ * is not `add` but a password reset: `users passwd` on a compromised account can be
329
+ * silently discarded by any concurrent write, and the admin is looking at a new password
330
+ * while the old one still works.
331
+ *
332
+ * READS ARE DELIBERATELY NOT LOCKED. The write lands through `rename`, which is atomic, so
333
+ * a reader sees the whole old file or the whole new one and never a torn mix. That
334
+ * matters: `roleOf()` runs in the web guard on EVERY api request, and a lock on that path
335
+ * would buy nothing and cost a syscall per request.
336
+ */
337
+ async function locked(body) {
338
+ // The locks directory, then `users.lock` opened for writing: a locks directory this user
339
+ // may not create, or a lock file it may not open for writing, throws `fileErrorOf`'s
340
+ // established error here too, rather than Node's sentence or a lock taken read-only.
341
+ const dir = path.dirname(lockFile());
342
+ try {
343
+ fs.mkdirSync(dir, { recursive: true });
344
+ }
345
+ catch (error) {
346
+ throw (0, format_1.fileErrorOf)(error, dir);
347
+ }
348
+ return await (0, lock_1.withFileLock)(lockFile(), body, { open: lock_1.OPEN_FOR_WRITE });
349
+ }
350
+ /**
351
+ * `locked`, for `core/sso`: an Okta sign-in that creates or links an account writes this file
352
+ * and `sso-identities.json` together, and two first sign-ins of one person must not both
353
+ * create it. Not re-entrant: nothing in `body` may call a function here that locks.
354
+ */
355
+ async function withUsersLock(body) {
356
+ return await locked(body);
357
+ }
358
+ /**
359
+ * The three tiers, widest first. `admin` manages people; `member` is today's behaviour and
360
+ * the default for a new account; `readonly` may look but not touch, and specifically may
361
+ * NOT read logs, env or mint tokens -- workspace logs carry LDAP bind passwords and OAuth
362
+ * client secrets, so "read-only" cannot mean "may read those".
363
+ */
364
+ exports.ROLES = Object.freeze(['admin', 'member', 'readonly']);
365
+ const RANK = Object.freeze({ admin: 3, member: 2, readonly: 1 });
366
+ /**
367
+ * A BLANK role column means admin, and that is not a default -- it is the migration.
368
+ *
369
+ * Every account created before roles existed has an empty column, and it has always been
370
+ * documented as `"" = full access`. Reading blank as anything narrower would
371
+ * silently demote every existing user, and on an install whose only account predates the
372
+ * change it would leave the box with NO admin and no way to make one from the GUI.
373
+ */
374
+ exports.IMPLICIT_ADMIN = 'admin';
375
+ /**
376
+ * The effective role for a stored column value.
377
+ *
378
+ * `stripText` here and below, not `trim()`, for the reason `parse` gives: `users role bob
379
+ * $'member\x1f'` has always made bob a member and was refused here as an unknown role, and
380
+ * a stored column holding one read as an admin.
381
+ */
382
+ function normaliseRole(role) {
383
+ const value = (0, format_1.stripText)(role || '').toLowerCase();
384
+ return exports.ROLES.includes(value) ? value : exports.IMPLICIT_ADMIN;
385
+ }
386
+ /** Whether `role` satisfies a minimum of `needed`. Unknown -> false. */
387
+ function atLeast(role, needed) {
388
+ return (RANK[role || ''] ?? 0) >= (RANK[needed || ''] ?? 99);
389
+ }
390
+ function requireValidRole(role) {
391
+ if (!exports.ROLES.includes((0, format_1.stripText)(role || '').toLowerCase())) {
392
+ throw new errors_1.ValidationError(`unknown role ${quote(role)} (want: ${exports.ROLES.join(', ')})`);
393
+ }
394
+ }
395
+ /**
396
+ * The effective role of `name`, or "" if there is no such account.
397
+ *
398
+ * Read live on every check rather than snapshotted into the session line: a demotion that
399
+ * only takes effect at the user's next sign-in is a demotion that has not happened, and
400
+ * the person you are demoting is the one least likely to sign out.
401
+ */
402
+ function roleOf(name) {
403
+ const stored = readAll().get(normalizeName(name));
404
+ return stored === undefined ? '' : normaliseRole(stored[2]);
405
+ }
406
+ function admins() {
407
+ return [...readAll().entries()]
408
+ .filter(([, [, , role]]) => normaliseRole(role) === 'admin')
409
+ .map(([name]) => name)
410
+ .sort(format_1.compareCodePoints);
411
+ }
412
+ /** Accounts that are admin only because their role column is blank. */
413
+ function implicitAdmins() {
414
+ return [...readAll().entries()]
415
+ .filter(([, [, , role]]) => !(0, format_1.stripText)(role || ''))
416
+ .map(([name]) => name)
417
+ .sort(format_1.compareCodePoints);
418
+ }
419
+ /**
420
+ * Refuse to remove the last way back in.
421
+ *
422
+ * Enforced here rather than in the web layer so `houston users remove` obeys it too -- a
423
+ * box with zero admins cannot make one from the GUI, and the repair is hand-editing a file
424
+ * most people would not know to look for.
425
+ */
426
+ function requireNotLastAdmin(name, users, what) {
427
+ const current = [...users.entries()]
428
+ .filter(([, [, , role]]) => normaliseRole(role) === 'admin')
429
+ .map(([who]) => who);
430
+ if (current.length === 1 && current[0] === name) {
431
+ throw new errors_1.ConflictError(`${quote(name)} is the only admin, so ${what} would leave this server with none ` +
432
+ 'and no way to make another from the GUI. Promote somebody first: ' +
433
+ '`houston users role <name> admin`');
434
+ }
435
+ }
436
+ /**
437
+ * The stored form of `name`. `lucy.felix` -> `lucy-felix`.
438
+ *
439
+ * People's names are dotted -- that is how every corporate directory writes them -- and
440
+ * refusing them outright was not the cosmetic problem it looked like. A box with no
441
+ * accounts also refuses to start `serve` on a network-reachable bind, so `users add
442
+ * lucy.felix` failing was the reason the GUI could not be brought up at all. Repro names
443
+ * have always been TRANSFORMED rather than rejected, and account names now agree.
444
+ *
445
+ * Length is deliberately NOT touched. Silently truncating somebody's identity is worse
446
+ * than refusing it, so a name still too long after this is `requireValidName`'s to reject
447
+ * and the person's to shorten.
448
+ */
449
+ function normalizeName(name) {
450
+ const cleaned = (name || '').toLowerCase().replace(/\./gu, '-');
451
+ return cleaned.replace(NAME_SEPARATORS, '-').replace(/^-+/u, '').replace(/-+$/u, '');
452
+ }
453
+ /**
454
+ * A string's length in CODE POINTS, where `String.length` counts UTF-16 units.
455
+ *
456
+ * The two agree until a character sits outside the Basic Multilingual Plane, and then
457
+ * `.length` counts it twice. Measured with `.length`, six emoji were twelve characters, so
458
+ * a six-character password cleared the twelve-character floor -- the enforced minimum
459
+ * halved for exactly the characters a person picks to look strong -- and the refusal's
460
+ * "(got N)" doubled every astral character in it. Iterating the string walks code points,
461
+ * and a lone surrogate counts as one of them.
462
+ */
463
+ function lengthChecked(value) {
464
+ return [...value].length;
465
+ }
466
+ /**
467
+ * The invariant for what may be STORED, applied to an already-normalised name.
468
+ *
469
+ * Every caller runs `normalizeName` first, so what arrives here is lowercase `[a-z0-9-]`
470
+ * already. That leaves exactly two ways to fail, and they have different fixes, so they
471
+ * say different things -- the single combined message used to answer "at most 31
472
+ * characters" to somebody whose name was `...`.
473
+ */
474
+ function requireValidName(name) {
475
+ if (!name) {
476
+ throw new errors_1.ValidationError('a user name needs at least one letter or digit — it becomes part of a workspace ' +
477
+ 'name, and therefore a DNS label.');
478
+ }
479
+ // Counted in code points (`lengthChecked`), like the password below. Through either front door
480
+ // the name is normalised and therefore ASCII, where the two counts agree; this keeps
481
+ // them agreeing for a caller that hands the check a name it did not normalise.
482
+ const length = lengthChecked(name);
483
+ if (length > NAME_MAX) {
484
+ throw new errors_1.ValidationError(`user name ${quote(name)} is ${length} characters; the limit is ${NAME_MAX}, ` +
485
+ 'because it becomes part of a workspace name and therefore a DNS label.');
486
+ }
487
+ if (!NAME_RE.test(name)) {
488
+ throw new errors_1.ValidationError(`invalid user name ${quote(name)} — lowercase letters, digits and '-', starting ` +
489
+ 'with a letter or digit. It becomes part of a workspace name and therefore a ' +
490
+ 'DNS label.');
491
+ }
492
+ }
493
+ /**
494
+ * The floor every typed password meets: `users add/passwd --ask-password`, the GUI's
495
+ * change-my-password and its first-run account all come through here, so this one count
496
+ * is the whole of the policy.
497
+ */
498
+ function requireValidPassword(password) {
499
+ const length = lengthChecked(password || '');
500
+ if (length < exports.MIN_PASSWORD) {
501
+ throw new errors_1.ValidationError(`password must be at least ${exports.MIN_PASSWORD} characters (got ${length})`);
502
+ }
503
+ }
504
+ // --- public API -----------------------------------------------------------------
505
+ /** Whether this box has any accounts at all. */
506
+ function anyUsers() {
507
+ return readAll().size > 0;
508
+ }
509
+ function listUsers() {
510
+ return [...readAll().entries()]
511
+ .sort(([a], [b]) => (0, format_1.compareCodePoints)(a, b))
512
+ .map(([name, [, created, role]]) => ({ name, createdAt: created, role }));
513
+ }
514
+ /**
515
+ * `admin` for the very first account, `member` for every one after it.
516
+ *
517
+ * Blank-means-admin is the MIGRATION for accounts that predate roles; it must not become
518
+ * the behaviour for new ones, or `houston users add bob` silently hands bob the ability to
519
+ * delete everybody's data. New accounts therefore always get an EXPLICIT role written to
520
+ * their line. The first one has to be admin, though: a box whose only account is a member
521
+ * has nobody who can promote anyone, and no way to fix it from the GUI.
522
+ */
523
+ function defaultRoleForNewAccount() {
524
+ return readAll().size === 0 ? 'admin' : 'member';
525
+ }
526
+ /**
527
+ * Bytes of entropy in a password houston generates. 12 bytes is ~96 bits: long enough that
528
+ * guessing it is not a threat model, short enough to read aloud once over a call.
529
+ */
530
+ const NEW_PASSWORD_BYTES = 12;
531
+ /**
532
+ * A password the server chose, not a person.
533
+ *
534
+ * Lives here rather than in the web layer because BOTH front ends need it and the argument
535
+ * is the same in both. An admin who types a colleague's password also knows it, which
536
+ * makes every audit line signed with that name deniable; generating it means an admin can
537
+ * reset the credential but never hold it. It is also the only real defence against
538
+ * distributed online guessing: the per-address throttle bounds one source, nothing bounds
539
+ * a thousand, and a ~96-bit secret does not care how many there are.
540
+ */
541
+ function mintPassword() {
542
+ return (0, node_crypto_1.randomBytes)(NEW_PASSWORD_BYTES).toString('base64url');
543
+ }
544
+ async function add(name, password, role = '') {
545
+ // Normalised HERE rather than only at the two front ends, so the service is correct on
546
+ // its own terms: `add` is what decides the stored form, and the returned User carries it
547
+ // back so a caller prints the name it really made instead of the one it was handed.
548
+ const stored = normalizeName(name);
549
+ requireValidName(stored);
550
+ requireValidPassword(password);
551
+ if (role)
552
+ requireValidRole(role);
553
+ // Derived OUTSIDE the lock: scrypt is ~100 ms by design and depends on nothing in the
554
+ // file, so holding the lock across it would serialise account creation on the one part
555
+ // that does not need to be.
556
+ const hashed = await hashPassword(password);
557
+ // Date, not a full timestamp: ":" is the field delimiter, and an ISO time
558
+ // ("...T08:52:23+00:00") splits straight into the role column. Only ever displayed, so
559
+ // day granularity is enough.
560
+ const created = new Date().toISOString().slice(0, 10);
561
+ const chosen = await locked(() => {
562
+ // Resolved inside the lock: `defaultRoleForNewAccount` answers "is the file empty?",
563
+ // so two concurrent first accounts would otherwise both read empty and both come out
564
+ // admin.
565
+ const picked = role || defaultRoleForNewAccount();
566
+ requireValidRole(picked);
567
+ const users = readAll();
568
+ if (users.has(stored)) {
569
+ throw new errors_1.ConflictError(`user ${quote(stored)} already exists (change the password with ` +
570
+ `\`houston users passwd ${stored}\`)`);
571
+ }
572
+ users.set(stored, [hashed, created, picked]);
573
+ writeAll(users);
574
+ // A new account inherits no Okta link. One left active for this name -- by a 1.x
575
+ // `users remove`, or a removal while the links file was unreadable -- would otherwise
576
+ // sign its old Okta person in as whoever this account is for, an admin included.
577
+ (0, sso_identities_1.forget)(stored);
578
+ return picked;
579
+ });
580
+ // Audited HERE, not at the two front ends. `core/audit.ts`'s own docstring records why:
581
+ // the single call site used to be JobManager.submit(), so everything synchronous wrote
582
+ // nothing -- and that set was the destructive operations. `houston users role` proved it
583
+ // by writing no line at all while the identical HTTP call wrote one.
584
+ (0, audit_1.record)('user-add', `${stored} role=${chosen}`);
585
+ return { name: stored, createdAt: created, role: chosen };
586
+ }
587
+ /**
588
+ * Replace a password. Returns how many live sessions that ended.
589
+ *
590
+ * The revocation belongs HERE, not at the two front ends, for the reason `core/audit.ts`
591
+ * gives about auditing: an invariant every caller has to remember is one the next caller
592
+ * silently breaks. A credential that has been replaced must not keep working through a
593
+ * session that outlived it -- changing a compromised password while the intruder stays
594
+ * signed in for seven days is not a fix.
595
+ *
596
+ * Revoked OUTSIDE the users lock: it takes a different file's lock, and holding one while
597
+ * reaching for another is how a deadlock gets built. The window between is harmless -- the
598
+ * old password stops verifying the moment the write lands.
599
+ */
600
+ async function setPassword(name, password) {
601
+ requireValidPassword(password);
602
+ const stored = normalizeName(name);
603
+ const hashed = await hashPassword(password);
604
+ await locked(() => {
605
+ const users = readAll();
606
+ const existing = users.get(stored);
607
+ if (existing === undefined) {
608
+ throw new errors_1.NotFoundError(`no user ${quote(stored)} (see \`houston users list\`)`);
609
+ }
610
+ users.set(stored, [hashed, existing[1], existing[2]]);
611
+ writeAll(users);
612
+ });
613
+ (0, audit_1.record)('user-passwd', stored);
614
+ return await (0, sessions_1.revokeUser)(stored);
615
+ }
616
+ /**
617
+ * Delete an account. Returns how many live sessions that ended.
618
+ *
619
+ * Same argument as `setPassword`: an account that can no longer sign in but is still
620
+ * signed in has not been removed.
621
+ */
622
+ async function remove(name) {
623
+ const stored = normalizeName(name);
624
+ await locked(() => {
625
+ const users = readAll();
626
+ if (!users.has(stored)) {
627
+ throw new errors_1.NotFoundError(`no user ${quote(stored)} (see \`houston users list\`)`);
628
+ }
629
+ requireNotLastAdmin(stored, users, 'removing them');
630
+ users.delete(stored);
631
+ writeAll(users);
632
+ // In the same lock, so no Okta sign-in can land between the two: a removed account's
633
+ // Okta link becomes a tombstone, and the person's next sign-in is refused rather than
634
+ // creating the account again.
635
+ (0, sso_identities_1.forget)(stored);
636
+ });
637
+ (0, audit_1.record)('user-remove', stored);
638
+ return await (0, sessions_1.revokeUser)(stored);
639
+ }
640
+ /** Change what `name` may do. Returns the updated user. */
641
+ async function setRole(name, role) {
642
+ requireValidRole(role);
643
+ const stored = normalizeName(name);
644
+ const wanted = normaliseRole(role);
645
+ const created = await locked(() => {
646
+ const users = readAll();
647
+ const existing = users.get(stored);
648
+ if (existing === undefined) {
649
+ throw new errors_1.NotFoundError(`no user ${quote(stored)} (see \`houston users list\`)`);
650
+ }
651
+ // Read AND checked under the lock: a demotion racing another demotion could otherwise
652
+ // take the last admin away, each having seen the other still in place.
653
+ if (wanted !== 'admin')
654
+ requireNotLastAdmin(stored, users, `making them ${role}`);
655
+ users.set(stored, [existing[0], existing[1], wanted]);
656
+ writeAll(users);
657
+ return existing[1];
658
+ });
659
+ (0, audit_1.record)('user-role', `${stored} -> ${wanted}`);
660
+ return { name: stored, createdAt: created, role: wanted };
661
+ }
662
+ // --- verification ------------------------------------------------------------------
663
+ /**
664
+ * Record a failed credential check.
665
+ *
666
+ * Written with origin `attempt`, never `session`: the name here is whatever the caller
667
+ * typed and belongs to nobody. It may not even be an account. Recording it as an ordinary
668
+ * line would make the log say "alice did something" when alice is the name that was
669
+ * guessed AT. The name is not validated first, on purpose -- an invalid one is exactly the
670
+ * traffic worth seeing, and the field sanitiser is what makes it safe to write down.
671
+ */
672
+ function auditFailure(name, source) {
673
+ (0, audit_1.audit)(name || '-', 'signin', source || 'local', {
674
+ origin: 'attempt',
675
+ outcome: 'denied',
676
+ });
677
+ }
678
+ /**
679
+ * Whether these credentials are valid. Constant-time; never cached.
680
+ *
681
+ * An unknown user still performs a full derivation: returning early would make the response
682
+ * time reveal which names exist.
683
+ *
684
+ * NOTHING HERE REFUSES A CORRECT PASSWORD. An earlier version consulted a lockout counter
685
+ * before checking, which had two reachable consequences: anyone who could reach the port
686
+ * could lock out a named colleague with five wrong guesses, and after `houston users passwd
687
+ * alice` every still-open tab replayed the OLD credential on its four-second poll, each
688
+ * poll sliding the window forward, so the account stayed locked and the correct NEW
689
+ * password was refused with it. That counter is gone entirely; prevention stops at the
690
+ * per-address throttle in the web layer, and what replaces the intent is DETECTION -- a
691
+ * failed check writes an audit line, which survives a restart as an in-memory counter
692
+ * could not.
693
+ */
694
+ async function verify(name, password, source = '') {
695
+ // A password that is not a string. The declared type rules that out at compile time, but
696
+ // the web layer hands this whatever JSON arrived, so the runtime guard stays -- written as
697
+ // a type test, which is the form that survives the type checker knowing better than the
698
+ // caller does.
699
+ if (!name || typeof password !== 'string')
700
+ return false;
701
+ // Looked up normalised, so somebody created as `lucy-felix` can sign in with the
702
+ // `lucy.felix` they were asked for and think of as their name. Audited RAW, though:
703
+ // an invalid name is exactly the traffic worth seeing, and normalising it first would
704
+ // launder a probe for `Lucy.Felix` into a tidy line about `lucy-felix`.
705
+ const stored = readAll().get(normalizeName(name));
706
+ if (stored === undefined) {
707
+ // Burn the same work as a real check so timing does not enumerate users. ONE
708
+ // derivation, exactly like the branch below.
709
+ await check(password, DUMMY_HASH);
710
+ auditFailure(name, source);
711
+ return false;
712
+ }
713
+ if (!(await check(password, stored[0]))) {
714
+ auditFailure(name, source);
715
+ return false;
716
+ }
717
+ return true;
718
+ }
719
+ /**
720
+ * A name quoted in a message by `quotedText`, which picks double quotes for a value holding a
721
+ * single one and escapes a backslash or a control character. This wrapped the value in
722
+ * single quotes as it was, so `users role bob "o'x"` said `unknown role 'o'x'` where the
723
+ * established message says `"o'x"`, and `a\b` lost its escaping.
724
+ */
725
+ function quote(value) {
726
+ return (0, format_1.quotedText)(value);
727
+ }
728
+ /**
729
+ * Answer `lib/teammode.ts` without it having to import this module.
730
+ *
731
+ * `core/kube/namespace` needs one bit from here -- whether this box has accounts -- and
732
+ * sits below it in the layer order. That registry's docstring records what naming the
733
+ * wrong remedy cost: a namespace was left permanently un-adoptable because the message
734
+ * said "HOUSTON_USER is not set" while it WAS.
735
+ */
736
+ function installTeamModeAnswer() {
737
+ return (0, teammode_1.installTeamModeProbe)(() => anyUsers());
738
+ }
739
+ installTeamModeAnswer();