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
package/routes.js
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { statSync, createReadStream } from 'node:fs'
|
|
3
|
+
import {
|
|
4
|
+
guardRequest, sendJson, clientIp, readParams, bearer, own, sendError, VERSION, UI_FILE, VENDOR_FILES, APP_FILES,
|
|
5
|
+
MAX_JSON_BODY, cachedFile, pageHeaders, ApiError, allowServerWide, ipKey, sha256, refuseSocket, logError,
|
|
6
|
+
ALLOW_TOKEN_API, atLeast, pathTooLong, cleanText, trimSlashes,
|
|
7
|
+
} from './platform/index.js'
|
|
8
|
+
import {
|
|
9
|
+
INSTALLERS, installer, hostScript, hostSignature, checkEnrollRate, enrollmentKey, offeredCredential,
|
|
10
|
+
} from './machines/index.js'
|
|
11
|
+
|
|
12
|
+
const MAX_IDENTITIES = Number(process.env.PISHA_MAX_SESSIONS ?? 500)
|
|
13
|
+
|
|
14
|
+
export function createRoutes(server, companies, accounts) {
|
|
15
|
+
const { isServerToken, serverIdentity } = server
|
|
16
|
+
|
|
17
|
+
// Who calls /api: the server token, only until there are users (or if this
|
|
18
|
+
// server was started to keep it); otherwise a finished sign-in.
|
|
19
|
+
function actorOf(req, token) {
|
|
20
|
+
if (token) {
|
|
21
|
+
if (isServerToken(token) && (ALLOW_TOKEN_API || !accounts.hasUsers())) return { token: true }
|
|
22
|
+
throw new ApiError(401, 'Unauthorized')
|
|
23
|
+
}
|
|
24
|
+
return accounts.actorOf(req)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// The company a dashboard or an admin call is for, by the id it names.
|
|
28
|
+
function named(id) {
|
|
29
|
+
const company = companies.get(String(id))
|
|
30
|
+
if (!company) throw new ApiError(404, 'Not Found: no such company')
|
|
31
|
+
return company
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// A call about one company, by someone who is in it. For anyone else it doesn't
|
|
35
|
+
// exist. A role too low is told so, and what no table mentions nobody may do.
|
|
36
|
+
async function companyCall(company, what, req, res, url, actor) {
|
|
37
|
+
const role = actor.token ? 'owner' : accounts.roleIn(actor, company.id)
|
|
38
|
+
if (!role) throw new ApiError(404, 'Not Found: no such company')
|
|
39
|
+
req.actor = actor.token ? null : actor
|
|
40
|
+
const allow = needed => { if (!atLeast(role, needed)) throw new ApiError(403, `Forbidden: this needs the role ${needed} in this company`) }
|
|
41
|
+
// Checked again once the body has arrived: a request that started before
|
|
42
|
+
// someone lost access doesn't act after it.
|
|
43
|
+
const bodyOf = async needed => {
|
|
44
|
+
const params = await readParams(req, url)
|
|
45
|
+
if (!actor.token) {
|
|
46
|
+
accounts.actorOf(req)
|
|
47
|
+
if (!atLeast(accounts.roleIn(actor, company.id), needed)) throw new ApiError(403, `Forbidden: this needs the role ${needed} in this company`)
|
|
48
|
+
}
|
|
49
|
+
return params
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// What is written down: every change, by whom, with what it was about and
|
|
53
|
+
// never its content. (Not what only moves things around on the screen.)
|
|
54
|
+
const written = (action, params) => {
|
|
55
|
+
if (action === 'org/positions' || action === 'terminal/ticket' || action === 'hosts/personas') return
|
|
56
|
+
const target = params.session ?? params.term ?? params.name ?? params.host ?? params.coordinator ?? params.email ?? params.user ?? params.id ?? params.board ?? null
|
|
57
|
+
company.platform.audit(actor, action, target == null ? null : cleanText(String(target).slice(0, 400)).slice(0, 200), clientIp(req))
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const people = own(accounts.companyMethods, what) ?? own(companies.companyMethods, what)
|
|
61
|
+
if (people) {
|
|
62
|
+
if (req.method !== people.method) throw new ApiError(405, 'Method Not Allowed')
|
|
63
|
+
allow(people.role)
|
|
64
|
+
const params = req.method === 'POST' ? await bodyOf(people.role) : {}
|
|
65
|
+
// (The role as it is now, for what it may give.)
|
|
66
|
+
const actorRole = actor.token ? 'owner' : accounts.roleIn(actor, company.id)
|
|
67
|
+
if (req.method === 'POST') written(what, params)
|
|
68
|
+
if (people.streams) {
|
|
69
|
+
written(what, params)
|
|
70
|
+
// (Once it has started answering, an error can only cut it short.)
|
|
71
|
+
return await people.run({ company, actor, actorRole, params, req, res, url }).catch(err => { if (res.headersSent) res.destroy(); else throw err })
|
|
72
|
+
}
|
|
73
|
+
return sendJson(res, 200, { ok: true, result: await people.run({ company, actor, actorRole, params, req, url }) })
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const { dashboardActions, dashboardRoles, openStream, dashboardReads } = company.dashboard
|
|
77
|
+
if (req.method === 'POST') {
|
|
78
|
+
const act = own(dashboardActions, what)
|
|
79
|
+
if (!act) throw new ApiError(404, 'Not Found')
|
|
80
|
+
const needed = own(dashboardRoles.actions, what)
|
|
81
|
+
allow(needed)
|
|
82
|
+
const params = await bodyOf(needed)
|
|
83
|
+
const result = await act(params, req)
|
|
84
|
+
written(what, params)
|
|
85
|
+
return sendJson(res, 200, { ok: true, result })
|
|
86
|
+
}
|
|
87
|
+
if (req.method !== 'GET') throw new ApiError(405, 'Method Not Allowed')
|
|
88
|
+
if (what === 'stream') { allow(dashboardRoles.reads.stream); return openStream(req, res) }
|
|
89
|
+
const fn = own(dashboardReads, what)
|
|
90
|
+
if (!fn) throw new ApiError(404, 'Not Found')
|
|
91
|
+
allow(own(dashboardRoles.reads, what))
|
|
92
|
+
return sendJson(res, 200, { ok: true, result: fn(url.searchParams) })
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// /api about the server itself: companies and users.
|
|
96
|
+
async function platformCall(what, req, res, url, actor) {
|
|
97
|
+
if (what === 'companies') {
|
|
98
|
+
if (req.method !== 'GET') throw new ApiError(405, 'Method Not Allowed')
|
|
99
|
+
if (actor.token || actor.is_platform_admin) return sendJson(res, 200, { ok: true, result: companies.list() })
|
|
100
|
+
const mine = companies.list().filter(c => accounts.roleIn(actor, c.id))
|
|
101
|
+
return sendJson(res, 200, { ok: true, result: mine.map(c => ({ id: c.id, name: c.name, status: c.status })) })
|
|
102
|
+
}
|
|
103
|
+
// A company waiting to be deleted: its owners and administrators can bring it back.
|
|
104
|
+
if (what === 'companies/restore') {
|
|
105
|
+
if (req.method !== 'POST') throw new ApiError(405, 'Method Not Allowed')
|
|
106
|
+
const id = String((await readParams(req, url)).company ?? '')
|
|
107
|
+
if (!actor.token && !actor.is_platform_admin && accounts.roleIn(actor, id) !== 'owner') throw new ApiError(404, 'Not Found: no company waiting to be deleted with that id')
|
|
108
|
+
const restored = companies.restore(id)
|
|
109
|
+
accounts.audit(actor, 'company-restored', id, req)
|
|
110
|
+
return sendJson(res, 200, { ok: true, result: restored })
|
|
111
|
+
}
|
|
112
|
+
// People across companies: each sees and changes only the companies it manages.
|
|
113
|
+
const people = own(accounts.peopleMethods, what)
|
|
114
|
+
if (people) {
|
|
115
|
+
if (req.method !== people.method) throw new ApiError(405, 'Method Not Allowed')
|
|
116
|
+
const params = req.method === 'POST' ? await readParams(req, url) : {}
|
|
117
|
+
// (Who it is now, once the body has arrived.)
|
|
118
|
+
const who = actor.token ? actor : accounts.actorOf(req)
|
|
119
|
+
const list = companies.list().filter(c => c.status !== 'deleting')
|
|
120
|
+
const result = await people.run({ actor: who, params, req, list, companyOf: named })
|
|
121
|
+
// Written down in each company it changed too, under the name the
|
|
122
|
+
// company's own screen uses: its log is whole, whichever screen was used.
|
|
123
|
+
const touched = what === 'people/set' ? [[params.company, params.role == null ? 'members/remove' : 'members/role', params.user]]
|
|
124
|
+
: what === 'people/invite' ? (Array.isArray(params.roles) ? params.roles : []).map(r => [r?.company, 'members/invite', params.email])
|
|
125
|
+
: what === 'people/invitations/cancel' ? (result?.companies ?? []).map(c => [c, 'invitations/cancel', result.email])
|
|
126
|
+
: []
|
|
127
|
+
for (const [id, action, target] of touched) {
|
|
128
|
+
companies.get(String(id ?? ''))?.platform.audit(who, action, target == null ? null : cleanText(String(target).slice(0, 400)).slice(0, 200), clientIp(req))
|
|
129
|
+
}
|
|
130
|
+
return sendJson(res, 200, { ok: true, result: what === 'people/invitations/cancel' ? { cancelled: true } : result })
|
|
131
|
+
}
|
|
132
|
+
if (!actor.token && !actor.is_platform_admin) throw new ApiError(403, 'Forbidden: this is for administrators of the server')
|
|
133
|
+
if (what === 'machines') {
|
|
134
|
+
if (req.method !== 'GET') throw new ApiError(405, 'Method Not Allowed')
|
|
135
|
+
return sendJson(res, 200, { ok: true, result: companies.machines() })
|
|
136
|
+
}
|
|
137
|
+
if (what === 'companies/create') {
|
|
138
|
+
if (req.method !== 'POST') throw new ApiError(405, 'Method Not Allowed')
|
|
139
|
+
const params = await readParams(req, url)
|
|
140
|
+
if (!actor.token && !accounts.actorOf(req).is_platform_admin) throw new ApiError(403, 'Forbidden: this is for administrators of the server')
|
|
141
|
+
const made = companies.adminMethods.createCompany(params)
|
|
142
|
+
accounts.audit(actor, 'company-created', made.id, req, made.name)
|
|
143
|
+
return sendJson(res, 200, { ok: true, result: made })
|
|
144
|
+
}
|
|
145
|
+
const method = own(accounts.adminMethods, what)
|
|
146
|
+
if (!method) throw new ApiError(404, 'Not Found')
|
|
147
|
+
if (req.method !== method.method) throw new ApiError(405, 'Method Not Allowed')
|
|
148
|
+
const params = req.method === 'POST' ? await readParams(req, url) : {}
|
|
149
|
+
if (!actor.token && !accounts.actorOf(req).is_platform_admin) throw new ApiError(403, 'Forbidden: this is for administrators of the server')
|
|
150
|
+
return sendJson(res, 200, { ok: true, result: method.run({ actor, params, req }) })
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function handle(req, res) {
|
|
154
|
+
if (!guardRequest(req, res)) return
|
|
155
|
+
try {
|
|
156
|
+
if (pathTooLong(req.url)) throw new ApiError(414, 'URI Too Long')
|
|
157
|
+
// (Written out, as a relative reference would take //x/ for the host x.)
|
|
158
|
+
const target = req.url ?? '/'
|
|
159
|
+
const url = new URL(target.startsWith('/') ? `http://localhost${target}` : target, 'http://localhost')
|
|
160
|
+
// Never the page: there, its own address would read as another site's.
|
|
161
|
+
if (url.pathname.startsWith('//')) throw new ApiError(404, 'Not Found')
|
|
162
|
+
const path = trimSlashes(url.pathname) || '/'
|
|
163
|
+
|
|
164
|
+
if (path === '/health') return sendJson(res, 200, { ok: true, result: 'ok', version: VERSION })
|
|
165
|
+
|
|
166
|
+
// Dashboard page: public HTML; it asks for the server token and sends it
|
|
167
|
+
// with every /api call.
|
|
168
|
+
if (req.method === 'GET' && (path === '/' || path === '/ui')) {
|
|
169
|
+
const page = cachedFile(UI_FILE, body => ({ headers: pageHeaders(body) }))
|
|
170
|
+
if (!page) throw new ApiError(404, 'Not Found')
|
|
171
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': page.body.length, 'Cache-Control': 'no-store', ...page.headers })
|
|
172
|
+
return res.end(page.body)
|
|
173
|
+
}
|
|
174
|
+
// What the page is made of: only scripts and styles by a plain name, from
|
|
175
|
+
// its own folder. (Public, like the page; not cached, so an update takes
|
|
176
|
+
// effect at once and the parts of a page are never from two versions.)
|
|
177
|
+
const uiFile = req.method === 'GET' ? /^\/ui\/([a-z0-9-]+)\.(js|css)$/.exec(path) : null
|
|
178
|
+
if (uiFile) {
|
|
179
|
+
const f = cachedFile(new URL(`./ui/${uiFile[1]}.${uiFile[2]}`, import.meta.url))
|
|
180
|
+
if (!f) throw new ApiError(404, 'Not Found')
|
|
181
|
+
res.writeHead(200, { 'Content-Type': uiFile[2] === 'js' ? 'text/javascript; charset=utf-8' : 'text/css; charset=utf-8', 'Content-Length': f.body.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' })
|
|
182
|
+
return res.end(f.body)
|
|
183
|
+
}
|
|
184
|
+
// The web terminal (xterm.js), served from here rather than a CDN, and
|
|
185
|
+
// what a phone needs to install the dashboard (its manifest and icons).
|
|
186
|
+
const fixed = req.method === 'GET' ? (Object.hasOwn(VENDOR_FILES, path) ? VENDOR_FILES[path] : Object.hasOwn(APP_FILES, path) ? APP_FILES[path] : null) : null
|
|
187
|
+
if (fixed) {
|
|
188
|
+
const [file, type] = fixed
|
|
189
|
+
const f = cachedFile(new URL(file, import.meta.url))
|
|
190
|
+
if (!f) throw new ApiError(404, 'Not Found')
|
|
191
|
+
res.writeHead(200, { 'Content-Type': type, 'Content-Length': f.body.length, 'Cache-Control': 'public, max-age=86400', 'X-Content-Type-Options': 'nosniff' })
|
|
192
|
+
return res.end(f.body)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// pisha-host: the program itself (public, like the dashboard page) and enrollment.
|
|
196
|
+
if (req.method === 'GET' && path === '/host/pisha-host.mjs') {
|
|
197
|
+
const f = hostScript()
|
|
198
|
+
if (!f) throw new ApiError(404, 'Not Found')
|
|
199
|
+
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Content-Length': f.body.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' })
|
|
200
|
+
return res.end(f.body)
|
|
201
|
+
}
|
|
202
|
+
// Its release signature, checked by pisha-host update with the key it
|
|
203
|
+
// already has: a server can't hand a machine a program of its own.
|
|
204
|
+
if (req.method === 'GET' && path === '/host/pisha-host.mjs.sig') {
|
|
205
|
+
const f = hostSignature()
|
|
206
|
+
if (!f) throw new ApiError(404, 'Not Found')
|
|
207
|
+
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': f.body.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' })
|
|
208
|
+
return res.end(f.body)
|
|
209
|
+
}
|
|
210
|
+
if (req.method === 'GET' && path.startsWith('/install/') && Object.hasOwn(INSTALLERS, path.slice('/install/'.length))) {
|
|
211
|
+
const f = installer(path.slice('/install/'.length))
|
|
212
|
+
if (!f) throw new ApiError(404, 'Not Found')
|
|
213
|
+
res.writeHead(200, { 'Content-Type': INSTALLERS[path.slice('/install/'.length)], 'Content-Length': f.body.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' })
|
|
214
|
+
return res.end(f.body)
|
|
215
|
+
}
|
|
216
|
+
// Proof that this is the server they remember (public, like the two above).
|
|
217
|
+
if (req.method === 'GET' && path === '/server-identity') {
|
|
218
|
+
if (!allowServerWide('server-identity', ipKey(clientIp(req)), 300)) throw new ApiError(429, 'Too Many Requests: retry in a minute')
|
|
219
|
+
return sendJson(res, 200, { ok: true, result: serverIdentity(url.searchParams.get('nonce')) })
|
|
220
|
+
}
|
|
221
|
+
if (path === '/host/enroll') {
|
|
222
|
+
if (req.method !== 'POST') throw new ApiError(405, 'Method Not Allowed')
|
|
223
|
+
checkEnrollRate(req)
|
|
224
|
+
const params = await readParams(req, url, 64 * 1024, { pool: 'public' })
|
|
225
|
+
const key = enrollmentKey(params.code)
|
|
226
|
+
const result = companies.forEnrollment(key).machines.enrollHost(params, req)
|
|
227
|
+
companies.enrolled(key)
|
|
228
|
+
return sendJson(res, 200, { ok: true, result })
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const token = bearer(req)
|
|
232
|
+
|
|
233
|
+
// A machine's secret stays in an Authorization header, which proxies hide
|
|
234
|
+
// from their logs: to connect, it trades it for a ticket of one use.
|
|
235
|
+
if (path === '/host/ticket') {
|
|
236
|
+
if (req.method !== 'POST') throw new ApiError(405, 'Method Not Allowed')
|
|
237
|
+
if (req.headers.origin) throw new ApiError(403, 'Forbidden')
|
|
238
|
+
const company = companies.of(token)
|
|
239
|
+
const host = token ? company.platform.db.prepare('SELECT id, public_key FROM hosts WHERE secret_hash = ?').get(sha256(token)) : null
|
|
240
|
+
if (!host) throw new ApiError(401, 'Unauthorized')
|
|
241
|
+
if (!company.platform.allow('hostticket', host.id, 60)) throw new ApiError(429, 'Too Many Requests: retry in a minute')
|
|
242
|
+
return sendJson(res, 200, { ok: true, result: company.machines.hostTicketAnswer(host, await readParams(req, url, 4096, { pool: 'public' })) })
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (path === '/bootstrap' || path.startsWith('/auth/')) return await accounts.handle(path, req, res, url)
|
|
246
|
+
|
|
247
|
+
if (path.startsWith('/api/')) {
|
|
248
|
+
// (Before a sign-in is finished too: the page needs to know what to ask for.)
|
|
249
|
+
if (path === '/api/me' && !token) return sendJson(res, 200, { ok: true, result: accounts.meAnswer(req) })
|
|
250
|
+
const actor = actorOf(req, token)
|
|
251
|
+
const what = path.slice('/api/'.length)
|
|
252
|
+
// /api/c/<company>/<what>.
|
|
253
|
+
if (what.startsWith('c/')) {
|
|
254
|
+
const m = /^c\/([^/]+)\/(.+)$/.exec(what)
|
|
255
|
+
if (!m) throw new ApiError(404, 'Not Found')
|
|
256
|
+
return await companyCall(named(m[1]), m[2], req, res, url, actor)
|
|
257
|
+
}
|
|
258
|
+
if (what === 'companies' || what.startsWith('companies/') || what === 'people' || what.startsWith('people/') || what === 'users' || what.startsWith('users/') || what === 'machines' || what === 'pending-links' || what === 'pending-links/cancel') return await platformCall(what, req, res, url, actor)
|
|
259
|
+
// Without a company: scripts with the server token, on the first one.
|
|
260
|
+
if (!actor.token) throw new ApiError(404, 'Not Found')
|
|
261
|
+
return await companyCall(companies.first(), what, req, res, url, actor)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Registration: the join token registers new names; the server token can
|
|
265
|
+
// also rotate an existing name's secret (reset).
|
|
266
|
+
if (path === '/register') {
|
|
267
|
+
const admin = isServerToken(token)
|
|
268
|
+
// (The server token says which company in the request; the join token is of one.)
|
|
269
|
+
const joining = admin ? null : companies.of(token)
|
|
270
|
+
if (!admin && !joining.platform.isJoinToken(token)) throw new ApiError(401, 'Unauthorized')
|
|
271
|
+
// New names: 10 a minute per address and 60 overall per company, and a cap
|
|
272
|
+
// in all, so per-session budgets can't be multiplied by registering more names.
|
|
273
|
+
if (!admin && (!allowServerWide('register-ip', ipKey(clientIp(req)), 10) || !joining.platform.allow('register', 'all', 60))) {
|
|
274
|
+
throw new ApiError(429, 'Too Many Requests: retry in a minute')
|
|
275
|
+
}
|
|
276
|
+
const roomForOne = () => {
|
|
277
|
+
if (!admin && joining.platform.db.prepare('SELECT COUNT(*) AS n FROM identities').get().n >= joining.platform.quota('max_sessions', MAX_IDENTITIES)) {
|
|
278
|
+
const max = joining.platform.quota('max_sessions', MAX_IDENTITIES)
|
|
279
|
+
throw new ApiError(403, `Forbidden: this server already has ${max} sessions; delete some in the dashboard (or raise PISHA_MAX_SESSIONS)`)
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
roomForOne()
|
|
283
|
+
const params = await readParams(req, url, admin ? MAX_JSON_BODY : 4096, admin ? undefined : { pool: 'public' })
|
|
284
|
+
roomForOne() // (others may have registered while this body arrived)
|
|
285
|
+
if (params.reset === true && !admin) {
|
|
286
|
+
throw new ApiError(403, 'Forbidden: only the server (admin) token can rotate an existing identity; delete the session from the dashboard and register it again, or ask the admin')
|
|
287
|
+
}
|
|
288
|
+
const target = admin && params.company != null ? named(params.company) : joining ?? companies.first()
|
|
289
|
+
return sendJson(res, 200, { ok: true, result: target.sessions.register(params.name, admin && params.reset === true, { joined: !admin }) })
|
|
290
|
+
}
|
|
291
|
+
// Admin: server token only. What is about one company says which (the first, if not).
|
|
292
|
+
if (path.startsWith('/admin/')) {
|
|
293
|
+
if (!isServerToken(token)) throw new ApiError(401, 'Unauthorized')
|
|
294
|
+
const method = path.slice('/admin/'.length)
|
|
295
|
+
const params = await readParams(req, url)
|
|
296
|
+
// (Once there are people, what is done with the token is written down.)
|
|
297
|
+
if (accounts.hasUsers()) accounts.audit({ token: true }, `admin-${method}`.slice(0, 60), params.company == null ? null : String(params.company).slice(0, 64), req)
|
|
298
|
+
if (method === 'recoverAccess') return sendJson(res, 200, { ok: true, result: accounts.recoverAccess(params, req) })
|
|
299
|
+
const overall = own(companies.adminMethods, method)
|
|
300
|
+
if (overall) return sendJson(res, 200, { ok: true, result: overall(params) })
|
|
301
|
+
const company = params.company != null ? named(params.company) : companies.first()
|
|
302
|
+
const fn = own(company.dashboard.adminMethods, method)
|
|
303
|
+
if (!fn) throw new ApiError(404, 'Not Found: method not found')
|
|
304
|
+
return sendJson(res, 200, { ok: true, result: fn(params) })
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Everything else: identity secret, in the company it says it is of.
|
|
308
|
+
const company = companies.of(token)
|
|
309
|
+
const { db, dataDir, readLimit, spendStorage } = company.platform
|
|
310
|
+
const { identityFromSecret, leases, notHolder, touch, readParamsAs, getUpdates } = company.sessions
|
|
311
|
+
const { canSeeFile, upload } = company.messaging
|
|
312
|
+
const name = identityFromSecret(token)
|
|
313
|
+
if (!name) throw new ApiError(401, 'Unauthorized')
|
|
314
|
+
// Once a session holds this name, only that session (its instance id,
|
|
315
|
+
// which the plugin keeps in memory) can act as it: a copy of
|
|
316
|
+
// identity.json alone can't speak for a coordinator. Another session can
|
|
317
|
+
// only take the name over by claiming it once the holder is gone.
|
|
318
|
+
const lease = leases.get(name)
|
|
319
|
+
// (claim, poll and release check the instance themselves.)
|
|
320
|
+
if (lease && path !== '/claimSession' && path !== '/getUpdates' && path !== '/releaseSession') {
|
|
321
|
+
const inst = String(req.headers['x-pisha-instance'] ?? '')
|
|
322
|
+
if (inst !== lease.instance) throw notHolder(name, inst)
|
|
323
|
+
}
|
|
324
|
+
// A session with a key acts only from the session id that proved it: its
|
|
325
|
+
// secret alone (a copy in a log, say) does nothing, connected or not.
|
|
326
|
+
const keyed = db.prepare('SELECT public_key, proven_instance FROM identities WHERE name = ?').get(name)
|
|
327
|
+
if (keyed?.public_key && path !== '/claimSession') {
|
|
328
|
+
const inst = String(req.headers['x-pisha-instance'] ?? '')
|
|
329
|
+
if (inst !== keyed.proven_instance) throw notHolder(name, inst)
|
|
330
|
+
}
|
|
331
|
+
touch(name)
|
|
332
|
+
|
|
333
|
+
if (req.method === 'GET' && path.startsWith('/file/')) {
|
|
334
|
+
readLimit(name, 'download')
|
|
335
|
+
let rel
|
|
336
|
+
try { rel = decodeURIComponent(path.slice('/file/'.length)) } catch { throw new ApiError(404, 'Not Found') }
|
|
337
|
+
const f = db.prepare('SELECT * FROM files WHERE path = ?').get(rel)
|
|
338
|
+
if (!f || !canSeeFile(name, f.file_id)) throw new ApiError(404, 'Not Found')
|
|
339
|
+
spendStorage('download', name, f.size, 2 * 1024 ** 3) // at most 2 GB of downloads an hour
|
|
340
|
+
const full = join(dataDir, f.path)
|
|
341
|
+
const st = statSync(full)
|
|
342
|
+
res.writeHead(200, {
|
|
343
|
+
'Content-Type': f.mime ?? 'application/octet-stream',
|
|
344
|
+
'Content-Length': st.size,
|
|
345
|
+
'X-Content-Type-Options': 'nosniff',
|
|
346
|
+
'Content-Disposition': 'attachment',
|
|
347
|
+
})
|
|
348
|
+
createReadStream(full).on('error', () => res.destroy()).pipe(res)
|
|
349
|
+
return
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Checked again once the body has arrived: a request that started before
|
|
353
|
+
// its session was disconnected, deleted or taken over by another session
|
|
354
|
+
// doesn't act after it.
|
|
355
|
+
const stillValid = () => {
|
|
356
|
+
if (identityFromSecret(token) !== name) throw new ApiError(401, 'Unauthorized')
|
|
357
|
+
const l = leases.get(name)
|
|
358
|
+
if (l && path !== '/claimSession' && path !== '/getUpdates' && path !== '/releaseSession' &&
|
|
359
|
+
String(req.headers['x-pisha-instance'] ?? '') !== l.instance) {
|
|
360
|
+
throw notHolder(name, String(req.headers['x-pisha-instance'] ?? ''))
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const method = path.slice(1)
|
|
364
|
+
if (method === 'sendDocument' || method === 'sendPhoto') {
|
|
365
|
+
if (req.method !== 'POST') throw new ApiError(405, 'Method Not Allowed')
|
|
366
|
+
const msg = await upload(name, method === 'sendPhoto' ? 'photo' : 'document', url.searchParams, req, stillValid)
|
|
367
|
+
return sendJson(res, 200, { ok: true, result: msg })
|
|
368
|
+
}
|
|
369
|
+
if (method === 'getUpdates') {
|
|
370
|
+
const params = await readParamsAs(name, req, url)
|
|
371
|
+
stillValid()
|
|
372
|
+
return getUpdates(name, params, res)
|
|
373
|
+
}
|
|
374
|
+
const fn = own(company.methods, method)
|
|
375
|
+
if (!fn) throw new ApiError(404, 'Not Found: method not found')
|
|
376
|
+
const params = await readParamsAs(name, req, url)
|
|
377
|
+
stillValid()
|
|
378
|
+
// A claim comes with its session id in the header too, like every later
|
|
379
|
+
// request: a plugin that doesn't send it (older than 0.0.2) would claim
|
|
380
|
+
// the name and then fail at everything — it is told now instead.
|
|
381
|
+
if (method === 'claimSession' && String(req.headers['x-pisha-instance'] ?? '') !== String(params.instance ?? '')) {
|
|
382
|
+
throw notHolder(name, String(req.headers['x-pisha-instance'] ?? ''))
|
|
383
|
+
}
|
|
384
|
+
return sendJson(res, 200, { ok: true, result: await fn(name, params) })
|
|
385
|
+
} catch (err) {
|
|
386
|
+
sendError(res, err)
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// A socket goes to the company whose ticket or secret it comes with, which
|
|
391
|
+
// does everything else about it.
|
|
392
|
+
function onUpgrade(req, socket, head) {
|
|
393
|
+
try {
|
|
394
|
+
const cred = offeredCredential(req)
|
|
395
|
+
const company = companies.all().find(c => c.machines.hasTicket(cred)) ?? companies.of(cred)
|
|
396
|
+
company.machines.onUpgrade(req, socket, head)
|
|
397
|
+
} catch (err) {
|
|
398
|
+
socket.on('error', () => {})
|
|
399
|
+
if (!(err instanceof ApiError)) logError(`bad upgrade request: ${err.message}`)
|
|
400
|
+
refuseSocket(socket, err instanceof ApiError ? `${err.code} Unavailable` : '500 Internal Server Error')
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
return { handle, onUpgrade }
|
|
405
|
+
}
|
package/server.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* pisha-server — the "Telegram" for Pisha.
|
|
4
|
+
*
|
|
5
|
+
* A small subset of the Telegram Bot API, shaped closely enough that Pisha
|
|
6
|
+
* plugin is a near-copy of the official Telegram channel plugin. Every Claude
|
|
7
|
+
* Code session is an identity (a "bot" that also acts as a "user" for others).
|
|
8
|
+
*
|
|
9
|
+
* Auth:
|
|
10
|
+
* - Server token (admin): the dashboard, /admin/* and rotating identities.
|
|
11
|
+
* - Join token: registers new names, nothing else.
|
|
12
|
+
* - Machine secret: pisha-host's link (/host/connect).
|
|
13
|
+
* - Identity secret: returned once by /register; every other call uses it.
|
|
14
|
+
* The sender of a message is always derived from the secret, never from
|
|
15
|
+
* a request field: sending as another name takes that name's secret (and,
|
|
16
|
+
* while its session holds the name, that session's instance id).
|
|
17
|
+
*
|
|
18
|
+
* Only Node built-ins: node:http, node:sqlite (Node >= 22.13).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
// This file only starts what is the whole server's. server/companies.js keeps
|
|
22
|
+
// the companies, and server/company.js joins the parts of one.
|
|
23
|
+
|
|
24
|
+
import { cleanupServerLimits, guarded, logError, openServerCredentials, startListening } from './platform/index.js'
|
|
25
|
+
import { createCompanies } from './companies.js'
|
|
26
|
+
import { createAccounts } from './accounts/index.js'
|
|
27
|
+
import { createRoutes } from './routes.js'
|
|
28
|
+
|
|
29
|
+
const credentials = openServerCredentials()
|
|
30
|
+
const companies = createCompanies(credentials)
|
|
31
|
+
const accounts = createAccounts(credentials, { control: companies.control, companyName: companies.nameOf, companyStatus: companies.statusOf, dropClients: companies.dropClients, cancelEnrollments: id => companies.get(id)?.machines.cancelEnrollments() })
|
|
32
|
+
const { handle, onUpgrade } = createRoutes(credentials, companies, accounts)
|
|
33
|
+
|
|
34
|
+
setInterval(guarded(cleanupServerLimits), 60 * 1000).unref()
|
|
35
|
+
|
|
36
|
+
// A bug reached by some request must not take the whole server down: logged.
|
|
37
|
+
// (Rate limited like every error line: nothing a client causes fills the disk.
|
|
38
|
+
// Set before any server starts, also while waiting for a certificate.)
|
|
39
|
+
// Before it is serving, a failure means it didn't start: it ends, with an
|
|
40
|
+
// error, so that whatever started it (systemd, Docker) knows.
|
|
41
|
+
let serving = false
|
|
42
|
+
const failed = what => err => { logError(`${what}: ${err?.stack ?? err}`); if (!serving) process.exit(1) }
|
|
43
|
+
process.on('uncaughtException', failed('uncaught'))
|
|
44
|
+
process.on('unhandledRejection', failed('unhandled rejection'))
|
|
45
|
+
|
|
46
|
+
const { servers } = await startListening(credentials, { handle, onUpgrade, nowServing: companies.nowServing, joinToken: companies.first().platform.joinToken })
|
|
47
|
+
serving = true
|
|
48
|
+
|
|
49
|
+
// Ctrl+C / SIGTERM: close right away. Dashboards keep a stream open (and
|
|
50
|
+
// reconnect), sessions keep a long poll open, and browsers keep idle
|
|
51
|
+
// keep-alive sockets: don't wait for any of them.
|
|
52
|
+
let stopping = false
|
|
53
|
+
function shutdown(signal) {
|
|
54
|
+
if (stopping) {
|
|
55
|
+
process.stderr.write('pisha-server: forced exit\n')
|
|
56
|
+
process.exit(1)
|
|
57
|
+
}
|
|
58
|
+
stopping = true
|
|
59
|
+
process.stderr.write(`\npisha-server: ${signal} received, shutting down…\n`)
|
|
60
|
+
companies.close()
|
|
61
|
+
for (const srv of servers) { srv.close(); srv.closeAllConnections?.() }
|
|
62
|
+
process.exit(0)
|
|
63
|
+
}
|
|
64
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'))
|
|
65
|
+
process.on('SIGINT', () => shutdown('SIGINT'))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createSessions } from './sessions.js'
|