pisha-server 0.0.12 → 0.0.13

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/company.js CHANGED
@@ -8,6 +8,7 @@ import { createOrganization } from './organization/index.js'
8
8
  import { createDashboard } from './dashboard/index.js'
9
9
  import { createBoards } from './boards/index.js'
10
10
  import { createUsage } from './usage/index.js'
11
+ import { createWebhooks } from './webhooks/index.js'
11
12
  import { upgradeStoredData } from './data-upgrade.js'
12
13
  import { cleanExports } from './company-export.js'
13
14
 
@@ -23,6 +24,7 @@ import { cleanExports } from './company-export.js'
23
24
  // machines pisha-host: joining, its link, terminals
24
25
  // organization squads, links between them, templates
25
26
  // boards task boards: people's and agents' tasks
27
+ // webhooks what other services send a department, and what came of it
26
28
  // dashboard what the dashboard reads and does
27
29
  export function createCompany(server, options) {
28
30
  const platform = createPlatform(server, options)
@@ -36,12 +38,14 @@ export function createCompany(server, options) {
36
38
  const organization = createOrganization(platform, { sessions, messaging, observation, machines })
37
39
  const boards = createBoards(platform, { sessions, messaging, members: options.members ?? (() => []) })
38
40
  const usage = createUsage(platform, { sessions, boards })
39
- const dashboard = createDashboard(platform, { sessions, messaging, inbox, plans, observation, machines, organization, permissions, boards, usage })
41
+ const webhooks = createWebhooks(platform, { sessions, messaging })
42
+ const dashboard = createDashboard(platform, { sessions, messaging, inbox, plans, observation, machines, organization, permissions, boards, usage, webhooks })
40
43
 
41
44
  // What a session can ask for, by its name in the request.
42
45
  const methods = {
43
46
  ...observation.observationMethods, ...machines.machineMethods, ...organization.organizationMethods,
44
47
  ...sessions.sessionMethods, ...messaging.messagingMethods, ...inbox.inboxMethods, ...plans.planMethods, ...boards.boardMethods,
48
+ ...webhooks.webhookMethods,
45
49
  }
46
50
 
47
51
  function cleanup() {
@@ -50,6 +54,7 @@ export function createCompany(server, options) {
50
54
  sessions.cleanupUpdates()
51
55
  observation.cleanupEvents()
52
56
  usage.cleanupUsage()
57
+ webhooks.cleanupWebhooks()
53
58
  platform.cleanupLimits()
54
59
  platform.cleanupAudit()
55
60
  platform.truncateLogHourly()
@@ -78,5 +83,5 @@ export function createCompany(server, options) {
78
83
  try { platform.db.close() } catch {}
79
84
  }
80
85
 
81
- return { id: options.id, platform, sessions, messaging, observation, machines, organization, boards, dashboard, methods, dropClients, close }
86
+ return { id: options.id, platform, sessions, messaging, observation, machines, organization, boards, webhooks, dashboard, methods, dropClients, close }
82
87
  }
@@ -2,7 +2,7 @@ import { rmSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { unix, now, guarded, bad, ApiError, VERSION, ROLES, AGENTS } from '../platform/index.js'
4
4
 
5
- export function createDashboard(platform, { sessions, observation, machines, messaging, inbox, plans, organization, permissions, boards, usage }) {
5
+ export function createDashboard(platform, { sessions, observation, machines, messaging, inbox, plans, organization, permissions, boards, usage, webhooks }) {
6
6
  const { rotateJoinToken, db, bus, broadcast, sseClients, truncateLog, dataDir, log, every } = platform
7
7
  const {
8
8
  register, approveSession, presenceOf, personaView, identityCreatedAt, identityExists, isOnline, linksOf,
@@ -167,6 +167,7 @@ export function createDashboard(platform, { sessions, observation, machines, mes
167
167
  'boards/task': q => boards.boardReads.task(q),
168
168
  'boards/trash': q => boards.boardReads.trash(q),
169
169
  usage: q => usage.usageReads.usage(q),
170
+ ...webhooks.webhookReads,
170
171
  events(q) {
171
172
  const limit = Math.max(1, Math.min(Number(q.get('limit') ?? 300) || 300, 1000))
172
173
  const before = Number(q.get('before') ?? Number.MAX_SAFE_INTEGER)
@@ -369,12 +370,13 @@ export function createDashboard(platform, { sessions, observation, machines, mes
369
370
  'inbox/answer': (p, req) => answerFromInbox(p, req.actor),
370
371
  'inbox/dismiss': (p, req) => dismissFromInbox(p, req.actor),
371
372
  ...Object.fromEntries(Object.entries(boards.boardActions).map(([k, fn]) => [k, (p, req) => fn(p, req.actor ?? null)])),
373
+ ...webhooks.webhookActions,
372
374
  }
373
375
 
374
376
  // Who may do each thing, at least. Whatever isn't here nobody may do, and the
375
377
  // server refuses to start (see the end): every new action says who it is for.
376
378
  const dashboardRoles = {
377
- reads: { inbox: 'observer', 'inbox/done': 'observer', timeline: 'observer', state: 'observer', events: 'observer', hosts: 'observer', messages: 'observer', stream: 'observer', boards: 'observer', 'boards/tasks': 'observer', 'boards/task': 'observer', 'boards/trash': 'manager', usage: 'observer' },
379
+ reads: { inbox: 'observer', 'inbox/done': 'observer', timeline: 'observer', state: 'observer', events: 'observer', hosts: 'observer', messages: 'observer', stream: 'observer', boards: 'observer', 'boards/tasks': 'observer', 'boards/task': 'observer', 'boards/trash': 'manager', usage: 'observer', webhooks: 'observer', 'webhooks/deliveries': 'observer', 'webhooks/delivery': 'observer' },
378
380
  actions: {
379
381
  'inbox/resolve': 'operator', 'inbox/read-all': 'operator', 'inbox/answer': 'operator', 'inbox/dismiss': 'operator', kick: 'operator', clear: 'operator', archive: 'operator', unarchive: 'operator',
380
382
  'terminals/open': 'operator', 'terminals/kill': 'operator', 'terminal/ticket': 'operator', 'hosts/personas': 'operator',
@@ -385,6 +387,7 @@ export function createDashboard(platform, { sessions, observation, machines, mes
385
387
  'permissions/save': 'manager', 'permissions/delete': 'manager', 'permissions/assign': 'manager',
386
388
  'tasks/create': 'operator', 'tasks/update': 'operator', 'tasks/comment': 'operator', 'tasks/notify': 'operator',
387
389
  'tasks/delete': 'manager', 'tasks/restore': 'manager', 'boards/create': 'manager', 'boards/update': 'manager', 'boards/delete': 'manager', 'boards/prefix': 'manager', 'boards/flow': 'manager', 'boards/github': 'manager', 'boards/github-off': 'manager', 'boards/github-merge': 'manager', 'boards/github-sync': 'operator', 'boards/github-watch': 'observer',
390
+ 'webhooks/create': 'manager', 'webhooks/update': 'manager', 'webhooks/secret': 'manager', 'webhooks/delete': 'manager', 'webhooks/test': 'manager', 'webhooks/redeliver': 'manager',
388
391
  },
389
392
  }
390
393
  for (const [table, roles] of [[dashboardActions, dashboardRoles.actions], [{ ...dashboardReads, stream: true }, dashboardRoles.reads]]) {
@@ -296,6 +296,8 @@ export function createMachines(platform, { sessions, observation, permissions })
296
296
  created_at: Number.isFinite(t?.created_at) ? t.created_at : null,
297
297
  // The permission profile it was opened with, by name (only for showing).
298
298
  profile: str(t?.profile, 40),
299
+ // Why its plugin didn't log in, as the machine read it (only for showing).
300
+ login_error: str(t?.login_error, 600),
299
301
  })).filter(t => t.id && NAME_RE.test(t.id))
300
302
  return {
301
303
  hostname: str(info.hostname, 100),
@@ -1,3 +1,3 @@
1
- export { createMessaging } from './messaging.js'
1
+ export { createMessaging, WEBHOOK_SENDER } from './messaging.js'
2
2
  export { createInbox } from './inbox.js'
3
3
  export { createPlans } from './plans.js'
@@ -1,10 +1,13 @@
1
1
  import { extname, join } from 'node:path'
2
- import { randomBytes } from 'node:crypto'
3
- import { rmSync } from 'node:fs'
2
+ import { createHash, randomBytes } from 'node:crypto'
3
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
4
4
  import {
5
5
  unix, now, cutText, cleanText, bad, ApiError, readBodyToFile,
6
6
  } from '../platform/index.js'
7
7
 
8
+ // The server's own sender of what a webhook brought (see server/webhooks).
9
+ export const WEBHOOK_SENDER = 'pisha:webhook'
10
+
8
11
  export function createMessaging(platform, { sessions }) {
9
12
  const {
10
13
  db, signAsServer, broadcast, inTx, bus, dataDir, allow, counted, rateLimit, spendStorage, ensureRoom, readLimit, groupLimit, quota,
@@ -225,6 +228,7 @@ export function createMessaging(platform, { sessions }) {
225
228
  // (A notice about a worker counts as the worker's: it shares that worker's
226
229
  // queue cap and goes when the worker is deleted.)
227
230
  inTx(() => { for (const r of recipients) if (!skip.has(r)) pushUpdate(r, { message: msg }, from) })
231
+ bus.emit('message-stored', row)
228
232
  // Tell the sender who isn't connected: queued (coordinators) or, in a group,
229
233
  // skipped (workers).
230
234
  return offline.length ? { ...msg, pisha_offline_recipients: offline } : msg
@@ -544,8 +548,30 @@ export function createMessaging(platform, { sessions }) {
544
548
  // such, from a sender no session can be (see server/boards).
545
549
  const boardNotice = (coordinator, text) => storeMessage('pisha:board', coordinator, { text, system: true })
546
550
 
551
+ // From a webhook to its department's coordinator: what an outside service
552
+ // sent, as it came, in an attached file; and the server's words about it
553
+ // (which name the file and its sha256: they are what is signed, so the
554
+ // plugin checks the file against them). See server/webhooks.
555
+ function webhookNotice(coordinator, textFor, { name, bytes }) {
556
+ ensureRoom()
557
+ if (db.prepare('SELECT COALESCE(SUM(size), 0) AS n FROM files').get().n + bytes.length > 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')
558
+ const fileId = `f_${randomBytes(12).toString('base64url')}`
559
+ const rel = `files/${fileId}.json`
560
+ mkdirSync(join(dataDir, 'files'), { recursive: true })
561
+ writeFileSync(join(dataDir, rel), bytes, { mode: 0o600, flag: 'wx' })
562
+ try {
563
+ db.prepare('INSERT INTO files (file_id, file_unique_id, path, name, mime, size, owner, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
564
+ .run(fileId, randomBytes(6).toString('hex'), rel, name.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120), 'application/json', bytes.length, WEBHOOK_SENDER, now())
565
+ return storeMessage(WEBHOOK_SENDER, coordinator, { text: textFor(fileId, createHash('sha256').update(bytes).digest('hex')), fileId, fileKind: 'document', system: true })
566
+ } catch (err) {
567
+ db.prepare('DELETE FROM files WHERE file_id = ?').run(fileId)
568
+ rmSync(join(dataDir, rel), { force: true })
569
+ throw err
570
+ }
571
+ }
572
+
547
573
  return {
548
- boardNotice, messagingMethods, cleanupMessages, upload, uploadMime, canSeeFile, related, messageView, closeGroup,
574
+ boardNotice, webhookNotice, messagingMethods, cleanupMessages, upload, uploadMime, canSeeFile, related, messageView, closeGroup,
549
575
  handOverGroup, fileRow,
550
576
  }
551
577
  }
@@ -126,8 +126,26 @@ export function createObservation(platform) {
126
126
  case 'session_end': a.tool = null; set('ended'); break
127
127
  }
128
128
  if (a.state !== 'waiting') a.waiting = null
129
+ // (Its prompt was answered, wherever: no longer with its coordinator.)
130
+ if (a.relayed_to && ((ev.kind === 'tool_end' && !ev.agent) || ev.kind === 'stop' || ev.kind === 'session_end' || (ev.kind === 'prompt' && !ev.channel))) a.relayed_to = null
129
131
  }
130
132
 
133
+ // A worker's permission prompt relayed to its coordinator (the plugin's
134
+ // "🔐 Permission:" message): the dashboard shows it as being decided there,
135
+ // until the call runs or the request is withdrawn. (Only what the dashboard
136
+ // shows: who may answer is the plugin's business.)
137
+ bus.on('message-stored', row => {
138
+ const text = String(row?.text ?? '')
139
+ if (!text.startsWith('🔐 Permission')) return
140
+ const coordinator = db.prepare("SELECT coordinator FROM identities WHERE name = ? AND role = 'worker'").get(row.from_name)?.coordinator
141
+ if (!coordinator || coordinator !== row.target) return
142
+ const a = activityOf(row.from_name)
143
+ const relayed = text.startsWith('🔐 Permission: ') ? coordinator : null
144
+ if ((a.relayed_to ?? null) === relayed) return
145
+ a.relayed_to = relayed
146
+ bus.emit('session-changed', row.from_name)
147
+ })
148
+
131
149
  // Per identity: at most 120 observe calls and 3000 events a minute.
132
150
  const observeLog = new Map() // name -> [{ t, n }]
133
151
 
@@ -182,6 +200,7 @@ export function createObservation(platform) {
182
200
  stored++
183
201
  } })
184
202
  if (stored) bus.emit('session-changed', name)
203
+ if (batch.length) bus.emit('observed', name, batch.map(({ ts, kind, rest }) => ({ ...rest, ts, kind })))
185
204
  if (tokens.length) bus.emit('tokens', name, tokens)
186
205
  return { stored: stored + tokens.length }
187
206
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pisha-server",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "Pisha: run teams of AI coding agents (Claude Code, Codex, Grok) from a self-hosted dashboard, with an inbox for your decisions",
5
5
  "keywords": [
6
6
  "pisha",
@@ -34,6 +34,7 @@
34
34
  "ui",
35
35
  "usage",
36
36
  "vendor",
37
+ "webhooks",
37
38
  "install",
38
39
  "pisha-host.mjs",
39
40
  "pisha-host.mjs.sig",
package/pisha-host.mjs CHANGED
@@ -39,7 +39,7 @@ import { fileURLToPath } from 'node:url'
39
39
  import { createCipheriv, createDecipheriv, createHash, createPrivateKey, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes, sign, verify } from 'node:crypto'
40
40
  import { promisify } from 'node:util'
41
41
 
42
- const VERSION = '0.0.12'
42
+ const VERSION = '0.0.13'
43
43
  // Who signs releases (scripts/release-sign.mjs): `update` only installs what
44
44
  // this key signed. Empty: this copy has no key to check with.
45
45
  const RELEASE_PUBLIC_KEY = 'MCowBQYDK2VwAyEA49ojJq4r4KLiWcRJiDxui2HzSZYpZA1qCBI4LLtOOyo'
@@ -562,7 +562,16 @@ function computeTrustedPath() {
562
562
  // A real node later on: the shim folders go after everything else.
563
563
  // None at all: they are left out (a shim that picks by folder never decides).
564
564
  const realNode = dirs.some(d => { const p = join(d, 'node'); try { accessSync(p, FS.X_OK) } catch { return false } return !dispatcherOf(p) && !untrustedExecutable(p) })
565
- return [...dirs, ...(realNode ? moved : [])].join(':') || '/usr/bin:/bin'
565
+ const path = [...dirs, ...(realNode ? moved : [])]
566
+ // No usable node on the PATH at all (a version manager's not loaded where
567
+ // this was started, a ~/.bashrc the installer couldn't write): the one this
568
+ // program runs on, which its launcher chose, or the plugin and its hooks
569
+ // couldn't start in any session.
570
+ if (!realNode) {
571
+ const own = dirname(process.execPath)
572
+ if (isAbsolute(own) && !untrustedFolder(own) && !untrustedExecutable(process.execPath) && !sessionRoots().some(r => within(realOr(own), r))) path.push(own)
573
+ }
574
+ return path.join(':') || '/usr/bin:/bin'
566
575
  }
567
576
  function computeTrustedFolders() {
568
577
  const roots = sessionRoots()
@@ -643,11 +652,13 @@ async function listTerminals() {
643
652
  agent: AGENT_IDS.includes(spec.agent) ? spec.agent : 'claude',
644
653
  profile: typeof spec.profile === 'string' ? spec.profile : null,
645
654
  created_at: Number(created) * 1000,
655
+ ...claudeCode.loginError(tname.slice(PREFIX.length), Number(created) * 1000),
646
656
  })
647
657
  }
648
658
  return list
649
659
  }
650
660
 
661
+
651
662
  // --- validation of what the server asks for -------------------------------------------
652
663
 
653
664
  function insideAllowed(real, folders) {
@@ -1278,12 +1289,15 @@ function sessionCommand(s, claude, dir, env) {
1278
1289
  if (s.personaInfo?.kind === 'agent') argv.push('--agent', s.personaInfo.name)
1279
1290
  // Its permission profile, as Claude Code's own rules: they are added to the
1280
1291
  // user's and the project's, and a rule that forbids wins over any that
1281
- // allows, wherever each one is.
1292
+ // allows, wherever each one is. Always with the session's own inbox, where
1293
+ // the plugin saves what other sessions and webhooks attach: it is outside
1294
+ // the working folder, and reading it must not wait for an absent user.
1295
+ // ("//" starts an absolute path in a rule.)
1282
1296
  const permissionsFile = join(dir, 'permissions.json')
1283
- if (s.permissions) {
1284
- writePrivate(permissionsFile, JSON.stringify({ permissions: { allow: s.permissions.allow, ask: s.permissions.ask, deny: s.permissions.deny } }, null, 2) + '\n')
1285
- argv.push('--settings', permissionsFile)
1286
- } else rmSync(permissionsFile, { force: true })
1297
+ const inbox = `Read(/${join(dir, 'inbox')}/**)`
1298
+ const p = s.permissions ?? { allow: [], ask: [], deny: [] }
1299
+ writePrivate(permissionsFile, JSON.stringify({ permissions: { allow: [inbox, ...p.allow], ask: p.ask, deny: p.deny } }, null, 2) + '\n')
1300
+ argv.push('--settings', permissionsFile)
1287
1301
  return argv
1288
1302
  }
1289
1303
 
@@ -1322,6 +1336,19 @@ export function answerLanded(screen, line) {
1322
1336
 
1323
1337
  const ASKING_ON_SCREEN = /^\s*❯\s*\d+\.\s|Esc to cancel|Enter to confirm/m
1324
1338
 
1339
+ // Why the plugin of a session didn't log in, if it said so since this start
1340
+ // (<state>/login-error.json): only the plugin's stderr knows otherwise, and
1341
+ // the dashboard would just show the session as disconnected.
1342
+ function loginError(name, since) {
1343
+ try {
1344
+ const file = join(pluginStateDir(name), 'login-error.json')
1345
+ const st = lstatSync(file)
1346
+ if (!st.isFile() || st.size > 4096 || st.mtimeMs < since - 2000) return {}
1347
+ const message = JSON.parse(readFileSync(file, 'utf8'))?.message
1348
+ return typeof message === 'string' && message ? { login_error: plain(message.replace(/\s+/g, ' ')).slice(0, 600) } : {}
1349
+ } catch { return {} }
1350
+ }
1351
+
1325
1352
  const claudeCode = {
1326
1353
  // Where the program is (checked, see claudeBinary), and which version.
1327
1354
  program: claudeBinary,
@@ -1342,6 +1369,8 @@ const claudeCode = {
1342
1369
  findPersona,
1343
1370
  personaPrompt,
1344
1371
  conversation: ownConversation,
1372
+ // Why its plugin didn't log in, if it said so (for the dashboard).
1373
+ loginError,
1345
1374
  // The Pisha plugin in its config: installed, and how it is set up.
1346
1375
  plugin: {
1347
1376
  status: pluginStatus,
@@ -1 +1 @@
1
- mV_Xs4Zu1h2EiHAlvzx7Lj7eRnI0RG1Y1z1kc0yxIGSQ3hdikrXgyfb4m6o1k9YvjpZPLFSx_j_xsHLwnQMqDw
1
+ ECnPFf64Gg00O6lfuvrVGylNFyyPcZxNnSjJXpPzQGJLYFkSHhpnI8q12o0voylVyULcoRHgj66Wrvx5S0h2Cg
package/platform/http.js CHANGED
@@ -86,6 +86,8 @@ const bodyPools = {
86
86
  main: { bytes: 0, cap: BODY_BYTES_IN_FLIGHT, free: 64 * 1024 },
87
87
  // (A registration's body, at most 4 KB, never counts: enrollments can't block it.)
88
88
  public: { bytes: 0, cap: 4 * 1024 * 1024, free: 4096, deadline: 10_000 },
89
+ // Webhooks from other services: anyone can send them too, and they are bigger.
90
+ hooks: { bytes: 0, cap: 16 * 1024 * 1024, free: 0, deadline: 10_000 },
89
91
  }
90
92
 
91
93
  // An upload, straight to its file: the same limits as readBody (size, idle
@@ -121,7 +123,7 @@ export function readBodyToFile(req, max, path) {
121
123
  req.on('close', () => { if (finish(false)) reject(new ApiError(400, 'Bad Request: connection closed')) })
122
124
  })
123
125
  }
124
- function readBody(req, max, { pool: poolName = 'main' } = {}) {
126
+ export function readBody(req, max, { pool: poolName = 'main' } = {}) {
125
127
  const pool = bodyPools[poolName]
126
128
  return new Promise((resolve, reject) => {
127
129
  if (Number(req.headers['content-length'] ?? 0) > max) {
package/platform/index.js CHANGED
@@ -29,6 +29,9 @@ export const FIRST_COMPANY = 'default'
29
29
  // session-changed (name) what the dashboard shows of it changed
30
30
  // notice (worker, text) its coordinator should hear this
31
31
  // context-cleared (name) /clear took effect in that session
32
+ // observed (name, events) what a session reported doing, as it was stored
33
+ // tokens (name, list) what it spent, and on what
34
+ // message-stored (row) a message, as it was stored
32
35
  export function createPlatform(server, { id, dir, quotas, routeEnrollment }) {
33
36
  // What repeats while this company runs, and stops with it.
34
37
  const timers = new Set()
package/routes.js CHANGED
@@ -3,7 +3,7 @@ import { statSync, createReadStream } from 'node:fs'
3
3
  import {
4
4
  guardRequest, sendJson, clientIp, readParams, bearer, own, sendError, VERSION, UI_FILE, VENDOR_FILES, APP_FILES,
5
5
  MAX_JSON_BODY, cachedFile, pageHeaders, ApiError, allowServerWide, ipKey, sha256, refuseSocket, logError,
6
- ALLOW_TOKEN_API, atLeast, pathTooLong, cleanText, trimSlashes,
6
+ ALLOW_TOKEN_API, atLeast, pathTooLong, cleanText, trimSlashes, countedServerWide,
7
7
  } from './platform/index.js'
8
8
  import {
9
9
  INSTALLERS, installer, hostScript, hostSignature, checkEnrollRate, enrollmentKey, offeredCredential,
@@ -228,6 +228,20 @@ export function createRoutes(server, companies, accounts) {
228
228
  return sendJson(res, 200, { ok: true, result })
229
229
  }
230
230
 
231
+ // A webhook from another service: anyone can send one, and only its
232
+ // secret makes it count (server/webhooks). Its path says nothing of
233
+ // the company: each one's webhooks are looked through.
234
+ if (path.startsWith('/hooks/')) {
235
+ if (req.method !== 'POST') throw new ApiError(405, 'Method Not Allowed')
236
+ const id = path.slice('/hooks/'.length)
237
+ const ip = ipKey(clientIp(req))
238
+ // (Guessing paths: a few misses a minute per address, then nothing.)
239
+ if (countedServerWide('webhook-miss', ip) >= 30) throw new ApiError(429, 'Too Many Requests: retry in a minute')
240
+ const company = companies.all().find(c => c.webhooks.has(id))
241
+ if (!company) { allowServerWide('webhook-miss', ip, 30); throw new ApiError(404, 'Not Found') }
242
+ return await company.webhooks.receive(id, req, res)
243
+ }
244
+
231
245
  const token = bearer(req)
232
246
 
233
247
  // A machine's secret stays in an Authorization header, which proxies hide
package/ui/addmachine.js CHANGED
@@ -86,6 +86,13 @@ export function renderAddMachine() {
86
86
  export const refreshAddMachine = () => { if (currentRoute().view === 'addmachine' && !$('addmachine').hidden) renderAddMachine() }
87
87
  // Done with it (a session or team opened from it, or cancelled): the next visit starts afresh.
88
88
  export const forgetAddMachine = () => { clearTimeout(draft?.slowTimer); draft = null }
89
+ // Coming to add a machine (the sidebar's "+", the palette, a link): one
90
+ // already added, or a code that expired unused, isn't shown again as if it
91
+ // were the new one. Halfway, it is kept. (Before the router draws the page:
92
+ // this module's listener was added first.)
93
+ window.addEventListener('hashchange', e => {
94
+ if (location.hash === '#/hosts/new' && !/#\/hosts\/new$/.test(e.oldURL) && draft && (draft.joined || expired())) forgetAddMachine()
95
+ })
89
96
 
90
97
  async function generate() {
91
98
  draft.generating = true
package/ui/back.js CHANGED
@@ -60,6 +60,7 @@ export function parentOf(r) {
60
60
  case 'addmachine': return '#/hosts'
61
61
  case 'boards': return null
62
62
  case 'usage': return null
63
+ case 'webhooks': return r.team ? `#/q/${enc(r.team)}` : null
63
64
  case 'board': return r.task ? `#/b/${r.board}` : '#/boards'
64
65
  case 'terminal': return `#/h/${enc(r.host)}`
65
66
  case 'session': {
@@ -92,6 +93,7 @@ export function placeName(hash) {
92
93
  case 'addmachine': return T.addTitle
93
94
  case 'boards': return T.boards
94
95
  case 'usage': return T.usage
96
+ case 'webhooks': return r.team ? T.whLogOf(team(r.team)) : T.whTitle
95
97
  case 'board': return state.boards.find(b => b.id === r.board)?.name ?? T.boards
96
98
  default: return T.leads
97
99
  }
package/ui/content.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { store } from './dom.js'
2
2
  import { T, COLLATOR } from './i18n.js'
3
- import { sessions, companyPref } from './state.js'
3
+ import { sessions, hosts, companyPref } from './state.js'
4
4
  import { esc, dur, now } from './format.js'
5
5
  import { nowPhrase } from './doing.js'
6
6
 
@@ -105,12 +105,24 @@ function md(src) {
105
105
  // The tool and its exact arguments, for a tooltip.
106
106
  const toolLine = t => [t?.name, t?.summary].filter(Boolean).join(' · ')
107
107
 
108
+ // Why the plugin of a session its machine runs didn't log in, as the machine
109
+ // read it (only on the machine the server opened it on).
110
+ export function loginError(s) {
111
+ const h = s?.host_id ? hosts.get(s.host_id) : null
112
+ return (h?.online && h.info?.terminals?.find(t => t.id === s.name)?.login_error) || null
113
+ }
114
+
108
115
  // session status (sidebar, pane headers, status bars). title: the detail
109
116
  // behind text, when there is more (the command it runs).
110
117
  export function status(s) {
111
118
  if (!s) return { dot: '', text: '' }
112
119
  const a = s.activity ?? {}
113
- if (!s.online) return { dot: '', text: T.offline(s.last_seen_at ? dur(now() - s.last_seen_at * 1000) : '—') }
120
+ if (!s.online) {
121
+ // Running on its machine, but its plugin said why it didn't log in.
122
+ const why = loginError(s)
123
+ if (why) return { dot: 'err', text: T.notJoined, title: why, why }
124
+ return { dot: '', text: T.offline(s.last_seen_at ? dur(now() - s.last_seen_at * 1000) : '—') }
125
+ }
114
126
  switch (a.state) {
115
127
  // (A phrase, not the command: the command itself is in the tooltip.)
116
128
  case 'tool': return { dot: 'ok pulse', text: `${nowPhrase(a.tool)} · ${dur(now() - (a.tool?.since ?? now()))}`, title: toolLine(a.tool) }