pisha-server 0.0.0-stage → 0.0.11

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 (125) 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 +1079 -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 +79 -0
  14. package/dashboard/dashboard.js +407 -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 +224 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +54 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3297 -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 +166 -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 +2093 -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 +40 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +103 -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 +141 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +653 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +179 -0
  89. package/ui/people.js +370 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +171 -0
  93. package/ui/routes.js +46 -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 +113 -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/session.js +42 -0
  105. package/ui/shell.css +122 -0
  106. package/ui/signin.js +120 -0
  107. package/ui/squads.js +370 -0
  108. package/ui/state.js +59 -0
  109. package/ui/stream.js +268 -0
  110. package/ui/styles.css +343 -0
  111. package/ui/team.js +115 -0
  112. package/ui/teams.js +58 -0
  113. package/ui/terminal.js +261 -0
  114. package/ui/theme.js +32 -0
  115. package/ui/timeline.js +163 -0
  116. package/ui/topbar.js +205 -0
  117. package/ui/voice-parse.js +98 -0
  118. package/ui/voice.js +320 -0
  119. package/vendor/InterVariable.woff2 +0 -0
  120. package/vendor/LICENSE-inter +92 -0
  121. package/vendor/LICENSE-xterm +21 -0
  122. package/vendor/README.md +8 -0
  123. package/vendor/addon-fit.js +2 -0
  124. package/vendor/xterm.css +218 -0
  125. package/vendor/xterm.js +2 -0
package/companies.js ADDED
@@ -0,0 +1,294 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { existsSync, mkdirSync, renameSync, rmSync, statSync } from 'node:fs'
3
+ import { DatabaseSync } from 'node:sqlite'
4
+ import { join } from 'node:path'
5
+ import {
6
+ ApiError, DATA_DIR, FIRST_COMPANY, VERSION, bad, cleanText, guarded, logError, now, openControl,
7
+ } from './platform/index.js'
8
+ import { createCompany } from './company.js'
9
+ import { streamExport } from './company-export.js'
10
+
11
+ const ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'
12
+ const COMPANY_NAME = /^[\p{L}\p{N} ._&-]{1,80}$/u
13
+ // A secret of a company: its kind, then the company. (The first company's have
14
+ // none, and an old one, being random, may look as if it had: see of().)
15
+ const CREDENTIAL_COMPANY = /^s[qjh]_([a-z0-9]{8})_/
16
+
17
+ // What a company may keep, when it isn't what the server starts with.
18
+ const QUOTAS = ['max_sessions', 'max_messages', 'max_events', 'max_updates', 'max_files_gb', 'max_db_mb', 'stored_text_mb_hour', 'retention_days', 'event_hours', 'inbox_days']
19
+ const RETENTION = ['retention_days', 'event_hours', 'inbox_days']
20
+
21
+ // How long a company waits after being deleted, in case it was a mistake.
22
+ const GRACE_MS = Number(process.env.PISHA_COMPANY_GRACE_MS ?? 30 * 24 * 3600_000)
23
+
24
+ // The copy of the data taken before a server first has companies: for going back
25
+ // if something goes wrong. It holds what sessions have deleted since, so it goes.
26
+ const BEFORE_COMPANIES = join(DATA_DIR, 'pisha-before-companies.db')
27
+ const COPY_KEPT_MS = 7 * 24 * 3600_000
28
+
29
+ export function createCompanies(server) {
30
+ // (First: if it fails, this server is as it was.)
31
+ if (!existsSync(join(DATA_DIR, 'control.db')) && existsSync(join(DATA_DIR, 'pisha.db'))) copyBeforeCompanies()
32
+ const control = openControl()
33
+
34
+ const open = new Map() // id -> a company running
35
+ const failed = new Set() // ids of those that could not start: the others go on
36
+ const deleting = new Set() // ids of those waiting to be deleted: stopped, their data kept
37
+ let serving = false
38
+
39
+ const row = id => control.prepare('SELECT * FROM companies WHERE id = ?').get(id)
40
+ const folderOf = id => (id === FIRST_COMPANY ? DATA_DIR : join(DATA_DIR, 'companies', id))
41
+ const quotasOf = r => { try { return JSON.parse(r.limits_json) } catch { return {} } }
42
+
43
+ function start(r) {
44
+ const company = createCompany(server, {
45
+ id: r.id, dir: folderOf(r.id), quotas: quotasOf(r),
46
+ // (Who works in it, for its boards: a task can be one of them's.)
47
+ members: () => control.prepare('SELECT u.id, u.name, u.github FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.company_id = ? AND u.disabled_at IS NULL ORDER BY u.name').all(r.id),
48
+ routeEnrollment: (hash, expires) => {
49
+ if (r.id !== FIRST_COMPANY) control.prepare('INSERT OR REPLACE INTO enrollment_routes (code_hash, company_id, expires_at) VALUES (?, ?, ?)').run(hash, r.id, expires)
50
+ },
51
+ })
52
+ if (serving) company.sessions.nowServing()
53
+ open.set(r.id, company)
54
+ return company
55
+ }
56
+
57
+ // A server's data as it was before companies is the first company, in place.
58
+ if (!row(FIRST_COMPANY)) control.prepare('INSERT INTO companies (id, name, created_at) VALUES (?, ?, ?)').run(FIRST_COMPANY, 'Default', now())
59
+ start(row(FIRST_COMPANY))
60
+ for (const r of control.prepare('SELECT * FROM companies WHERE id != ?').all(FIRST_COMPANY)) {
61
+ if (r.status === 'deleting') { deleting.add(r.id); continue }
62
+ try { start(r) } catch (err) {
63
+ failed.add(r.id)
64
+ logError(`company ${r.id} could not start: ${err.stack ?? err}`)
65
+ }
66
+ }
67
+
68
+ function cleanup() {
69
+ control.prepare('DELETE FROM enrollment_routes WHERE expires_at < ?').run(now())
70
+ try { if (now() - statSync(BEFORE_COMPANIES).mtimeMs > COPY_KEPT_MS) rmSync(BEFORE_COMPANIES, { force: true }) } catch {}
71
+ // Their time is up: gone, with all that was theirs.
72
+ for (const r of control.prepare("SELECT id, name FROM companies WHERE status = 'deleting' AND delete_after < ?").all(now())) {
73
+ rmSync(folderOf(r.id), { recursive: true, force: true })
74
+ control.prepare('DELETE FROM companies WHERE id = ?').run(r.id)
75
+ deleting.delete(r.id)
76
+ control.prepare('INSERT INTO platform_audit (at, action, target, detail) VALUES (?, ?, ?, ?)').run(now(), 'company-deleted', r.id, r.name)
77
+ process.stderr.write(`pisha-server: company "${r.name}" (${r.id}) deleted, with its data\n`)
78
+ }
79
+ }
80
+ setInterval(guarded(cleanup), 3600_000).unref()
81
+ cleanup()
82
+
83
+ const nameOf = id => row(id)?.name ?? null
84
+ const statusOf = id => { const r = row(id); return r ? { status: r.status, delete_after: r.delete_after } : {} }
85
+ // Across every company: someone lost a session, or all their access.
86
+ const dropClients = match => { for (const c of open.values()) c.dropClients(match) }
87
+
88
+ const stopped = id => (failed.has(id) ? 'could not start; see the server log' : deleting.has(id) ? 'is being deleted' : null)
89
+ const refuseIfStopped = id => { if (id && stopped(id)) throw new ApiError(503, `Service Unavailable: this company ${stopped(id)}`) }
90
+
91
+ const first = () => open.get(FIRST_COMPANY)
92
+ const get = id => open.get(id) ?? null
93
+
94
+ // The company a credential says it is of: it only opens that one. A prefix of
95
+ // no company is an old secret that looks like one by chance.
96
+ function of(credential) {
97
+ const id = CREDENTIAL_COMPANY.exec(String(credential ?? ''))?.[1]
98
+ refuseIfStopped(id)
99
+ return (id && open.get(id)) || first()
100
+ }
101
+
102
+ function forEnrollment(key) {
103
+ const id = control.prepare('SELECT company_id FROM enrollment_routes WHERE code_hash = ?').get(key)?.company_id
104
+ refuseIfStopped(id)
105
+ return (id && open.get(id)) || first()
106
+ }
107
+ const enrolled = key => control.prepare('DELETE FROM enrollment_routes WHERE code_hash = ?').run(key)
108
+
109
+ function cleanQuotas(limits) {
110
+ const out = {}
111
+ for (const [k, v] of Object.entries(limits ?? {})) {
112
+ if (!QUOTAS.includes(k)) throw bad(`unknown limit "${k}": it can be ${QUOTAS.join(', ')}`)
113
+ if (!Number.isSafeInteger(v) || v < 1) throw bad(`${k} must be a whole number above zero`)
114
+ out[k] = v
115
+ }
116
+ return out
117
+ }
118
+
119
+ const view = r => ({ id: r.id, name: r.name, status: failed.has(r.id) ? 'unavailable' : r.status, limits: quotasOf(r), created_at: r.created_at, delete_after: r.delete_after ?? undefined })
120
+ const list = () => control.prepare('SELECT * FROM companies ORDER BY created_at, id').all().map(view)
121
+
122
+ // Which machines serve which companies, by what each machine says it is:
123
+ // for looking at, never for deciding anything.
124
+ function machines() {
125
+ const byMachine = new Map()
126
+ for (const c of open.values()) {
127
+ for (const h of c.machines.listHosts()) {
128
+ const key = h.info?.machine ?? h.id
129
+ if (!byMachine.has(key)) byMachine.set(key, { machine: key, hostname: h.info?.hostname ?? h.name, instances: [] })
130
+ byMachine.get(key).instances.push({
131
+ company: c.id, company_name: nameOf(c.id), host: h.id, name: h.name, online: h.online, os_user: h.info?.os_user ?? null,
132
+ sessions: h.info?.terminals?.length ?? 0, max_sessions: h.info?.max_sessions ?? null,
133
+ })
134
+ }
135
+ }
136
+ return [...byMachine.values()].map(m => {
137
+ const users = new Set(m.instances.map(i => i.os_user))
138
+ return {
139
+ ...m,
140
+ sessions: m.instances.reduce((n, i) => n + i.sessions, 0),
141
+ isolation: m.machine.startsWith('h_') ? 'unknown' : m.instances.length < 2 ? 'dedicated' : users.size === m.instances.length && !users.has(null) ? 'os-user' : 'same-user',
142
+ }
143
+ }).sort((a, b) => String(a.hostname).localeCompare(String(b.hostname)))
144
+ }
145
+
146
+ function newId() {
147
+ for (;;) {
148
+ const id = [...randomBytes(8)].map(b => ID_ALPHABET[b % ID_ALPHABET.length]).join('')
149
+ if (!row(id) && !existsSync(folderOf(id))) return id
150
+ }
151
+ }
152
+
153
+ function add(p) {
154
+ const name = typeof p.name === 'string' ? cleanText(p.name.slice(0, 200)).trim() : ''
155
+ if (!COMPANY_NAME.test(name)) throw bad('the name may have letters, digits, spaces and . _ & - (max 80)')
156
+ if (control.prepare('SELECT 1 FROM companies WHERE name = ?').get(name)) throw new ApiError(409, `Conflict: there is already a company called "${name}"`)
157
+ const limits = cleanQuotas(p.limits)
158
+ const id = newId()
159
+ mkdirSync(join(DATA_DIR, 'companies'), { recursive: true, mode: 0o700 })
160
+ control.prepare('INSERT INTO companies (id, name, limits_json, created_at) VALUES (?, ?, ?, ?)').run(id, name, JSON.stringify(limits), now())
161
+ let company
162
+ try { company = start(row(id)) } catch (err) {
163
+ control.prepare('DELETE FROM companies WHERE id = ?').run(id)
164
+ rmSync(folderOf(id), { recursive: true, force: true })
165
+ throw err
166
+ }
167
+ process.stderr.write(`pisha-server: company "${name}" (${id}) created\n`)
168
+ return { ...view(row(id)), join_token: company.platform.joinToken().token }
169
+ }
170
+
171
+ // Limits: from now on (each module reads them when it needs them).
172
+ function setQuotas(p) {
173
+ const id = String(p.company ?? '')
174
+ const company = get(id)
175
+ if (!company) throw new ApiError(404, 'Not Found: no such company')
176
+ const limits = cleanQuotas(p.limits)
177
+ control.prepare('UPDATE companies SET limits_json = ? WHERE id = ?').run(JSON.stringify(limits), id)
178
+ company.platform.setQuotas(limits)
179
+ return view(row(id))
180
+ }
181
+
182
+ // Stopped now, and deleted when its time is up. Until then it can come back whole.
183
+ function scheduleDelete(company, confirm) {
184
+ const r = row(company.id)
185
+ if (company.id === FIRST_COMPANY) throw new ApiError(409, 'Conflict: the first company can\'t be deleted')
186
+ if (confirm !== r.name) throw bad('write the name of the company, exactly, to confirm')
187
+ const at = now() + GRACE_MS
188
+ control.prepare("UPDATE companies SET status = 'deleting', delete_after = ? WHERE id = ?").run(at, company.id)
189
+ control.prepare('DELETE FROM enrollment_routes WHERE company_id = ?').run(company.id)
190
+ deleting.add(company.id)
191
+ open.delete(company.id)
192
+ company.close()
193
+ process.stderr.write(`pisha-server: company "${r.name}" (${company.id}) stopped: it will be deleted on ${new Date(at).toISOString()}\n`)
194
+ return { id: company.id, status: 'deleting', delete_after: at }
195
+ }
196
+ function restore(id) {
197
+ const r = row(id)
198
+ if (!r || !deleting.has(id)) throw new ApiError(404, 'Not Found: no company waiting to be deleted with that id')
199
+ control.prepare("UPDATE companies SET status = 'active', delete_after = NULL WHERE id = ?").run(id)
200
+ deleting.delete(id)
201
+ start(row(id))
202
+ process.stderr.write(`pisha-server: company "${r.name}" (${id}) restored\n`)
203
+ return view(row(id))
204
+ }
205
+
206
+ // What is about the company itself, for those in it. (See routes.js for who.)
207
+ // Companies whose export is being sent, and whether a database copy is
208
+ // under way in the server: only the copy takes a disk and a processor, so
209
+ // only it is one at a time in the whole server. Sending it, at the pace the
210
+ // reader takes, holds nobody else up.
211
+ const exporting = new Set()
212
+ let copying = false
213
+ const oneCopy = async fn => {
214
+ if (copying) throw new ApiError(409, 'Conflict: an export is being prepared on this server; try again in a moment')
215
+ copying = true
216
+ try { return await fn() } finally { copying = false }
217
+ }
218
+ const companyMethods = {
219
+ 'company/audit': {
220
+ role: 'manager', method: 'GET',
221
+ run({ company, url }) {
222
+ const before = Number(url.searchParams.get('before')) || undefined
223
+ const limit = Math.max(1, Math.min(Number(url.searchParams.get('limit')) || 100, 500))
224
+ return company.platform.auditLog({ before, limit })
225
+ },
226
+ },
227
+ 'company/retention': {
228
+ role: 'manager', method: 'GET',
229
+ run: ({ company }) => ({ retention_days: company.platform.quota('retention_days', 7), event_hours: company.platform.quota('event_hours', Number(process.env.OBSERVE_TTL_HOURS ?? 24)), inbox_days: company.platform.quota('inbox_days', 90) }),
230
+ },
231
+ 'company/retention/set': {
232
+ role: 'owner', method: 'POST',
233
+ run({ company, params }) {
234
+ const wanted = Object.fromEntries(RETENTION.filter(k => params[k] != null).map(k => [k, params[k]]))
235
+ const limits = { ...quotasOf(row(company.id)), ...cleanQuotas(wanted) }
236
+ if ((limits.retention_days ?? 0) > 3650 || (limits.event_hours ?? 0) > 8760 || (limits.inbox_days ?? 0) > 3650) throw bad('at most 3650 days of messages or of the inbox, and 8760 hours of activity')
237
+ control.prepare('UPDATE companies SET limits_json = ? WHERE id = ?').run(JSON.stringify(limits), company.id)
238
+ company.platform.setQuotas(limits)
239
+ return { retention_days: limits.retention_days ?? 7, event_hours: limits.event_hours ?? null, inbox_days: limits.inbox_days ?? 90 }
240
+ },
241
+ },
242
+ // (It answers by itself: a whole company goes down the response as it is read.)
243
+ 'company/export': {
244
+ role: 'owner', method: 'GET', streams: true,
245
+ async run({ company, res }) {
246
+ if (exporting.has(company.id)) throw new ApiError(409, 'Conflict: an export of this company is under way; try again when it ends')
247
+ if (copying) throw new ApiError(409, 'Conflict: an export is being prepared on this server; try again in a moment')
248
+ if (!company.platform.allow('export', 'all', 5, 3600_000)) throw new ApiError(429, 'Too Many Requests: at most 5 exports an hour')
249
+ exporting.add(company.id)
250
+ try { await streamExport(company, { id: company.id, name: row(company.id).name, pisha: VERSION }, res, { oneCopy }) } finally { exporting.delete(company.id) }
251
+ },
252
+ },
253
+ 'company/delete': {
254
+ role: 'owner', method: 'POST',
255
+ run: ({ company, params }) => scheduleDelete(company, params.confirm),
256
+ },
257
+ }
258
+
259
+ const adminMethods = {
260
+ createCompany: add,
261
+ listCompanies: list,
262
+ setCompanyLimits: setQuotas,
263
+ }
264
+
265
+ function nowServing() {
266
+ serving = true
267
+ for (const c of open.values()) c.sessions.nowServing()
268
+ }
269
+
270
+ function close() {
271
+ for (const c of open.values()) c.close()
272
+ try { control.close() } catch {}
273
+ }
274
+
275
+ return {
276
+ control, companyMethods, restore, machines, first, get, of, nameOf, statusOf, dropClients, all: () => [...open.values()], list, adminMethods, forEnrollment, enrolled, nowServing, close,
277
+ }
278
+ }
279
+
280
+ // (Refusing to go on without it. Under another name until it is whole.)
281
+ function copyBeforeCompanies() {
282
+ const partial = `${BEFORE_COMPANIES}.partial`
283
+ rmSync(partial, { force: true })
284
+ const db = new DatabaseSync(join(DATA_DIR, 'pisha.db'))
285
+ try {
286
+ db.prepare('VACUUM INTO ?').run(partial)
287
+ renameSync(partial, BEFORE_COMPANIES)
288
+ process.stderr.write(`pisha-server: a copy of the data before companies is in ${BEFORE_COMPANIES}; it is deleted after 7 days\n`)
289
+ } catch (err) {
290
+ rmSync(partial, { force: true })
291
+ process.stderr.write(`pisha-server: cannot copy the data before upgrading it (${err.message}). Nothing changed\n`)
292
+ process.exit(1)
293
+ } finally { db.close() }
294
+ }
@@ -0,0 +1,101 @@
1
+ import { createReadStream, lstatSync, readdirSync, rmSync } from 'node:fs'
2
+ import { randomBytes } from 'node:crypto'
3
+ import { join } from 'node:path'
4
+ import { Readable } from 'node:stream'
5
+ import { pipeline } from 'node:stream/promises'
6
+ import { Worker } from 'node:worker_threads'
7
+ import { createGzip } from 'node:zlib'
8
+
9
+ // A company as a .tar.gz: its database and its attachments, and what it is.
10
+ // Only those: its join token and the server's keys aren't its data.
11
+ const BLOCK = 512
12
+
13
+ function tarHeader(name, size, mtime) {
14
+ const h = Buffer.alloc(BLOCK)
15
+ const octal = (value, at, length) => h.write(`${Math.floor(value).toString(8).padStart(length - 1, '0')}\0`, at, length, 'latin1')
16
+ h.write(name, 0, 100, 'utf8')
17
+ octal(0o600, 100, 8)
18
+ octal(0, 108, 8)
19
+ octal(0, 116, 8)
20
+ octal(size, 124, 12)
21
+ octal(mtime / 1000, 136, 12)
22
+ h.write(' ', 148, 8, 'latin1') // (counted as spaces, until it is known)
23
+ h.write('0', 156, 1, 'latin1')
24
+ h.write('ustar\0' + '00', 257, 8, 'latin1')
25
+ let sum = 0
26
+ for (const b of h) sum += b
27
+ h.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'latin1')
28
+ return h
29
+ }
30
+ const padding = size => Buffer.alloc((BLOCK - size % BLOCK) % BLOCK)
31
+
32
+ async function* tarOf(entries) {
33
+ for (const { name, path, text } of entries) {
34
+ if (text != null) {
35
+ const body = Buffer.from(text)
36
+ yield tarHeader(name, body.length, Date.now())
37
+ yield body
38
+ yield padding(body.length)
39
+ continue
40
+ }
41
+ const st = lstatSync(path)
42
+ yield tarHeader(name, st.size, st.mtimeMs)
43
+ // (What was read so far is what the header says: a file that changed is cut or filled.)
44
+ let sent = 0
45
+ for await (const chunk of createReadStream(path, { end: Math.max(0, st.size - 1), ...(st.size ? {} : { start: 0, end: -1 }) })) { sent += chunk.length; yield chunk }
46
+ if (sent < st.size) yield Buffer.alloc(st.size - sent)
47
+ yield padding(st.size)
48
+ }
49
+ yield Buffer.alloc(BLOCK * 2)
50
+ }
51
+
52
+ // The copy in a thread of its own, with its own connection: on the one that
53
+ // answers every company, nobody would get an answer until it ended.
54
+ const COPY_DATABASE = `
55
+ const { workerData } = require('node:worker_threads')
56
+ const { DatabaseSync } = require('node:sqlite')
57
+ const db = new DatabaseSync(workerData.file, { readOnly: true })
58
+ db.prepare('VACUUM INTO ?').run(workerData.copy)
59
+ db.close()`
60
+ function copyDatabase(file, copy) {
61
+ return new Promise((resolve, reject) => {
62
+ const worker = new Worker(COPY_DATABASE, { eval: true, workerData: { file, copy }, execArgv: ['--no-warnings'] })
63
+ worker.once('error', reject)
64
+ worker.once('exit', code => (code === 0 ? resolve() : reject(new Error(`copying the database ended with ${code}`))))
65
+ worker.unref()
66
+ })
67
+ }
68
+
69
+ // oneCopy(fn): runs the copy, one at a time in the server (see companies.js).
70
+ export async function streamExport(company, about, res, { oneCopy = fn => fn() } = {}) {
71
+ const { dataDir } = company.platform
72
+ const copy = join(dataDir, `export-${randomBytes(8).toString('hex')}.db`)
73
+ try {
74
+ await oneCopy(() => copyDatabase(join(dataDir, 'pisha.db'), copy))
75
+ const files = []
76
+ for (const f of readdirSync(join(dataDir, 'files'))) {
77
+ const path = join(dataDir, 'files', f)
78
+ if (lstatSync(path).isFile() && lstatSync(path).size) files.push({ name: `files/${f}`, path })
79
+ }
80
+ const date = new Date().toISOString().slice(0, 10)
81
+ res.writeHead(200, {
82
+ 'Content-Type': 'application/gzip',
83
+ 'Content-Disposition': `attachment; filename="pisha-${company.id}-${date}.tar.gz"`,
84
+ 'Cache-Control': 'no-store',
85
+ 'X-Content-Type-Options': 'nosniff',
86
+ })
87
+ const entries = [
88
+ { name: 'company.json', text: `${JSON.stringify({ ...about, exported_at: new Date().toISOString() }, null, 2)}\n` },
89
+ { name: 'pisha.db', path: copy },
90
+ ...files,
91
+ ]
92
+ await pipeline(Readable.from(tarOf(entries)), createGzip(), res)
93
+ } finally {
94
+ rmSync(copy, { force: true })
95
+ }
96
+ }
97
+
98
+ // What an export that didn't end left behind.
99
+ export function cleanExports(dir) {
100
+ try { for (const f of readdirSync(dir)) if (/^export-[0-9a-f]{16}\.db$/.test(f)) rmSync(join(dir, f), { force: true }) } catch {}
101
+ }
package/company.js ADDED
@@ -0,0 +1,79 @@
1
+ import { createPlatform, guarded } from './platform/index.js'
2
+ import { createSessions } from './sessions/index.js'
3
+ import { createMessaging, createInbox, createPlans } from './messaging/index.js'
4
+ import { createObservation } from './observation/index.js'
5
+ import { createPermissions } from './permissions/index.js'
6
+ import { createMachines } from './machines/index.js'
7
+ import { createOrganization } from './organization/index.js'
8
+ import { createDashboard } from './dashboard/index.js'
9
+ import { createBoards } from './boards/index.js'
10
+ import { upgradeStoredData } from './data-upgrade.js'
11
+ import { cleanExports } from './company-export.js'
12
+
13
+ // One company: its data and every module working on it, with nothing shared
14
+ // with any other but what is the whole server's (see server/server.js).
15
+ // Each part gets what is below it, so what depends on what can be read here
16
+ // (test/modules.test.mjs checks it stays so):
17
+ // platform configuration, HTTP, database, keys, limits
18
+ // sessions identities, their queues, who holds a name and who is online
19
+ // messaging messages, groups, attachments
20
+ // observation what each session is doing
21
+ // permissions permission profiles: what the agents may do without asking
22
+ // machines pisha-host: joining, its link, terminals
23
+ // organization squads, links between them, templates
24
+ // boards task boards: people's and agents' tasks
25
+ // dashboard what the dashboard reads and does
26
+ export function createCompany(server, options) {
27
+ const platform = createPlatform(server, options)
28
+ const sessions = createSessions(platform)
29
+ const messaging = createMessaging(platform, { sessions })
30
+ const inbox = createInbox(platform, { sessions })
31
+ const plans = createPlans(platform, { sessions })
32
+ const observation = createObservation(platform)
33
+ const permissions = createPermissions(platform, { sessions })
34
+ const machines = createMachines(platform, { sessions, observation, permissions })
35
+ const organization = createOrganization(platform, { sessions, messaging, observation, machines })
36
+ const boards = createBoards(platform, { sessions, messaging, members: options.members ?? (() => []) })
37
+ const dashboard = createDashboard(platform, { sessions, messaging, inbox, plans, observation, machines, organization, permissions, boards })
38
+
39
+ // What a session can ask for, by its name in the request.
40
+ const methods = {
41
+ ...observation.observationMethods, ...machines.machineMethods, ...organization.organizationMethods,
42
+ ...sessions.sessionMethods, ...messaging.messagingMethods, ...inbox.inboxMethods, ...plans.planMethods, ...boards.boardMethods,
43
+ }
44
+
45
+ function cleanup() {
46
+ messaging.cleanupMessages()
47
+ inbox.cleanupInbox()
48
+ sessions.cleanupUpdates()
49
+ observation.cleanupEvents()
50
+ platform.cleanupLimits()
51
+ platform.cleanupAudit()
52
+ platform.truncateLogHourly()
53
+ }
54
+ platform.every(60 * 1000, guarded(cleanup))
55
+ cleanup()
56
+ cleanExports(options.dir)
57
+
58
+ upgradeStoredData(platform, { messaging, observation, machines })
59
+ observation.restoreActivity()
60
+
61
+ // Someone lost access: what they have open closes now, not at their next request.
62
+ function dropClients(match) {
63
+ machines.dropTickets(match)
64
+ for (const res of [...platform.sseClients]) if (res.actor && match(res.actor)) { platform.sseClients.delete(res); try { res.end() } catch {} }
65
+ for (const ws of [...machines.wsClients]) if (ws.actor && match(ws.actor)) ws.close(4403, 'access changed')
66
+ }
67
+
68
+ // The server is stopping: everything open ends right away.
69
+ function close() {
70
+ platform.stopTimers()
71
+ for (const w of [...sessions.waiters.values()]) sessions.finishPoll(w, null, [])
72
+ for (const res of platform.sseClients) { try { res.end() } catch {} }
73
+ platform.sseClients.clear()
74
+ for (const ws of machines.wsClients) ws.close(1001, 'server shutting down')
75
+ try { platform.db.close() } catch {}
76
+ }
77
+
78
+ return { id: options.id, platform, sessions, messaging, observation, machines, organization, boards, dashboard, methods, dropClients, close }
79
+ }