pisha-server 0.0.0-stage → 0.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/accounts/accounts.js +754 -0
- package/accounts/index.js +1 -0
- package/accounts/passwords.js +41 -0
- package/accounts/totp.js +54 -0
- package/boards/boards.js +1079 -0
- package/boards/github.js +212 -0
- package/boards/index.js +1 -0
- package/boards/sync.js +980 -0
- package/companies.js +294 -0
- package/company-export.js +101 -0
- package/company.js +79 -0
- package/dashboard/dashboard.js +407 -0
- package/dashboard/index.js +1 -0
- package/data-upgrade.js +69 -0
- package/install/linux.sh +181 -0
- package/install/macos.sh +121 -0
- package/install/windows.bat +54 -0
- package/machines/index.js +3 -0
- package/machines/machines.js +910 -0
- package/messaging/inbox.js +252 -0
- package/messaging/index.js +3 -0
- package/messaging/messaging.js +551 -0
- package/messaging/plans.js +67 -0
- package/observation/index.js +1 -0
- package/observation/observation.js +224 -0
- package/organization/index.js +1 -0
- package/organization/organization.js +218 -0
- package/package.json +54 -4
- package/permissions/index.js +1 -0
- package/permissions/permissions.js +211 -0
- package/pisha-host.mjs +3297 -0
- package/pisha-host.mjs.sig +1 -0
- package/platform/acme.js +207 -0
- package/platform/basics.js +14 -0
- package/platform/config.js +154 -0
- package/platform/control.js +93 -0
- package/platform/credentials.js +151 -0
- package/platform/database.js +251 -0
- package/platform/errors.js +13 -0
- package/platform/files.js +50 -0
- package/platform/http.js +207 -0
- package/platform/index.js +58 -0
- package/platform/limits.js +122 -0
- package/platform/listen.js +183 -0
- package/platform/roles.js +6 -0
- package/platform/stream.js +19 -0
- package/platform/text.js +83 -0
- package/platform/ws.js +186 -0
- package/routes.js +405 -0
- package/server.js +65 -0
- package/sessions/index.js +1 -0
- package/sessions/sessions.js +533 -0
- package/ui/LICENSE-affectui.txt +26 -0
- package/ui/addmachine.js +151 -0
- package/ui/api.js +20 -0
- package/ui/app.js +143 -0
- package/ui/attention.js +78 -0
- package/ui/back.js +166 -0
- package/ui/boards.js +958 -0
- package/ui/chat.js +388 -0
- package/ui/content.js +157 -0
- package/ui/dialogs.js +135 -0
- package/ui/doing.js +112 -0
- package/ui/dom.js +6 -0
- package/ui/ds-base.css +146 -0
- package/ui/ds-components.css +229 -0
- package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
- package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
- package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
- package/ui/format.js +25 -0
- package/ui/i18n.js +2093 -0
- package/ui/icons/apple-touch-icon.png +0 -0
- package/ui/icons/icon-192.png +0 -0
- package/ui/icons/icon-512.png +0 -0
- package/ui/icons/maskable-512.png +0 -0
- package/ui/icons.js +40 -0
- package/ui/inbox.js +535 -0
- package/ui/index.html +103 -0
- package/ui/machines.js +261 -0
- package/ui/manifest.webmanifest +16 -0
- package/ui/mosaic.js +189 -0
- package/ui/nav.js +141 -0
- package/ui/newteam.js +223 -0
- package/ui/org.js +653 -0
- package/ui/overlays.css +126 -0
- package/ui/palette.js +179 -0
- package/ui/people.js +370 -0
- package/ui/permissions.js +202 -0
- package/ui/qr.js +158 -0
- package/ui/router.js +171 -0
- package/ui/routes.js +46 -0
- package/ui/screen-boards.css +241 -0
- package/ui/screen-inbox.css +201 -0
- package/ui/screen-machines.css +76 -0
- package/ui/screen-mosaic.css +26 -0
- package/ui/screen-newteam.css +90 -0
- package/ui/screen-org.css +113 -0
- package/ui/screen-session.css +99 -0
- package/ui/screen-signin.css +28 -0
- package/ui/screen-team.css +80 -0
- package/ui/screen-teams.css +41 -0
- package/ui/session.js +42 -0
- package/ui/shell.css +122 -0
- package/ui/signin.js +120 -0
- package/ui/squads.js +370 -0
- package/ui/state.js +59 -0
- package/ui/stream.js +268 -0
- package/ui/styles.css +343 -0
- package/ui/team.js +115 -0
- package/ui/teams.js +58 -0
- package/ui/terminal.js +261 -0
- package/ui/theme.js +32 -0
- package/ui/timeline.js +163 -0
- package/ui/topbar.js +205 -0
- package/ui/voice-parse.js +98 -0
- package/ui/voice.js +320 -0
- package/vendor/InterVariable.woff2 +0 -0
- package/vendor/LICENSE-inter +92 -0
- package/vendor/LICENSE-xterm +21 -0
- package/vendor/README.md +8 -0
- package/vendor/addon-fit.js +2 -0
- package/vendor/xterm.css +218 -0
- package/vendor/xterm.js +2 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { now } from './basics.js'
|
|
4
|
+
import { logError } from './http.js'
|
|
5
|
+
|
|
6
|
+
export function openDatabase(dir) {
|
|
7
|
+
const db = new DatabaseSync(join(dir, 'pisha.db'))
|
|
8
|
+
db.exec(`
|
|
9
|
+
PRAGMA journal_mode = WAL;
|
|
10
|
+
PRAGMA synchronous = NORMAL;
|
|
11
|
+
PRAGMA foreign_keys = ON;
|
|
12
|
+
PRAGMA secure_delete = ON;
|
|
13
|
+
CREATE TABLE IF NOT EXISTS identities (
|
|
14
|
+
name TEXT PRIMARY KEY,
|
|
15
|
+
secret_hash TEXT NOT NULL UNIQUE,
|
|
16
|
+
created_at INTEGER NOT NULL,
|
|
17
|
+
last_seen_at INTEGER
|
|
18
|
+
);
|
|
19
|
+
CREATE TABLE IF NOT EXISTS groups (
|
|
20
|
+
id TEXT PRIMARY KEY,
|
|
21
|
+
created_at INTEGER NOT NULL
|
|
22
|
+
);
|
|
23
|
+
CREATE TABLE IF NOT EXISTS group_invites (
|
|
24
|
+
group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
|
|
25
|
+
name TEXT NOT NULL,
|
|
26
|
+
invited_by TEXT NOT NULL,
|
|
27
|
+
created_at INTEGER NOT NULL,
|
|
28
|
+
PRIMARY KEY (group_id, name)
|
|
29
|
+
);
|
|
30
|
+
CREATE TABLE IF NOT EXISTS group_members (
|
|
31
|
+
group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
|
|
32
|
+
name TEXT NOT NULL,
|
|
33
|
+
PRIMARY KEY (group_id, name)
|
|
34
|
+
);
|
|
35
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
36
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
37
|
+
from_name TEXT NOT NULL,
|
|
38
|
+
target TEXT NOT NULL,
|
|
39
|
+
text TEXT,
|
|
40
|
+
reply_to INTEGER,
|
|
41
|
+
file_id TEXT,
|
|
42
|
+
file_kind TEXT,
|
|
43
|
+
created_at INTEGER NOT NULL,
|
|
44
|
+
edited_at INTEGER
|
|
45
|
+
);
|
|
46
|
+
CREATE TABLE IF NOT EXISTS updates (
|
|
47
|
+
update_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
48
|
+
recipient TEXT NOT NULL,
|
|
49
|
+
payload TEXT NOT NULL,
|
|
50
|
+
created_at INTEGER NOT NULL
|
|
51
|
+
);
|
|
52
|
+
CREATE INDEX IF NOT EXISTS updates_recipient ON updates(recipient, update_id);
|
|
53
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
54
|
+
file_id TEXT PRIMARY KEY,
|
|
55
|
+
file_unique_id TEXT NOT NULL,
|
|
56
|
+
path TEXT NOT NULL,
|
|
57
|
+
name TEXT,
|
|
58
|
+
mime TEXT,
|
|
59
|
+
size INTEGER NOT NULL,
|
|
60
|
+
owner TEXT NOT NULL,
|
|
61
|
+
created_at INTEGER NOT NULL
|
|
62
|
+
);
|
|
63
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
64
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
65
|
+
session TEXT NOT NULL,
|
|
66
|
+
ts INTEGER NOT NULL,
|
|
67
|
+
kind TEXT NOT NULL,
|
|
68
|
+
data TEXT NOT NULL
|
|
69
|
+
);
|
|
70
|
+
CREATE INDEX IF NOT EXISTS events_session ON events(session, id);
|
|
71
|
+
CREATE TABLE IF NOT EXISTS hosts (
|
|
72
|
+
id TEXT PRIMARY KEY,
|
|
73
|
+
name TEXT NOT NULL,
|
|
74
|
+
secret_hash TEXT NOT NULL UNIQUE,
|
|
75
|
+
created_at INTEGER NOT NULL,
|
|
76
|
+
last_seen_at INTEGER,
|
|
77
|
+
info TEXT
|
|
78
|
+
);
|
|
79
|
+
CREATE TABLE IF NOT EXISTS host_enrollments (
|
|
80
|
+
code_hash TEXT PRIMARY KEY,
|
|
81
|
+
name TEXT NOT NULL,
|
|
82
|
+
created_at INTEGER NOT NULL,
|
|
83
|
+
expires_at INTEGER NOT NULL,
|
|
84
|
+
configure_plugin INTEGER NOT NULL DEFAULT 1
|
|
85
|
+
);
|
|
86
|
+
CREATE TABLE IF NOT EXISTS reactions (
|
|
87
|
+
message_id INTEGER NOT NULL,
|
|
88
|
+
from_name TEXT NOT NULL,
|
|
89
|
+
emoji TEXT NOT NULL,
|
|
90
|
+
created_at INTEGER NOT NULL,
|
|
91
|
+
PRIMARY KEY (message_id, from_name)
|
|
92
|
+
);
|
|
93
|
+
CREATE TABLE IF NOT EXISTS leases (
|
|
94
|
+
name TEXT PRIMARY KEY,
|
|
95
|
+
instance TEXT NOT NULL,
|
|
96
|
+
since INTEGER NOT NULL
|
|
97
|
+
);
|
|
98
|
+
CREATE TABLE IF NOT EXISTS squad_templates (
|
|
99
|
+
name TEXT PRIMARY KEY,
|
|
100
|
+
spec TEXT NOT NULL,
|
|
101
|
+
created_at INTEGER NOT NULL
|
|
102
|
+
);
|
|
103
|
+
-- What the dashboard says of a squad (its coordinator's name): a title,
|
|
104
|
+
-- its goal, and where its card is in the org chart.
|
|
105
|
+
CREATE TABLE IF NOT EXISTS squads (
|
|
106
|
+
coordinator TEXT PRIMARY KEY,
|
|
107
|
+
title TEXT,
|
|
108
|
+
goal TEXT,
|
|
109
|
+
x REAL,
|
|
110
|
+
y REAL,
|
|
111
|
+
updated_at INTEGER NOT NULL
|
|
112
|
+
);
|
|
113
|
+
-- Who did what in this company: never what a message or a terminal said.
|
|
114
|
+
CREATE TABLE IF NOT EXISTS audit (
|
|
115
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
116
|
+
at INTEGER NOT NULL,
|
|
117
|
+
who TEXT,
|
|
118
|
+
action TEXT NOT NULL,
|
|
119
|
+
target TEXT,
|
|
120
|
+
ip TEXT
|
|
121
|
+
);
|
|
122
|
+
CREATE INDEX IF NOT EXISTS audit_at ON audit(at);
|
|
123
|
+
-- Two coordinators (of two squads) that work with each other: a < b.
|
|
124
|
+
CREATE TABLE IF NOT EXISTS inbox (
|
|
125
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
126
|
+
session TEXT NOT NULL,
|
|
127
|
+
kind TEXT NOT NULL,
|
|
128
|
+
text TEXT NOT NULL,
|
|
129
|
+
options TEXT,
|
|
130
|
+
recommended TEXT,
|
|
131
|
+
ref TEXT,
|
|
132
|
+
created_at INTEGER NOT NULL,
|
|
133
|
+
resolved_at INTEGER
|
|
134
|
+
);
|
|
135
|
+
CREATE TABLE IF NOT EXISTS squad_links (
|
|
136
|
+
a TEXT NOT NULL,
|
|
137
|
+
b TEXT NOT NULL,
|
|
138
|
+
created_at INTEGER NOT NULL,
|
|
139
|
+
PRIMARY KEY (a, b)
|
|
140
|
+
);
|
|
141
|
+
`)
|
|
142
|
+
|
|
143
|
+
// Indexes for the per-session message lookups (presence, relations, files):
|
|
144
|
+
// without them every one of those reads the whole table.
|
|
145
|
+
db.exec(`
|
|
146
|
+
CREATE INDEX IF NOT EXISTS messages_from ON messages(from_name, target, created_at);
|
|
147
|
+
CREATE INDEX IF NOT EXISTS messages_target ON messages(target, created_at);
|
|
148
|
+
CREATE INDEX IF NOT EXISTS messages_file ON messages(file_id);
|
|
149
|
+
CREATE INDEX IF NOT EXISTS messages_from_time ON messages(from_name, created_at);
|
|
150
|
+
CREATE INDEX IF NOT EXISTS messages_time ON messages(created_at);
|
|
151
|
+
CREATE INDEX IF NOT EXISTS events_ts ON events(ts);
|
|
152
|
+
CREATE INDEX IF NOT EXISTS events_session_ts ON events(session, ts, id);
|
|
153
|
+
CREATE INDEX IF NOT EXISTS updates_time ON updates(created_at);
|
|
154
|
+
CREATE INDEX IF NOT EXISTS files_path ON files(path);
|
|
155
|
+
CREATE INDEX IF NOT EXISTS files_owner ON files(owner, created_at);
|
|
156
|
+
CREATE INDEX IF NOT EXISTS files_time ON files(created_at);
|
|
157
|
+
`)
|
|
158
|
+
|
|
159
|
+
// Additive migrations for databases created by earlier versions.
|
|
160
|
+
for (const [table, column, type] of [
|
|
161
|
+
['identities', 'role', 'TEXT'], // coordinator | worker, set at login
|
|
162
|
+
['identities', 'coordinator', 'TEXT'], // a worker's coordinator
|
|
163
|
+
['messages', 'system', 'INTEGER NOT NULL DEFAULT 0'], // notices generated by the server
|
|
164
|
+
['identities', 'cleared_at', 'INTEGER'], // dashboard: the session's chat was cleared at (ms)
|
|
165
|
+
['identities', 'archived_at', 'INTEGER'], // dashboard: archived (hidden from the main views) at (ms)
|
|
166
|
+
['groups', 'owner', 'TEXT'], // who created the group (null: created before groups were private)
|
|
167
|
+
['identities', 'host_id', 'TEXT'], // the machine that opened it from the dashboard (its name is reserved for it)
|
|
168
|
+
['group_members', 'joined_at', 'INTEGER'], // only messages from then on are visible to the member
|
|
169
|
+
['messages', 'auto', 'INTEGER NOT NULL DEFAULT 0'], // an automatic reply (pairing code, /help): no "relation"
|
|
170
|
+
['updates', 'sender', 'TEXT'], // who it came from (per-sender queue cap)
|
|
171
|
+
['identities', 'epoch', 'TEXT'], // random, per registration: what sessions pin (a name registered again gets a new one)
|
|
172
|
+
['identities', 'opened_role', 'TEXT'], // the role the dashboard opened it with (on a machine)
|
|
173
|
+
['identities', 'opened_persona', 'TEXT'], // and the persona (skill or agent id on that machine)
|
|
174
|
+
['identities', 'opened_coordinator', 'TEXT'], // and, for a worker, the coordinator it was opened under (shown until it logs in)
|
|
175
|
+
['identities', 'agent', 'TEXT'], // which agent runs it: claude, codex or grok (null: claude)
|
|
176
|
+
['identities', 'persona', 'TEXT'], // the persona it says it follows, set at login (JSON: kind, name, description)
|
|
177
|
+
['identities', 'description', 'TEXT'], // what it is for, written in the dashboard (org chart)
|
|
178
|
+
['messages', 'fyi', 'INTEGER NOT NULL DEFAULT 0'], // information only: no report expected
|
|
179
|
+
['identities', 'needs_approval', 'INTEGER NOT NULL DEFAULT 0'], // registered with the join token: can't direct workers until approved in the dashboard
|
|
180
|
+
['messages', 'sig', 'TEXT'], // the sender's signature (the plugin's signing.js): the server only carries it
|
|
181
|
+
['messages', 'report', 'TEXT'], // a worker's final report on a task: done | blocked | failed | question
|
|
182
|
+
['host_enrollments', 'ticket', 'TEXT'], // a random id for the code (shown to the dashboard)
|
|
183
|
+
['hosts', 'enrollment', 'TEXT'], // the ticket of the code it enrolled with
|
|
184
|
+
['hosts', 'public_key', 'TEXT'], // the machine's key, from its first proof: its secret alone isn't enough after that
|
|
185
|
+
['identities', 'public_key', 'TEXT'], // the same for a session
|
|
186
|
+
['identities', 'proven_instance', 'TEXT'], // the session id that proved it holds that key
|
|
187
|
+
['inbox', 'version', 'INTEGER NOT NULL DEFAULT 1'], // goes up each time its coordinator changes it
|
|
188
|
+
['inbox', 'updated_at', 'INTEGER'], // when it last did
|
|
189
|
+
['inbox', 'answer', 'TEXT'], // what the user answered from the dashboard
|
|
190
|
+
['inbox', 'answered_by', 'TEXT'], // and who
|
|
191
|
+
['inbox', 'closed_reason', 'TEXT'], // why its coordinator closed it
|
|
192
|
+
['inbox', 'dismissed_by', 'TEXT'], // who put a question away without answering it
|
|
193
|
+
['inbox', 'epoch', 'TEXT'], // the registration of its coordinator that wrote it (identities.epoch)
|
|
194
|
+
]) {
|
|
195
|
+
const cols = db.prepare(`PRAGMA table_info(${table})`).all().map(c => c.name)
|
|
196
|
+
if (!cols.includes(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// When a machine first connected (null: enrolled, never connected yet). The
|
|
200
|
+
// machines already there when the column is added have connected before.
|
|
201
|
+
if (!db.prepare('PRAGMA table_info(hosts)').all().some(c => c.name === 'first_connected_at')) {
|
|
202
|
+
db.exec('BEGIN; ALTER TABLE hosts ADD COLUMN first_connected_at INTEGER; UPDATE hosts SET first_connected_at = last_seen_at; COMMIT')
|
|
203
|
+
}
|
|
204
|
+
db.exec('CREATE INDEX IF NOT EXISTS updates_sender ON updates(recipient, sender, update_id)')
|
|
205
|
+
db.exec('CREATE INDEX IF NOT EXISTS updates_by_sender ON updates(sender)')
|
|
206
|
+
db.exec('CREATE INDEX IF NOT EXISTS group_members_by_name ON group_members(name, group_id)')
|
|
207
|
+
db.exec('CREATE INDEX IF NOT EXISTS groups_owner ON groups(owner)')
|
|
208
|
+
|
|
209
|
+
// "Have these two written to each other?" (getChat, notices): only real
|
|
210
|
+
// messages count, so a pile of automatic replies can't make it a scan.
|
|
211
|
+
db.exec('CREATE INDEX IF NOT EXISTS messages_relation ON messages(from_name, target, created_at) WHERE system = 0 AND auto = 0')
|
|
212
|
+
db.exec("UPDATE identities SET epoch = lower(hex(randomblob(12))) WHERE epoch IS NULL")
|
|
213
|
+
// (Written before the inbox said whose registration: the one there now.)
|
|
214
|
+
db.exec('UPDATE inbox SET epoch = (SELECT epoch FROM identities WHERE name = inbox.session) WHERE epoch IS NULL')
|
|
215
|
+
|
|
216
|
+
// Several writes in one transaction (one disk sync instead of one each).
|
|
217
|
+
// Re-entrant: an inner call just joins the outer transaction.
|
|
218
|
+
let txDepth = 0
|
|
219
|
+
function inTx(fn) {
|
|
220
|
+
if (txDepth) return fn()
|
|
221
|
+
db.exec('BEGIN')
|
|
222
|
+
txDepth++
|
|
223
|
+
try { return fn() } finally { txDepth--; db.exec('COMMIT') }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
let lastTruncate = now()
|
|
227
|
+
function truncateLog() {
|
|
228
|
+
lastTruncate = now()
|
|
229
|
+
try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)') } catch (err) { logError(`could not truncate the write-ahead log: ${err.message}`) }
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// (What was deleted is overwritten in the database file, but stays in the
|
|
233
|
+
// write-ahead log until this.)
|
|
234
|
+
function truncateLogHourly() {
|
|
235
|
+
if (now() - lastTruncate >= 3600_000) truncateLog()
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const AUDIT_KEPT_MS = 365 * 24 * 3600_000
|
|
239
|
+
const AUDIT_MAX = 200_000
|
|
240
|
+
const audit = (actor, action, target, ip) => db.prepare('INSERT INTO audit (at, who, action, target, ip) VALUES (?, ?, ?, ?, ?)')
|
|
241
|
+
.run(now(), actor?.email ?? (actor?.token ? 'server token' : null), String(action).slice(0, 60), target == null ? null : String(target).slice(0, 200), ip == null ? null : String(ip).slice(0, 64))
|
|
242
|
+
function auditLog({ before = Number.MAX_SAFE_INTEGER, limit = 100 } = {}) {
|
|
243
|
+
return db.prepare('SELECT id, at, who, action, target, ip FROM audit WHERE id < ? ORDER BY id DESC LIMIT ?').all(before, limit)
|
|
244
|
+
}
|
|
245
|
+
function cleanupAudit() {
|
|
246
|
+
db.prepare('DELETE FROM audit WHERE at < ?').run(now() - AUDIT_KEPT_MS)
|
|
247
|
+
db.prepare('DELETE FROM audit WHERE id <= (SELECT id FROM audit ORDER BY id DESC LIMIT 1 OFFSET ?)').run(AUDIT_MAX)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
return { db, inTx, truncateLog, truncateLogHourly, audit, auditLog, cleanupAudit }
|
|
251
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export class ApiError extends Error {
|
|
2
|
+
constructor(code, description, extra) {
|
|
3
|
+
super(description)
|
|
4
|
+
this.code = code
|
|
5
|
+
this.extra = extra
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export const bad = d => new ApiError(400, `Bad Request: ${d}`)
|
|
9
|
+
|
|
10
|
+
// Periodic work: an error (e.g. the database is busy) is logged, never fatal.
|
|
11
|
+
export const guarded = fn => () => {
|
|
12
|
+
try { fn() } catch (err) { process.stderr.write(`pisha-server: ${fn.name || 'timer'}: ${err?.stack ?? err}\n`) }
|
|
13
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { statSync, readFileSync } from 'node:fs'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import { TLS, PUBLIC_URL } from './config.js'
|
|
4
|
+
|
|
5
|
+
// Public files (the page, xterm.js, pisha-host) are read once and kept:
|
|
6
|
+
// every answer shares the same bytes, so requests piled up on a connection
|
|
7
|
+
// that doesn't read can't make the server copy a file for each. Read again
|
|
8
|
+
// only when the file changes on disk.
|
|
9
|
+
const fileCache = new Map() // path -> { body, mtimeMs, size, ...extra }
|
|
10
|
+
export function cachedFile(file, extra = () => ({})) {
|
|
11
|
+
let st
|
|
12
|
+
try { st = statSync(file) } catch { return null }
|
|
13
|
+
if (!st.isFile()) return null
|
|
14
|
+
const key = String(file)
|
|
15
|
+
const c = fileCache.get(key)
|
|
16
|
+
if (c && c.mtimeMs === st.mtimeMs && c.size === st.size) return c
|
|
17
|
+
const body = readFileSync(file)
|
|
18
|
+
const entry = { body, mtimeMs: st.mtimeMs, size: st.size, ...extra(body) }
|
|
19
|
+
fileCache.set(key, entry)
|
|
20
|
+
return entry
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// The dashboard page: a strict Content-Security-Policy (only its own inline
|
|
24
|
+
// script, by hash, and scripts from this server), and no framing.
|
|
25
|
+
export function pageHeaders(html) {
|
|
26
|
+
const text = html.toString('utf8')
|
|
27
|
+
const hashes = [...text.matchAll(/<script>([\s\S]*?)<\/script>/g)]
|
|
28
|
+
.map(m => `'sha256-${createHash('sha256').update(m[1], 'utf8').digest('base64')}'`)
|
|
29
|
+
return {
|
|
30
|
+
'Content-Security-Policy': [
|
|
31
|
+
"default-src 'none'",
|
|
32
|
+
`script-src 'self' ${hashes.join(' ')}`,
|
|
33
|
+
"style-src 'self' 'unsafe-inline'",
|
|
34
|
+
"img-src 'self' data:",
|
|
35
|
+
"font-src 'self'",
|
|
36
|
+
"connect-src 'self'",
|
|
37
|
+
"manifest-src 'self'",
|
|
38
|
+
"frame-ancestors 'none'",
|
|
39
|
+
"base-uri 'none'",
|
|
40
|
+
"form-action 'none'",
|
|
41
|
+
].join('; '),
|
|
42
|
+
'X-Frame-Options': 'DENY',
|
|
43
|
+
'X-Content-Type-Options': 'nosniff',
|
|
44
|
+
'Referrer-Policy': 'no-referrer',
|
|
45
|
+
'Cross-Origin-Opener-Policy': 'same-origin', // a page that opened the dashboard can't steer it
|
|
46
|
+
// (Also behind a TLS proxy, which doesn't add it by itself. A browser
|
|
47
|
+
// ignores this header over plain http, so a local visit isn't affected.)
|
|
48
|
+
...(TLS || PUBLIC_URL.startsWith('https://') ? { 'Strict-Transport-Security': 'max-age=31536000' } : {}),
|
|
49
|
+
}
|
|
50
|
+
}
|
package/platform/http.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { openSync, closeSync, rmSync, writeSync } from 'node:fs'
|
|
2
|
+
import { PUBLIC_URL, TRUST_PROXY, TLS, PORT, MAX_JSON_BODY } from './config.js'
|
|
3
|
+
import { allowServerWide } from './limits.js'
|
|
4
|
+
import { ApiError, bad } from './errors.js'
|
|
5
|
+
|
|
6
|
+
// The address hosts and plugins use: PUBLIC_URL, or what the browser used.
|
|
7
|
+
export function serverBaseUrl(req) {
|
|
8
|
+
if (PUBLIC_URL) return PUBLIC_URL
|
|
9
|
+
const fwd = h => (TRUST_PROXY ? String(req.headers[h] ?? '').split(',')[0].trim() : '')
|
|
10
|
+
let proto = fwd('x-forwarded-proto') || (TLS ? 'https' : 'http')
|
|
11
|
+
if (proto !== 'http' && proto !== 'https') proto = TLS ? 'https' : 'http'
|
|
12
|
+
let host = String(req.headers.host ?? '') // never X-Forwarded-Host: set PUBLIC_URL behind a proxy
|
|
13
|
+
if (!/^[A-Za-z0-9.-]+(:\d{1,5})?$|^\[[0-9A-Fa-f:.]+\](:\d{1,5})?$/.test(host)) host = `127.0.0.1:${PORT}`
|
|
14
|
+
return `${proto}://${host}`
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// A request made from this dashboard's own page (a browser always says where from).
|
|
18
|
+
export function sameOrigin(req) {
|
|
19
|
+
try {
|
|
20
|
+
const origin = new URL(req.headers.origin).host
|
|
21
|
+
return origin === req.headers.host || (!!PUBLIC_URL && origin === new URL(PUBLIC_URL).host)
|
|
22
|
+
} catch { return false }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Host side: trade the code for a permanent secret. Public, rate-limited.
|
|
26
|
+
// The client's address. Behind a reverse proxy every request comes from the
|
|
27
|
+
// proxy, so with --trust-proxy the last X-Forwarded-For entry (the one the
|
|
28
|
+
// proxy itself added) is used.
|
|
29
|
+
export function clientIp(req) {
|
|
30
|
+
if (TRUST_PROXY) {
|
|
31
|
+
const xff = String(req.headers['x-forwarded-for'] ?? '').split(',').map(x => x.trim()).filter(Boolean)
|
|
32
|
+
if (xff.length) return xff[xff.length - 1].slice(0, 64)
|
|
33
|
+
}
|
|
34
|
+
return req.socket.remoteAddress ?? '?'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// A refused upgrade (or bad request) is answered and then closed for good:
|
|
38
|
+
// end() alone leaves the socket half open as long as the client wants.
|
|
39
|
+
export function refuseSocket(socket, status) {
|
|
40
|
+
try { socket.end(`HTTP/1.1 ${status}\r\n\r\n`) } catch {}
|
|
41
|
+
setTimeout(() => { try { socket.destroy() } catch {} }, 1000).unref()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function sendJson(res, status, body) {
|
|
45
|
+
if (res.writableEnded) return
|
|
46
|
+
const data = JSON.stringify(body)
|
|
47
|
+
// (Never cached: answers carry messages and session state.)
|
|
48
|
+
res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data), 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' })
|
|
49
|
+
res.end(data)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Error lines in the log: at most 60 a minute in all (a client that keeps
|
|
53
|
+
// causing them can't fill the disk), and how many were left out.
|
|
54
|
+
let errorsDropped = 0
|
|
55
|
+
export function logError(text) {
|
|
56
|
+
if (!allowServerWide('error-log', 'all', 60)) { errorsDropped++; return }
|
|
57
|
+
if (errorsDropped) { process.stderr.write(`pisha-server: (${errorsDropped} more errors not logged)\n`); errorsDropped = 0 }
|
|
58
|
+
process.stderr.write(`pisha-server: ${text}\n`)
|
|
59
|
+
}
|
|
60
|
+
export function sendError(res, err) {
|
|
61
|
+
if (err instanceof ApiError) {
|
|
62
|
+
sendJson(res, err.code, { ok: false, error_code: err.code, description: err.message, ...(err.extra ?? {}) })
|
|
63
|
+
} else if (err instanceof RangeError || err instanceof URIError || err?.code === 'ERR_INVALID_URL' ||
|
|
64
|
+
(err instanceof TypeError && /primitive value|toPrimitive/.test(err.message))) {
|
|
65
|
+
// A parameter that can't even be read (nested a thousand times, an object
|
|
66
|
+
// where text was expected…): the client's mistake, not worth a stack trace.
|
|
67
|
+
sendJson(res, 400, { ok: false, error_code: 400, description: 'Bad Request: invalid parameters' })
|
|
68
|
+
} else {
|
|
69
|
+
logError(`internal error: ${err?.stack ?? err}`)
|
|
70
|
+
sendJson(res, 500, { ok: false, error_code: 500, description: 'Internal Server Error' })
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Request body, up to `max` bytes. A client that stops sending for 30 s is
|
|
75
|
+
// cut off (requests have no overall timeout, for long polls and uploads).
|
|
76
|
+
const BODY_IDLE_MS = 30_000
|
|
77
|
+
|
|
78
|
+
// Bodies are held in memory while they arrive: a whole body within a
|
|
79
|
+
// deadline (a minute; uploads: one per 64 KB/s, at least a minute), and
|
|
80
|
+
// what goes past each body's first 64 KB at most BODY_BYTES_IN_FLIGHT across
|
|
81
|
+
// the server, so slow senders can't pile up — while small bodies (every
|
|
82
|
+
// poll, every message) never wait on big ones. Requests anyone can send
|
|
83
|
+
// (enrollment, registration) have their own small pool and a short deadline.
|
|
84
|
+
const BODY_BYTES_IN_FLIGHT = 256 * 1024 * 1024
|
|
85
|
+
const bodyPools = {
|
|
86
|
+
main: { bytes: 0, cap: BODY_BYTES_IN_FLIGHT, free: 64 * 1024 },
|
|
87
|
+
// (A registration's body, at most 4 KB, never counts: enrollments can't block it.)
|
|
88
|
+
public: { bytes: 0, cap: 4 * 1024 * 1024, free: 4096, deadline: 10_000 },
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// An upload, straight to its file: the same limits as readBody (size, idle
|
|
92
|
+
// time, overall deadline), without holding it in memory. Returns its size.
|
|
93
|
+
export function readBodyToFile(req, max, path) {
|
|
94
|
+
return new Promise((resolve, reject) => {
|
|
95
|
+
let fd
|
|
96
|
+
try { fd = openSync(path, 'wx', 0o600) } catch (err) { reject(err); return }
|
|
97
|
+
let size = 0
|
|
98
|
+
let done = false
|
|
99
|
+
let idle = null
|
|
100
|
+
const finish = ok => {
|
|
101
|
+
if (done) return false
|
|
102
|
+
done = true
|
|
103
|
+
clearTimeout(idle); clearTimeout(deadline)
|
|
104
|
+
try { closeSync(fd) } catch {}
|
|
105
|
+
if (!ok) rmSync(path, { force: true })
|
|
106
|
+
return true
|
|
107
|
+
}
|
|
108
|
+
const fail = err => { if (finish(false)) { reject(err); req.destroy() } }
|
|
109
|
+
const deadline = setTimeout(() => fail(new ApiError(408, 'Request Timeout')), Math.max(60_000, Math.ceil(max / 65_536) * 1000))
|
|
110
|
+
const arm = () => { clearTimeout(idle); idle = setTimeout(() => fail(new ApiError(408, 'Request Timeout')), BODY_IDLE_MS) }
|
|
111
|
+
arm()
|
|
112
|
+
req.on('data', c => {
|
|
113
|
+
if (done) return
|
|
114
|
+
arm()
|
|
115
|
+
size += c.length
|
|
116
|
+
if (size > max) return fail(new ApiError(413, `Request Entity Too Large (max ${max} bytes)`))
|
|
117
|
+
try { writeSync(fd, c) } catch (err) { fail(err) }
|
|
118
|
+
})
|
|
119
|
+
req.on('end', () => { if (finish(true)) resolve(size) })
|
|
120
|
+
req.on('error', () => { if (finish(false)) reject(new ApiError(400, 'Bad Request: connection closed')) })
|
|
121
|
+
req.on('close', () => { if (finish(false)) reject(new ApiError(400, 'Bad Request: connection closed')) })
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
function readBody(req, max, { pool: poolName = 'main' } = {}) {
|
|
125
|
+
const pool = bodyPools[poolName]
|
|
126
|
+
return new Promise((resolve, reject) => {
|
|
127
|
+
if (Number(req.headers['content-length'] ?? 0) > max) {
|
|
128
|
+
reject(new ApiError(413, `Request Entity Too Large (max ${max} bytes)`))
|
|
129
|
+
req.destroy()
|
|
130
|
+
return
|
|
131
|
+
}
|
|
132
|
+
const chunks = []
|
|
133
|
+
let size = 0
|
|
134
|
+
let idle = null
|
|
135
|
+
let done = false
|
|
136
|
+
let counted = 0
|
|
137
|
+
const finish = () => { if (done) return false; done = true; clearTimeout(idle); clearTimeout(deadline); pool.bytes -= counted; return true }
|
|
138
|
+
const fail = err => { if (finish()) { reject(err); req.destroy() } }
|
|
139
|
+
const deadline = setTimeout(() => fail(new ApiError(408, 'Request Timeout')), pool.deadline ?? Math.max(60_000, Math.ceil(max / 65_536) * 1000))
|
|
140
|
+
const arm = () => {
|
|
141
|
+
clearTimeout(idle)
|
|
142
|
+
idle = setTimeout(() => fail(new ApiError(408, 'Request Timeout')), BODY_IDLE_MS)
|
|
143
|
+
}
|
|
144
|
+
arm()
|
|
145
|
+
req.on('data', c => {
|
|
146
|
+
if (done) return
|
|
147
|
+
arm()
|
|
148
|
+
size += c.length
|
|
149
|
+
const count = Math.max(0, size - pool.free) - counted
|
|
150
|
+
counted += count
|
|
151
|
+
pool.bytes += count
|
|
152
|
+
if (size > max) return fail(new ApiError(413, `Request Entity Too Large (max ${max} bytes)`))
|
|
153
|
+
if (pool.bytes > pool.cap) return fail(new ApiError(503, 'Service Unavailable: the server is busy receiving other requests; retry'))
|
|
154
|
+
chunks.push(c)
|
|
155
|
+
})
|
|
156
|
+
req.on('end', () => { if (finish()) resolve(Buffer.concat(chunks)) })
|
|
157
|
+
// (A client that drops the connection mid-body is its own business, not an internal error.)
|
|
158
|
+
req.on('error', () => { if (finish()) reject(new ApiError(400, 'Bad Request: connection closed')) })
|
|
159
|
+
req.on('close', () => { if (finish()) reject(new ApiError(400, 'Bad Request: connection closed')) })
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Request parameters: query string plus a JSON object body. A plain object
|
|
164
|
+
// with no prototype, and only the body's own keys: "__proto__" and friends
|
|
165
|
+
// can't make a parameter appear that wasn't sent.
|
|
166
|
+
const RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
|
167
|
+
export async function readParams(req, url, max = MAX_JSON_BODY, opts) {
|
|
168
|
+
const params = Object.create(null)
|
|
169
|
+
for (const [k, v] of url.searchParams) if (!RESERVED_KEYS.has(k)) params[k] = v
|
|
170
|
+
if (req.method === 'POST') {
|
|
171
|
+
const buf = await readBody(req, max, opts)
|
|
172
|
+
if (buf.length) {
|
|
173
|
+
let body
|
|
174
|
+
try { body = JSON.parse(buf.toString('utf8')) } catch { throw bad('body is not valid JSON') }
|
|
175
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) throw bad('body must be a JSON object')
|
|
176
|
+
for (const k of Object.keys(body)) if (!RESERVED_KEYS.has(k)) params[k] = body[k]
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return params
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export const own = (table, key) => (Object.hasOwn(table, key) ? table[key] : undefined)
|
|
183
|
+
|
|
184
|
+
export function bearer(req) {
|
|
185
|
+
const h = req.headers.authorization ?? ''
|
|
186
|
+
return h.startsWith('Bearer ') ? h.slice(7).trim() : ''
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Every request: at most 32 answers waiting on one connection (requests
|
|
190
|
+
// piled up without reading the answers), and a connection whose request
|
|
191
|
+
// body never finishes arriving is closed shortly after it was answered
|
|
192
|
+
// (an early refusal doesn't read it; trickled bytes would keep it open).
|
|
193
|
+
const inFlightBySocket = new WeakMap()
|
|
194
|
+
export function guardRequest(req, res) {
|
|
195
|
+
const sock = req.socket
|
|
196
|
+
const n = (inFlightBySocket.get(sock) ?? 0) + 1
|
|
197
|
+
inFlightBySocket.set(sock, n)
|
|
198
|
+
res.once('close', () => inFlightBySocket.set(sock, (inFlightBySocket.get(sock) ?? 1) - 1))
|
|
199
|
+
if (n > 32) { sock.destroy(); return false }
|
|
200
|
+
res.once('finish', () => {
|
|
201
|
+
if (req.complete) return
|
|
202
|
+
const t = setTimeout(() => { if (!req.complete) sock.destroy() }, 2000)
|
|
203
|
+
t.unref?.()
|
|
204
|
+
req.once('end', () => clearTimeout(t))
|
|
205
|
+
})
|
|
206
|
+
return true
|
|
207
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// What every module of the server can use. The configuration goes first: a
|
|
2
|
+
// wrong option or --help ends here, before anything is opened.
|
|
3
|
+
import { EventEmitter } from 'node:events'
|
|
4
|
+
|
|
5
|
+
export * from './config.js'
|
|
6
|
+
export * from './errors.js'
|
|
7
|
+
export * from './basics.js'
|
|
8
|
+
export * from './text.js'
|
|
9
|
+
export * from './files.js'
|
|
10
|
+
export { ipKey, allowServerWide, countedServerWide, cleanupServerLimits } from './limits.js'
|
|
11
|
+
export * from './http.js'
|
|
12
|
+
export { acceptWebSocket } from './ws.js'
|
|
13
|
+
export { startListening } from './listen.js'
|
|
14
|
+
export { openServerCredentials } from './credentials.js'
|
|
15
|
+
export { openControl } from './control.js'
|
|
16
|
+
export * from './roles.js'
|
|
17
|
+
|
|
18
|
+
import { openCompanyCredentials } from './credentials.js'
|
|
19
|
+
import { openDatabase } from './database.js'
|
|
20
|
+
import { createLimits, whyNoRoom } from './limits.js'
|
|
21
|
+
import { ApiError } from './errors.js'
|
|
22
|
+
import { createStream } from './stream.js'
|
|
23
|
+
|
|
24
|
+
export const FIRST_COMPANY = 'default'
|
|
25
|
+
|
|
26
|
+
// What the modules of one company share while the server runs: its data, its
|
|
27
|
+
// budgets, its dashboards, and what is the whole server's. The bus is how a
|
|
28
|
+
// module tells the ones above it what happened, without knowing them:
|
|
29
|
+
// session-changed (name) what the dashboard shows of it changed
|
|
30
|
+
// notice (worker, text) its coordinator should hear this
|
|
31
|
+
// context-cleared (name) /clear took effect in that session
|
|
32
|
+
export function createPlatform(server, { id, dir, quotas, routeEnrollment }) {
|
|
33
|
+
// What repeats while this company runs, and stops with it.
|
|
34
|
+
const timers = new Set()
|
|
35
|
+
const every = (ms, fn) => { const t = setInterval(fn, ms); t.unref(); timers.add(t) }
|
|
36
|
+
const stopTimers = () => { for (const t of timers) clearInterval(t); timers.clear() }
|
|
37
|
+
// The first company's credentials have no prefix, as they always were.
|
|
38
|
+
const credentialPrefix = id === FIRST_COMPANY ? '' : `${id}_`
|
|
39
|
+
// (The credentials first: they make the company's folder.)
|
|
40
|
+
const credentials = openCompanyCredentials(dir, server, { id, credentialPrefix })
|
|
41
|
+
const opened = openDatabase(dir)
|
|
42
|
+
// Looked at every few seconds, not on every write.
|
|
43
|
+
let roomUntil = 0, noRoom = null
|
|
44
|
+
function ensureRoom() {
|
|
45
|
+
const t = Date.now()
|
|
46
|
+
if (t >= roomUntil) { noRoom = whyNoRoom(opened.db, dir, quotas.max_db_mb); roomUntil = t + 5000 }
|
|
47
|
+
if (noRoom) throw new ApiError(507, `Insufficient Storage: ${noRoom}`)
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
...server, companyId: id, dataDir: dir, credentialPrefix, routeEnrollment, every, stopTimers,
|
|
51
|
+
quota: (what, otherwise) => quotas[what] ?? otherwise,
|
|
52
|
+
setQuotas: limits => { quotas = limits; roomUntil = 0 },
|
|
53
|
+
ensureRoom,
|
|
54
|
+
log: text => process.stderr.write(`pisha-server: ${credentialPrefix && `[${id}] `}${text}\n`),
|
|
55
|
+
...credentials, ...opened, ...createStream(every),
|
|
56
|
+
...createLimits(), bus: new EventEmitter(),
|
|
57
|
+
}
|
|
58
|
+
}
|