pisha-server 0.0.0-stage → 0.0.12

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 (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1087 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +82 -0
  14. package/dashboard/dashboard.js +408 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +231 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +55 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3303 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +168 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2145 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +41 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +105 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +142 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +669 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +180 -0
  89. package/ui/people.js +371 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +173 -0
  93. package/ui/routes.js +47 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +119 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/screen-usage.css +60 -0
  105. package/ui/session.js +42 -0
  106. package/ui/shell.css +122 -0
  107. package/ui/signin.js +120 -0
  108. package/ui/squads.js +371 -0
  109. package/ui/state.js +59 -0
  110. package/ui/stream.js +269 -0
  111. package/ui/styles.css +343 -0
  112. package/ui/team.js +115 -0
  113. package/ui/teams.js +58 -0
  114. package/ui/terminal.js +261 -0
  115. package/ui/theme.js +32 -0
  116. package/ui/timeline.js +163 -0
  117. package/ui/topbar.js +211 -0
  118. package/ui/usage.js +175 -0
  119. package/ui/voice-parse.js +98 -0
  120. package/ui/voice.js +320 -0
  121. package/usage/index.js +1 -0
  122. package/usage/usage.js +127 -0
  123. package/vendor/InterVariable.woff2 +0 -0
  124. package/vendor/LICENSE-inter +92 -0
  125. package/vendor/LICENSE-xterm +21 -0
  126. package/vendor/README.md +8 -0
  127. package/vendor/addon-fit.js +2 -0
  128. package/vendor/xterm.css +218 -0
  129. package/vendor/xterm.js +2 -0
@@ -0,0 +1,754 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { readFileSync, writeFileSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import {
5
+ ApiError, DATA_DIR, FIRST_COMPANY, ROLES, TLS, TRUST_PROXY, PUBLIC_URL, allowServerWide, countedServerWide, atLeast, bad, bearer, clientIp,
6
+ cleanText, guarded, ipKey, now, readParams, sameOrigin, sendJson, serverBaseUrl, sha256,
7
+ } from '../platform/index.js'
8
+ import { NOBODY, checkNewPassword, hashPassword, passwordMatches } from './passwords.js'
9
+ import { checkTotp, newTotpSecret, openSecret, sealSecret } from './totp.js'
10
+
11
+ const COOKIE = 'pisha_session'
12
+ const SESSION_MS = 7 * 24 * 3600_000 // however much it is used
13
+ const IDLE_MS = 24 * 3600_000 // without being used
14
+ const INVITE_MS = 7 * 24 * 3600_000
15
+ const RESET_MS = 24 * 3600_000
16
+ const RECOVERY_CODES = 10
17
+ const EMAIL = /^[^\s@]{1,100}@[^\s@]{1,150}\.[^\s@]{1,50}$/
18
+
19
+ const tooMany = () => new ApiError(429, 'Too Many Requests: wait a few minutes and try again')
20
+ const cleanEmail = v => (typeof v === 'string' ? v.trim().toLowerCase().slice(0, 300) : '')
21
+ const cleanName = v => (typeof v === 'string' ? cleanText(v.slice(0, 200)).replace(/\s+/g, ' ').trim().slice(0, 80) : '')
22
+
23
+ // Who can sign in, and what they are in each company. It is about the whole
24
+ // server, in control.db: nothing here reads what is inside a company.
25
+ //
26
+ // A session goes through stages: 'totp' (password right, code missing),
27
+ // 'totp_setup' (password right, and this user must set codes up first) and 'ok'.
28
+ // Only the last one reaches anything beyond the screens to get there.
29
+ export function createAccounts(server, { control, companyName, companyStatus, dropClients, cancelEnrollments }) {
30
+ const { isServerToken } = server
31
+
32
+ // The key for TOTP secrets: in the data folder, not in the database.
33
+ const KEY_FILE = join(DATA_DIR, 'totp-key')
34
+ const totpKey = (() => {
35
+ try {
36
+ const k = Buffer.from(readFileSync(KEY_FILE, 'utf8').trim(), 'base64url')
37
+ if (k.length === 32) return k
38
+ } catch {}
39
+ const k = randomBytes(32)
40
+ writeFileSync(KEY_FILE, `${k.toString('base64url')}\n`, { mode: 0o600 })
41
+ return k
42
+ })()
43
+
44
+ const q = sql => control.prepare(sql)
45
+ const userById = id => q('SELECT * FROM users WHERE id = ?').get(id)
46
+ const userByEmail = email => q('SELECT * FROM users WHERE email = ?').get(email)
47
+ const hasUsers = () => !!q('SELECT 1 FROM users LIMIT 1').get()
48
+ // (The oldest first: the one someone lands in, when it isn't said which.)
49
+ const membershipsOf = id => q('SELECT company_id, role FROM memberships WHERE user_id = ? ORDER BY created_at').all(id)
50
+ const roleIn = (user, company) => q('SELECT role FROM memberships WHERE user_id = ? AND company_id = ?').get(user.id, company)?.role ?? null
51
+ const ownersOf = company => q("SELECT COUNT(*) AS n FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.company_id = ? AND m.role = 'owner' AND u.disabled_at IS NULL").get(company).n
52
+
53
+ function audit(actor, action, target, req, detail = null) {
54
+ q('INSERT INTO platform_audit (at, user_id, action, target, ip, detail) VALUES (?, ?, ?, ?, ?, ?)')
55
+ .run(now(), actor?.id ?? (actor?.token ? 'server-token' : null), action, target ?? null, req ? clientIp(req) : null, detail)
56
+ }
57
+
58
+ // Whoever can write in terminals, or run the server, signs in with codes.
59
+ const needsTotp = user => !!user.is_platform_admin || membershipsOf(user.id).some(m => atLeast(m.role, 'operator'))
60
+ function stageOf(user, session) {
61
+ if (user.totp_enabled_at) return session.mfa_ok ? 'ok' : 'totp'
62
+ return needsTotp(user) ? 'totp_setup' : 'ok'
63
+ }
64
+
65
+ function isHttps(req) {
66
+ return TLS || PUBLIC_URL.startsWith('https://') || (TRUST_PROXY && String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim() === 'https')
67
+ }
68
+ // Over https, a name browsers keep to this very host: a neighbour under the
69
+ // same domain can't set it.
70
+ const cookieName = req => (isHttps(req) ? `__Host-${COOKIE}` : COOKIE)
71
+ const cookieLine = (req, value, maxAge) => `${cookieName(req)}=${value}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${isHttps(req) ? '; Secure' : ''}`
72
+
73
+ function cookieOf(req) {
74
+ const name = cookieName(req)
75
+ for (const part of String(req.headers.cookie ?? '').split(';')) {
76
+ const [k, v] = part.trim().split('=')
77
+ if (k === name) return v ?? ''
78
+ }
79
+ return ''
80
+ }
81
+
82
+ function startSession(req, res, user, mfaOk) {
83
+ const token = randomBytes(32).toString('base64url')
84
+ const t = now()
85
+ q('INSERT INTO login_sessions (token_hash, user_id, mfa_ok, ip, created_at, last_seen_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
86
+ .run(sha256(token), user.id, mfaOk ? 1 : 0, clientIp(req), t, t, t + SESSION_MS)
87
+ q('UPDATE users SET last_login_at = ? WHERE id = ?').run(t, user.id)
88
+ res.setHeader('Set-Cookie', cookieLine(req, token, Math.floor(SESSION_MS / 1000)))
89
+ return { token_hash: sha256(token), user_id: user.id, mfa_ok: mfaOk ? 1 : 0 }
90
+ }
91
+
92
+ // The second factor done: the session goes on under a new token, so one known
93
+ // from before (planted in this browser for the victim to finish) is worth nothing.
94
+ function finishSession(req, res, session) {
95
+ const token = randomBytes(32).toString('base64url')
96
+ q('UPDATE login_sessions SET token_hash = ?, mfa_ok = 1 WHERE token_hash = ?').run(sha256(token), session.token_hash)
97
+ res.setHeader('Set-Cookie', cookieLine(req, token, Math.floor(SESSION_MS / 1000)))
98
+ return { ...session, token_hash: sha256(token), mfa_ok: 1 }
99
+ }
100
+
101
+ // The session a request comes with, if it is still good.
102
+ function sessionOf(req) {
103
+ const token = cookieOf(req)
104
+ if (!token) return null
105
+ const hash = sha256(token)
106
+ const s = q('SELECT * FROM login_sessions WHERE token_hash = ?').get(hash)
107
+ if (!s) return null
108
+ const t = now()
109
+ if (s.expires_at < t || s.last_seen_at + IDLE_MS < t) { endSession(hash); return null }
110
+ const user = userById(s.user_id)
111
+ if (!user || user.disabled_at) return null
112
+ // (Written at most once a minute: one write per request would keep the database busy.)
113
+ if (t - s.last_seen_at > 60_000) q('UPDATE login_sessions SET last_seen_at = ? WHERE token_hash = ?').run(t, hash)
114
+ return { session: s, user }
115
+ }
116
+
117
+ function endSession(hash) {
118
+ q('DELETE FROM login_sessions WHERE token_hash = ?').run(hash)
119
+ dropClients(a => a?.session === hash)
120
+ }
121
+
122
+ function endAllSessions(userId, { except = null } = {}) {
123
+ q('DELETE FROM login_sessions WHERE user_id = ? AND token_hash IS NOT ?').run(userId, except)
124
+ dropClients(a => a?.id === userId && a.session !== except)
125
+ }
126
+
127
+ // Who is calling, for what needs a finished sign-in. A request with a cookie
128
+ // that changes something must come from this dashboard's own page.
129
+ function actorOf(req) {
130
+ const found = sessionOf(req)
131
+ if (!found || stageOf(found.user, found.session) !== 'ok') throw new ApiError(401, 'Unauthorized')
132
+ if (req.method !== 'GET' && !sameOrigin(req)) throw new ApiError(403, 'Forbidden')
133
+ const { user, session } = found
134
+ return { id: user.id, email: user.email, name: user.name, is_platform_admin: !!user.is_platform_admin, session: session.token_hash }
135
+ }
136
+
137
+ function me(user, session) {
138
+ const stage = stageOf(user, session)
139
+ // (Which companies, only once the sign-in is finished.)
140
+ const mine = stage === 'ok' ? membershipsOf(user.id).map(m => ({ id: m.company_id, name: companyName(m.company_id), role: m.role, ...companyStatus(m.company_id) })).filter(c => c.name) : []
141
+ const companies = mine.filter(c => c.status !== 'deleting').map(({ id, name, role }) => ({ id, name, role }))
142
+ return {
143
+ stage,
144
+ // (Those of theirs waiting to be deleted: an owner can bring them back.)
145
+ deleting: mine.filter(c => c.status === 'deleting' && c.role === 'owner').map(({ id, name, delete_after }) => ({ id, name, delete_after })),
146
+ user: { id: user.id, email: user.email, name: user.name, github: user.github ?? null, is_platform_admin: !!user.is_platform_admin, totp_enabled: !!user.totp_enabled_at },
147
+ companies,
148
+ }
149
+ }
150
+
151
+ // Codes for this user: a new secret until one of its codes is entered.
152
+ function setUpTotp(user) {
153
+ const secret = newTotpSecret()
154
+ q('UPDATE users SET totp_secret_enc = ?, totp_last_step = NULL WHERE id = ?').run(sealSecret(totpKey, user.id, secret), user.id)
155
+ const label = encodeURIComponent(`Pisha:${user.email}`)
156
+ return { secret, uri: `otpauth://totp/${label}?secret=${secret}&issuer=Pisha&algorithm=SHA1&digits=6&period=30` }
157
+ }
158
+
159
+ // Wrong codes: 5 every 5 minutes per person, however many sessions try.
160
+ // (Only the wrong ones: signing in often is no reason to wait.)
161
+ const CODES_WINDOW = 5 * 60_000
162
+ function checkCodeBudget(user) { if (countedServerWide('wrong-code', user.id, CODES_WINDOW) >= 5) throw tooMany() }
163
+ const codeFailed = user => allowServerWide('wrong-code', user.id, 1000, CODES_WINDOW)
164
+
165
+ function codeIsGood(user, code) {
166
+ const step = checkTotp(openSecret(totpKey, user.id, user.totp_secret_enc), String(code ?? '').replace(/\s/g, ''), user.totp_last_step)
167
+ if (step === null) return false
168
+ q('UPDATE users SET totp_last_step = ? WHERE id = ?').run(step, user.id)
169
+ return true
170
+ }
171
+
172
+ function recoveryCodeIsGood(user, code) {
173
+ const hash = sha256(String(code ?? '').trim().toLowerCase())
174
+ return q('UPDATE recovery_codes SET used_at = ? WHERE user_id = ? AND code_hash = ? AND used_at IS NULL').run(now(), user.id, hash).changes > 0
175
+ }
176
+
177
+ function newRecoveryCodes(user) {
178
+ q('DELETE FROM recovery_codes WHERE user_id = ?').run(user.id)
179
+ const codes = Array.from({ length: RECOVERY_CODES }, () => randomBytes(10).toString('hex'))
180
+ for (const c of codes) q('INSERT INTO recovery_codes (user_id, code_hash) VALUES (?, ?)').run(user.id, sha256(c))
181
+ return codes
182
+ }
183
+
184
+ // Wrong passwords: 10 every 15 minutes per address and account, also per /48 for
185
+ // IPv6, where one site has many /64. Only wrong ones count, so someone else's
186
+ // failures never lock out whoever has the right password, however many
187
+ // addresses they come from. (The cost: guesses spread over very many addresses
188
+ // aren't stopped. Those who can do anything have a second factor as well.)
189
+ const PASSWORD_WINDOW = 15 * 60_000
190
+ const passwordKey = (req, email) => `${ipKey(clientIp(req))}\0${email}`
191
+ const siteKey = (req, email) => { const ip = ipKey(clientIp(req)); return ip.endsWith('/64') ? `${ip.split(':').slice(0, 3).join(':')}\0${email}` : null }
192
+ function checkPasswordBudget(req, email) {
193
+ const site = siteKey(req, email)
194
+ if (countedServerWide('wrong-password', passwordKey(req, email), PASSWORD_WINDOW) >= 10 || (site && countedServerWide('wrong-password-site', site, PASSWORD_WINDOW) >= 50)) throw tooMany()
195
+ }
196
+ function passwordFailed(req, email) {
197
+ allowServerWide('wrong-password', passwordKey(req, email), 1000, PASSWORD_WINDOW)
198
+ const site = siteKey(req, email)
199
+ if (site) allowServerWide('wrong-password-site', site, 1000, PASSWORD_WINDOW)
200
+ }
201
+ // What a password was checked against may be out of date when the check ends
202
+ // (it takes time, on purpose): a reset or a disable meanwhile wins.
203
+ const stillHolds = user => { const now_ = userById(user.id); return !!now_ && !now_.disabled_at && now_.password_hash === user.password_hash }
204
+ const dropResetLinks = email => q("DELETE FROM invitations WHERE kind = 'reset' AND email = ? AND used_at IS NULL").run(email)
205
+
206
+ async function newUser({ email, name, password, isAdmin = false }) {
207
+ checkNewPassword(password)
208
+ const id = `u_${randomBytes(9).toString('base64url')}`
209
+ const password_hash = await hashPassword(password)
210
+ q('INSERT INTO users (id, email, name, password_hash, is_platform_admin, created_at) VALUES (?, ?, ?, ?, ?, ?)')
211
+ .run(id, email, name, password_hash, isAdmin ? 1 : 0, now())
212
+ return userById(id)
213
+ }
214
+
215
+ // Joining never lowers anyone: an invitation for less is no way to demote
216
+ // someone, least of all an owner. (Changing a role is members/role.)
217
+ function addMember(user, company, role, by) {
218
+ const current = roleIn(user, company)
219
+ if (current && atLeast(current, role)) return current
220
+ q(`INSERT INTO memberships (user_id, company_id, role, created_by, created_at) VALUES (?, ?, ?, ?, ?)
221
+ ON CONFLICT(user_id, company_id) DO UPDATE SET role = excluded.role`).run(user.id, company, role, by ?? null, now())
222
+ return role
223
+ }
224
+
225
+ // Pending invitations to this company for someone whose place in it was just decided.
226
+ // Whoever could manage a company stopped being able to: what they made stops too,
227
+ // and a later promotion doesn't bring it back.
228
+ // (An invitation can be for several companies: only this one's part goes.)
229
+ const dropInvitationsBy = (company, userId) => { for (const r of pendingInvites('created_by = ?', userId)) withoutCompany(r, company) }
230
+ const dropInvitationsFor = (company, email) => { for (const r of pendingInvites('email = ?', email)) withoutCompany(r, company) }
231
+
232
+ // Pending invitations, as rows; each company one names, with the role it gives there.
233
+ const pendingInvites = (where, ...args) => q(`SELECT * FROM invitations WHERE kind = 'invite' AND used_at IS NULL AND ${where}`).all(...args)
234
+ const invitedTo = row => [[row.company_id, row.role], ...alsoOf(row).map(a => [a.company, a.role])].filter(([c]) => c)
235
+ const roleInInvite = (row, company) => invitedTo(row).find(([c]) => c === company)?.[1] ?? null
236
+ // That company taken out of an invitation; the rest of it stays. One left
237
+ // with no company (and not for an administrator) is gone.
238
+ function withoutCompany(row, company) {
239
+ const rest = invitedTo(row).filter(([c]) => c !== company)
240
+ if (rest.length === invitedTo(row).length) return false
241
+ if (!rest.length && !row.is_platform_admin) { q('DELETE FROM invitations WHERE token_hash = ?').run(row.token_hash); return true }
242
+ const [first, ...also] = rest
243
+ q('UPDATE invitations SET company_id = ?, role = ?, also = ? WHERE token_hash = ?')
244
+ .run(first?.[0] ?? null, first?.[1] ?? null, also.length ? JSON.stringify(also.map(([c, r]) => ({ company: c, role: r }))) : null, row.token_hash)
245
+ return true
246
+ }
247
+
248
+ // A link of one use, to copy by hand: there is no mail in this server.
249
+ function newLink(req, kind, fields, ttl, by) {
250
+ const token = randomBytes(32).toString('base64url')
251
+ q('INSERT INTO invitations (token_hash, kind, email, company_id, role, is_platform_admin, created_by, expires_at, also) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
252
+ .run(sha256(token), kind, fields.email, fields.company ?? null, fields.role ?? null, fields.isAdmin ? 1 : 0, by ?? null, now() + ttl, fields.also?.length ? JSON.stringify(fields.also) : null)
253
+ return { link: `${serverBaseUrl(req)}/#/${kind}/${token}`, expires_at: now() + ttl }
254
+ }
255
+
256
+ function linkFor(kind, token) {
257
+ const row = q('SELECT * FROM invitations WHERE token_hash = ? AND kind = ?').get(sha256(String(token ?? '')), kind)
258
+ if (!row || row.used_at || row.expires_at < now()) throw new ApiError(404, 'Not Found: this link is wrong, was used already, or has expired')
259
+ return row
260
+ }
261
+
262
+ // A link says what whoever made it could give then. It is good while they
263
+ // still can: someone who lost that doesn't leave a way back behind them.
264
+ // The other companies an invitation is for, as they were written.
265
+ function alsoOf(row) {
266
+ let list = []
267
+ try { list = JSON.parse(row.also ?? '[]') } catch {}
268
+ return (Array.isArray(list) ? list : []).filter(a => a && typeof a.company === 'string' && ROLES.includes(a.role))
269
+ }
270
+ // Whoever made an invitation may still give that role in that company.
271
+ function inviterCanFor(createdBy, company, role) {
272
+ if (!createdBy) return true // (the server token)
273
+ const by = userById(createdBy)
274
+ if (!by || by.disabled_at) return false
275
+ if (by.is_platform_admin) return true
276
+ const mine = roleIn(by, company)
277
+ return !!mine && atLeast(mine, 'manager') && canGrant(mine, role)
278
+ }
279
+
280
+ function inviterStillCan(row) {
281
+ if (!row.created_by) return true // (the server token)
282
+ const by = userById(row.created_by)
283
+ if (!by || by.disabled_at) return false
284
+ if (by.is_platform_admin) return true
285
+ if (row.kind !== 'invite' || !row.company_id || row.is_platform_admin) return false
286
+ const role = roleIn(by, row.company_id)
287
+ return !!role && atLeast(role, 'manager') && canGrant(role, row.role)
288
+ }
289
+
290
+ // /auth/* and /bootstrap. Anyone can call them, so each has its limit, and the
291
+ // bodies are small.
292
+ async function handle(path, req, res, url) {
293
+ const answer = result => sendJson(res, 200, { ok: true, result })
294
+ if (path === '/auth/status') return answer({ needs_owner: !hasUsers() })
295
+ if (req.method !== 'POST') throw new ApiError(405, 'Method Not Allowed')
296
+ if (req.headers.origin && !sameOrigin(req)) throw new ApiError(403, 'Forbidden')
297
+ if (!allowServerWide('auth-ip', ipKey(clientIp(req)), 60)) throw tooMany()
298
+ const params = await readParams(req, url, 4096, { pool: 'public' })
299
+
300
+ if (path === '/bootstrap') {
301
+ if (!allowServerWide('bootstrap', ipKey(clientIp(req)), 10)) throw tooMany()
302
+ if (!isServerToken(bearer(req))) throw new ApiError(401, 'Unauthorized')
303
+ if (hasUsers()) throw new ApiError(409, 'Conflict: this server has users already')
304
+ const email = cleanEmail(params.email), name = cleanName(params.name)
305
+ if (!EMAIL.test(email)) throw bad('this is not an email address')
306
+ if (!name) throw bad('a name is needed')
307
+ const user = await newUser({ email, name, password: params.password, isAdmin: true })
308
+ addMember(user, FIRST_COMPANY, 'owner', null)
309
+ audit(user, 'bootstrap', user.email, req)
310
+ const s = startSession(req, res, user, false)
311
+ return answer(me(user, s))
312
+ }
313
+
314
+ if (path === '/auth/login') {
315
+ const email = cleanEmail(params.email)
316
+ if (!allowServerWide('login-ip', ipKey(clientIp(req)), 30)) throw tooMany()
317
+ checkPasswordBudget(req, email)
318
+ const user = userByEmail(email)
319
+ const good = await passwordMatches(String(params.password ?? '').slice(0, 200), user?.password_hash ?? NOBODY)
320
+ if (!user || !good || !stillHolds(user)) {
321
+ passwordFailed(req, email)
322
+ // (Only for an account: what is typed for no account is written nowhere.)
323
+ if (user) audit(user, 'login-failed', email, req)
324
+ throw new ApiError(401, 'Unauthorized: wrong email or password')
325
+ }
326
+ const s = startSession(req, res, user, false)
327
+ audit(user, 'login', user.email, req)
328
+ return answer(me(user, s))
329
+ }
330
+
331
+ if (path === '/auth/invite/info') {
332
+ const row = linkFor('invite', params.token)
333
+ if (!inviterStillCan(row)) throw new ApiError(404, 'Not Found: this link is wrong, was used already, or has expired')
334
+ const names = [row.company_id, ...alsoOf(row).map(a => a.company)].filter(Boolean).map(companyName).filter(Boolean)
335
+ return answer({ email: row.email, company: names.length ? names.join(', ') : null, role: row.role, known: !!userByEmail(row.email) })
336
+ }
337
+
338
+ if (path === '/auth/invite/accept') {
339
+ if (!allowServerWide('accept', ipKey(clientIp(req)), 30)) throw tooMany()
340
+ const row = linkFor('invite', params.token)
341
+ if (!inviterStillCan(row)) throw new ApiError(404, 'Not Found: this link is wrong, was used already, or has expired')
342
+ let user = userByEmail(row.email)
343
+ if (user) {
344
+ // Someone who has an account already: joining another company needs its password.
345
+ checkPasswordBudget(req, user.email)
346
+ if (!await passwordMatches(String(params.password ?? '').slice(0, 200), user.password_hash) || !stillHolds(user)) {
347
+ passwordFailed(req, user.email)
348
+ audit(user, 'invite-password-failed', row.company_id ?? 'platform', req)
349
+ throw new ApiError(401, 'Unauthorized: wrong password')
350
+ }
351
+ if (row.is_platform_admin) q('UPDATE users SET is_platform_admin = 1 WHERE id = ?').run(user.id)
352
+ } else {
353
+ const name = cleanName(params.name)
354
+ if (!name) throw bad('a name is needed')
355
+ user = await newUser({ email: row.email, name, password: params.password, isAdmin: !!row.is_platform_admin })
356
+ }
357
+ // (Used up only now: a password refused above doesn't waste the link. Taken
358
+ // once, whatever else arrived while the password was being worked out.)
359
+ if (!q('UPDATE invitations SET used_at = ? WHERE token_hash = ? AND used_at IS NULL').run(now(), row.token_hash).changes) throw new ApiError(404, 'Not Found: this link was used already')
360
+ if (row.company_id && companyName(row.company_id)) addMember(user, row.company_id, row.role, row.created_by)
361
+ audit(user, 'invite-accepted', row.company_id ?? 'platform', req, row.role)
362
+ // The other companies it was for, as far as whoever made it still may give them.
363
+ for (const a of alsoOf(row)) {
364
+ if (!companyName(a.company) || !inviterCanFor(row.created_by, a.company, a.role)) continue
365
+ addMember(user, a.company, a.role, row.created_by)
366
+ audit(user, 'invite-accepted', a.company, req, a.role)
367
+ }
368
+ user = userById(user.id)
369
+ const s = startSession(req, res, user, false)
370
+ return answer(me(user, s))
371
+ }
372
+
373
+ if (path === '/auth/reset') {
374
+ if (!allowServerWide('accept', ipKey(clientIp(req)), 30)) throw tooMany()
375
+ const row = linkFor('reset', params.token)
376
+ const user = userByEmail(row.email)
377
+ if (!user || !inviterStillCan(row)) throw new ApiError(404, 'Not Found: this link is wrong, was used already, or has expired')
378
+ checkNewPassword(params.password)
379
+ const hash = await hashPassword(params.password)
380
+ if (!q('UPDATE invitations SET used_at = ? WHERE token_hash = ? AND used_at IS NULL').run(now(), row.token_hash).changes) throw new ApiError(404, 'Not Found: this link was used already')
381
+ q('UPDATE users SET password_hash = ? WHERE id = ?').run(hash, user.id)
382
+ dropResetLinks(user.email)
383
+ if (row.role === 'clear-totp') {
384
+ q('UPDATE users SET totp_secret_enc = NULL, totp_enabled_at = NULL, totp_last_step = NULL WHERE id = ?').run(user.id)
385
+ q('DELETE FROM recovery_codes WHERE user_id = ?').run(user.id)
386
+ }
387
+ endAllSessions(user.id)
388
+ audit(user, 'password-reset', user.email, req)
389
+ return answer({ done: true })
390
+ }
391
+
392
+ // From here on, a session that has at least the right password.
393
+ const found = sessionOf(req)
394
+ if (!found) throw new ApiError(401, 'Unauthorized')
395
+ const { user, session } = found
396
+
397
+ if (path === '/auth/logout') {
398
+ endSession(session.token_hash)
399
+ res.setHeader('Set-Cookie', cookieLine(req, '', 0))
400
+ audit(user, 'logout', user.email, req)
401
+ return answer({ done: true })
402
+ }
403
+
404
+ if (path === '/auth/totp') {
405
+ if (!user.totp_enabled_at) throw bad('this account has no codes set up')
406
+ checkCodeBudget(user)
407
+ const good = params.recovery != null ? recoveryCodeIsGood(user, params.recovery) : codeIsGood(user, params.code)
408
+ if (!good) {
409
+ codeFailed(user)
410
+ audit(user, 'totp-failed', user.email, req)
411
+ throw new ApiError(401, 'Unauthorized: wrong code')
412
+ }
413
+ const finished = finishSession(req, res, session)
414
+ audit(user, params.recovery != null ? 'recovery-code-used' : 'totp-ok', user.email, req)
415
+ return answer(me(userById(user.id), finished))
416
+ }
417
+
418
+ if (path === '/auth/totp/setup') {
419
+ if (user.totp_enabled_at) throw new ApiError(409, 'Conflict: codes are set up already')
420
+ return answer(setUpTotp(user))
421
+ }
422
+
423
+ if (path === '/auth/totp/enable') {
424
+ if (user.totp_enabled_at || !user.totp_secret_enc) throw bad('ask for a new secret first')
425
+ checkCodeBudget(user)
426
+ if (!codeIsGood(user, params.code)) { codeFailed(user); throw new ApiError(401, 'Unauthorized: wrong code') }
427
+ q('UPDATE users SET totp_enabled_at = ? WHERE id = ?').run(now(), user.id)
428
+ const finished = finishSession(req, res, session)
429
+ audit(user, 'totp-enabled', user.email, req)
430
+ const codes = newRecoveryCodes(user)
431
+ return answer({ recovery_codes: codes, ...me(userById(user.id), finished) })
432
+ }
433
+
434
+ // Their own GitHub user (or none): what boards in step with GitHub assign them by.
435
+ if (path === '/auth/profile') {
436
+ if (stageOf(user, session) !== 'ok') throw new ApiError(401, 'Unauthorized')
437
+ const raw = String(params.github ?? '').trim().replace(/^@/, '')
438
+ if (raw && !/^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/.test(raw)) throw bad('that is not a GitHub user name')
439
+ const taken = raw && q('SELECT 1 FROM users WHERE lower(github) = lower(?) AND id != ?').get(raw, user.id)
440
+ if (taken) throw bad('another person here already has that GitHub user')
441
+ q('UPDATE users SET github = ? WHERE id = ?').run(raw || null, user.id)
442
+ return answer(me(userById(user.id), session))
443
+ }
444
+
445
+ if (path === '/auth/password') {
446
+ if (stageOf(user, session) !== 'ok') throw new ApiError(401, 'Unauthorized')
447
+ if (!allowServerWide('password', user.id, 5, 15 * 60_000)) throw tooMany()
448
+ if (!await passwordMatches(String(params.current ?? '').slice(0, 200), user.password_hash)) throw new ApiError(401, 'Unauthorized: wrong password')
449
+ checkNewPassword(params.password)
450
+ const next = await hashPassword(params.password)
451
+ // (Only if nothing changed meanwhile: this session may have ended, or another password been set.)
452
+ if (!sessionOf(req) || !q('UPDATE users SET password_hash = ? WHERE id = ? AND password_hash = ?').run(next, user.id, user.password_hash).changes) throw new ApiError(401, 'Unauthorized')
453
+ dropResetLinks(user.email)
454
+ endAllSessions(user.id, { except: session.token_hash })
455
+ audit(user, 'password-changed', user.email, req)
456
+ return answer({ done: true })
457
+ }
458
+
459
+ throw new ApiError(404, 'Not Found')
460
+ }
461
+
462
+ // GET /api/me: also before finishing the sign-in, so the page knows what to ask.
463
+ function meAnswer(req) {
464
+ const found = sessionOf(req)
465
+ if (!found) throw new ApiError(401, 'Unauthorized')
466
+ return me(found.user, found.session)
467
+ }
468
+
469
+ function checkRole(role) {
470
+ if (!ROLES.includes(role)) throw bad(`the role must be one of: ${ROLES.join(', ')}`)
471
+ }
472
+
473
+ // Nobody gives more than they have. The server token and owners give anything.
474
+ const canGrant = (actorRole, role) => atLeast(actorRole, role) && (actorRole === 'owner' || role !== 'owner')
475
+
476
+ function listMembers(companyId) {
477
+ return q(`SELECT u.id, u.email, u.name, u.disabled_at, u.totp_enabled_at, m.role, m.created_at FROM memberships m
478
+ JOIN users u ON u.id = m.user_id WHERE m.company_id = ? ORDER BY u.name`).all(companyId)
479
+ .map(r => ({ id: r.id, email: r.email, name: r.name, role: r.role, disabled: !!r.disabled_at, totp: !!r.totp_enabled_at, since: r.created_at }))
480
+ }
481
+
482
+ const companyMethods = {
483
+ members: { role: 'manager', method: 'GET', run: ({ company }) => listMembers(company.id) },
484
+ 'members/invite': {
485
+ role: 'manager', method: 'POST',
486
+ run({ company, actor, actorRole, params, req }) {
487
+ const email = cleanEmail(params.email)
488
+ if (!EMAIL.test(email)) throw bad('this is not an email address')
489
+ checkRole(params.role)
490
+ if (!canGrant(actorRole, params.role)) throw new ApiError(403, 'Forbidden: you can\'t give that role')
491
+ audit(actor, 'member-invited', company.id, req, `${email} as ${params.role}`)
492
+ return newLink(req, 'invite', { email, company: company.id, role: params.role }, INVITE_MS, actor.id)
493
+ },
494
+ },
495
+ 'members/role': {
496
+ role: 'manager', method: 'POST',
497
+ run({ company, actor, actorRole, params, req }) {
498
+ const target = userById(String(params.user ?? ''))
499
+ const current = target && roleIn(target, company.id)
500
+ if (!current) throw bad('that person is not in this company')
501
+ checkRole(params.role)
502
+ if (!canGrant(actorRole, params.role) || !canGrant(actorRole, current)) throw new ApiError(403, 'Forbidden: you can\'t change that role')
503
+ if (current === 'owner' && params.role !== 'owner' && ownersOf(company.id) <= 1) throw new ApiError(409, 'Conflict: a company needs an owner')
504
+ q('UPDATE memberships SET role = ? WHERE user_id = ? AND company_id = ?').run(params.role, target.id, company.id)
505
+ dropInvitationsFor(company.id, target.email)
506
+ if (atLeast(current, 'manager') && !atLeast(params.role, 'manager')) {
507
+ company.machines.cancelEnrollments()
508
+ dropInvitationsBy(company.id, target.id)
509
+ }
510
+ company.dropClients(a => a?.id === target.id)
511
+ audit(actor, 'member-role', company.id, req, `${target.email}: ${current} to ${params.role}`)
512
+ return { id: target.id, role: params.role }
513
+ },
514
+ },
515
+ 'members/remove': {
516
+ role: 'manager', method: 'POST',
517
+ run({ company, actor, actorRole, params, req }) {
518
+ const target = userById(String(params.user ?? ''))
519
+ const current = target && roleIn(target, company.id)
520
+ if (!current) throw bad('that person is not in this company')
521
+ if (!canGrant(actorRole, current)) throw new ApiError(403, 'Forbidden: you can\'t remove that person')
522
+ if (current === 'owner' && ownersOf(company.id) <= 1) throw new ApiError(409, 'Conflict: a company needs an owner')
523
+ q('DELETE FROM memberships WHERE user_id = ? AND company_id = ?').run(target.id, company.id)
524
+ dropInvitationsFor(company.id, target.email)
525
+ // Who could manage the company may have kept its join token, or a code.
526
+ const couldManage = atLeast(current, 'manager')
527
+ if (couldManage) {
528
+ company.machines.cancelEnrollments()
529
+ dropInvitationsBy(company.id, target.id)
530
+ }
531
+ company.dropClients(a => a?.id === target.id)
532
+ audit(actor, 'member-removed', company.id, req, target.email)
533
+ return { id: target.id, removed: true, rotate_join_token: couldManage }
534
+ },
535
+ },
536
+ invitations: {
537
+ role: 'manager', method: 'GET',
538
+ // (Also those for several companies that name this one.)
539
+ run: ({ company }) => pendingInvites('expires_at > ? ORDER BY expires_at', now()).filter(r => roleInInvite(r, company.id))
540
+ // (The id is a hash of a hash: it can cancel, but it can't be used as the link.)
541
+ .map(r => ({ id: sha256(r.token_hash), email: r.email, role: roleInInvite(r, company.id), expires_at: r.expires_at })),
542
+ },
543
+ 'invitations/cancel': {
544
+ role: 'manager', method: 'POST',
545
+ run({ company, actor, actorRole, params, req }) {
546
+ const row = pendingInvites('1').find(r => sha256(r.token_hash) === String(params.id ?? '') && roleInInvite(r, company.id))
547
+ if (!row) throw bad('no such invitation')
548
+ if (!canGrant(actorRole, roleInInvite(row, company.id))) throw new ApiError(403, 'Forbidden: you can\'t cancel that one')
549
+ // (Only this company's part: an invitation for others too still holds there.)
550
+ withoutCompany(row, company.id)
551
+ audit(actor, 'invitation-cancelled', company.id, req, row.email)
552
+ return { cancelled: true }
553
+ },
554
+ },
555
+ 'join-token': { role: 'manager', method: 'GET', run: ({ company }) => ({ join_token: company.platform.joinToken().token }) },
556
+ 'join-token/rotate': {
557
+ role: 'manager', method: 'POST',
558
+ run({ company, actor, req }) {
559
+ audit(actor, 'join-token-rotated', company.id, req)
560
+ return company.platform.rotateJoinToken()
561
+ },
562
+ },
563
+ }
564
+
565
+ // What only an administrator of the server does (or the server token).
566
+ const adminMethods = {
567
+ 'users': {
568
+ method: 'GET',
569
+ run: () => q('SELECT id, email, name, is_platform_admin, disabled_at, totp_enabled_at, last_login_at FROM users ORDER BY name').all()
570
+ .map(r => ({ id: r.id, email: r.email, name: r.name, is_platform_admin: !!r.is_platform_admin, disabled: !!r.disabled_at, totp: !!r.totp_enabled_at, last_login_at: r.last_login_at, companies: membershipsOf(r.id).map(m => ({ id: m.company_id, role: m.role })) })),
571
+ },
572
+ 'users/invite': {
573
+ method: 'POST',
574
+ run({ actor, params, req }) {
575
+ const email = cleanEmail(params.email)
576
+ if (!EMAIL.test(email)) throw bad('this is not an email address')
577
+ if (params.company != null) { if (!companyName(String(params.company))) throw bad('no such company'); checkRole(params.role) }
578
+ audit(actor, 'user-invited', params.company == null ? 'platform' : String(params.company), req, `${email}${params.role ? ` as ${params.role}` : ''}${params.is_platform_admin === true ? ' (administrator)' : ''}`)
579
+ return newLink(req, 'invite', { email, company: params.company == null ? null : String(params.company), role: params.role ?? null, isAdmin: params.is_platform_admin === true }, INVITE_MS, actor.id)
580
+ },
581
+ },
582
+ // Links not used yet, of any kind, across the server, and cancelling one.
583
+ 'pending-links': {
584
+ method: 'GET',
585
+ run: () => q('SELECT token_hash, kind, email, company_id, role, is_platform_admin, expires_at FROM invitations WHERE used_at IS NULL AND expires_at > ? ORDER BY expires_at').all(now())
586
+ .map(r => ({ id: sha256(r.token_hash), kind: r.kind, email: r.email, company: r.company_id, role: r.role === 'clear-totp' ? null : r.role, clears_codes: r.role === 'clear-totp', is_platform_admin: !!r.is_platform_admin, expires_at: r.expires_at })),
587
+ },
588
+ 'pending-links/cancel': {
589
+ method: 'POST',
590
+ run({ actor, params, req }) {
591
+ const row = q('SELECT token_hash, kind, email FROM invitations WHERE used_at IS NULL').all().find(r => sha256(r.token_hash) === String(params.id ?? ''))
592
+ if (!row) throw bad('no such link')
593
+ q('DELETE FROM invitations WHERE token_hash = ?').run(row.token_hash)
594
+ audit(actor, 'link-cancelled', row.email, req, row.kind)
595
+ return { cancelled: true }
596
+ },
597
+ },
598
+ 'users/disable': { method: 'POST', run: args => setDisabled(args, true) },
599
+ 'users/enable': { method: 'POST', run: args => setDisabled(args, false) },
600
+ 'users/reset': {
601
+ method: 'POST',
602
+ run({ actor, params, req }) {
603
+ const target = userById(String(params.user ?? ''))
604
+ if (!target) throw bad('no such user')
605
+ audit(actor, 'password-reset-link', target.email, req, params.clear_totp === true ? 'with codes cleared' : null)
606
+ dropResetLinks(target.email) // (Only the last one works.)
607
+ return newLink(req, 'reset', { email: target.email, role: params.clear_totp === true ? 'clear-totp' : null }, RESET_MS, actor.id)
608
+ },
609
+ },
610
+ // To read what is inside a company, an administrator has to join it, and it is written down.
611
+ 'companies/join': {
612
+ method: 'POST',
613
+ run({ actor, params, req }) {
614
+ const company = String(params.company ?? '')
615
+ if (!companyName(company)) throw bad('no such company')
616
+ if (actor.token) throw bad('the server token has no account: invite someone instead')
617
+ checkRole(params.role ?? 'owner')
618
+ const role = addMember(actor, company, params.role ?? 'owner', actor.id)
619
+ audit(actor, 'admin-joined-company', company, req, role)
620
+ return { company, role }
621
+ },
622
+ },
623
+ }
624
+
625
+ function setDisabled({ actor, params, req }, disabled) {
626
+ const target = userById(String(params.user ?? ''))
627
+ if (!target) throw bad('no such user')
628
+ if (disabled && target.id === actor.id) throw bad('you can\'t disable yourself')
629
+ if (disabled && target.is_platform_admin && !q('SELECT 1 FROM users WHERE is_platform_admin = 1 AND disabled_at IS NULL AND id != ?').get(target.id)) throw new ApiError(409, 'Conflict: the server needs an administrator')
630
+ if (disabled) for (const m of membershipsOf(target.id)) if (m.role === 'owner' && ownersOf(m.company_id) <= 1) throw new ApiError(409, `Conflict: this is the only owner of the company ${companyName(m.company_id) ?? m.company_id}`)
631
+ q('UPDATE users SET disabled_at = ? WHERE id = ?').run(disabled ? now() : null, target.id)
632
+ // As with removing them from a company: their ways back go too.
633
+ const managed = disabled ? membershipsOf(target.id).filter(m => atLeast(m.role, 'manager')) : []
634
+ for (const m of managed) {
635
+ cancelEnrollments(m.company_id)
636
+ dropInvitationsBy(m.company_id, target.id)
637
+ }
638
+ if (disabled) endAllSessions(target.id)
639
+ audit(actor, disabled ? 'user-disabled' : 'user-enabled', target.email, req)
640
+ return { id: target.id, disabled, rotate_join_token: managed.map(m => companyName(m.company_id)) }
641
+ }
642
+
643
+ // The server token gets someone back in: a link to set a new password, and
644
+ // new codes, for whoever lost theirs.
645
+ function recoverAccess(p, req) {
646
+ const target = userByEmail(cleanEmail(p.email))
647
+ if (!target) throw bad('no such user')
648
+ audit({ token: true }, 'access-recovered', target.email, req)
649
+ dropResetLinks(target.email)
650
+ return newLink(req, 'reset', { email: target.email, role: 'clear-totp' }, RESET_MS, null)
651
+ }
652
+
653
+ // Sessions that ran out take their open streams and terminals with them.
654
+ function sweep() {
655
+ const t = now()
656
+ for (const s of q('SELECT token_hash FROM login_sessions WHERE expires_at < ? OR last_seen_at < ?').all(t, t - IDLE_MS)) endSession(s.token_hash)
657
+ q('DELETE FROM invitations WHERE expires_at < ?').run(t - 30 * 24 * 3600_000)
658
+ q('DELETE FROM platform_audit WHERE at < ?').run(t - 365 * 24 * 3600_000)
659
+ q('DELETE FROM platform_audit WHERE id <= (SELECT id FROM platform_audit ORDER BY id DESC LIMIT 1 OFFSET 200000)').run()
660
+ }
661
+ setInterval(guarded(sweep), 60_000).unref()
662
+
663
+ // Settings → People, across companies: who is in which and with what role,
664
+ // for whoever manages them (an administrator of the server: all of them).
665
+ // Changing one reuses what each company's People does, effects included.
666
+ const isAdmin = actor => !!(actor?.token || actor?.is_platform_admin)
667
+ const managing = (actor, companyId) => (isAdmin(actor) ? 'owner' : roleIn(actor, companyId))
668
+ const managedBy = (actor, list) => list.filter(c => { const r = managing(actor, c.id); return !!r && atLeast(r, 'manager') })
669
+ const peopleMethods = {
670
+ people: {
671
+ method: 'GET',
672
+ run({ actor, list }) {
673
+ const mine = managedBy(actor, list)
674
+ const ids = new Set(mine.map(c => c.id))
675
+ const users = q('SELECT id, email, name, is_platform_admin, disabled_at FROM users ORDER BY name').all()
676
+ .map(u => ({ id: u.id, email: u.email, name: u.name, is_platform_admin: !!u.is_platform_admin, disabled: !!u.disabled_at, roles: Object.fromEntries(membershipsOf(u.id).filter(m => ids.has(m.company_id)).map(m => [m.company_id, m.role])) }))
677
+ .filter(u => isAdmin(actor) || Object.keys(u.roles).length)
678
+ const invitations = q("SELECT token_hash, email, company_id, role, also, expires_at FROM invitations WHERE kind = 'invite' AND used_at IS NULL AND expires_at > ? ORDER BY expires_at").all(now())
679
+ .map(r => ({ id: sha256(r.token_hash), email: r.email, expires_at: r.expires_at, roles: Object.fromEntries([[r.company_id, r.role], ...alsoOf(r).map(a => [a.company, a.role])].filter(([c]) => c && ids.has(c))) }))
680
+ .filter(i => Object.keys(i.roles).length)
681
+ return { admin: isAdmin(actor), companies: mine.map(c => ({ id: c.id, name: c.name, my_role: managing(actor, c.id) })), users, invitations }
682
+ },
683
+ },
684
+ // One person's role in one company: given, changed, or taken away (role: null).
685
+ 'people/set': {
686
+ method: 'POST',
687
+ async run({ actor, params, req, list, companyOf }) {
688
+ const company = companyOf(String(params.company ?? ''))
689
+ const actorRole = managing(actor, company.id)
690
+ if (!actorRole || !atLeast(actorRole, 'manager')) throw new ApiError(404, 'Not Found: no such company')
691
+ const target = userById(String(params.user ?? ''))
692
+ if (!target) throw bad('no such person')
693
+ const current = roleIn(target, company.id)
694
+ const role = params.role == null || params.role === '' ? null : String(params.role)
695
+ if (!role) {
696
+ if (!current) return { id: target.id, role: null }
697
+ return companyMethods['members/remove'].run({ company, actor, actorRole, params: { user: target.id }, req })
698
+ }
699
+ checkRole(role)
700
+ if (current) return companyMethods['members/role'].run({ company, actor, actorRole, params: { user: target.id, role }, req })
701
+ if (!canGrant(actorRole, role)) throw new ApiError(403, 'Forbidden: you can\'t give that role')
702
+ // (Someone a manager can see: already in another company it manages.)
703
+ if (!isAdmin(actor) && !managedBy(actor, list).some(c => roleIn(target, c.id))) throw bad('that person is not in a company you manage: invite them')
704
+ addMember(target, company.id, role, actor.id ?? null)
705
+ audit(actor, 'member-added', company.id, req, `${target.email} as ${role}`)
706
+ return { id: target.id, role }
707
+ },
708
+ },
709
+ // One link for several companies, each with its role.
710
+ 'people/invite': {
711
+ method: 'POST',
712
+ run({ actor, params, req, list, companyOf }) {
713
+ const email = cleanEmail(params.email)
714
+ if (!EMAIL.test(email)) throw bad('this is not an email address')
715
+ const seen = new Set()
716
+ const wanted = (Array.isArray(params.roles) ? params.roles : []).filter(r => r && r.role && !seen.has(r.company) && seen.add(r.company))
717
+ for (const w of wanted) {
718
+ const company = companyOf(String(w.company ?? ''))
719
+ checkRole(w.role)
720
+ const actorRole = managing(actor, company.id)
721
+ if (!actorRole || !atLeast(actorRole, 'manager')) throw new ApiError(404, 'Not Found: no such company')
722
+ if (!canGrant(actorRole, w.role)) throw new ApiError(403, `Forbidden: you can't give the role ${w.role} in ${company.name}`)
723
+ }
724
+ const admin = params.is_platform_admin === true
725
+ if (admin && !isAdmin(actor)) throw new ApiError(403, 'Forbidden: only an administrator of the server makes another')
726
+ if (!wanted.length && !admin) throw bad('choose a role in at least one company')
727
+ for (const w of wanted) audit(actor, 'member-invited', w.company, req, `${email} as ${w.role}`)
728
+ if (admin) audit(actor, 'user-invited', 'platform', req, `${email} (administrator)`)
729
+ const [first, ...also] = wanted.map(w => ({ company: String(w.company), role: w.role }))
730
+ return newLink(req, 'invite', { email, company: first?.company ?? null, role: first?.role ?? null, isAdmin: admin, also }, INVITE_MS, actor.id ?? null)
731
+ },
732
+ },
733
+ 'people/invitations/cancel': {
734
+ method: 'POST',
735
+ run({ actor, params, req, list }) {
736
+ const row = pendingInvites('1').find(r => sha256(r.token_hash) === String(params.id ?? ''))
737
+ if (!row) throw bad('no such invitation')
738
+ const ids = new Set(managedBy(actor, list).map(c => c.id))
739
+ const all = invitedTo(row)
740
+ // An administrator cancels all of it; a manager, the part for the
741
+ // companies they manage (the rest still holds).
742
+ const mine = isAdmin(actor) ? all : all.filter(([c, r]) => ids.has(c) && canGrant(managing(actor, c), r))
743
+ if (!mine.length && !isAdmin(actor)) throw new ApiError(403, 'Forbidden: you can\'t cancel that one')
744
+ if (isAdmin(actor) || mine.length === all.length) q('DELETE FROM invitations WHERE token_hash = ?').run(row.token_hash)
745
+ else for (const [c] of mine) withoutCompany(pendingInvites('token_hash = ?', row.token_hash)[0], c)
746
+ for (const [c] of mine) audit(actor, 'invitation-cancelled', c, req, row.email)
747
+ // (Which companies, for their own logs: see routes.js.)
748
+ return { cancelled: true, companies: (isAdmin(actor) ? all : mine).map(([c]) => c), email: row.email }
749
+ },
750
+ },
751
+ }
752
+
753
+ return { handle, actorOf, meAnswer, roleIn, hasUsers, companyMethods, adminMethods, peopleMethods, audit, recoverAccess }
754
+ }