pisha-server 0.0.0-stage → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1087 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +82 -0
  14. package/dashboard/dashboard.js +408 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +231 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +55 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3303 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +168 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2145 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +41 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +105 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +142 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +669 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +180 -0
  89. package/ui/people.js +371 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +173 -0
  93. package/ui/routes.js +47 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +119 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/screen-usage.css +60 -0
  105. package/ui/session.js +42 -0
  106. package/ui/shell.css +122 -0
  107. package/ui/signin.js +120 -0
  108. package/ui/squads.js +371 -0
  109. package/ui/state.js +59 -0
  110. package/ui/stream.js +269 -0
  111. package/ui/styles.css +343 -0
  112. package/ui/team.js +115 -0
  113. package/ui/teams.js +58 -0
  114. package/ui/terminal.js +261 -0
  115. package/ui/theme.js +32 -0
  116. package/ui/timeline.js +163 -0
  117. package/ui/topbar.js +211 -0
  118. package/ui/usage.js +175 -0
  119. package/ui/voice-parse.js +98 -0
  120. package/ui/voice.js +320 -0
  121. package/usage/index.js +1 -0
  122. package/usage/usage.js +127 -0
  123. package/vendor/InterVariable.woff2 +0 -0
  124. package/vendor/LICENSE-inter +92 -0
  125. package/vendor/LICENSE-xterm +21 -0
  126. package/vendor/README.md +8 -0
  127. package/vendor/addon-fit.js +2 -0
  128. package/vendor/xterm.css +218 -0
  129. package/vendor/xterm.js +2 -0
@@ -0,0 +1 @@
1
+ mV_Xs4Zu1h2EiHAlvzx7Lj7eRnI0RG1Y1z1kc0yxIGSQ3hdikrXgyfb4m6o1k9YvjpZPLFSx_j_xsHLwnQMqDw
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Minimal ACME client (RFC 8555) for pisha-server: gets and renews a TLS
3
+ * certificate from Let's Encrypt with the HTTP-01 challenge. Only Node
4
+ * built-ins — no dependencies.
5
+ *
6
+ * const acme = createAcme({ domain, email, directory, dir, log })
7
+ * acme.challenge(token) → key authorization to serve at
8
+ * /.well-known/acme-challenge/<token>, or null
9
+ * await acme.ensureCertificate() → { key, cert } (PEM), issuing or renewing if needed
10
+ *
11
+ * Keys and certificates are stored in `dir` (account.key.pem, <domain>.key.pem,
12
+ * <domain>.crt.pem) so restarts don't ask for a new certificate.
13
+ */
14
+
15
+ import { createHash, generateKeyPairSync, createPrivateKey, sign, X509Certificate } from 'node:crypto'
16
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+
19
+ export const LETS_ENCRYPT = 'https://acme-v02.api.letsencrypt.org/directory'
20
+ export const LETS_ENCRYPT_STAGING = 'https://acme-staging-v02.api.letsencrypt.org/directory'
21
+
22
+ // Renew when less than a third of the certificate's lifetime is left, as Let's
23
+ // Encrypt recommends (90-day certificates → at 30 days; shorter ones scale down).
24
+ const RENEW_FRACTION = 1 / 3
25
+
26
+ const b64u = buf => Buffer.from(buf).toString('base64url')
27
+
28
+ // --- DER encoding (just what a CSR needs) ---------------------------------------
29
+
30
+ function derLength(n) {
31
+ if (n < 0x80) return Buffer.from([n])
32
+ const bytes = []
33
+ while (n > 0) { bytes.unshift(n & 0xff); n >>= 8 }
34
+ return Buffer.from([0x80 | bytes.length, ...bytes])
35
+ }
36
+ const tlv = (tag, content) => Buffer.concat([Buffer.from([tag]), derLength(content.length), content])
37
+ const seq = (...items) => tlv(0x30, Buffer.concat(items))
38
+ const set = (...items) => tlv(0x31, Buffer.concat(items))
39
+ function oid(dotted) {
40
+ const parts = dotted.split('.').map(Number)
41
+ const bytes = [40 * parts[0] + parts[1]]
42
+ for (const p of parts.slice(2)) {
43
+ const chunk = [p & 0x7f]
44
+ for (let v = p >> 7; v > 0; v >>= 7) chunk.unshift(0x80 | (v & 0x7f))
45
+ bytes.push(...chunk)
46
+ }
47
+ return tlv(0x06, Buffer.from(bytes))
48
+ }
49
+
50
+ // PKCS#10 certificate signing request for one DNS name, signed with an EC P-256 key.
51
+ export function createCsr(domain, privateKey, publicKey) {
52
+ const subject = seq(set(seq(oid('2.5.4.3'), tlv(0x0c, Buffer.from(domain))))) // CN=<domain>
53
+ const spki = publicKey.export({ type: 'spki', format: 'der' })
54
+ const san = seq(tlv(0x82, Buffer.from(domain))) // dNSName
55
+ const extensions = seq(seq(oid('2.5.29.17'), tlv(0x04, san))) // subjectAltName
56
+ const attributes = tlv(0xa0, seq(oid('1.2.840.113549.1.9.14'), set(extensions))) // extensionRequest
57
+ const info = seq(tlv(0x02, Buffer.from([0])), subject, spki, attributes)
58
+ const signature = sign('sha256', info, privateKey) // DER ECDSA signature
59
+ return seq(info, seq(oid('1.2.840.10045.4.3.2')), tlv(0x03, Buffer.concat([Buffer.from([0]), signature])))
60
+ }
61
+
62
+ // --- keys ---------------------------------------------------------------------------
63
+
64
+ function loadOrCreateKey(file) {
65
+ if (existsSync(file)) return createPrivateKey(readFileSync(file))
66
+ const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
67
+ writeFileSync(file, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 })
68
+ return privateKey
69
+ }
70
+
71
+ function jwkOf(privateKey) {
72
+ const { crv, kty, x, y } = privateKey.export({ format: 'jwk' })
73
+ return { crv, kty, x, y } // members in lexicographic order, as RFC 7638 requires for the thumbprint
74
+ }
75
+
76
+ // --- client --------------------------------------------------------------------------
77
+
78
+ export function createAcme({ domain, email, directory = LETS_ENCRYPT, dir, log = () => {} }) {
79
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
80
+ const accountKey = loadOrCreateKey(join(dir, 'account.key.pem'))
81
+ const jwk = jwkOf(accountKey)
82
+ const thumbprint = b64u(createHash('sha256').update(JSON.stringify(jwk)).digest())
83
+ const certFile = join(dir, `${domain}.crt.pem`)
84
+ const keyFile = join(dir, `${domain}.key.pem`)
85
+ const tokens = new Map() // token -> key authorization, while a challenge is pending
86
+
87
+ let dirCache = null
88
+ let nonce = null
89
+ let kid = null
90
+
91
+ async function getDirectory() {
92
+ if (!dirCache) {
93
+ const res = await fetch(directory)
94
+ if (!res.ok) throw new Error(`ACME directory ${directory}: HTTP ${res.status}`)
95
+ dirCache = await res.json()
96
+ }
97
+ return dirCache
98
+ }
99
+
100
+ async function newNonce() {
101
+ const res = await fetch((await getDirectory()).newNonce, { method: 'HEAD' })
102
+ return res.headers.get('replay-nonce')
103
+ }
104
+
105
+ // Signed POST (JWS, ES256). payload undefined = POST-as-GET.
106
+ async function post(url, payload, { useJwk = false, accept } = {}) {
107
+ for (let attempt = 0; attempt < 3; attempt++) {
108
+ const protectedHeader = { alg: 'ES256', nonce: nonce ?? await newNonce(), url, ...(useJwk ? { jwk } : { kid }) }
109
+ nonce = null
110
+ const p64 = b64u(JSON.stringify(protectedHeader))
111
+ const body64 = payload === undefined ? '' : b64u(JSON.stringify(payload))
112
+ const sig = sign('sha256', Buffer.from(`${p64}.${body64}`), { key: accountKey, dsaEncoding: 'ieee-p1363' })
113
+ const res = await fetch(url, {
114
+ method: 'POST',
115
+ headers: { 'Content-Type': 'application/jose+json', ...(accept ? { Accept: accept } : {}) },
116
+ body: JSON.stringify({ protected: p64, payload: body64, signature: b64u(sig) }),
117
+ })
118
+ nonce = res.headers.get('replay-nonce')
119
+ const type = res.headers.get('content-type') ?? ''
120
+ const body = type.includes('json') ? await res.json() : await res.text()
121
+ if (res.ok) return { body, location: res.headers.get('location'), headers: res.headers }
122
+ if (body?.type === 'urn:ietf:params:acme:error:badNonce') continue // retry with the fresh nonce
123
+ throw new Error(`ACME ${url}: ${res.status} ${body?.detail ?? body}`)
124
+ }
125
+ throw new Error('ACME: too many bad nonces')
126
+ }
127
+
128
+ async function ensureAccount() {
129
+ if (kid) return
130
+ const { location } = await post((await getDirectory()).newAccount, {
131
+ termsOfServiceAgreed: true,
132
+ ...(email ? { contact: [`mailto:${email}`] } : {}),
133
+ }, { useJwk: true })
134
+ kid = location
135
+ }
136
+
137
+ async function poll(url, done, { tries = 40, delay = 1500 } = {}) {
138
+ for (let i = 0; i < tries; i++) {
139
+ const { body } = await post(url)
140
+ if (done(body)) return body
141
+ if (body.status === 'invalid') throw new Error(`ACME: ${url} is invalid: ${JSON.stringify(body.error ?? body.challenges?.find(c => c.error)?.error ?? body)}`)
142
+ await new Promise(r => setTimeout(r, delay))
143
+ }
144
+ throw new Error(`ACME: timed out waiting for ${url}`)
145
+ }
146
+
147
+ async function issue() {
148
+ log(`requesting a certificate for ${domain} from ${directory}`)
149
+ await ensureAccount()
150
+ const { body: order, location: orderUrl } = await post((await getDirectory()).newOrder, {
151
+ identifiers: [{ type: 'dns', value: domain }],
152
+ })
153
+ for (const authzUrl of order.authorizations) {
154
+ const { body: authz } = await post(authzUrl)
155
+ if (authz.status === 'valid') continue
156
+ const challenge = authz.challenges.find(c => c.type === 'http-01')
157
+ if (!challenge) throw new Error('ACME: no http-01 challenge offered')
158
+ tokens.set(challenge.token, `${challenge.token}.${thumbprint}`)
159
+ try {
160
+ await post(challenge.url, {})
161
+ await poll(authzUrl, a => a.status === 'valid')
162
+ } finally {
163
+ tokens.delete(challenge.token)
164
+ }
165
+ }
166
+ const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
167
+ await post(order.finalize, { csr: b64u(createCsr(domain, privateKey, publicKey)) })
168
+ const done = await poll(orderUrl, o => o.status === 'valid' && o.certificate)
169
+ const { body: chain } = await post(done.certificate, undefined, { accept: 'application/pem-certificate-chain' })
170
+ const key = privateKey.export({ type: 'pkcs8', format: 'pem' })
171
+ // (Each written whole and then renamed: a crash never leaves half a file.)
172
+ writeFileSync(`${keyFile}.new`, key, { mode: 0o600 })
173
+ writeFileSync(`${certFile}.new`, chain)
174
+ renameSync(`${keyFile}.new`, keyFile)
175
+ renameSync(`${certFile}.new`, certFile)
176
+ log(`certificate for ${domain} issued, valid until ${new X509Certificate(chain).validTo}`)
177
+ return { key, cert: chain }
178
+ }
179
+
180
+ function stored() {
181
+ try {
182
+ const cert = readFileSync(certFile, 'utf8')
183
+ const key = readFileSync(keyFile, 'utf8')
184
+ const x = new X509Certificate(cert)
185
+ if (!x.checkHost(domain)) return null
186
+ // (The key must be this certificate's: a crash between the two writes
187
+ // of an older version could leave a mismatched pair.)
188
+ if (!x.checkPrivateKey(createPrivateKey(key))) return null
189
+ const from = Date.parse(x.validFrom)
190
+ const to = Date.parse(x.validTo)
191
+ return { key, cert, expires: to, renewAt: to - (to - from) * RENEW_FRACTION }
192
+ } catch { return null }
193
+ }
194
+
195
+ return {
196
+ domain,
197
+ challenge: token => tokens.get(token) ?? null,
198
+ // The stored certificate unless it's in the last third of its life; otherwise a new one.
199
+ async ensureCertificate({ force = false } = {}) {
200
+ const s = stored()
201
+ if (s && !force && Date.now() < s.renewAt) return { key: s.key, cert: s.cert, renewed: false }
202
+ const fresh = await issue()
203
+ return { ...fresh, renewed: true }
204
+ },
205
+ storedCertificate: () => stored(),
206
+ }
207
+ }
@@ -0,0 +1,14 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ export const sha256 = s => createHash('sha256').update(s).digest('hex')
4
+ export const now = () => Date.now()
5
+ export const unix = ms => Math.floor(ms / 1000)
6
+ // A path without the slashes at its end. (A loop: a regular expression takes
7
+ // time quadratic in a run of slashes, and this runs before any check.)
8
+ export function trimSlashes(path) {
9
+ let end = path.length
10
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--
11
+ return path.slice(0, end)
12
+ }
13
+ // (As it came: a URL parser takes a path starting with // for a host.)
14
+ export const pathTooLong = rawUrl => { const q = String(rawUrl ?? '').indexOf('?'); return (q < 0 ? String(rawUrl ?? '').length : q) > 2048 }
@@ -0,0 +1,154 @@
1
+ import { parseArgs } from 'node:util'
2
+ import { LETS_ENCRYPT_STAGING, LETS_ENCRYPT } from './acme.js'
3
+ import { join } from 'node:path'
4
+ import { readFileSync, existsSync } from 'node:fs'
5
+ import { homedir } from 'node:os'
6
+
7
+ // Command-line flags win over environment variables.
8
+ //
9
+ // --host <ip> interface to listen on (default 127.0.0.1: this machine only)
10
+ // --all-interfaces same as --host 0.0.0.0 (every IP of the machine)
11
+ // --port <n> default 7787
12
+ // --public-url <url> the address agents and browsers use, e.g. https://pisha.example.com
13
+ // (behind a TLS reverse proxy): the setup and enrollment commands use it, and
14
+ // the dashboard's terminal accepts it as its Origin
15
+ // --trust-proxy behind a reverse proxy: take the client's address from X-Forwarded-For
16
+ // --data-dir <path> default ~/.pisha (or ./data, if it already has a server's data)
17
+ //
18
+ // HTTPS without a reverse proxy:
19
+ // --domain <name> get and renew a Let's Encrypt certificate automatically (needs ports 80 and 443)
20
+ // --acme-email <addr> contact address for Let's Encrypt (optional)
21
+ // --acme-staging use Let's Encrypt's staging environment (for trying it out)
22
+ // --acme-directory <url> another ACME server
23
+ // --tls-cert <file> --tls-key <file> use your own certificate (reloaded when the files change)
24
+ // --http-port <n> port for ACME challenges and the HTTP→HTTPS redirect (default 80)
25
+ const { values: ARGS } = (() => {
26
+ try {
27
+ return parseArgs({
28
+ options: {
29
+ host: { type: 'string' },
30
+ 'all-interfaces': { type: 'boolean' },
31
+ port: { type: 'string' },
32
+ 'public-url': { type: 'string' },
33
+ 'data-dir': { type: 'string' },
34
+ domain: { type: 'string' },
35
+ 'acme-email': { type: 'string' },
36
+ 'acme-staging': { type: 'boolean' },
37
+ 'acme-directory': { type: 'string' },
38
+ 'tls-cert': { type: 'string' },
39
+ 'tls-key': { type: 'string' },
40
+ 'http-port': { type: 'string' },
41
+ 'trust-proxy': { type: 'boolean' },
42
+ 'allow-token-api': { type: 'boolean' },
43
+ help: { type: 'boolean', short: 'h' },
44
+ },
45
+ })
46
+ } catch (err) {
47
+ process.stderr.write(`pisha-server: ${err.message}\nRun with --help to see the options.\n`)
48
+ process.exit(2)
49
+ }
50
+ })()
51
+
52
+ if (ARGS.help) {
53
+ process.stdout.write(`Usage: node server.js [options]
54
+
55
+ --host <ip> Interface to listen on (default 127.0.0.1: this machine only). Env: HOST
56
+ --all-interfaces Listen on every IP of the machine (same as --host 0.0.0.0)
57
+ --port <n> Port (default 7787). Env: PORT
58
+ --public-url <url> Public address, e.g. https://pisha.example.com. Env: PUBLIC_URL
59
+ --data-dir <path> Database and files (default ~/.pisha, or ./data if it already has a server's). Env: DATA_DIR
60
+
61
+ HTTPS, built in (no reverse proxy needed):
62
+ --domain <name> Get and renew a Let's Encrypt certificate automatically. Env: PISHA_DOMAIN
63
+ Needs the domain's DNS pointing here and ports 80 and 443 reachable.
64
+ --acme-email <addr> Contact address for Let's Encrypt (optional). Env: ACME_EMAIL
65
+ --acme-staging Use Let's Encrypt staging (test certificates, higher limits)
66
+ --acme-directory <url> Another ACME server. Env: ACME_DIRECTORY
67
+ --tls-cert <file> Your own certificate (PEM, full chain). Env: TLS_CERT
68
+ --tls-key <file> Its private key (PEM). Env: TLS_KEY
69
+ Both are reloaded automatically when the files change.
70
+ --http-port <n> Port for ACME challenges and the HTTP→HTTPS redirect (default 80)
71
+ --trust-proxy Behind a reverse proxy: take the client address from X-Forwarded-For
72
+ (for rate limits). Only with a proxy that sets it. Env: TRUST_PROXY=1
73
+
74
+ Accounts:
75
+ --allow-token-api Keep the server token working on /api once there are users, for your
76
+ own scripts. It acts on any company. Env: PISHA_ALLOW_TOKEN_API=1
77
+
78
+ With HTTPS the server listens on all interfaces and port 443 by default.
79
+
80
+ Examples:
81
+ node server.js # http://127.0.0.1:7787, this machine only
82
+ node server.js --domain pisha.example.com # https://pisha.example.com, automatic certificate
83
+ node server.js --tls-cert full.pem --tls-key key.pem --public-url https://pisha.example.com
84
+ `)
85
+ process.exit(0)
86
+ }
87
+
88
+ export const DOMAIN = (ARGS.domain ?? process.env.PISHA_DOMAIN ?? '').trim().toLowerCase()
89
+ export const TLS_CERT = ARGS['tls-cert'] ?? process.env.TLS_CERT ?? ''
90
+ export const TLS_KEY = ARGS['tls-key'] ?? process.env.TLS_KEY ?? ''
91
+
92
+ // 'http' (default), 'acme' (automatic Let's Encrypt) or 'files' (your own certificate)
93
+ export const TLS_MODE = DOMAIN ? 'acme' : (TLS_CERT || TLS_KEY) ? 'files' : 'http'
94
+ export const TLS = TLS_MODE !== 'http'
95
+ export const ACME_DIRECTORY = ARGS['acme-directory'] ?? process.env.ACME_DIRECTORY ?? (ARGS['acme-staging'] ? LETS_ENCRYPT_STAGING : LETS_ENCRYPT)
96
+ export const ACME_EMAIL = ARGS['acme-email'] ?? process.env.ACME_EMAIL ?? ''
97
+ export const HTTP_PORT = Number(ARGS['http-port'] ?? process.env.HTTP_PORT ?? 80)
98
+ export const TRUST_PROXY = ARGS['trust-proxy'] === true || process.env.TRUST_PROXY === '1'
99
+ export const ALLOW_TOKEN_API = ARGS['allow-token-api'] === true || process.env.PISHA_ALLOW_TOKEN_API === '1'
100
+
101
+ export const PORT = Number(ARGS.port ?? process.env.PORT ?? (TLS ? 443 : 7787))
102
+ export const HOST = ARGS['all-interfaces'] ? '0.0.0.0' : (ARGS.host ?? process.env.HOST ?? (TLS ? '0.0.0.0' : '127.0.0.1'))
103
+ // Where it keeps everything: --data-dir or DATA_DIR; else a data/ folder here
104
+ // that already has a server's data (a copy of the repository run as before);
105
+ // else ~/.pisha, wherever it is started from (npx pisha-server).
106
+ export const DATA_DIR = ARGS['data-dir'] ?? process.env.DATA_DIR ?? (existsSync(join(process.cwd(), 'data', 'pisha.db')) ? join(process.cwd(), 'data') : join(homedir(), '.pisha'))
107
+ export const PUBLIC_URL = (ARGS['public-url'] ?? process.env.PUBLIC_URL ?? (DOMAIN ? `https://${DOMAIN}${PORT === 443 ? '' : `:${PORT}`}` : '')).replace(/\/+$/, '')
108
+ for (const [label, n] of [['port', PORT], ['http port', HTTP_PORT]]) {
109
+ if (!Number.isInteger(n) || n < 1 || n > 65535) {
110
+ process.stderr.write(`pisha-server: invalid ${label} "${n}"\n`)
111
+ process.exit(2)
112
+ }
113
+ }
114
+ if (DOMAIN && !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(DOMAIN)) {
115
+ process.stderr.write(`pisha-server: invalid domain "${DOMAIN}"\n`)
116
+ process.exit(2)
117
+ }
118
+ if (TLS_MODE === 'files' && !(TLS_CERT && TLS_KEY)) {
119
+ process.stderr.write('pisha-server: --tls-cert and --tls-key go together\n')
120
+ process.exit(2)
121
+ }
122
+ // (It goes into the commands the dashboard gives: nothing a shell would read.)
123
+ if (PUBLIC_URL && !/^https?:\/\/[^\s/'"`$\\&|;<>()^%!]+(\/[^\s'"`$\\&|;<>()^%!]*)?$/.test(PUBLIC_URL)) {
124
+ process.stderr.write(`pisha-server: invalid public URL "${PUBLIC_URL}" (expected http(s)://host[:port])\n`)
125
+ process.exit(2)
126
+ }
127
+ export const MAX_JSON_BODY = 1024 * 1024 // 1 MB
128
+ export const UI_FILE = new URL('../ui/index.html', import.meta.url)
129
+
130
+ // xterm.js for the web terminal, vendored (see vendor/README.md).
131
+ export const VENDOR_FILES = {
132
+ '/vendor/xterm.js': ['./vendor/xterm.js', 'text/javascript; charset=utf-8'],
133
+ '/vendor/addon-fit.js': ['./vendor/addon-fit.js', 'text/javascript; charset=utf-8'],
134
+ '/vendor/xterm.css': ['./vendor/xterm.css', 'text/css; charset=utf-8'],
135
+ '/vendor/InterVariable.woff2': ['./vendor/InterVariable.woff2', 'font/woff2'],
136
+ }
137
+
138
+ // What a phone needs to install the dashboard as an app (no service worker:
139
+ // it is a live page, with nothing to keep offline).
140
+ export const APP_FILES = {
141
+ '/manifest.webmanifest': ['./ui/manifest.webmanifest', 'application/manifest+json'],
142
+ '/icons/icon-192.png': ['./ui/icons/icon-192.png', 'image/png'],
143
+ '/icons/icon-512.png': ['./ui/icons/icon-512.png', 'image/png'],
144
+ '/icons/maskable-512.png': ['./ui/icons/maskable-512.png', 'image/png'],
145
+ '/icons/apple-touch-icon.png': ['./ui/icons/apple-touch-icon.png', 'image/png'],
146
+ // (The name in the logo, Space Grotesk Bold: see ui/fonts/LICENSE-space-grotesk.txt.)
147
+ '/fonts/space-grotesk-700.woff2': ['./ui/fonts/space-grotesk-latin-700-normal.woff2', 'font/woff2'],
148
+ '/fonts/space-grotesk-ext-700.woff2': ['./ui/fonts/space-grotesk-latin-ext-700-normal.woff2', 'font/woff2'],
149
+ }
150
+
151
+ // Single source of truth: server/package.json.
152
+ export const VERSION = (() => {
153
+ try { return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version } catch { return '0.0.0' }
154
+ })()
@@ -0,0 +1,93 @@
1
+ import { DatabaseSync } from 'node:sqlite'
2
+ import { join } from 'node:path'
3
+ import { DATA_DIR } from './config.js'
4
+
5
+ // What is common to all companies. Everything else is in each company's folder.
6
+ export function openControl() {
7
+ const control = new DatabaseSync(join(DATA_DIR, 'control.db'))
8
+ control.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 companies (
14
+ id TEXT PRIMARY KEY,
15
+ name TEXT NOT NULL UNIQUE,
16
+ status TEXT NOT NULL DEFAULT 'active',
17
+ limits_json TEXT NOT NULL DEFAULT '{}',
18
+ created_at INTEGER NOT NULL,
19
+ delete_after INTEGER
20
+ );
21
+ CREATE TABLE IF NOT EXISTS users (
22
+ id TEXT PRIMARY KEY,
23
+ email TEXT NOT NULL UNIQUE,
24
+ name TEXT NOT NULL,
25
+ password_hash TEXT NOT NULL,
26
+ totp_secret_enc TEXT,
27
+ totp_enabled_at INTEGER,
28
+ totp_last_step INTEGER,
29
+ is_platform_admin INTEGER NOT NULL DEFAULT 0,
30
+ disabled_at INTEGER,
31
+ created_at INTEGER NOT NULL,
32
+ last_login_at INTEGER
33
+ );
34
+ CREATE TABLE IF NOT EXISTS memberships (
35
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
36
+ company_id TEXT NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
37
+ role TEXT NOT NULL,
38
+ created_by TEXT,
39
+ created_at INTEGER NOT NULL,
40
+ PRIMARY KEY (user_id, company_id)
41
+ );
42
+ CREATE TABLE IF NOT EXISTS login_sessions (
43
+ token_hash TEXT PRIMARY KEY,
44
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
45
+ mfa_ok INTEGER NOT NULL DEFAULT 0,
46
+ ip TEXT,
47
+ created_at INTEGER NOT NULL,
48
+ last_seen_at INTEGER NOT NULL,
49
+ expires_at INTEGER NOT NULL
50
+ );
51
+ CREATE TABLE IF NOT EXISTS recovery_codes (
52
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
53
+ code_hash TEXT NOT NULL,
54
+ used_at INTEGER,
55
+ PRIMARY KEY (user_id, code_hash)
56
+ );
57
+ -- Links of one use: to join (kind invite) or to set a new password (kind reset).
58
+ CREATE TABLE IF NOT EXISTS invitations (
59
+ token_hash TEXT PRIMARY KEY,
60
+ kind TEXT NOT NULL,
61
+ email TEXT NOT NULL,
62
+ company_id TEXT REFERENCES companies(id) ON DELETE CASCADE,
63
+ role TEXT,
64
+ is_platform_admin INTEGER NOT NULL DEFAULT 0,
65
+ created_by TEXT,
66
+ expires_at INTEGER NOT NULL,
67
+ used_at INTEGER
68
+ );
69
+ CREATE TABLE IF NOT EXISTS platform_audit (
70
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
71
+ at INTEGER NOT NULL,
72
+ user_id TEXT,
73
+ action TEXT NOT NULL,
74
+ target TEXT,
75
+ ip TEXT,
76
+ detail TEXT
77
+ );
78
+ -- Which company a machine's one-time code is for: a code says nothing itself.
79
+ -- (The first company's codes aren't here: a code nobody knows goes to it.)
80
+ CREATE TABLE IF NOT EXISTS enrollment_routes (
81
+ code_hash TEXT PRIMARY KEY,
82
+ company_id TEXT NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
83
+ expires_at INTEGER NOT NULL
84
+ );
85
+ `)
86
+ // An invitation to several companies at once: the first in company_id and
87
+ // role, the rest here (JSON: [{ company, role }]).
88
+ if (!control.prepare('PRAGMA table_info(invitations)').all().some(c => c.name === 'also')) control.exec('ALTER TABLE invitations ADD COLUMN also TEXT')
89
+ // (A person's GitHub user: boards in step with GitHub give them its issues.)
90
+ if (!control.prepare('PRAGMA table_info(users)').all().some(c => c.name === 'github')) control.exec('ALTER TABLE users ADD COLUMN github TEXT')
91
+ control.exec('CREATE UNIQUE INDEX IF NOT EXISTS users_github ON users(lower(github)) WHERE github IS NOT NULL')
92
+ return control
93
+ }
@@ -0,0 +1,151 @@
1
+ import { mkdirSync, chmodSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import {
4
+ randomBytes, generateKeyPairSync, createPrivateKey, createPublicKey, createHash, sign as signBytes,
5
+ timingSafeEqual, verify as verifyBytes,
6
+ } from 'node:crypto'
7
+ import { DATA_DIR } from './config.js'
8
+ import { sha256 } from './basics.js'
9
+ import { ApiError, bad } from './errors.js'
10
+
11
+ const sameSecret = (token, secret) => typeof token === 'string' && token !== '' &&
12
+ timingSafeEqual(Buffer.from(sha256(token)), Buffer.from(sha256(secret)))
13
+
14
+ // What is the server's, whichever company a request is for.
15
+ export function openServerCredentials() {
16
+ // Messages, attachments and observation are private: only this user can read
17
+ // the data folder and what the server creates in it.
18
+ process.umask(0o077)
19
+ mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 })
20
+ try { chmodSync(DATA_DIR, 0o700) } catch {}
21
+
22
+ // Server token: PISHA_SERVER_TOKEN if set; otherwise the one saved in
23
+ // DATA_DIR/server-token; otherwise a new one, generated and saved there so
24
+ // restarts keep the same token and plugins don't need reconfiguring.
25
+ const TOKEN_FILE = join(DATA_DIR, 'server-token')
26
+ const { token: SERVER_TOKEN, source: TOKEN_SOURCE } = (() => {
27
+ const fromEnv = process.env.PISHA_SERVER_TOKEN ?? process.env.SWARM_SERVER_TOKEN // SWARM_: former name
28
+ if (fromEnv) {
29
+ if (fromEnv.length < 16) {
30
+ process.stderr.write('pisha-server: PISHA_SERVER_TOKEN must be at least 16 chars\n')
31
+ process.exit(1)
32
+ }
33
+ return { token: fromEnv, source: 'env PISHA_SERVER_TOKEN' }
34
+ }
35
+ try {
36
+ const saved = readFileSync(TOKEN_FILE, 'utf8').trim()
37
+ if (saved.length >= 16) return { token: saved, source: TOKEN_FILE }
38
+ } catch {}
39
+ const generated = randomBytes(24).toString('hex')
40
+ writeFileSync(TOKEN_FILE, generated + '\n', { mode: 0o600 })
41
+ return { token: generated, source: `${TOKEN_FILE} (new)` }
42
+ })()
43
+
44
+ // This server's own key: made the first time it starts, and kept. Machines and
45
+ // sessions remember it, and from then on talk only to whoever can prove to hold
46
+ // it. Never replaced by itself: that would look like an impostor to all of them.
47
+ const SERVER_KEY_FILE = join(DATA_DIR, 'server-key')
48
+ const SERVER_KEY = (() => {
49
+ let pem = null
50
+ try { pem = readFileSync(SERVER_KEY_FILE) } catch (err) {
51
+ if (err.code !== 'ENOENT') { process.stderr.write(`pisha-server: cannot read ${SERVER_KEY_FILE}: ${err.message}\n`); process.exit(1) }
52
+ }
53
+ if (pem === null) {
54
+ pem = generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' })
55
+ writeFileSync(SERVER_KEY_FILE, pem, { mode: 0o600, flag: 'wx' })
56
+ }
57
+ try {
58
+ const privateKey = createPrivateKey(pem)
59
+ if (privateKey.asymmetricKeyType !== 'ed25519') throw new Error('not an Ed25519 key')
60
+ const pub = createPublicKey(privateKey).export({ format: 'der', type: 'spki' }).toString('base64url')
61
+ const hash = createHash('sha256').update(pub).digest('hex')
62
+ return { privateKey, public: pub, hash, fingerprint: hash.slice(0, 16).replace(/(.{4})(?=.)/g, '$1 ') }
63
+ } catch (err) {
64
+ process.stderr.write(`pisha-server: ${SERVER_KEY_FILE} is not a usable key (${err.message}). Put the backup back; a new key would make every machine and session refuse this server\n`)
65
+ process.exit(1)
66
+ }
67
+ })()
68
+ const signAsServer = fields => signBytes(null, Buffer.from(JSON.stringify(fields)), SERVER_KEY.privateKey).toString('base64url')
69
+
70
+ const isServerToken = token => sameSecret(token, SERVER_TOKEN)
71
+
72
+ // Anyone can ask this server to prove it holds its key, on a nonce of their own.
73
+ // The answer also brings a challenge of one use, for them to do the same.
74
+ const serverChallenges = new Map() // challenge -> expires (ms)
75
+ function serverIdentity(nonce) {
76
+ if (typeof nonce !== 'string' || !/^[A-Za-z0-9_-]{16,128}$/.test(nonce)) throw bad('nonce must be 16 to 128 URL-safe characters')
77
+ for (const [c, exp] of serverChallenges) { if (exp >= Date.now() && serverChallenges.size < 5000) break; serverChallenges.delete(c) }
78
+ const challenge = randomBytes(24).toString('base64url')
79
+ serverChallenges.set(challenge, Date.now() + 60_000)
80
+ return { key: SERVER_KEY.public, challenge, sig: signAsServer(['pisha-server-identity-1', nonce, challenge]) }
81
+ }
82
+ function takeChallenge(challenge) {
83
+ const exp = serverChallenges.get(challenge)
84
+ serverChallenges.delete(challenge)
85
+ return exp !== undefined && exp >= Date.now()
86
+ }
87
+
88
+ // Signed for this server and this purpose only: useless anywhere else.
89
+ function proofIsGood(publicKey, purpose, subject, challenge, extra, proof) {
90
+ try {
91
+ const key = createPublicKey({ key: Buffer.from(String(publicKey), 'base64url'), format: 'der', type: 'spki' })
92
+ if (key.asymmetricKeyType !== 'ed25519') return false
93
+ return verifyBytes(null, Buffer.from(JSON.stringify(['pisha-client-proof-1', SERVER_KEY.public, purpose, subject, String(challenge), String(extra)])), key, Buffer.from(String(proof), 'base64url'))
94
+ } catch {
95
+ return false
96
+ }
97
+ }
98
+
99
+ return {
100
+ SERVER_TOKEN, TOKEN_SOURCE, SERVER_KEY_FILE, SERVER_KEY, signAsServer, isServerToken, serverIdentity,
101
+ takeChallenge, proofIsGood,
102
+ }
103
+ }
104
+
105
+ // What is a company's: its folder, and the token its machines join with.
106
+ export function openCompanyCredentials(dir, { SERVER_TOKEN }, { credentialPrefix }) {
107
+ mkdirSync(join(dir, 'files'), { recursive: true, mode: 0o700 })
108
+ for (const p of [dir, join(dir, 'files')]) { try { chmodSync(p, 0o700) } catch {} }
109
+ for (const f of ['pisha.db', 'pisha.db-wal', 'pisha.db-shm']) { try { chmodSync(join(dir, f), 0o600) } catch {} }
110
+
111
+ // Join token: lets a machine register NEW session names (POST /register
112
+ // without reset) and nothing else. It is what plugins and enrolled machines
113
+ // keep on disk; the server token above is the admin credential (dashboard,
114
+ // web terminals, /admin, rotating identities) and never leaves the browser.
115
+ const JOIN_TOKEN_FILE = join(dir, 'join-token')
116
+ // (The first company's, the one a server without companies has.)
117
+ const FROM_ENV = credentialPrefix ? null : process.env.PISHA_JOIN_TOKEN
118
+ let { token: JOIN_TOKEN, source: JOIN_TOKEN_SOURCE } = (() => {
119
+ const fromEnv = FROM_ENV
120
+ if (fromEnv) {
121
+ if (fromEnv.length < 16 || fromEnv === SERVER_TOKEN) {
122
+ process.stderr.write('pisha-server: PISHA_JOIN_TOKEN must be at least 16 chars and differ from the server token\n')
123
+ process.exit(1)
124
+ }
125
+ return { token: fromEnv, source: 'env PISHA_JOIN_TOKEN' }
126
+ }
127
+ try {
128
+ const saved = readFileSync(JOIN_TOKEN_FILE, 'utf8').trim()
129
+ if (saved.length >= 16 && saved !== SERVER_TOKEN) return { token: saved, source: JOIN_TOKEN_FILE }
130
+ } catch {}
131
+ const generated = `sj_${credentialPrefix}${randomBytes(24).toString('hex')}`
132
+ writeFileSync(JOIN_TOKEN_FILE, generated + '\n', { mode: 0o600 })
133
+ return { token: generated, source: `${JOIN_TOKEN_FILE} (new)` }
134
+ })()
135
+
136
+ const isJoinToken = token => sameSecret(token, JOIN_TOKEN)
137
+ const joinToken = () => ({ token: JOIN_TOKEN, source: JOIN_TOKEN_SOURCE })
138
+
139
+ // A new join token: machines configured with the old one can no longer
140
+ // register new names (their existing identities keep working).
141
+ function rotateJoinToken() {
142
+ if (FROM_ENV) throw new ApiError(409, 'Conflict: the join token comes from PISHA_JOIN_TOKEN; change it there')
143
+ JOIN_TOKEN = `sj_${credentialPrefix}${randomBytes(24).toString('hex')}`
144
+ JOIN_TOKEN_SOURCE = JOIN_TOKEN_FILE
145
+ writeFileSync(JOIN_TOKEN_FILE, JOIN_TOKEN + '\n', { mode: 0o600 })
146
+ process.stderr.write(`pisha-server: ${credentialPrefix && `[${credentialPrefix.slice(0, -1)}] `}join token rotated\n`)
147
+ return { join_token: JOIN_TOKEN }
148
+ }
149
+
150
+ return { isJoinToken, joinToken, rotateJoinToken }
151
+ }