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
@@ -0,0 +1,533 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import {
3
+ cleanText, cutText, bad, ApiError, guarded, sha256, now, unix, sendError, sendJson, readParams, AGENTS,
4
+ } from '../platform/index.js'
5
+
6
+ export function createSessions(platform) {
7
+ const { db, bus, readLimit, allow, takeChallenge, proofIsGood, quota, companyId, credentialPrefix, every } = platform
8
+
9
+ const MAX_UPDATES = Number(process.env.PISHA_MAX_UPDATES ?? 500_000) // undelivered updates kept, in all
10
+ const MAX_UPDATES_PER_SESSION = 10_000 // undelivered updates kept, per recipient
11
+ const UPDATE_TTL_MS = 24 * 60 * 60 * 1000 // like Telegram: unconfirmed updates kept 24h
12
+ const POLL_MAX_TIMEOUT_S = 50
13
+ const ONLINE_GRACE_MS = 15 * 1000 // gap allowed between two polls of a live plugin
14
+
15
+ // A session that stops polling (lost network, its machine asleep) is announced
16
+ // DOWN only after this long: a short network cut doesn't wake its coordinator
17
+ // twice (DOWN, then back online) nor drop what was waiting for it.
18
+ const LOST_GRACE_MS = Number(process.env.PISHA_LOST_GRACE_MS ?? 2 * 60_000)
19
+ const NAME_RE = /^[A-Za-z0-9_-]{1,32}$/
20
+
21
+ // The persona a session says it follows (at login): what its kind and name
22
+ // are, and its description, short. Like its role, the session's own word.
23
+ function personaOf(p) {
24
+ if (!p || typeof p !== 'object' || !['skill', 'agent'].includes(p.kind)) return null
25
+ const name = typeof p.name === 'string' ? cleanText(p.name.slice(0, 128)).replace(/\s+/g, ' ').trim().slice(0, 64) : ''
26
+ if (!name) return null
27
+ const description = typeof p.description === 'string' ? cleanText(p.description.slice(0, 600)).replace(/\s+/g, ' ').trim().slice(0, 300) : ''
28
+ return JSON.stringify({ kind: p.kind, name, description })
29
+ }
30
+ function personaView(name) {
31
+ try { return JSON.parse(db.prepare('SELECT persona FROM identities WHERE name = ?').get(name)?.persona ?? 'null') } catch { return null }
32
+ }
33
+
34
+ // joined: it came with the join token, not from the dashboard or its admin.
35
+ function register(name, reset, { joined = false } = {}) {
36
+ if (typeof name !== 'string' || !NAME_RE.test(name)) throw bad('name must match [A-Za-z0-9_-]{1,32}')
37
+ const existing = db.prepare('SELECT name FROM identities WHERE name = ?').get(name)
38
+ if (existing && !reset) {
39
+ throw new ApiError(409, `Conflict: identity "${name}" already registered. Use the existing secret, or register with reset: true to rotate it.`)
40
+ }
41
+ const secret = `sq_${credentialPrefix}${randomBytes(24).toString('base64url')}`
42
+ if (existing) {
43
+ db.prepare('UPDATE identities SET secret_hash = ?, needs_approval = 0, public_key = NULL, proven_instance = NULL WHERE name = ?').run(sha256(secret), name)
44
+ // A rotated identity must not keep a stale poller (or answer) alive.
45
+ dropAnswer(name); servedUpTo.delete(name)
46
+ const w = waiters.get(name)
47
+ if (w) finishPoll(w, conflict())
48
+ } else {
49
+ db.prepare('INSERT INTO identities (name, secret_hash, created_at, epoch, needs_approval) VALUES (?, ?, ?, ?, ?)').run(name, sha256(secret), now(), randomBytes(12).toString('hex'), joined ? 1 : 0)
50
+ }
51
+ return { name, secret }
52
+ }
53
+
54
+ function identityFromSecret(secret) {
55
+ if (!secret) return null
56
+ const row = db.prepare('SELECT name FROM identities WHERE secret_hash = ?').get(sha256(secret))
57
+ return row ? row.name : null
58
+ }
59
+
60
+ function identityExists(name) {
61
+ return !!db.prepare('SELECT 1 FROM identities WHERE name = ?').get(name)
62
+ }
63
+
64
+ // last_seen_at is written at most every 10 s per name (one database write per
65
+ // request would let a refused caller keep the database busy).
66
+ const lastTouched = new Map()
67
+ function touch(name) {
68
+ const t = now()
69
+ if (t - (lastTouched.get(name) ?? 0) < 10_000) return
70
+ lastTouched.set(name, t)
71
+ db.prepare('UPDATE identities SET last_seen_at = ? WHERE name = ?').run(t, name)
72
+ }
73
+
74
+ // pisha_identity: which registration of that name it is (sessions pin it:
75
+ // a name deleted and registered again by someone else is told apart).
76
+ const epochOf = name => db.prepare('SELECT epoch FROM identities WHERE name = ?').get(name)?.epoch ?? undefined
77
+ const userObj = name => ({ id: name, is_bot: false, first_name: name, username: name, pisha_identity: epochOf(name) })
78
+ const linkKey = (x, y) => (x < y ? [x, y] : [y, x])
79
+ const linked = (x, y) => !!db.prepare('SELECT 1 FROM squad_links WHERE a = ? AND b = ?').get(...linkKey(x, y))
80
+ const linksOf = name => db.prepare('SELECT a, b FROM squad_links WHERE a = ? OR b = ? ORDER BY a, b').all(name, name).map(r => (r.a === name ? r.b : r.a))
81
+
82
+ // A message is visible to whoever sent it, received it, or is in its group —
83
+ // and only from that identity's creation on: a name deleted and registered
84
+ // again doesn't inherit the old one's history.
85
+ const identityCreatedAt = name => db.prepare('SELECT created_at FROM identities WHERE name = ?').get(name)?.created_at ?? Infinity
86
+
87
+ const waiters = new Map() // name -> { res, timer, offset, limit }
88
+
89
+ const conflict = () => new ApiError(409, 'Conflict: terminated by other getUpdates request; make sure that only one pisha plugin instance is running for this name')
90
+
91
+ const pushCount = new Map()
92
+ const MAX_UPDATES_PER_SENDER = 500 // undelivered, per sender and recipient
93
+ function pushUpdate(recipient, payload, sender = null) {
94
+ db.prepare('INSERT INTO updates (recipient, payload, created_at, sender) VALUES (?, ?, ?, ?)').run(recipient, JSON.stringify(payload), now(), sender)
95
+ // One sender can't push out what others sent: its own oldest go first.
96
+ if (sender) db.prepare('DELETE FROM updates WHERE recipient = ? AND sender = ? AND update_id <= (SELECT update_id FROM updates WHERE recipient = ? AND sender = ? ORDER BY update_id DESC LIMIT 1 OFFSET ?)').run(recipient, sender, recipient, sender, MAX_UPDATES_PER_SENDER)
97
+ // A recipient that never picks them up keeps at most the newest
98
+ // MAX_UPDATES_PER_SESSION (checked every 500 updates, not on each one).
99
+ const n = (pushCount.get(recipient) ?? 0) + 1
100
+ pushCount.set(recipient, n % 500)
101
+ if (n >= 500) db.prepare('DELETE FROM updates WHERE recipient = ? AND update_id <= (SELECT update_id FROM updates WHERE recipient = ? ORDER BY update_id DESC LIMIT 1 OFFSET ?)').run(recipient, recipient, MAX_UPDATES_PER_SESSION)
102
+ const w = waiters.get(recipient)
103
+ if (w) {
104
+ const updates = readUpdates(recipient, w.offset, w.limit)
105
+ if (updates.length) finishPoll(w, null, updates)
106
+ }
107
+ }
108
+
109
+ // At most about 1 MB per answer (always at least one update): the plugin
110
+ // simply asks again for the rest.
111
+ const MAX_ANSWER_BYTES = 1024 * 1024
112
+ const servedUpTo = new Map() // name -> highest update_id already handed out
113
+ function readUpdates(recipient, offset, limit) {
114
+ const out = []
115
+ let bytes = 0
116
+ for (const r of db.prepare('SELECT update_id, payload FROM updates WHERE recipient = ? AND update_id >= ? ORDER BY update_id LIMIT ?').iterate(recipient, offset, limit)) {
117
+ const size = Buffer.byteLength(r.payload)
118
+ if (out.length && bytes + size > MAX_ANSWER_BYTES) break
119
+ bytes += size
120
+ out.push({ update_id: r.update_id, ...JSON.parse(r.payload) })
121
+ }
122
+ if (out.length) servedUpTo.set(recipient, Math.max(servedUpTo.get(recipient) ?? 0, out[out.length - 1].update_id))
123
+ return out
124
+ }
125
+ const lastAnswer = new Map() // name -> the last immediate answer (still being sent?)
126
+ function dropAnswer(name) {
127
+ const pa = lastAnswer.get(name)
128
+ if (pa && !pa.res.writableFinished && !pa.res.destroyed) { try { pa.res.destroy() } catch {} }
129
+ lastAnswer.delete(name)
130
+ }
131
+
132
+ function finishPoll(w, err, result = []) {
133
+ clearTimeout(w.timer)
134
+ if (waiters.get(w.name) === w) waiters.delete(w.name)
135
+ if (w.res.writableEnded) return
136
+ if (!err) markPolled(w.name)
137
+ if (err) sendError(w.res, err)
138
+ else sendJson(w.res, 200, { ok: true, result })
139
+ }
140
+
141
+ function getUpdates(name, params, res) {
142
+ const n = (v, d) => (Number.isFinite(Number(v)) ? Math.trunc(Number(v)) : d)
143
+ const offset = n(params.offset, 0)
144
+ const limit = Math.max(1, Math.min(n(params.limit, 100), 100))
145
+ const timeout = Math.max(0, Math.min(n(params.timeout, 0), POLL_MAX_TIMEOUT_S))
146
+
147
+ // Session lease: once a session holds the name, only that session (its
148
+ // instance) may poll; a caller without an instance is refused, so a copy of
149
+ // the secret can't read or drain its queue. Names nobody claimed get the
150
+ // plain Telegram behaviour below.
151
+ const instance = params.instance != null ? String(params.instance) : ''
152
+ if (instance && !/^[A-Za-z0-9_-]{8,64}$/.test(instance)) throw bad('invalid instance')
153
+ if (instance) checkLease(name, instance)
154
+ else if (leases.has(name)) throw new ApiError(409, `Conflict: "${name}" is held by a Pisha session`, { parameters: { reason: 'name_in_use' } })
155
+ if (timeout === 0) readLimit(name) // after the checks: a refused caller doesn't use the holder's budget
156
+
157
+ // Asking again for updates already handed out (offset at or below what was
158
+ // served) and getting them at once counts like a quick poll; a plugin
159
+ // working through its queue always asks for new ones and is never limited.
160
+ // Decided before reading anything.
161
+ const rereads = offset <= (servedUpTo.get(name) ?? -1) &&
162
+ !!db.prepare('SELECT 1 FROM updates WHERE recipient = ? AND update_id >= ? LIMIT 1').get(name, offset)
163
+ if (timeout !== 0 && rereads) readLimit(name, 'poll')
164
+ // An answer still being sent to this name: no second one meanwhile.
165
+ // (Only for the same session instance, and only for a short while: a
166
+ // connection that never finishes can't block the name.)
167
+ const pa = lastAnswer.get(name)
168
+ if (pa && pa.instance === instance && Date.now() - pa.at < 30_000 && !pa.res.writableFinished && !pa.res.destroyed && !pa.res.closed) {
169
+ throw new ApiError(429, 'Too Many Requests: the previous answer is still being sent')
170
+ }
171
+
172
+ // Like Telegram: an offset confirms every update below it.
173
+ if (offset > 0) db.prepare('DELETE FROM updates WHERE recipient = ? AND update_id < ?').run(name, offset)
174
+
175
+ // Newest poller wins; the previous one gets 409, exactly like Telegram.
176
+ // (With leases, both pollers belong to the same session.)
177
+ const prev = waiters.get(name)
178
+ if (prev) finishPoll(prev, conflict())
179
+
180
+ const updates = readUpdates(name, offset, limit)
181
+ if (updates.length || timeout === 0) {
182
+ markPolled(name)
183
+ // An earlier answer to this name still unread is dropped: a name never
184
+ // holds more than one unread answer on the server.
185
+ dropAnswer(name)
186
+ lastAnswer.set(name, { res, at: Date.now(), instance })
187
+ return sendJson(res, 200, { ok: true, result: updates })
188
+ }
189
+ markPolled(name)
190
+
191
+ const w = { name, res, offset, limit, timer: null }
192
+ w.timer = setTimeout(() => finishPoll(w, null, []), timeout * 1000)
193
+ res.on('close', () => {
194
+ clearTimeout(w.timer)
195
+ if (waiters.get(name) === w) waiters.delete(name)
196
+ // The plugin dropped the connection mid-poll: its session ended (or lost
197
+ // the network). Offline right away instead of after the grace window.
198
+ if (!res.writableEnded) presence.set(name, { ...(presence.get(name) ?? {}), lastPollAt: now(), disconnected: true, pollingSince: null })
199
+ })
200
+ waiters.set(name, w)
201
+ }
202
+
203
+ // Delivery rules (not part of the Bot API):
204
+ // - A worker only receives messages while it's connected. Sending to a
205
+ // disconnected worker is refused, so a task never waits in a queue for a
206
+ // session that may not come back; the sender can give it to someone else.
207
+ // - A coordinator always receives: messages to it are queued while it's away.
208
+ // - Sessions with no known role (plain Bot API clients) keep Telegram's
209
+ // behaviour: queued.
210
+ function roleOf(name) {
211
+ return db.prepare('SELECT role FROM identities WHERE name = ?').get(name)?.role ?? null
212
+ }
213
+
214
+ // A name taken with the join token could be one some worker is waiting for
215
+ // as its coordinator: whoever got there first would give it orders. So until
216
+ // it is approved in the dashboard it writes to nobody who follows it, or who
217
+ // might (a session that hasn't said yet), and those who follow it only greet it.
218
+ const approvalRow = name => db.prepare('SELECT needs_approval, role, coordinator, opened_role FROM identities WHERE name = ?').get(name)
219
+ const notApproved = name => new ApiError(403, `Forbidden: "${name}" has not been approved as a coordinator yet: the user must approve it in the dashboard (open that session: Approve as coordinator)`, { parameters: { reason: 'approval_pending' } })
220
+ function checkApproval(from, target, hello) {
221
+ if (target.startsWith('#')) {
222
+ // A group is a message to each member: the same rule, member by member.
223
+ for (const { name } of db.prepare('SELECT name FROM group_members WHERE group_id = ? AND name != ?').all(target, from)) checkApproval(from, name, false)
224
+ return
225
+ }
226
+ const f = approvalRow(from), t = approvalRow(target)
227
+ if (!f || !t) return
228
+ // (A worker whose coordinator was deleted still follows that name, in its own
229
+ // pins, and only the column was cleared: it might follow whoever takes it now.)
230
+ // (Opened as a worker and not logged in yet counts: it will follow someone.)
231
+ const isWorker = s => s.role === 'worker' || (s.role == null && s.opened_role === 'worker')
232
+ const mightFollow = (worker, name) => worker.coordinator === name || (isWorker(worker) && worker.coordinator == null)
233
+ if (f.needs_approval && (mightFollow(t, from) || (t.role == null && !t.opened_role))) throw notApproved(from)
234
+ if (t.needs_approval && mightFollow(f, target) && !hello) throw notApproved(target)
235
+ }
236
+ function approveSession(name) {
237
+ if (!identityExists(name)) throw bad('session not found')
238
+ db.prepare('UPDATE identities SET needs_approval = 0 WHERE name = ?').run(name)
239
+ bus.emit('session-changed', name)
240
+ return { session: name, approved: true }
241
+ }
242
+
243
+ const sessionMethods = {
244
+
245
+ getMe(name) {
246
+ readLimit(name)
247
+ return { ...userObj(name), is_bot: true }
248
+ },
249
+
250
+ // A session claims its name before polling. First come, first served: while
251
+ // the session holding the name is online, any other session is refused.
252
+ claimSession(name, p) {
253
+ const instance = String(p.instance ?? '')
254
+ if (!/^[A-Za-z0-9_-]{8,64}$/.test(instance)) throw bad('instance is required')
255
+ const lease = leases.get(name)
256
+ // A connected session keeps its name: nobody can take it over (not even
257
+ // with its identity secret). The dashboard admin can disconnect it.
258
+ // (Checked before the rate limit: a copy of the secret refused here must
259
+ // not use up the budget of the session that holds the name.)
260
+ if (lease && lease.instance !== instance && holdsName(name, lease)) throw nameInUse(name, lease)
261
+ // (The key too: a copy of the secret refused for lack of it must not use it up either.)
262
+ const provenKey = sessionKeyProved(name, instance, p)
263
+ if (!allow('claim', name, 20)) throw new ApiError(429, 'Too Many Requests: retry in a minute')
264
+ if (provenKey) db.prepare('UPDATE identities SET public_key = ?, proven_instance = ? WHERE name = ?').run(provenKey, instance, name)
265
+ // (solo: a plain Claude Code session opened from the dashboard, outside any squad.)
266
+ const role = ['coordinator', 'worker', 'solo'].includes(p.role) ? p.role : null
267
+ const coordinator = role === 'worker' && NAME_RE.test(String(p.coordinator ?? '')) ? String(p.coordinator) : null
268
+ if (role) db.prepare('UPDATE identities SET role = ?, coordinator = ?, persona = ? WHERE name = ?').run(role, coordinator, personaOf(p.persona), name)
269
+ // Which agent it is, as its plugin says (an older one says nothing: Claude Code).
270
+ if (AGENTS.includes(p.agent)) db.prepare('UPDATE identities SET agent = ? WHERE name = ?').run(p.agent, name)
271
+ const approval = approvalRow(name)
272
+ // (It may have just become one to approve, or to wait for.)
273
+ if (role && (role === 'coordinator' ? approval.needs_approval : coordinator && approvalRow(coordinator)?.needs_approval)) setImmediate(() => bus.emit('session-changed', role === 'coordinator' ? name : coordinator))
274
+ // An archived session that logs in again is active again.
275
+ if (db.prepare('UPDATE identities SET archived_at = NULL WHERE name = ? AND archived_at IS NOT NULL').run(name).changes) {
276
+ setImmediate(() => bus.emit('session-changed', name))
277
+ }
278
+ if (!lease || lease.instance !== instance) setLease(name, instance)
279
+ else delete lease.restoredUntil
280
+ markPolled(name) // a claim is a sign of life: don't let the down sweep fire before the first poll
281
+ return {
282
+ name, role, since: unix(leases.get(name).since),
283
+ // (What the server's notices to it are signed for.)
284
+ ...(credentialPrefix ? { company: companyId } : {}),
285
+ ...(role === 'coordinator' && approval.needs_approval ? { approval_pending: true } : {}),
286
+ ...(role === 'worker' && coordinator && approvalRow(coordinator)?.needs_approval ? { coordinator_pending: true } : {}),
287
+ }
288
+ },
289
+
290
+ // reason: 'logout' (the user left) or 'exit' (Claude Code is closing).
291
+ releaseSession(name, p) {
292
+ const lease = leases.get(name)
293
+ if (lease && lease.instance === String(p.instance ?? '')) {
294
+ if (!allow('release', name, 20)) throw new ApiError(429, 'Too Many Requests: retry in a minute')
295
+ if (!lease.downNotified) announceDown(name, p.reason === 'exit' ? 'exit' : 'logout')
296
+ dropLease(name)
297
+ const w = waiters.get(name)
298
+ if (w) finishPoll(w, null, [])
299
+ presence.set(name, { ...(presence.get(name) ?? {}), lastPollAt: now(), disconnected: true, pollingSince: null })
300
+ }
301
+ return true
302
+ },
303
+ }
304
+
305
+ // Presence: a plugin is "online" while it long-polls. It dies with its Claude
306
+ // Code session (stdin EOF), so online means the session is running.
307
+ const presence = new Map() // name -> { pollingSince, lastPollAt, disconnected }
308
+
309
+ // Leases: which session (plugin instance) holds each name. Kept in the
310
+ // database too: after a server restart, the names that were held stay
311
+ // reserved for their sessions for RESTART_GRACE_MS, so a copy of a secret
312
+ // can't grab a name while its session reconnects.
313
+ const leases = new Map() // name -> { instance, since, downNotified, restoredUntil? }
314
+ const RESTART_GRACE_MS = 2 * 60 * 1000
315
+ for (const r of db.prepare('SELECT name, instance, since FROM leases').all()) {
316
+ leases.set(r.name, { instance: r.instance, since: r.since, downNotified: false, restoredUntil: now() + RESTART_GRACE_MS })
317
+ }
318
+
319
+ function setLease(name, instance) {
320
+ dropAnswer(name) // a new holder starts clean (and an unread answer of the old one goes)
321
+ servedUpTo.delete(name)
322
+ const lease = { instance, since: now(), downNotified: false }
323
+ leases.set(name, lease)
324
+ db.prepare('INSERT OR REPLACE INTO leases (name, instance, since) VALUES (?, ?, ?)').run(name, instance, lease.since)
325
+ bus.emit('instance-started', name)
326
+ return lease
327
+ }
328
+
329
+ function dropLease(name) {
330
+ leases.delete(name)
331
+ db.prepare('DELETE FROM leases WHERE name = ?').run(name)
332
+ }
333
+
334
+ // The lease's session still has the name: it is online, or the server just
335
+ // restarted and it hasn't had time to reconnect.
336
+ function holdsName(name, lease) {
337
+ return isOnline(name) || (lease?.restoredUntil ?? 0) > now()
338
+ }
339
+
340
+ function nameInUse(name, lease) {
341
+ const p = presence.get(name)
342
+ const ago = p?.lastPollAt ? Math.round((now() - p.lastPollAt) / 1000) : null
343
+ return new ApiError(409, `Conflict: name "${name}" is in use by another active session (connected since ${new Date(lease.since).toISOString()}${ago != null ? `, last seen ${ago}s ago` : ''})`,
344
+ { parameters: { reason: 'name_in_use', since: unix(lease.since) } })
345
+ }
346
+
347
+ function kickHolder(name) {
348
+ const w = waiters.get(name)
349
+ if (w) finishPoll(w, new ApiError(409, `Conflict: name "${name}" was taken over by another session`, { parameters: { reason: 'taken_over' } }))
350
+ presence.set(name, { ...(presence.get(name) ?? {}), lastPollAt: now(), disconnected: true, pollingSince: null })
351
+ }
352
+
353
+ function checkLease(name, instance) {
354
+ const lease = leases.get(name)
355
+ if (!lease) {
356
+ setLease(name, instance)
357
+ return
358
+ }
359
+ if (lease.instance === instance) {
360
+ delete lease.restoredUntil
361
+ // Same session polling again after we announced it down (network blip).
362
+ if (lease.downNotified) {
363
+ lease.downNotified = false
364
+ db.prepare('INSERT OR REPLACE INTO leases (name, instance, since) VALUES (?, ?, ?)').run(name, lease.instance, lease.since)
365
+ bus.emit('notice', name, `🔌 ${name} is back online (same session).`)
366
+ }
367
+ return
368
+ }
369
+ if (holdsName(name, lease)) {
370
+ throw new ApiError(409, `Conflict: name "${name}" was taken over by another session`, { parameters: { reason: 'taken_over' } })
371
+ }
372
+ setLease(name, instance) // previous holder is gone
373
+ }
374
+
375
+ function announceDown(worker, reason) {
376
+ const lease = leases.get(worker)
377
+ if (lease) lease.downNotified = true
378
+ // Only a worker's queue is dropped (its tasks go back to the coordinator);
379
+ // what waits for a coordinator, or a session without a role, is kept.
380
+ if (roleOf(worker) !== 'worker') return
381
+ // Drop what the worker never picked up.
382
+ // Only the coordinator's own messages are quoted (the tasks to reassign),
383
+ // at most 10; anything else (other sessions, groups) is only counted: a
384
+ // notice must not show the coordinator what it couldn't see. Only those
385
+ // few rows are read (a queue can hold thousands).
386
+ const coord = db.prepare('SELECT coordinator FROM identities WHERE name = ?').get(worker)?.coordinator
387
+ const total = db.prepare('SELECT COUNT(*) AS n FROM updates WHERE recipient = ?').get(worker).n
388
+ const coordRows = coord ? db.prepare('SELECT payload FROM updates WHERE recipient = ? AND sender = ? ORDER BY update_id LIMIT 11').all(worker, coord) : []
389
+ const coordCount = coord ? db.prepare('SELECT COUNT(*) AS n FROM updates WHERE recipient = ? AND sender = ?').get(worker, coord).n : 0
390
+ db.prepare('DELETE FROM updates WHERE recipient = ?').run(worker)
391
+ const fromCoord = coordRows.map(u => JSON.parse(u.payload).message).filter(m => m && !m.pisha_notice && m.chat?.type === 'private')
392
+ const msgs = { length: total }
393
+ const others = total - coordCount
394
+ // Quoted as data: this text was written by the sender, not by the server.
395
+ const lost = fromCoord.slice(0, 10)
396
+ .map(m => `${JSON.stringify(cutText((m.text ?? m.caption ?? '(attachment)').replace(/\s+/g, ' '), 120))}`)
397
+ if (coordCount > 10) lost.push(`and ${coordCount - 10} more of yours`)
398
+ if (others) lost.push(`and ${others} from other sessions or groups`)
399
+ const what = {
400
+ logout: `🔌 ${worker} left Pisha (logout).`,
401
+ exit: `🔌 ${worker} disconnected: its Claude Code session was closed.`,
402
+ lost: `⚠️ ${worker} is DOWN: it stopped responding (lost connection or its machine went down).`,
403
+ }[reason]
404
+ const parts = [what]
405
+ if (msgs.length) parts.push(`It never picked up ${msgs.length} message(s), which were dropped: ${lost.join('; ')}.`)
406
+ parts.push('If it had a task in progress, it will not finish it: consider reassigning it to another active worker.')
407
+ bus.emit('notice', worker, parts.join(' '))
408
+ }
409
+
410
+ // Leases whose holder stopped polling without releasing (crash, lost network).
411
+ // Sessions held before a restart keep their names for RESTART_GRACE_MS from
412
+ // when the server is actually answering again (not from when it started
413
+ // loading), and nobody is declared lost before that.
414
+ let serving = false
415
+ function nowServing() {
416
+ if (serving) return
417
+ serving = true
418
+ for (const lease of leases.values()) if (lease.restoredUntil) lease.restoredUntil = now() + RESTART_GRACE_MS
419
+ }
420
+ function sweepLeases() {
421
+ if (!serving) return
422
+ for (const [name, lease] of leases) {
423
+ if (!lease.downNotified && !holdsName(name, lease) && now() - (presence.get(name)?.lastPollAt ?? 0) >= LOST_GRACE_MS) {
424
+ announceDown(name, 'lost')
425
+ // Gone: a server restart doesn't keep the name for it any more (the same
426
+ // session can still come back: its instance is still known here).
427
+ db.prepare('DELETE FROM leases WHERE name = ?').run(name)
428
+ }
429
+ }
430
+ }
431
+ every(3000, guarded(sweepLeases))
432
+
433
+ function markPolled(name) {
434
+ const p = presence.get(name)
435
+ const back = !p || p.disconnected || now() - p.lastPollAt >= ONLINE_GRACE_MS
436
+ presence.set(name, { pollingSince: p && !p.disconnected && p.pollingSince ? p.pollingSince : now(), lastPollAt: now(), disconnected: false })
437
+ // An archived session that comes back (also without logging in again, after
438
+ // a network blip) is active again, as one that claims its name is.
439
+ if (back && db.prepare('UPDATE identities SET archived_at = NULL WHERE name = ? AND archived_at IS NOT NULL').run(name).changes) bus.emit('session-changed', name)
440
+ }
441
+
442
+ function isOnline(name) {
443
+ if (waiters.has(name)) return true
444
+ const p = presence.get(name)
445
+ return !!p && !p.disconnected && now() - p.lastPollAt < ONLINE_GRACE_MS
446
+ }
447
+
448
+ // A worker that stopped responding and isn't announced DOWN yet: seconds
449
+ // until it is (unless it comes back), or null.
450
+ function downIn(name) {
451
+ if (isOnline(name) || roleOf(name) !== 'worker') return null
452
+ const lease = leases.get(name)
453
+ if (!lease || lease.downNotified) return null
454
+ const at = Math.max((presence.get(name)?.lastPollAt ?? 0) + LOST_GRACE_MS, lease.restoredUntil ?? 0)
455
+ return Math.max(0, Math.ceil((at - now()) / 1000))
456
+ }
457
+
458
+ // A deleted session: nothing about it stays in memory, and a poll it left open ends.
459
+ function forgetSession(name) {
460
+ dropLease(name)
461
+ dropAnswer(name); servedUpTo.delete(name); lastTouched.delete(name); pushCount.delete(name)
462
+ presence.delete(name)
463
+ const w = waiters.get(name)
464
+ if (w) finishPoll(w, new ApiError(401, 'Unauthorized'))
465
+ }
466
+
467
+ function presenceOf(name) {
468
+ const online = isOnline(name)
469
+ const left = downIn(name)
470
+ const p = presence.get(name)
471
+ const lastMsg = db.prepare('SELECT MAX(created_at) AS t FROM messages WHERE from_name = ?').get(name)?.t
472
+ const pending = db.prepare('SELECT COUNT(*) AS n FROM updates WHERE recipient = ?').get(name)?.n ?? 0
473
+ return {
474
+ online,
475
+ connected_since: online && p?.pollingSince ? unix(p.pollingSince) : null,
476
+ last_seen_at: p?.lastPollAt ? unix(p.lastPollAt) : null,
477
+ last_message_at: lastMsg ? unix(lastMsg) : null,
478
+ pending_updates: pending,
479
+ ...(left != null ? { down_in: left } : {}),
480
+ }
481
+ }
482
+
483
+ function cleanupUpdates() {
484
+ db.prepare('DELETE FROM updates WHERE created_at < ?').run(now() - UPDATE_TTL_MS)
485
+ db.prepare('DELETE FROM updates WHERE update_id <= (SELECT update_id FROM updates ORDER BY update_id DESC LIMIT 1 OFFSET ?)').run(quota('max_updates', MAX_UPDATES))
486
+ }
487
+
488
+ const keyRefused = text => new ApiError(403, `Forbidden: ${text}`, { parameters: { reason: 'key_refused' } })
489
+
490
+ // A session's key, for a claim: remembered the first time, required after that.
491
+ // (Null: a plugin older than 0.0.7, for a name that never had a key.)
492
+ function sessionKeyProved(name, instance, p) {
493
+ const known = db.prepare('SELECT public_key FROM identities WHERE name = ?').get(name)?.public_key ?? null
494
+ if (p.signing_key == null) {
495
+ if (known) throw keyRefused(`the session "${name}" has a key, and this login doesn't prove it: update the Pisha plugin (0.0.7 or later) on that machine`)
496
+ return null
497
+ }
498
+ const offered = String(p.signing_key)
499
+ const fresh = takeChallenge(String(p.challenge ?? ''))
500
+ if (!fresh || !proofIsGood(offered, 'claim', name, p.challenge, instance, p.proof)) throw keyRefused('this login does not prove its key; try again')
501
+ if (known && known !== offered) throw keyRefused(`the session "${name}" has a different key on this server. If it really moved to another machine or lost its key, delete it in the dashboard and open it again; if not, something else may be using its secret`)
502
+ return offered
503
+ }
504
+
505
+ // A request for a held name without the holder's session id. With no id at
506
+ // all it is most likely a plugin older than 0.0.2: said so.
507
+ const notHolder = (name, inst) => inst
508
+ ? new ApiError(409, `Conflict: "${name}" is connected from another session`, { parameters: { reason: 'name_in_use' } })
509
+ : new ApiError(409, `Conflict: "${name}" is connected, and this request has no session id: update the Pisha plugin (0.0.2 or later) on that machine`, { parameters: { reason: 'plugin_outdated' } })
510
+ // A session's requests still sending their body: at most 8 at a time. While
511
+ // a session holds the name, requests without its session id (a copy of the
512
+ // secret) have their own 2, so they can never use up the holder's.
513
+ const bodiesInFlight = new Map()
514
+ async function readParamsAs(name, req, url) {
515
+ const lease = leases.get(name)
516
+ const other = lease && String(req.headers['x-pisha-instance'] ?? '') !== lease.instance
517
+ const key = other ? `${name}\0other` : name
518
+ const n = bodiesInFlight.get(key) ?? 0
519
+ if (n >= (other ? 2 : 8)) throw new ApiError(429, 'Too Many Requests: too many requests still sending their body')
520
+ bodiesInFlight.set(key, n + 1)
521
+ try { return await readParams(req, url) } finally {
522
+ const m = (bodiesInFlight.get(key) ?? 1) - 1
523
+ if (m > 0) bodiesInFlight.set(key, m); else bodiesInFlight.delete(key)
524
+ }
525
+ }
526
+
527
+ return {
528
+ sessionMethods, cleanupUpdates, nowServing, waiters, finishPoll, userObj, identityCreatedAt, linked,
529
+ NAME_RE, identityExists, roleOf, checkApproval, linkKey, isOnline, downIn, presence, pushUpdate,
530
+ presenceOf, personaView, register, approveSession, linksOf, forgetSession, leases, kickHolder,
531
+ announceDown, dropLease, keyRefused, holdsName, identityFromSecret, notHolder, touch, readParamsAs, getUpdates,
532
+ }
533
+ }
@@ -0,0 +1,26 @@
1
+ The dashboard's look (ds-base.css, ds-components.css and the screens'
2
+ styles) follows affectUI's free components, https://www.affectui.com,
3
+ which are under the MIT License. Only free (MIT) items were used; no
4
+ affectUI Pro item or its source is part of this project.
5
+
6
+ MIT License
7
+
8
+ Copyright (c) affectUI (https://www.affectui.com)
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.