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.
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/accounts/accounts.js +754 -0
- package/accounts/index.js +1 -0
- package/accounts/passwords.js +41 -0
- package/accounts/totp.js +54 -0
- package/boards/boards.js +1079 -0
- package/boards/github.js +212 -0
- package/boards/index.js +1 -0
- package/boards/sync.js +980 -0
- package/companies.js +294 -0
- package/company-export.js +101 -0
- package/company.js +79 -0
- package/dashboard/dashboard.js +407 -0
- package/dashboard/index.js +1 -0
- package/data-upgrade.js +69 -0
- package/install/linux.sh +181 -0
- package/install/macos.sh +121 -0
- package/install/windows.bat +54 -0
- package/machines/index.js +3 -0
- package/machines/machines.js +910 -0
- package/messaging/inbox.js +252 -0
- package/messaging/index.js +3 -0
- package/messaging/messaging.js +551 -0
- package/messaging/plans.js +67 -0
- package/observation/index.js +1 -0
- package/observation/observation.js +224 -0
- package/organization/index.js +1 -0
- package/organization/organization.js +218 -0
- package/package.json +54 -4
- package/permissions/index.js +1 -0
- package/permissions/permissions.js +211 -0
- package/pisha-host.mjs +3297 -0
- package/pisha-host.mjs.sig +1 -0
- package/platform/acme.js +207 -0
- package/platform/basics.js +14 -0
- package/platform/config.js +154 -0
- package/platform/control.js +93 -0
- package/platform/credentials.js +151 -0
- package/platform/database.js +251 -0
- package/platform/errors.js +13 -0
- package/platform/files.js +50 -0
- package/platform/http.js +207 -0
- package/platform/index.js +58 -0
- package/platform/limits.js +122 -0
- package/platform/listen.js +183 -0
- package/platform/roles.js +6 -0
- package/platform/stream.js +19 -0
- package/platform/text.js +83 -0
- package/platform/ws.js +186 -0
- package/routes.js +405 -0
- package/server.js +65 -0
- package/sessions/index.js +1 -0
- package/sessions/sessions.js +533 -0
- package/ui/LICENSE-affectui.txt +26 -0
- package/ui/addmachine.js +151 -0
- package/ui/api.js +20 -0
- package/ui/app.js +143 -0
- package/ui/attention.js +78 -0
- package/ui/back.js +166 -0
- package/ui/boards.js +958 -0
- package/ui/chat.js +388 -0
- package/ui/content.js +157 -0
- package/ui/dialogs.js +135 -0
- package/ui/doing.js +112 -0
- package/ui/dom.js +6 -0
- package/ui/ds-base.css +146 -0
- package/ui/ds-components.css +229 -0
- package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
- package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
- package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
- package/ui/format.js +25 -0
- package/ui/i18n.js +2093 -0
- package/ui/icons/apple-touch-icon.png +0 -0
- package/ui/icons/icon-192.png +0 -0
- package/ui/icons/icon-512.png +0 -0
- package/ui/icons/maskable-512.png +0 -0
- package/ui/icons.js +40 -0
- package/ui/inbox.js +535 -0
- package/ui/index.html +103 -0
- package/ui/machines.js +261 -0
- package/ui/manifest.webmanifest +16 -0
- package/ui/mosaic.js +189 -0
- package/ui/nav.js +141 -0
- package/ui/newteam.js +223 -0
- package/ui/org.js +653 -0
- package/ui/overlays.css +126 -0
- package/ui/palette.js +179 -0
- package/ui/people.js +370 -0
- package/ui/permissions.js +202 -0
- package/ui/qr.js +158 -0
- package/ui/router.js +171 -0
- package/ui/routes.js +46 -0
- package/ui/screen-boards.css +241 -0
- package/ui/screen-inbox.css +201 -0
- package/ui/screen-machines.css +76 -0
- package/ui/screen-mosaic.css +26 -0
- package/ui/screen-newteam.css +90 -0
- package/ui/screen-org.css +113 -0
- package/ui/screen-session.css +99 -0
- package/ui/screen-signin.css +28 -0
- package/ui/screen-team.css +80 -0
- package/ui/screen-teams.css +41 -0
- package/ui/session.js +42 -0
- package/ui/shell.css +122 -0
- package/ui/signin.js +120 -0
- package/ui/squads.js +370 -0
- package/ui/state.js +59 -0
- package/ui/stream.js +268 -0
- package/ui/styles.css +343 -0
- package/ui/team.js +115 -0
- package/ui/teams.js +58 -0
- package/ui/terminal.js +261 -0
- package/ui/theme.js +32 -0
- package/ui/timeline.js +163 -0
- package/ui/topbar.js +205 -0
- package/ui/voice-parse.js +98 -0
- package/ui/voice.js +320 -0
- package/vendor/InterVariable.woff2 +0 -0
- package/vendor/LICENSE-inter +92 -0
- package/vendor/LICENSE-xterm +21 -0
- package/vendor/README.md +8 -0
- package/vendor/addon-fit.js +2 -0
- package/vendor/xterm.css +218 -0
- package/vendor/xterm.js +2 -0
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
import { extname, join } from 'node:path'
|
|
2
|
+
import { randomBytes } from 'node:crypto'
|
|
3
|
+
import { rmSync } from 'node:fs'
|
|
4
|
+
import {
|
|
5
|
+
unix, now, cutText, cleanText, bad, ApiError, readBodyToFile,
|
|
6
|
+
} from '../platform/index.js'
|
|
7
|
+
|
|
8
|
+
export function createMessaging(platform, { sessions }) {
|
|
9
|
+
const {
|
|
10
|
+
db, signAsServer, broadcast, inTx, bus, dataDir, allow, counted, rateLimit, spendStorage, ensureRoom, readLimit, groupLimit, quota,
|
|
11
|
+
companyId, credentialPrefix, log,
|
|
12
|
+
} = platform
|
|
13
|
+
const {
|
|
14
|
+
userObj, identityCreatedAt, linked, NAME_RE, identityExists, roleOf, checkApproval, linkKey, isOnline,
|
|
15
|
+
downIn, presence, pushUpdate,
|
|
16
|
+
} = sessions
|
|
17
|
+
|
|
18
|
+
const MAX_TEXT = 32_000 // per message, chars
|
|
19
|
+
const MAX_FILE_BYTES = 50 * 1024 * 1024 // 50 MB
|
|
20
|
+
const STORED_TEXT_MB_PER_HOUR = 100 // per session, as it lands on disk (quota stored_text_mb_hour)
|
|
21
|
+
const UPLOAD_BUDGET_BYTES = 500 * 1024 * 1024 // per identity per hour
|
|
22
|
+
const MAX_FILES_GB = Number(process.env.PISHA_MAX_FILES_GB ?? 10) // attachments kept, in all
|
|
23
|
+
const INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000 // an invitation to a group nobody used
|
|
24
|
+
const MAX_REACTIONS = 1_000_000 // kept, in all: the oldest go first
|
|
25
|
+
const MAX_MESSAGES = Number(process.env.PISHA_MAX_MESSAGES ?? 2_000_000) // messages kept, in all
|
|
26
|
+
// How long messages and attachments are kept (a company can say otherwise).
|
|
27
|
+
const retainedMs = () => quota('retention_days', 7) * 24 * 60 * 60 * 1000
|
|
28
|
+
const GROUP_RE = /^#[A-Za-z0-9_-]{1,32}$/
|
|
29
|
+
const PHOTO_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp'])
|
|
30
|
+
|
|
31
|
+
// The chat a recipient sees. In a DM, Telegram's chat.id is the other party's
|
|
32
|
+
// id, so replying to chat_id goes back to the sender. Same here.
|
|
33
|
+
function chatFor(target, fromName) {
|
|
34
|
+
if (target.startsWith('#')) return { id: target, type: 'group', title: target }
|
|
35
|
+
return { id: fromName, type: 'private', username: fromName, first_name: fromName }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function fileRow(fileId) {
|
|
39
|
+
return fileId ? db.prepare('SELECT * FROM files WHERE file_id = ?').get(fileId) : null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function messageObj(row, { withReply = true } = {}) {
|
|
43
|
+
const msg = {
|
|
44
|
+
message_id: row.id,
|
|
45
|
+
from: userObj(row.from_name),
|
|
46
|
+
chat: chatFor(row.target, row.from_name),
|
|
47
|
+
date: unix(row.created_at),
|
|
48
|
+
}
|
|
49
|
+
if (row.edited_at) msg.edit_date = unix(row.edited_at)
|
|
50
|
+
if (row.system) {
|
|
51
|
+
msg.pisha_notice = true // generated by the server, not by the sender
|
|
52
|
+
// Signed for its company too: the same name elsewhere can't be shown it.
|
|
53
|
+
// (The first company's stay as they were: its plugins may be older.)
|
|
54
|
+
if (credentialPrefix) msg.pisha_company = companyId
|
|
55
|
+
msg.pisha_server_sig = signAsServer([...(credentialPrefix ? ['pisha-notice-2', companyId] : ['pisha-notice-1']), row.from_name, row.target, row.id, msg.date, row.text ?? ''])
|
|
56
|
+
}
|
|
57
|
+
// A task's lifecycle (see the plugin): information that needs no report,
|
|
58
|
+
// and a worker's final report on its tasks.
|
|
59
|
+
if (row.fyi) msg.pisha_fyi = true
|
|
60
|
+
if (row.report) msg.pisha_report = row.report
|
|
61
|
+
if (row.sig) msg.pisha_sig = row.sig
|
|
62
|
+
const f = fileRow(row.file_id)
|
|
63
|
+
if (f) {
|
|
64
|
+
if (row.text) msg.caption = row.text
|
|
65
|
+
const fileInfo = { file_id: f.file_id, file_unique_id: f.file_unique_id, file_size: f.size }
|
|
66
|
+
if (row.file_kind === 'photo') msg.photo = [fileInfo]
|
|
67
|
+
else msg.document = { ...fileInfo, file_name: f.name ?? undefined, mime_type: f.mime ?? undefined }
|
|
68
|
+
} else {
|
|
69
|
+
msg.text = row.text ?? ''
|
|
70
|
+
}
|
|
71
|
+
if (withReply && row.reply_to) {
|
|
72
|
+
const r = db.prepare('SELECT * FROM messages WHERE id = ?').get(row.reply_to)
|
|
73
|
+
// (Only while its author can still see what it quotes: after leaving a
|
|
74
|
+
// group, a later edit of the quoted message isn't shown through it.)
|
|
75
|
+
if (r && (row.system || canSeeMessage(row.from_name, r))) {
|
|
76
|
+
// The quoted message is only a reference: its first 500 characters
|
|
77
|
+
// (a short reply can't make the server store a long text again).
|
|
78
|
+
const q = messageObj(r, { withReply: false })
|
|
79
|
+
for (const k of ['text', 'caption']) if (typeof q[k] === 'string' && q[k].length > 500) q[k] = `${cutText(q[k], 500)}…`
|
|
80
|
+
msg.reply_to_message = q
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return msg
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// The last member left: the group and its history go away, so a new group
|
|
87
|
+
// with the same name starts empty.
|
|
88
|
+
// An owner that leaves (or is deleted) passes the group to the member who
|
|
89
|
+
// has been in it longest: someone can still invite.
|
|
90
|
+
function handOverGroup(id, leaving) {
|
|
91
|
+
if (db.prepare('SELECT owner FROM groups WHERE id = ?').get(id)?.owner !== leaving) return
|
|
92
|
+
const next = db.prepare('SELECT name FROM group_members WHERE group_id = ? ORDER BY joined_at, name LIMIT 1').get(id)?.name
|
|
93
|
+
if (next) db.prepare('UPDATE groups SET owner = ? WHERE id = ?').run(next, id)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Two sessions that have written to each other (since both current
|
|
97
|
+
// identities exist), or share a group: only then does one see the other's
|
|
98
|
+
// presence (getChat, and when a send says who is offline).
|
|
99
|
+
function related(name, id) {
|
|
100
|
+
if (id === name) return true
|
|
101
|
+
const ident = db.prepare('SELECT created_at FROM identities WHERE name = ?').get(id)
|
|
102
|
+
if (!ident) return false
|
|
103
|
+
const since = Math.max(identityCreatedAt(name), ident.created_at)
|
|
104
|
+
const wrote = (a, b) => db.prepare('SELECT 1 FROM messages WHERE from_name = ? AND target = ? AND system = 0 AND auto = 0 AND created_at >= ? LIMIT 1').get(a, b, since)
|
|
105
|
+
if ((wrote(name, id) && wrote(id, name)) || linked(name, id)) return true
|
|
106
|
+
// (A shared group isn't a relation while the approval rule keeps these two apart.)
|
|
107
|
+
if (!db.prepare('SELECT 1 FROM group_members a JOIN group_members b ON a.group_id = b.group_id WHERE a.name = ? AND b.name = ? LIMIT 1').get(name, id)) return false
|
|
108
|
+
try { checkApproval(name, id, false); checkApproval(id, name, false) } catch { return false }
|
|
109
|
+
return true
|
|
110
|
+
}
|
|
111
|
+
function closeGroup(id) {
|
|
112
|
+
if (!GROUP_RE.test(String(id))) return // only groups have a history to delete
|
|
113
|
+
db.prepare('DELETE FROM groups WHERE id = ?').run(id)
|
|
114
|
+
db.prepare('DELETE FROM group_invites WHERE group_id = ?').run(id)
|
|
115
|
+
db.prepare('DELETE FROM messages WHERE target = ?').run(id)
|
|
116
|
+
}
|
|
117
|
+
function canSeeMessage(name, row) {
|
|
118
|
+
if (row.created_at < identityCreatedAt(name)) return false
|
|
119
|
+
if (row.from_name === name || row.target === name) return true
|
|
120
|
+
if (!row.target.startsWith('#')) return false
|
|
121
|
+
const member = db.prepare('SELECT joined_at FROM group_members WHERE group_id = ? AND name = ?').get(row.target, name)
|
|
122
|
+
return !!member && row.created_at >= (member.joined_at ?? 0)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Who receives a message sent to `target` by `from`.
|
|
126
|
+
function recipientsOf(target, from) {
|
|
127
|
+
if (target.startsWith('#')) {
|
|
128
|
+
return db.prepare('SELECT name FROM group_members WHERE group_id = ? AND name != ?').all(target, from).map(r => r.name)
|
|
129
|
+
}
|
|
130
|
+
return [target]
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function resolveTarget(chatId, from) {
|
|
134
|
+
if (typeof chatId !== 'string' || chatId === '') throw bad('chat_id is required')
|
|
135
|
+
if (chatId.startsWith('#')) {
|
|
136
|
+
if (!GROUP_RE.test(chatId)) throw bad('invalid group id')
|
|
137
|
+
if (!db.prepare('SELECT 1 FROM group_members WHERE group_id = ? AND name = ?').get(chatId, from)) {
|
|
138
|
+
throw new ApiError(403, `Forbidden: not a member of ${chatId}`)
|
|
139
|
+
}
|
|
140
|
+
return chatId
|
|
141
|
+
}
|
|
142
|
+
if (!NAME_RE.test(chatId) || !identityExists(chatId)) throw bad('chat not found')
|
|
143
|
+
if (chatId === from) throw bad('cannot message yourself')
|
|
144
|
+
return chatId
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const COORDINATOR_PAIR_MAX = 60
|
|
148
|
+
const COORDINATOR_AUTO_MAX = 10
|
|
149
|
+
const REPORTS = ['done', 'blocked', 'failed', 'question']
|
|
150
|
+
|
|
151
|
+
// A sender's signature: carried as it came, never read here.
|
|
152
|
+
function sigParam(v) {
|
|
153
|
+
if (v == null || v === '') return null
|
|
154
|
+
if (typeof v !== 'string' || !/^[A-Za-z0-9_-]{1,1024}$/.test(v)) throw bad('invalid pisha_sig')
|
|
155
|
+
return v
|
|
156
|
+
}
|
|
157
|
+
// What a text costs the disk: its bytes (a character can take four), in the
|
|
158
|
+
// message and again in each recipient's queue. The budget in characters
|
|
159
|
+
// doesn't see either.
|
|
160
|
+
function spendStored(from, text, recipients) {
|
|
161
|
+
spendStorage('stored-text', from, Buffer.byteLength(text ?? '', 'utf8') * (1 + recipients.length), quota('stored_text_mb_hour', STORED_TEXT_MB_PER_HOUR) * 1024 ** 2)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Two coordinators can keep each other busy forever: each message wakes the
|
|
165
|
+
// other, in a group or edited too. So many an hour between each two, then the
|
|
166
|
+
// user decides. All checked before any is charged. (The plugin's own replies
|
|
167
|
+
// say they are, which a client can say of anything: a small budget apart.)
|
|
168
|
+
function spendCoordinatorPairs(from, target, auto = false) {
|
|
169
|
+
if (roleOf(from) !== 'coordinator') return
|
|
170
|
+
const pairs = recipientsOf(target, from).filter(r => roleOf(r) === 'coordinator').map(r => [r, linkKey(from, r).join('\0')])
|
|
171
|
+
const [bucket, max] = auto ? ['coordinators-auto', COORDINATOR_AUTO_MAX] : ['coordinators', COORDINATOR_PAIR_MAX]
|
|
172
|
+
for (const [other, key] of pairs) {
|
|
173
|
+
if (counted(bucket, key, 3600_000) >= max) throw new ApiError(429, `Too Many Requests: "${from}" and "${other}" (two coordinators) have sent each other ${max} messages in the last hour; no more for now, so two sessions can't keep each other going. Tell the user`, { parameters: { reason: 'coordinators_limit', retry_after: 3600 } })
|
|
174
|
+
}
|
|
175
|
+
for (const [, key] of pairs) allow(bucket, key, max, 3600_000)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function storeMessage(from, target, { text, replyTo, fileId, fileKind, system = false, auto = false, fyi = false, report = null, sig = null, hello = false }) {
|
|
179
|
+
if (text != null && typeof text !== 'string') throw bad('text must be a string')
|
|
180
|
+
// (Far too long is refused before the cleaning, which costs the whole text.)
|
|
181
|
+
if (text && text.length > MAX_TEXT * 2) throw bad(`message is too long (max ${MAX_TEXT} chars)`)
|
|
182
|
+
text = cleanText(text)
|
|
183
|
+
if (text && text.length > MAX_TEXT) throw bad(`message is too long (max ${MAX_TEXT} chars)`)
|
|
184
|
+
if (!text && !fileId) throw bad('message text is empty')
|
|
185
|
+
let reply = null
|
|
186
|
+
if (replyTo != null && replyTo !== '') {
|
|
187
|
+
reply = Number(replyTo)
|
|
188
|
+
// Only a message the sender can see: otherwise the reply would hand its
|
|
189
|
+
// text back (reply_to_message) to someone who never received it.
|
|
190
|
+
const replied = Number.isInteger(reply) ? db.prepare('SELECT * FROM messages WHERE id = ?').get(reply) : null
|
|
191
|
+
if (!replied || !canSeeMessage(from, replied)) throw bad('message to be replied not found')
|
|
192
|
+
}
|
|
193
|
+
// A standalone session (role "solo") is outside every squad: it neither
|
|
194
|
+
// sends nor takes messages.
|
|
195
|
+
if (!system && roleOf(from) === 'solo') throw new ApiError(403, 'Forbidden: this is a standalone session: it does not message other sessions')
|
|
196
|
+
if (!system && !target.startsWith('#') && roleOf(target) === 'solo') throw new ApiError(403, `Forbidden: "${target}" is a standalone Claude Code session: it does not take messages from other sessions`)
|
|
197
|
+
if (!system) checkApproval(from, target, hello)
|
|
198
|
+
if (!system) spendCoordinatorPairs(from, target, auto)
|
|
199
|
+
const recipients = recipientsOf(target, from)
|
|
200
|
+
// (When it was last seen only for a session it is related to, as getChat.)
|
|
201
|
+
// A worker that stopped responding is sent to until it is announced DOWN:
|
|
202
|
+
// it gets the message when it comes back, or the notice lists it as dropped.
|
|
203
|
+
const offline = recipients.filter(r => !isOnline(r)).map(r => {
|
|
204
|
+
const left = downIn(r)
|
|
205
|
+
return {
|
|
206
|
+
name: r,
|
|
207
|
+
last_seen_at: presence.get(r)?.lastPollAt && related(from, r) ? unix(presence.get(r).lastPollAt) : null, // (no queue count per member)
|
|
208
|
+
queued: roleOf(r) !== 'worker' || left != null,
|
|
209
|
+
...(left != null && related(from, r) ? { down_in: left } : {}),
|
|
210
|
+
}
|
|
211
|
+
})
|
|
212
|
+
const dropped = offline.filter(o => !o.queued)
|
|
213
|
+
if (!system && !target.startsWith('#') && dropped.length) {
|
|
214
|
+
const o = dropped[0]
|
|
215
|
+
throw new ApiError(403, `Forbidden: "${o.name}" is a worker and is not connected right now; the message was not sent`,
|
|
216
|
+
{ parameters: { reason: 'recipient_offline', name: o.name, last_seen_at: o.last_seen_at } })
|
|
217
|
+
}
|
|
218
|
+
if (!system) { ensureRoom(); spendStored(from, text, recipients) }
|
|
219
|
+
const info = db.prepare('INSERT INTO messages (from_name, target, text, reply_to, file_id, file_kind, created_at, system, auto, fyi, report, sig) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
|
|
220
|
+
.run(from, target, text ?? null, reply, fileId ?? null, fileKind ?? null, now(), system ? 1 : 0, auto ? 1 : 0, fyi ? 1 : 0, report, sig)
|
|
221
|
+
const row = db.prepare('SELECT * FROM messages WHERE id = ?').get(info.lastInsertRowid)
|
|
222
|
+
const msg = messageObj(row)
|
|
223
|
+
broadcast('message', messageView(row))
|
|
224
|
+
const skip = new Set(dropped.map(o => o.name))
|
|
225
|
+
// (A notice about a worker counts as the worker's: it shares that worker's
|
|
226
|
+
// queue cap and goes when the worker is deleted.)
|
|
227
|
+
inTx(() => { for (const r of recipients) if (!skip.has(r)) pushUpdate(r, { message: msg }, from) })
|
|
228
|
+
// Tell the sender who isn't connected: queued (coordinators) or, in a group,
|
|
229
|
+
// skipped (workers).
|
|
230
|
+
return offline.length ? { ...msg, pisha_offline_recipients: offline } : msg
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const messagingMethods = {
|
|
234
|
+
|
|
235
|
+
sendMessage(name, p) {
|
|
236
|
+
rateLimit(name)
|
|
237
|
+
spendStorage('text', name, String(p.text ?? '').length)
|
|
238
|
+
const target = resolveTarget(p.chat_id, name)
|
|
239
|
+
const report = p.pisha_report == null || p.pisha_report === '' ? null : String(p.pisha_report)
|
|
240
|
+
if (report && !REPORTS.includes(report)) throw bad(`pisha_report must be one of: ${REPORTS.join(', ')}`)
|
|
241
|
+
return storeMessage(name, target, {
|
|
242
|
+
text: p.text,
|
|
243
|
+
replyTo: p.reply_to_message_id ?? p.reply_parameters?.message_id,
|
|
244
|
+
auto: p.pisha_auto === true,
|
|
245
|
+
fyi: p.pisha_fyi === true,
|
|
246
|
+
report,
|
|
247
|
+
sig: sigParam(p.pisha_sig),
|
|
248
|
+
hello: p.pisha_hello === true,
|
|
249
|
+
})
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
editMessageText(name, p) {
|
|
253
|
+
rateLimit(name)
|
|
254
|
+
const id = Number(p.message_id)
|
|
255
|
+
if (typeof p.text !== 'string' || !p.text) throw bad('text is required')
|
|
256
|
+
if (p.text.length > MAX_TEXT * 2) throw bad(`message is too long (max ${MAX_TEXT} chars)`)
|
|
257
|
+
// (Charged on the text as sent, before the cleaning and the lookup, which
|
|
258
|
+
// cost the same whether or not the edit goes through.)
|
|
259
|
+
spendStorage('text', name, p.text.length)
|
|
260
|
+
p.text = cleanText(p.text)
|
|
261
|
+
if (p.text.length > MAX_TEXT) throw bad(`message is too long (max ${MAX_TEXT} chars)`)
|
|
262
|
+
if (!p.text) throw bad('text is required')
|
|
263
|
+
const row = db.prepare('SELECT * FROM messages WHERE id = ?').get(id)
|
|
264
|
+
// Server notices carry the worker's name but are the server's words: not editable.
|
|
265
|
+
// (Only this identity's own messages: a name registered again can't edit the old one's.)
|
|
266
|
+
if (!row || row.system || row.from_name !== name || row.target !== String(p.chat_id) || row.created_at < identityCreatedAt(name)) throw bad('message to edit not found')
|
|
267
|
+
if (row.file_id) throw bad('there is no text in the message to edit')
|
|
268
|
+
if (row.text === p.text) throw bad('message is not modified')
|
|
269
|
+
// Still allowed to write there (a group you left is closed to you).
|
|
270
|
+
resolveTarget(row.target, name)
|
|
271
|
+
checkApproval(name, row.target, false)
|
|
272
|
+
ensureRoom()
|
|
273
|
+
spendCoordinatorPairs(name, row.target)
|
|
274
|
+
const recipients = recipientsOf(row.target, name)
|
|
275
|
+
spendStored(name, p.text, recipients)
|
|
276
|
+
db.prepare('UPDATE messages SET text = ?, edited_at = ?, sig = ? WHERE id = ?').run(p.text, now(), sigParam(p.pisha_sig), id)
|
|
277
|
+
const edited = db.prepare('SELECT * FROM messages WHERE id = ?').get(id)
|
|
278
|
+
const msg = messageObj(edited)
|
|
279
|
+
// Only to whoever can see the original, and not queued for workers that
|
|
280
|
+
// are offline (like a new message).
|
|
281
|
+
for (const r of recipients) {
|
|
282
|
+
if (!canSeeMessage(r, edited)) continue
|
|
283
|
+
if (!isOnline(r) && roleOf(r) === 'worker') continue
|
|
284
|
+
pushUpdate(r, { edited_message: msg }, name)
|
|
285
|
+
}
|
|
286
|
+
// The dashboard shows the new text too (what the recipients now have).
|
|
287
|
+
broadcast('edited', messageView(edited))
|
|
288
|
+
return msg
|
|
289
|
+
},
|
|
290
|
+
|
|
291
|
+
setMessageReaction(name, p) {
|
|
292
|
+
rateLimit(name)
|
|
293
|
+
const id = Number(p.message_id)
|
|
294
|
+
const row = db.prepare('SELECT * FROM messages WHERE id = ?').get(id)
|
|
295
|
+
// You can react to messages you received: DMs addressed to you, or groups you're in.
|
|
296
|
+
if (!row || row.from_name === name || !canSeeMessage(name, row)) throw bad('message not found')
|
|
297
|
+
const reaction = Array.isArray(p.reaction) ? p.reaction : []
|
|
298
|
+
const emoji = typeof reaction[0]?.emoji === 'string' ? cutText(cleanText(reaction[0].emoji.slice(0, 64)), 16) || null : null
|
|
299
|
+
if (emoji) {
|
|
300
|
+
db.prepare('INSERT OR REPLACE INTO reactions (message_id, from_name, emoji, created_at) VALUES (?, ?, ?, ?)').run(id, name, emoji, now())
|
|
301
|
+
} else {
|
|
302
|
+
db.prepare('DELETE FROM reactions WHERE message_id = ? AND from_name = ?').run(id, name)
|
|
303
|
+
}
|
|
304
|
+
// Counted as this sender's (the per-sender queue cap applies), and only to
|
|
305
|
+
// an author who can still see the message (not a later holder of the name).
|
|
306
|
+
if (row.from_name !== name && canSeeMessage(row.from_name, row)) {
|
|
307
|
+
pushUpdate(row.from_name, {
|
|
308
|
+
message_reaction: {
|
|
309
|
+
chat: chatFor(row.target, name),
|
|
310
|
+
message_id: id,
|
|
311
|
+
user: userObj(name),
|
|
312
|
+
date: unix(now()),
|
|
313
|
+
old_reaction: [],
|
|
314
|
+
new_reaction: emoji ? [{ type: 'emoji', emoji }] : [],
|
|
315
|
+
},
|
|
316
|
+
}, name)
|
|
317
|
+
}
|
|
318
|
+
return true
|
|
319
|
+
},
|
|
320
|
+
|
|
321
|
+
sendChatAction(name, p) {
|
|
322
|
+
readLimit(name, 'action')
|
|
323
|
+
resolveTarget(p.chat_id, name)
|
|
324
|
+
const action = ['typing', 'upload_document', 'upload_photo'].includes(p.action) ? p.action : 'typing'
|
|
325
|
+
chatActions.set(`${name}->${p.chat_id}`, { action, at: now() })
|
|
326
|
+
return true
|
|
327
|
+
},
|
|
328
|
+
|
|
329
|
+
getFile(name, p) {
|
|
330
|
+
readLimit(name)
|
|
331
|
+
const f = fileRow(String(p.file_id ?? ''))
|
|
332
|
+
if (!f || !canSeeFile(name, f.file_id)) throw bad('wrong file_id or the file is temporarily unavailable')
|
|
333
|
+
return { file_id: f.file_id, file_unique_id: f.file_unique_id, file_size: f.size, file_path: f.path }
|
|
334
|
+
},
|
|
335
|
+
|
|
336
|
+
// Groups are private: whoever creates one owns it, and others join only
|
|
337
|
+
// after the group's owner invites them (inviteToGroup).
|
|
338
|
+
joinGroup(name, p) {
|
|
339
|
+
groupLimit(name) // (their own budget: retried invites can't block sending)
|
|
340
|
+
const id = String(p.chat_id ?? '')
|
|
341
|
+
if (!GROUP_RE.test(id)) throw bad('group id must look like #name')
|
|
342
|
+
const members = () => db.prepare('SELECT name FROM group_members WHERE group_id = ? ORDER BY name').all(id).map(r => r.name)
|
|
343
|
+
const ownerOf = () => db.prepare('SELECT owner FROM groups WHERE id = ?').get(id)?.owner ?? null
|
|
344
|
+
// Not just "true": whether this created the group, who owns it and who is in
|
|
345
|
+
// it, so a session can tell if someone set the group up before it.
|
|
346
|
+
if (db.prepare('SELECT 1 FROM group_members WHERE group_id = ? AND name = ?').get(id, name)) return { created: false, owner: ownerOf(), members: members() }
|
|
347
|
+
const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(id)
|
|
348
|
+
// Every limit before anything is written (a refused join leaves no empty group behind).
|
|
349
|
+
// A session is in at most 50 groups.
|
|
350
|
+
if (db.prepare('SELECT COUNT(*) AS n FROM group_members WHERE name = ?').get(name).n >= 50) throw new ApiError(403, 'Forbidden: a session can be in at most 50 groups')
|
|
351
|
+
let created = false
|
|
352
|
+
if (!group) {
|
|
353
|
+
// (Whoever creates a name owns it: not one still waiting to be approved.
|
|
354
|
+
// It can still take part in the groups of others.)
|
|
355
|
+
if (db.prepare('SELECT needs_approval FROM identities WHERE name = ?').get(name)?.needs_approval) throw new ApiError(403, `Forbidden: "${name}" can't create a group until it is approved in the dashboard`, { parameters: { reason: 'approval_pending' } })
|
|
356
|
+
// At most 50 groups owned per session.
|
|
357
|
+
if (db.prepare('SELECT COUNT(*) AS n FROM groups WHERE owner = ?').get(name).n >= 50) throw new ApiError(403, 'Forbidden: a session can own at most 50 groups')
|
|
358
|
+
db.prepare('INSERT INTO groups (id, created_at, owner) VALUES (?, ?, ?)').run(id, now(), name)
|
|
359
|
+
created = true
|
|
360
|
+
} else if (!db.prepare('SELECT 1 FROM group_invites WHERE group_id = ? AND name = ?').get(id, name)) {
|
|
361
|
+
throw new ApiError(403, `Forbidden: ${id} is private; a member has to invite "${name}" first`, { parameters: { reason: 'not_invited' } })
|
|
362
|
+
} else if (db.prepare('SELECT COUNT(*) AS n FROM group_members WHERE group_id = ?').get(id).n >= 50) {
|
|
363
|
+
// At most 50 members: every message to a group is written once per member.
|
|
364
|
+
throw new ApiError(403, 'Forbidden: a group has at most 50 members')
|
|
365
|
+
}
|
|
366
|
+
db.prepare('INSERT OR IGNORE INTO group_members (group_id, name, joined_at) VALUES (?, ?, ?)').run(id, name, now())
|
|
367
|
+
db.prepare('DELETE FROM group_invites WHERE group_id = ? AND name = ?').run(id, name)
|
|
368
|
+
return { created, owner: created ? name : ownerOf(), members: members() }
|
|
369
|
+
},
|
|
370
|
+
|
|
371
|
+
inviteToGroup(name, p) {
|
|
372
|
+
groupLimit(name) // (their own budget: retried invites can't block sending)
|
|
373
|
+
const id = String(p.chat_id ?? '')
|
|
374
|
+
const who = String(p.name ?? '')
|
|
375
|
+
if (!GROUP_RE.test(id)) throw bad('group id must look like #name')
|
|
376
|
+
if (!NAME_RE.test(who) || !identityExists(who)) throw bad('no session with that name')
|
|
377
|
+
if (!db.prepare('SELECT 1 FROM group_members WHERE group_id = ? AND name = ?').get(id, name)) {
|
|
378
|
+
throw new ApiError(403, `Forbidden: not a member of ${id}`)
|
|
379
|
+
}
|
|
380
|
+
const owner = db.prepare('SELECT owner FROM groups WHERE id = ?').get(id)?.owner
|
|
381
|
+
if (owner && owner !== name) throw new ApiError(403, `Forbidden: only the group's owner ("${owner}") invites to ${id}`)
|
|
382
|
+
// (Already in it: nothing to invite to, and no way back in after leaving.)
|
|
383
|
+
if (db.prepare('SELECT 1 FROM group_members WHERE group_id = ? AND name = ?').get(id, who)) return true
|
|
384
|
+
db.prepare('INSERT INTO group_invites (group_id, name, invited_by, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (group_id, name) DO UPDATE SET invited_by = excluded.invited_by, created_at = excluded.created_at').run(id, who, name, now())
|
|
385
|
+
return true
|
|
386
|
+
},
|
|
387
|
+
|
|
388
|
+
leaveChat(name, p) {
|
|
389
|
+
rateLimit(name)
|
|
390
|
+
const id = String(p.chat_id ?? '')
|
|
391
|
+
// Only groups can be left (closing one deletes its messages: a DM's
|
|
392
|
+
// "chat id" is a session name and must never get here).
|
|
393
|
+
if (!GROUP_RE.test(id)) throw bad('chat_id must be a group (#name)')
|
|
394
|
+
if (!db.prepare('SELECT 1 FROM group_members WHERE group_id = ? AND name = ?').get(id, name)) throw bad('not a member of that group')
|
|
395
|
+
db.prepare('DELETE FROM group_members WHERE group_id = ? AND name = ?').run(id, name)
|
|
396
|
+
// (Whoever left can't keep bringing others in.)
|
|
397
|
+
db.prepare('DELETE FROM group_invites WHERE group_id = ? AND (invited_by = ? OR name = ?)').run(id, name, name)
|
|
398
|
+
// The last one out closes the group (it can be created again from scratch).
|
|
399
|
+
if (!db.prepare('SELECT 1 FROM group_members WHERE group_id = ?').get(id)) closeGroup(id)
|
|
400
|
+
else handOverGroup(id, name)
|
|
401
|
+
return true
|
|
402
|
+
},
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const chatActions = new Map()
|
|
406
|
+
|
|
407
|
+
function canSeeFile(name, fileId) {
|
|
408
|
+
const msgs = db.prepare('SELECT * FROM messages WHERE file_id = ?').all(fileId)
|
|
409
|
+
return msgs.some(m => canSeeMessage(name, m))
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// When a worker leaves (logout), its Claude Code closes, or it stops polling
|
|
413
|
+
// (crash, lost network), its coordinator gets one notice from the server. The
|
|
414
|
+
// worker's undelivered messages are dropped and listed, so they never turn up
|
|
415
|
+
// later as stale work.
|
|
416
|
+
function announce(worker, text) {
|
|
417
|
+
const row = db.prepare('SELECT role, coordinator FROM identities WHERE name = ?').get(worker)
|
|
418
|
+
if (row?.role !== 'worker' || !row.coordinator || roleOf(row.coordinator) !== 'coordinator') return
|
|
419
|
+
// A session picks its coordinator itself: notices only reach a coordinator
|
|
420
|
+
// that has written to this worker, so nobody can fill a coordinator's chat
|
|
421
|
+
// by declaring itself its worker.
|
|
422
|
+
const since = Math.max(identityCreatedAt(worker), identityCreatedAt(row.coordinator))
|
|
423
|
+
if (!db.prepare('SELECT 1 FROM messages WHERE from_name = ? AND target = ? AND system = 0 AND auto = 0 AND created_at >= ? LIMIT 1').get(row.coordinator, worker, since)) return
|
|
424
|
+
// At most 10 notices a minute per worker, so a session can't flood a coordinator.
|
|
425
|
+
if (!allow('notice', `${worker}->${row.coordinator}`, 10)) return
|
|
426
|
+
try {
|
|
427
|
+
storeMessage(worker, row.coordinator, { text, system: true })
|
|
428
|
+
} catch (err) {
|
|
429
|
+
log(`notice for ${row.coordinator} failed: ${err.message}`)
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
bus.on('notice', announce)
|
|
434
|
+
|
|
435
|
+
// An upload's type: only a plain "type/subtype" (no parameters, nothing
|
|
436
|
+
// long), or none — it is stored and sent on with the file.
|
|
437
|
+
const uploadMime = v => {
|
|
438
|
+
const t = String(v ?? '').split(';')[0].trim().toLowerCase()
|
|
439
|
+
return /^[a-z0-9][\w.+-]{0,60}\/[a-z0-9][\w.+-]{0,60}$/.test(t) && t !== 'application/octet-stream' ? t : null
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// Upload: raw body, params in the query string (sendDocument / sendPhoto).
|
|
443
|
+
const uploadsInFlight = new Map() // name -> { n, bytes }
|
|
444
|
+
let uploadBytesInFlight = 0 // all sessions' uploads still arriving
|
|
445
|
+
async function upload(name, kind, query, req, stillValid = () => {}) {
|
|
446
|
+
rateLimit(name)
|
|
447
|
+
const target = resolveTarget(query.get('chat_id'), name)
|
|
448
|
+
ensureRoom()
|
|
449
|
+
spendStorage('text', name, String(query.get('caption') ?? '').length) // a caption is message text
|
|
450
|
+
const fileName = (query.get('filename') ?? 'file').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120) || 'file'
|
|
451
|
+
// Disk budget: at most 500 MB of uploads per identity per hour, counting
|
|
452
|
+
// the ones still arriving; and at most two at a time.
|
|
453
|
+
const declared = Number(req.headers['content-length'])
|
|
454
|
+
if (!Number.isSafeInteger(declared) || declared <= 0) throw new ApiError(411, 'Length Required')
|
|
455
|
+
if (declared > MAX_FILE_BYTES) throw new ApiError(413, `Request Entity Too Large (max ${MAX_FILE_BYTES} bytes)`)
|
|
456
|
+
const flight = uploadsInFlight.get(name) ?? { n: 0, bytes: 0 }
|
|
457
|
+
const lastHour = db.prepare('SELECT COALESCE(SUM(size), 0) AS n FROM files WHERE owner = ? AND created_at > ?').get(name, now() - 3600_000).n
|
|
458
|
+
if (flight.n >= 2) throw new ApiError(429, 'Too Many Requests: two uploads at a time')
|
|
459
|
+
if (lastHour + flight.bytes + declared > UPLOAD_BUDGET_BYTES) throw new ApiError(429, 'Too Many Requests: upload budget for this hour used up')
|
|
460
|
+
// Per session, at most 2 GB kept (so one session can't fill the server's total alone).
|
|
461
|
+
if (db.prepare('SELECT COALESCE(SUM(size), 0) AS n FROM files WHERE owner = ?').get(name).n + declared > 2 * 1024 ** 3) throw new ApiError(429, 'Too Many Requests: this session keeps 2 GB of attachments already; old ones expire after 7 days')
|
|
462
|
+
if (db.prepare('SELECT COUNT(*) AS n FROM files WHERE owner = ?').get(name).n >= 10_000) throw new ApiError(429, 'Too Many Requests: this session keeps too many attachments; old ones expire after 7 days')
|
|
463
|
+
const allFiles = db.prepare('SELECT COALESCE(SUM(size), 0) AS n FROM files').get().n
|
|
464
|
+
// (Counting every session's uploads still arriving.)
|
|
465
|
+
if (allFiles + uploadBytesInFlight + declared > quota('max_files_gb', MAX_FILES_GB) * 1024 ** 3) throw new ApiError(507, 'Insufficient Storage: the server keeps no more attachments until old ones expire')
|
|
466
|
+
flight.n++; flight.bytes += declared
|
|
467
|
+
uploadsInFlight.set(name, flight)
|
|
468
|
+
uploadBytesInFlight += declared
|
|
469
|
+
const ext = (extname(fileName).toLowerCase().replace(/[^.a-z0-9]/g, '') || '.bin')
|
|
470
|
+
const fileId = `f_${randomBytes(12).toString('base64url')}`
|
|
471
|
+
const uniqueId = randomBytes(6).toString('hex')
|
|
472
|
+
const rel = `files/${fileId}${ext}`
|
|
473
|
+
// Written to disk as it arrives (not held in memory), and removed if
|
|
474
|
+
// anything below fails.
|
|
475
|
+
let size
|
|
476
|
+
try {
|
|
477
|
+
size = await readBodyToFile(req, Math.min(declared, MAX_FILE_BYTES), join(dataDir, rel))
|
|
478
|
+
} finally {
|
|
479
|
+
flight.n--; flight.bytes -= declared
|
|
480
|
+
uploadBytesInFlight -= declared
|
|
481
|
+
if (!flight.n) uploadsInFlight.delete(name)
|
|
482
|
+
}
|
|
483
|
+
try {
|
|
484
|
+
if (size === 0) throw bad('file is empty')
|
|
485
|
+
stillValid()
|
|
486
|
+
// (The recipient again too: it may have been deleted while the file arrived.)
|
|
487
|
+
resolveTarget(query.get('chat_id'), name)
|
|
488
|
+
} catch (err) { rmSync(join(dataDir, rel), { force: true }); throw err }
|
|
489
|
+
const realKind = kind === 'photo' && PHOTO_EXTS.has(ext) ? 'photo' : 'document'
|
|
490
|
+
db.prepare('INSERT INTO files (file_id, file_unique_id, path, name, mime, size, owner, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
|
|
491
|
+
.run(fileId, uniqueId, rel, fileName, uploadMime(req.headers['content-type']), size, name, now())
|
|
492
|
+
try {
|
|
493
|
+
return storeMessage(name, target, {
|
|
494
|
+
text: query.get('caption') || null,
|
|
495
|
+
replyTo: query.get('reply_to_message_id'),
|
|
496
|
+
fileId,
|
|
497
|
+
fileKind: realKind,
|
|
498
|
+
sig: sigParam(query.get('pisha_sig')),
|
|
499
|
+
})
|
|
500
|
+
} catch (err) {
|
|
501
|
+
// (Not sent: the file goes too.)
|
|
502
|
+
db.prepare('DELETE FROM files WHERE file_id = ?').run(fileId)
|
|
503
|
+
rmSync(join(dataDir, rel), { force: true })
|
|
504
|
+
throw err
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function cleanupMessages() {
|
|
509
|
+
const t = now()
|
|
510
|
+
const MESSAGE_TTL_MS = retainedMs(), FILE_TTL_MS = retainedMs()
|
|
511
|
+
// Groups nobody is in (left behind by older versions) are closed.
|
|
512
|
+
for (const g of db.prepare('SELECT id FROM groups WHERE NOT EXISTS (SELECT 1 FROM group_members WHERE group_id = groups.id)').all()) closeGroup(g.id)
|
|
513
|
+
db.prepare('DELETE FROM group_invites WHERE created_at < ?').run(t - INVITE_TTL_MS)
|
|
514
|
+
for (const f of db.prepare('SELECT file_id, path FROM files WHERE created_at < ?').all(t - FILE_TTL_MS)) {
|
|
515
|
+
try { rmSync(join(dataDir, f.path), { force: true }) } catch {}
|
|
516
|
+
db.prepare('DELETE FROM files WHERE file_id = ?').run(f.file_id)
|
|
517
|
+
}
|
|
518
|
+
db.prepare('DELETE FROM reactions WHERE message_id IN (SELECT id FROM messages WHERE created_at < ?)').run(t - MESSAGE_TTL_MS)
|
|
519
|
+
db.prepare('DELETE FROM reactions WHERE created_at < ? OR message_id NOT IN (SELECT id FROM messages)').run(t - MESSAGE_TTL_MS)
|
|
520
|
+
db.prepare('DELETE FROM reactions WHERE rowid <= (SELECT rowid FROM reactions ORDER BY rowid DESC LIMIT 1 OFFSET ?)').run(MAX_REACTIONS)
|
|
521
|
+
db.prepare('DELETE FROM messages WHERE created_at < ?').run(t - MESSAGE_TTL_MS)
|
|
522
|
+
// Over the cap: the oldest go first.
|
|
523
|
+
db.prepare('DELETE FROM messages WHERE id <= (SELECT id FROM messages ORDER BY id DESC LIMIT 1 OFFSET ?)').run(quota('max_messages', MAX_MESSAGES))
|
|
524
|
+
for (const [k, v] of chatActions) if (t - v.at > 10_000) chatActions.delete(k)
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
function messageView(row) {
|
|
528
|
+
const f = fileRow(row.file_id)
|
|
529
|
+
return {
|
|
530
|
+
id: row.id,
|
|
531
|
+
from: row.from_name,
|
|
532
|
+
target: row.target,
|
|
533
|
+
text: row.text != null ? (row.text.length > 4000 ? `${cutText(row.text, 4000)}…` : row.text) : null,
|
|
534
|
+
file: f ? { name: f.name, size: f.size, kind: row.file_kind } : null,
|
|
535
|
+
system: !!row.system,
|
|
536
|
+
...(row.fyi ? { fyi: true } : {}),
|
|
537
|
+
...(row.report ? { report: row.report } : {}),
|
|
538
|
+
created_at: row.created_at,
|
|
539
|
+
edited_at: row.edited_at ?? null,
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// From a task board to a coordinator: the server's own words, signed as
|
|
544
|
+
// such, from a sender no session can be (see server/boards).
|
|
545
|
+
const boardNotice = (coordinator, text) => storeMessage('pisha:board', coordinator, { text, system: true })
|
|
546
|
+
|
|
547
|
+
return {
|
|
548
|
+
boardNotice, messagingMethods, cleanupMessages, upload, uploadMime, canSeeFile, related, messageView, closeGroup,
|
|
549
|
+
handOverGroup, fileRow,
|
|
550
|
+
}
|
|
551
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { now, cleanText, bad, ApiError } from '../platform/index.js'
|
|
2
|
+
|
|
3
|
+
// A coordinator's plan: the tasks it is working through, as it tells them,
|
|
4
|
+
// for the user and the team's page. The whole list each time (it replaces the
|
|
5
|
+
// last); Pisha checks its shape and keeps it, and says whose word it is.
|
|
6
|
+
const STATES = ['todo', 'doing', 'done', 'blocked', 'waiting']
|
|
7
|
+
const MAX_TASKS = 100
|
|
8
|
+
const MAX_TITLE = 160
|
|
9
|
+
const MAX_NOTE = 240
|
|
10
|
+
const MAX_REF = 500
|
|
11
|
+
const PER_HOUR = 120
|
|
12
|
+
|
|
13
|
+
export function createPlans(platform, { sessions }) {
|
|
14
|
+
const { db, broadcast, allow, rateLimit, spendStorage } = platform
|
|
15
|
+
const { roleOf, NAME_RE } = sessions
|
|
16
|
+
|
|
17
|
+
db.exec('CREATE TABLE IF NOT EXISTS plans (coordinator TEXT PRIMARY KEY, title TEXT, tasks TEXT NOT NULL, updated_at INTEGER NOT NULL)')
|
|
18
|
+
|
|
19
|
+
const view = r => ({ coordinator: r.coordinator, title: r.title, tasks: JSON.parse(r.tasks), updated_at: r.updated_at })
|
|
20
|
+
const list = () => db.prepare('SELECT * FROM plans ORDER BY coordinator').all().map(view)
|
|
21
|
+
|
|
22
|
+
const short = (value, max, what) => {
|
|
23
|
+
const text = cleanText(String(value ?? '')).replace(/\s+/g, ' ').trim()
|
|
24
|
+
if (text.length > max) throw bad(`${what} is too long (max ${max} chars)`)
|
|
25
|
+
return text
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function setPlan(name, p) {
|
|
29
|
+
rateLimit(name)
|
|
30
|
+
const row = db.prepare('SELECT needs_approval FROM identities WHERE name = ?').get(name)
|
|
31
|
+
if (roleOf(name) !== 'coordinator' || row?.needs_approval) throw new ApiError(403, 'Forbidden: only an approved coordinator keeps a plan')
|
|
32
|
+
if (!Array.isArray(p.tasks)) throw bad('tasks must be the whole list: an array, empty to clear it')
|
|
33
|
+
if (p.tasks.length > MAX_TASKS) throw bad(`at most ${MAX_TASKS} tasks: put the small ones together`)
|
|
34
|
+
const tasks = p.tasks.map((t, i) => {
|
|
35
|
+
const where = `task ${i + 1}`
|
|
36
|
+
if (!t || typeof t !== 'object') throw bad(`${where} must be an object with title and state`)
|
|
37
|
+
const title = short(t.title, MAX_TITLE, `${where}'s title`)
|
|
38
|
+
if (!title) throw bad(`${where} needs a title`)
|
|
39
|
+
if (!STATES.includes(t.state)) throw bad(`${where}'s state must be one of: ${STATES.join(', ')} (waiting: it waits on the user's decision)`)
|
|
40
|
+
const who = t.who == null || t.who === '' ? null : String(t.who)
|
|
41
|
+
if (who && !NAME_RE.test(who)) throw bad(`${where}'s who must be a session's name`)
|
|
42
|
+
return { title, state: t.state, ...(who ? { who } : {}), ...(t.ref ? { ref: short(t.ref, MAX_REF, `${where}'s ref`) } : {}), ...(t.note ? { note: short(t.note, MAX_NOTE, `${where}'s note`) } : {}) }
|
|
43
|
+
})
|
|
44
|
+
// (Since when each task has been under way: kept while it stays so, under
|
|
45
|
+
// the same title and person, so the dashboard can say how long it has taken.)
|
|
46
|
+
const before = JSON.parse(db.prepare('SELECT tasks FROM plans WHERE coordinator = ?').get(name)?.tasks ?? '[]')
|
|
47
|
+
const key = t => `${t.who ?? ''}\u0000${t.title}`
|
|
48
|
+
const was = new Map(before.filter(t => t.state === 'doing' && t.since).map(t => [key(t), t.since]))
|
|
49
|
+
for (const t of tasks) if (t.state === 'doing') t.since = was.get(key(t)) ?? now()
|
|
50
|
+
const title = short(p.title, MAX_TITLE, 'title') || null
|
|
51
|
+
if (!allow('plan', name, PER_HOUR, 3600_000)) throw new ApiError(429, `Too Many Requests: at most ${PER_HOUR} changes an hour: send it when a task changes, not on every step`)
|
|
52
|
+
const json = JSON.stringify(tasks)
|
|
53
|
+
spendStorage('text', name, json.length)
|
|
54
|
+
if (tasks.length || title) db.prepare('INSERT INTO plans (coordinator, title, tasks, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(coordinator) DO UPDATE SET title = excluded.title, tasks = excluded.tasks, updated_at = excluded.updated_at').run(name, title, json, now())
|
|
55
|
+
else db.prepare('DELETE FROM plans WHERE coordinator = ?').run(name)
|
|
56
|
+
broadcast('plans', list())
|
|
57
|
+
const count = s => tasks.filter(t => t.state === s).length
|
|
58
|
+
return { tasks: tasks.length, done: count('done'), doing: count('doing'), blocked: count('blocked'), waiting: count('waiting'), todo: count('todo') }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// (A coordinator deleted: its plan goes with it.)
|
|
62
|
+
function forget(name) {
|
|
63
|
+
if (db.prepare('DELETE FROM plans WHERE coordinator = ?').run(name).changes) broadcast('plans', list())
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return { planMethods: { setPlan }, list, forget }
|
|
67
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createObservation } from './observation.js'
|