slatebox 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,797 @@
1
+ // Install, change, upgrade and run Slatebox on a Docker host: this computer
2
+ // (the default) or a Linux server over SSH. One flow for both:
3
+ //
4
+ // preflight -> image -> plan -> confirm -> secrets -> files -> start -> health
5
+ // -> (rollback on failure) -> first account -> backup schedule -> record
6
+ import { existsSync, readdirSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import { EXIT, InstallError } from '../errors.mjs'
9
+ import { firstAdmin, makeSetupLink, setupState, stillWaiting } from '../setup-link.mjs'
10
+ import { checkArch, checkCpu, DEFAULT_IMAGE, FALLBACK_CAPABILITIES, inspectImage, normalArch, pinImage, probeImage, refreshTag, resolveImage } from '../image.mjs'
11
+ import { emptyPlan } from '../plan.mjs'
12
+ import { installDir, recordText, writeRecord } from '../record.mjs'
13
+ import { COMPOSE_FILE, hostPort, ports, renderCompose, SECRETS_FILE, SETTINGS_FILE } from '../render/compose.mjs'
14
+ import { settingsFor } from '../render/settings.mjs'
15
+ import { shq } from '../runner.mjs'
16
+ import { secretValues } from '../secret-values.mjs'
17
+ import { envFileText, parseEnvFile } from '../secrets.mjs'
18
+ import { firstFreePort, localHost, MARKER, parseKeyValues, portFree, remotePreflightScript, sshHost, which } from './hosts.mjs'
19
+ import { checkTeamAddress, ensureTeamAddress, TUNNEL_TOKEN } from './address.mjs'
20
+ import { credentialsPath } from '../cloud.mjs'
21
+
22
+ const SLATEBOX = '/opt/slatebox/bin/slatebox'
23
+ const KEPT_FILE = 'secrets.kept.env'
24
+ const BACKUP_SCRIPT = 'backup.sh'
25
+
26
+ export function hostFor(ctx, answers) {
27
+ if (answers.target === 'ssh') return sshHost(ctx, answers.ssh, { name: answers.name, home: ctx.home })
28
+ return localHost(ctx, { dir: installDir(ctx.home, answers.name), name: answers.name })
29
+ }
30
+
31
+ // The folder is stored absolute (answers.mjs makes it so once), so it never
32
+ // depends on the directory the installer runs from.
33
+ export const backupsDir = (host, answers) =>
34
+ answers.backups.to === 'default' || answers.backups.to === 'off' || answers.backups.to.startsWith('s3://')
35
+ ? join(host.dir, 'backups')
36
+ : answers.backups.to
37
+
38
+ const KEK = 'SLATEBOX_KEY_ENCRYPTION_KEY'
39
+ const PENDING_TOKEN = 'pending-team-address-claim'
40
+
41
+ /** Native Windows has no sh, crontab or file modes; Docker Desktop's WSL 2 integration is the way there. */
42
+ export function refuseWindows(ctx) {
43
+ if ((ctx.platform || process.platform) === 'win32') {
44
+ throw new InstallError(EXIT.PRECONDITION, 'Native Windows is not supported for installs on this computer or over SSH. Run the installer inside WSL 2 (Ubuntu) with Docker Desktop\'s WSL integration on, or use --target export or --target k8s.')
45
+ }
46
+ }
47
+
48
+ const lastLine = text => text.trim().split('\n').filter(Boolean).pop() || ''
49
+
50
+ /** The port a local install should use when nothing says otherwise. */
51
+ export async function defaultLocalPort() {
52
+ return (await firstFreePort(7070)) ?? 7070
53
+ }
54
+
55
+ // ------------------------------------------------------------------ preflight
56
+
57
+ /**
58
+ * What to do when this computer has no docker command. Nothing is installed
59
+ * for the person here: Docker Desktop, OrbStack and Podman need their own
60
+ * installers and, on Linux, root.
61
+ */
62
+ export function dockerMissing(ctx) {
63
+ const lines = ['Docker is not installed on this computer, and Slatebox runs in one Docker container. Nothing was changed.']
64
+ const platform = ctx.platform || process.platform
65
+ if (which('podman', ctx.env.PATH)) {
66
+ lines.push('Podman is installed: turn on its Docker compatibility so the docker command works (the podman-docker package on Linux, or Docker compatibility in Podman Desktop), make sure `docker compose version` answers, then run this again.')
67
+ } else if (platform === 'darwin') {
68
+ lines.push('Install Docker Desktop (https://docs.docker.com/desktop/setup/install/mac-install/) or OrbStack (https://orbstack.dev), start it, then run this again.')
69
+ } else if (platform === 'linux') {
70
+ lines.push('Install Docker Engine (https://docs.docker.com/engine/install/), for example: curl -fsSL https://get.docker.com | sudo sh. Then run this again.')
71
+ } else {
72
+ lines.push('Install Docker (https://docs.docker.com/get-started/get-docker/), start it, then run this again.')
73
+ }
74
+ lines.push('To install on another machine instead, run npx slatebox there, or: npx slatebox install ssh <user@host>.')
75
+ return lines.join(' ')
76
+ }
77
+
78
+ async function preflightLocal(ctx, host) {
79
+ const version = await host.docker(['version', '--format', '{{.Server.Version}}'])
80
+ if (version.code === 127) throw new InstallError(EXIT.PRECONDITION, dockerMissing(ctx), { docker: 'missing', podman: Boolean(which('podman', ctx.env.PATH)) })
81
+ if (version.code !== 0) {
82
+ throw new InstallError(EXIT.PRECONDITION, `Docker is not running on this computer (${lastLine(version.stderr) || 'docker version failed'}). Start Docker Desktop, OrbStack, Podman or the Docker service, then run this again.`, { docker: 'stopped' })
83
+ }
84
+ const compose = await host.docker(['compose', 'version', '--short'])
85
+ if (compose.code !== 0) throw new InstallError(EXIT.PRECONDITION, 'Docker Compose v2 (`docker compose`) is missing. Install the compose plugin, then run this again.')
86
+ const arch = await host.docker(['version', '--format', '{{.Server.Arch}}'])
87
+ // cron runs with PATH=/usr/bin:/bin; Docker Desktop and OrbStack live elsewhere.
88
+ return { docker: version.stdout.trim(), compose: compose.stdout.trim(), arch: arch.code === 0 ? arch.stdout.trim() : null, docker_path: which('docker', ctx.env.PATH), aws_path: which('aws', ctx.env.PATH) }
89
+ }
90
+
91
+ async function checkPorts(host, answers, facts, existing) {
92
+ if (existing.container.exists) return // the install already holds its ports
93
+ const publish = ports(answers).map(hostPort)
94
+ let taken
95
+ if (host.kind === 'local') {
96
+ taken = []
97
+ for (const port of publish) if (!(await portFree(port))) taken.push(port)
98
+ } else {
99
+ const listening = new Set((facts.listening || '').split(/\s+/).filter(Boolean).map(Number))
100
+ taken = publish.filter(port => listening.has(port))
101
+ }
102
+ if (taken.length) {
103
+ throw new InstallError(EXIT.PRECONDITION, `Port ${taken.join(' and ')} on ${host.where} ${taken.length > 1 ? 'are' : 'is'} taken. Free ${taken.length > 1 ? 'them' : 'it'}, or choose another port with --port <number>.`, { field: 'address.port' })
104
+ }
105
+ }
106
+
107
+ async function hostKeyHelp(ctx, ssh, where) {
108
+ const scan = await ctx.run('ssh-keyscan', ['-p', String(ssh.port), '--', ssh.host], { timeout: 20_000 }).catch(() => null)
109
+ const prints = scan?.code === 0 && scan.stdout.trim() ? await ctx.run('ssh-keygen', ['-lf', '-'], { input: scan.stdout }).catch(() => null) : null
110
+ const lines = prints?.code === 0 ? prints.stdout.trim().split('\n').map(line => ` ${line}`) : []
111
+ const login = `ssh ${ssh.port !== 22 ? `-p ${ssh.port} ` : ''}${where}`
112
+ return `${where} is not in your known_hosts yet, so ssh refused to connect (Host key verification failed). Nothing was changed.\n` +
113
+ (lines.length ? `The server offers these host keys:\n${lines.join('\n')}\nCheck one against what your provider or the server's console shows (ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub on the server), then ` : 'Then ') +
114
+ `connect once yourself and accept the key: ${login}\nRun the installer again afterwards.`
115
+ }
116
+
117
+ async function preflightSsh(ctx, host, answers) {
118
+ const publish = ports(answers).map(hostPort)
119
+ const result = await host.remote('sh -s', { input: remotePreflightScript(publish), timeout: 60_000 })
120
+ if (result.code !== 0 && /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(result.stderr)) {
121
+ if (/HAS CHANGED/i.test(result.stderr)) throw new InstallError(EXIT.PRECONDITION, `The host key of ${host.where} has CHANGED since you last connected. That can mean someone is in the middle. Nothing was changed; find out why before you remove the old key (ssh-keygen -R ${answers.ssh.host}).`)
122
+ throw new InstallError(EXIT.PRECONDITION, await hostKeyHelp(ctx, answers.ssh, host.where), { needs: 'host-key' })
123
+ }
124
+ if (result.code !== 0 && !result.stdout) {
125
+ throw new InstallError(EXIT.PRECONDITION, `Cannot reach ${host.where} over SSH: ${lastLine(result.stderr)}. Check the host, user and key (ssh ${host.where} must work without a password prompt).`)
126
+ }
127
+ const facts = parseKeyValues(result.stdout)
128
+ if (facts.uid !== '0') {
129
+ if (facts.sudo !== 'yes' || answers.ssh.sudo === 'no') {
130
+ throw new InstallError(EXIT.PRECONDITION, `${host.where} is not root and has no passwordless sudo. Connect as root, or allow this user to run sudo without a password.`)
131
+ }
132
+ host.sudo = 'sudo -n '
133
+ }
134
+ if (!['x86_64', 'aarch64', 'arm64'].includes(facts.arch)) {
135
+ throw new InstallError(EXIT.PRECONDITION, `${host.where} is ${facts.arch}; Slatebox runs on 64-bit Intel/AMD (x86_64) or ARM (aarch64).`)
136
+ }
137
+ if (facts.docker_path?.includes('/snap/')) {
138
+ throw new InstallError(EXIT.PRECONDITION, `Docker on ${host.where} is the snap package, which cannot run Slatebox's volume and restart settings reliably. Remove it (snap remove docker) and install Docker Engine from docs.docker.com.`)
139
+ }
140
+ facts.needsDocker = !facts.docker_path || !facts.docker_server
141
+ if (facts.needsDocker && !answers.ssh.installDocker) {
142
+ throw new InstallError(EXIT.PRECONDITION,
143
+ `Docker is not ${facts.docker_path ? 'running' : 'installed'} on ${host.where}. Nothing was changed. To let the installer install Docker Engine from get.docker.com, run again with --install-docker.`,
144
+ { needs: 'install-docker' })
145
+ }
146
+ if (!facts.needsDocker && !facts.compose) throw new InstallError(EXIT.PRECONDITION, `Docker Compose v2 is missing on ${host.where}. Install docker-compose-plugin, then run again.`)
147
+ const diskGb = Number(facts.disk_kb || 0) / 1024 / 1024
148
+ if (facts.disk_kb && diskGb < 5) throw new InstallError(EXIT.PRECONDITION, `${host.where} has ${diskGb.toFixed(1)} GB free; Slatebox needs at least 5 GB.`)
149
+ return facts
150
+ }
151
+
152
+ // ------------------------------------------------------------------ state
153
+
154
+ async function existingState(host, answers) {
155
+ const files = {}
156
+ for (const file of [COMPOSE_FILE, SETTINGS_FILE, SECRETS_FILE, KEPT_FILE, BACKUP_SCRIPT]) files[file] = await host.readFile(join(host.dir, file))
157
+ let container = { exists: false }
158
+ const inspected = await host.docker(['inspect', '--format', '{{json .}}', answers.name])
159
+ if (inspected.code === 0) {
160
+ const info = JSON.parse(inspected.stdout)
161
+ container = { exists: true, running: info.State?.Running, health: info.State?.Health?.Status, image: info.Image }
162
+ }
163
+ // The data volume outlives the container and this computer's files (uninstall keeps it).
164
+ const volume = (await host.docker(['volume', 'inspect', `${answers.name}-data`])).code === 0
165
+ return { files, container, volume }
166
+ }
167
+
168
+ /**
169
+ * A new key encryption key over existing data would make every key people
170
+ * saved unreadable, and the app cannot tell. So: never, unless asked for.
171
+ */
172
+ function guardKey(ctx, host, answers, stored, secrets, existing) {
173
+ if (!(KEK in secrets) || secrets[KEK] !== 'generate' || stored[KEK]) return
174
+ if (!existing.volume && !existing.container.exists) return
175
+ if (ctx.flags['new-encryption-key']) return
176
+ const path = join(host.dir, SECRETS_FILE)
177
+ throw new InstallError(EXIT.PRECONDITION,
178
+ `The data volume ${answers.name}-data on ${host.where} already holds a Slatebox, but ${path} has no SLATEBOX_KEY_ENCRYPTION_KEY for it. ` +
179
+ 'A new key would make every AI and call key people saved unreadable. Nothing was changed.\n' +
180
+ `Put the original secrets.env back at ${path} (from where you backed it up, or from the home or user that installed it: --home <dir>), then run again. ` +
181
+ 'To start over with a new key and lose the saved keys, add --new-encryption-key.',
182
+ { needs: 'encryption-key', path })
183
+ }
184
+
185
+ // ------------------------------------------------------------------ health
186
+
187
+ async function start(host, timeout) {
188
+ const up = await host.compose(['up', '-d', '--wait', '--wait-timeout', String(timeout)], { timeout: (timeout + 120) * 1000 })
189
+ return up.code === 0 ? { ok: true } : { ok: false, why: lastLine(up.stderr) || 'docker compose up failed' }
190
+ }
191
+
192
+ async function health(ctx, host, answers) {
193
+ const deep = await host.docker(['exec', answers.name, SLATEBOX, 'health', '--deep', '--wait', '60'], { timeout: 120_000 })
194
+ if (deep.code !== 0) return { ok: false, why: lastLine(deep.stderr) || 'slatebox health failed' }
195
+ if (answers.address.team) return teamHealth(ctx, host, answers)
196
+ // From outside, the way a browser asks.
197
+ const url = `${answers.address.url}/readyz`
198
+ let outside = false
199
+ for (let attempt = 0; attempt < 10 && !outside; attempt++) {
200
+ try {
201
+ const response = await ctx.fetch(url, { signal: AbortSignal.timeout(5000) })
202
+ outside = response.ok && (await response.json().catch(() => null))?.ok === true
203
+ } catch { /* retry */ }
204
+ if (!outside) await new Promise(resolve => setTimeout(resolve, 1000))
205
+ }
206
+ if (!outside) {
207
+ const why = `Slatebox is healthy inside the container, but ${url} does not answer from here.`
208
+ if (host.kind === 'local' && answers.address.port !== null) return { ok: false, why }
209
+ return { ok: true, warning: `${why} Check DNS, the firewall and that ports ${ports(answers).map(p => p.split(':')[0]).join('/')} are open.` }
210
+ }
211
+ return { ok: true }
212
+ }
213
+
214
+ /** The tunnel's connections, from inside the container; null when the image cannot say. */
215
+ export async function tunnelState(host, name, wait = 0) {
216
+ const result = await host.docker(['exec', name, SLATEBOX, 'tunnel', '--json', ...(wait ? ['--wait', String(wait)] : [])], { timeout: (wait + 30) * 1000 })
217
+ try { return JSON.parse(lastLine(result.stdout)) } catch { return null }
218
+ }
219
+
220
+ /**
221
+ * A team address is healthy when the container's cloudflared holds connections and the address
222
+ * answers from here through Cloudflare. A tunnel that is slow to come up is a warning, not a
223
+ * rollback: Slatebox itself is healthy, and the tunnel keeps trying on its own.
224
+ */
225
+ async function teamHealth(ctx, host, answers) {
226
+ const tunnel = await tunnelState(host, answers.name, 60)
227
+ if (tunnel?.ready) ctx.out.step('tunnel', 'ok', `Secure tunnel connected (${tunnel.connections} connection${tunnel.connections === 1 ? '' : 's'})`)
228
+ // A refused tunnel stays down until it gets a new token: no point probing the address.
229
+ if (tunnel?.state === 'failed') {
230
+ return { ok: true, warning: `Slatebox is healthy on this computer, but Cloudflare refused its secure tunnel (a revoked token or a suspended address), so ${answers.address.url} does not reach it. See slatebox status and slatebox logs --service tunnel; slatebox address rotate gets a new token.` }
231
+ }
232
+
233
+ const url = `${answers.address.url}/readyz`
234
+ const attempts = ctx.teamHealthAttempts ?? 30
235
+ for (let attempt = 0; attempt < attempts; attempt++) {
236
+ try {
237
+ const response = await ctx.fetch(url, { signal: AbortSignal.timeout(8000) })
238
+ if (response.ok && (await response.json().catch(() => null))?.ok === true) {
239
+ ctx.out.step('address', 'ok', `${answers.address.url} answers`)
240
+ return { ok: true }
241
+ }
242
+ } catch { /* retry */ }
243
+ if (attempt < attempts - 1) await new Promise(resolve => setTimeout(resolve, ctx.teamHealthDelay ?? 2000))
244
+ }
245
+ const why = tunnel?.ready ? `${answers.address.url} does not answer from here yet` : 'the secure tunnel has not connected yet'
246
+ return { ok: true, warning: `Slatebox is healthy on this computer, but ${why}. It keeps trying by itself; check with slatebox status and slatebox logs --service tunnel.` }
247
+ }
248
+
249
+ async function startAndCheck(ctx, host, answers) {
250
+ const started = await start(host, ctx.healthTimeout)
251
+ if (!started.ok) return started
252
+ return health(ctx, host, answers)
253
+ }
254
+
255
+ // ------------------------------------------------------------------ backups
256
+
257
+ function backupScript(host, answers, facts) {
258
+ const to = answers.backups.to
259
+ const s3 = to.startsWith('s3://')
260
+ const dir = backupsDir(host, answers)
261
+ const bucket = `${to.replace(/\/$/, '')}/`
262
+ return `#!/bin/sh
263
+ # Written by the slatebox installer: one backup of the Slatebox "${answers.name}",
264
+ # keeping the last ${answers.backups.keep}. Run by ${host.kind === 'ssh' ? 'a systemd timer or cron' : 'cron'}; safe to run by hand.
265
+ set -u
266
+ umask 077
267
+ docker=${shq(facts.docker_path || 'docker')}
268
+ stamp=$(date -u +%Y%m%d-%H%M%S)
269
+ ${s3 ? `aws=${shq(facts.aws_path || 'aws')}
270
+ bucket=${shq(bucket)}
271
+ "$docker" exec ${shq(answers.name)} ${SLATEBOX} backup | "$aws" s3 cp - "$bucket"slatebox-"$stamp".gz || exit 1
272
+ echo "backup written to $bucket""slatebox-$stamp.gz (keep old ones with a bucket lifecycle rule)"` : `dir=${shq(dir)}
273
+ mkdir -p "$dir"
274
+ file="$dir/slatebox-$stamp.gz"
275
+ if "$docker" exec ${shq(answers.name)} ${SLATEBOX} backup > "$file.part"; then
276
+ mv "$file.part" "$file"
277
+ echo "backup written to $file"
278
+ else
279
+ rm -f "$file.part"
280
+ echo "the backup failed; earlier backups are kept" >&2
281
+ exit 1
282
+ fi
283
+ ls -1t "$dir"/slatebox-*.gz 2>/dev/null | tail -n +${answers.backups.keep + 1} | while read -r old; do rm -f "$old"; done`}
284
+ `
285
+ }
286
+
287
+ const MARK = name => `# slatebox-installer:${name}`
288
+
289
+ async function scheduleBackups(ctx, host, answers, facts) {
290
+ const script = join(host.dir, BACKUP_SCRIPT)
291
+ if (host.kind === 'local') {
292
+ const listed = await ctx.run('crontab', ['-l'])
293
+ const current = listed.code === 0 ? listed.stdout : ''
294
+ const lines = current.split('\n')
295
+ const ours = lines.filter(line => line.endsWith(MARK(answers.name)))
296
+ const want = answers.backups.to === 'off' ? [] : [`${answers.backups.schedule} /bin/sh ${shq(script)} >> ${shq(join(host.dir, 'backup.log'))} 2>&1 ${MARK(answers.name)}`]
297
+ // Only the installer's own line is ever touched; the rest of the crontab stays byte for byte.
298
+ if (ours.length === want.length && ours.every((line, i) => line === want[i])) return 'unchanged'
299
+ const others = lines.filter(line => !line.endsWith(MARK(answers.name)))
300
+ while (others.length && others.at(-1) === '') others.pop()
301
+ const next = [...others, ...want].length ? `${[...others, ...want].join('\n')}\n` : ''
302
+ const written = await ctx.run('crontab', ['-'], { input: next })
303
+ if (written.code !== 0) throw new Error(`crontab: ${lastLine(written.stderr)}`)
304
+ return answers.backups.to === 'off' ? 'removed' : 'cron'
305
+ }
306
+ const unit = `slatebox-${answers.name}-backup`
307
+ const daily = /^(\d+) (\d+) \* \* \*$/.exec(answers.backups.schedule)
308
+ if (answers.backups.to === 'off') {
309
+ await host.sh(`systemctl disable --now ${unit}.timer 2>/dev/null; rm -f /etc/systemd/system/${unit}.service /etc/systemd/system/${unit}.timer /etc/cron.d/${unit}; systemctl daemon-reload 2>/dev/null; true`)
310
+ return 'removed'
311
+ }
312
+ if (facts?.systemd === 'yes' && daily) {
313
+ // ssh.dir is checked in answers.mjs (letters, digits, . _ - /), so the path needs no quoting here.
314
+ const service = `[Unit]\nDescription=Back up Slatebox ${answers.name}\n\n[Service]\nType=oneshot\nExecStart=/bin/sh ${script}\n`
315
+ const timer = `[Unit]\nDescription=Back up Slatebox ${answers.name} daily\n\n[Timer]\nOnCalendar=*-*-* ${daily[2].padStart(2, '0')}:${daily[1].padStart(2, '0')}:00\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n`
316
+ await host.writeFile(`/etc/systemd/system/${unit}.service`, service, 0o644)
317
+ await host.writeFile(`/etc/systemd/system/${unit}.timer`, timer, 0o644)
318
+ const enabled = await host.sh(`systemctl daemon-reload && systemctl enable --now ${unit}.timer`)
319
+ if (enabled.code !== 0) throw new Error(`systemctl: ${lastLine(enabled.stderr)}`)
320
+ return 'systemd timer'
321
+ }
322
+ await host.writeFile(`/etc/cron.d/${unit}`, `# Written by the slatebox installer\n${answers.backups.schedule} root /bin/sh ${shq(script)} >> ${shq(join(host.dir, 'backup.log'))} 2>&1\n`, 0o644)
323
+ return facts?.cron === 'yes' ? 'cron' : 'cron (no cron daemon found: install cron for the schedule to run)'
324
+ }
325
+
326
+ // ------------------------------------------------------------------ apply
327
+
328
+ /**
329
+ * Install, change or upgrade. Returns the done event's fields.
330
+ * @param {object} options {record?: object, planOnly?: boolean, imageRef?: string, action?: 'install'|'upgrade'|'change'}
331
+ */
332
+ export async function applyDocker(ctx, answers, options = {}) {
333
+ refuseWindows(ctx)
334
+ const host = hostFor(ctx, answers)
335
+ try {
336
+ return await applyOn(ctx, host, answers, options)
337
+ } finally {
338
+ await host.close?.()
339
+ }
340
+ }
341
+
342
+ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef, archive, refresh = false }) {
343
+ const { out } = ctx
344
+ out.step('preflight', 'start', `Checking ${host.where}`)
345
+ const facts = host.kind === 'ssh' ? await preflightSsh(ctx, host, answers) : await preflightLocal(ctx, host)
346
+ const existing = facts.needsDocker
347
+ ? { files: {}, container: { exists: false }, volume: false }
348
+ : await existingState(host, answers)
349
+ await checkPorts(host, answers, facts, existing)
350
+ out.step('preflight', 'ok', `${host.where}: Docker ${facts.docker || facts.docker_server || '(to be installed)'}`)
351
+ // Docker first, then the name: nobody claims a name on a machine that cannot run Slatebox.
352
+ const team = answers.address.team ? await checkTeamAddress(ctx, answers) : null
353
+
354
+ // The image. Before a yes, only what is already on the host is looked at:
355
+ // nothing is pulled or loaded (an upgrade fetches its tag first, because
356
+ // whether it is newer is the question the plan answers).
357
+ const dockerMissing = host.kind === 'ssh' && facts.needsDocker
358
+ const wanted = imageRef || answers.image || DEFAULT_IMAGE
359
+ let image = { ref: wanted, pinned: wanted, id: null }
360
+ let caps = FALLBACK_CAPABILITIES
361
+ let imageReady = false
362
+ const ready = async () => {
363
+ caps = await probeImage(host.docker, image.id)
364
+ await checkCpu(host.docker, image.id)
365
+ checkArch(image, facts.arch, host.where)
366
+ imageReady = true
367
+ }
368
+ if (!dockerMissing && !archive) {
369
+ if (refresh) await refreshTag(host.docker, wanted, out.step.bind(out))
370
+ const info = await inspectImage(host.docker, wanted)
371
+ if (info) {
372
+ image = pinImage(wanted, info)
373
+ await ready()
374
+ }
375
+ }
376
+
377
+ const stored = { ...parseEnvFile(existing.files[KEPT_FILE] || ''), ...parseEnvFile(existing.files[SECRETS_FILE] || '') }
378
+ let settings, composeText, settingsText, scriptText, secretsText, generated, kept
379
+ const render = async () => {
380
+ settings = settingsFor(answers, caps)
381
+ guardKey(ctx, host, answers, stored, settings.secrets, existing)
382
+ composeText = renderCompose(answers, { image: image.pinned, hostGateway: settings.hostGateway })
383
+ settingsText = envFileText(settings.env, `Settings for the Slatebox "${answers.name}", written by the slatebox installer. No secrets.`)
384
+ scriptText = answers.backups.to === 'off' ? null : backupScript(host, answers, facts)
385
+ // The key encryption key is made once and then kept; referenced keys are read now. Before
386
+ // the plan is approved, a team address that is still to be claimed has no token: the plan
387
+ // shows a stand-in, and nothing is written until the claim has brought the real one.
388
+ const pending = team && !ctx.tunnelToken && !stored[TUNNEL_TOKEN]
389
+ const secrets = await secretValues(pending ? { ...ctx, tunnelToken: PENDING_TOKEN } : ctx, settings.secrets, stored)
390
+ generated = secrets.generated
391
+ kept = Object.fromEntries(Object.entries(stored).filter(([name]) => !(name in secrets.values) && name === KEK))
392
+ secretsText = envFileText(secrets.values, `Secrets for the Slatebox "${answers.name}". Keep a copy of SLATEBOX_KEY_ENCRYPTION_KEY with your backups.`)
393
+ }
394
+ await render()
395
+ const previousImage = existing.container.image
396
+ const changedFrom = () => Boolean(existing.container.exists && image.id && previousImage && previousImage !== image.id)
397
+ let imageChanged = changedFrom()
398
+ const secretsPath = join(host.dir, SECRETS_FILE)
399
+
400
+ const changes = []
401
+ if (!existing.container.exists) changes.push(existing.files[COMPOSE_FILE] ? 'start the stopped install again' : existing.volume ? `create the container on the existing data volume ${answers.name}-data` : 'create the container and its data volume')
402
+ if (imageChanged) changes.push(`new image (${previousImage.slice(7, 19)} -> ${image.id.slice(7, 19)})`)
403
+ if (!imageReady && existing.container.exists) changes.push(`the image ${archive ? `from ${archive}` : wanted}, if it differs from the running one`)
404
+ if (existing.files[COMPOSE_FILE] !== null && existing.files[COMPOSE_FILE] !== undefined && existing.files[COMPOSE_FILE] !== composeText) changes.push(`${COMPOSE_FILE} changes`)
405
+ if (existing.files[SETTINGS_FILE] !== null && existing.files[SETTINGS_FILE] !== undefined && existing.files[SETTINGS_FILE] !== settingsText) changes.push(`${SETTINGS_FILE} changes`)
406
+ if (existing.container.exists && !existing.container.running) changes.push('start the stopped container')
407
+ if (existing.files[SECRETS_FILE] && existing.files[SECRETS_FILE] !== secretsText) changes.push(`${SECRETS_FILE} changes (a key was added, removed or changed)`)
408
+ if ((existing.files[BACKUP_SCRIPT] ?? null) !== scriptText) changes.push(scriptText ? 'backup schedule' : 'remove the backup schedule')
409
+
410
+ const fresh = !existing.files[COMPOSE_FILE] && !existing.container.exists
411
+ const nothing = imageReady && !fresh && !changes.length && existing.container.running && existing.container.health === 'healthy'
412
+ const action = nothing ? 'nothing' : fresh ? 'install' : imageChanged || (!imageReady && refresh) ? 'upgrade' : 'change'
413
+ const plan = emptyPlan({
414
+ action, target: answers.target, name: answers.name, where: host.where, address: answers.address.url,
415
+ image: { ref: image.ref, pinned: image.pinned, previous: previousImage },
416
+ ports: ports(answers),
417
+ secretsLocation: `${secretsPath} on ${host.where} (mode 0600${host.kind === 'ssh' ? ', root' : ''})`,
418
+ warnings: [...settings.warnings], notes: [...settings.notes], changes: fresh ? [] : changes,
419
+ })
420
+ if (dockerMissing) {
421
+ plan.commands.push(`install Docker Engine on ${host.where}: curl -fsSL https://get.docker.com | sh`)
422
+ plan.warnings.push(`--install-docker runs Docker's install script from get.docker.com as root on ${host.where}, as it is on the day you run it (it is not pinned or checked by this installer). To install Docker yourself instead, see https://docs.docker.com/engine/install/ and run this again without --install-docker.`)
423
+ }
424
+ if (!imageReady) {
425
+ plan.commands.push(archive ? `docker load < ${archive} (on ${host.where}, after you confirm)` : `docker pull ${wanted} (on ${host.where}, after you confirm)`)
426
+ plan.notes.push(`${archive ? `The image is loaded from ${archive}` : `${wanted} is not on ${host.where} yet: it is pulled`} after you confirm, and checked before anything starts. Until then the plan assumes the current image's settings.`)
427
+ }
428
+ if (!nothing) {
429
+ plan.files.push(
430
+ { path: secretsPath, note: existing.files[SECRETS_FILE] ? 'kept; only changed keys are rewritten' : `new: SLATEBOX_KEY_ENCRYPTION_KEY${ctx.flags['new-encryption-key'] && existing.volume ? ' (a NEW key: keys saved with the old one become unreadable)' : ''} and any keys you referenced` },
431
+ { path: join(host.dir, SETTINGS_FILE) }, { path: join(host.dir, COMPOSE_FILE) },
432
+ ...(scriptText ? [{ path: join(host.dir, BACKUP_SCRIPT), note: `${answers.backups.schedule}, keeps ${answers.backups.keep}, into ${answers.backups.to.startsWith('s3://') ? answers.backups.to : backupsDir(host, answers)}` }] : []),
433
+ { path: join(host.dir, 'install.yaml'), note: 'the install record, no secrets' },
434
+ )
435
+ if (imageChanged && existing.container.running) plan.commands.push(`back up first: ${join(backupsDir(host, answers), `pre-upgrade-${previousImage.slice(7, 19)}-${image.id.slice(7, 19)}.gz`)}`)
436
+ if ((imageChanged || (!imageReady && existing.container.exists)) && !existing.container.running) {
437
+ plan.warnings.push(`The container is not running, so no backup can be taken before the ${imageChanged ? 'upgrade' : 'change'}: if it fails there is no copy to roll the data back to. Take one yourself first if you have an older backup to restore from (slatebox restore <file>).`)
438
+ }
439
+ plan.commands.push(`docker compose -p ${answers.name} up -d --wait`, `docker exec ${answers.name} slatebox health --deep`)
440
+ if (scriptText) plan.commands.push(host.kind === 'local' ? `crontab: ${answers.backups.schedule} ${join(host.dir, BACKUP_SCRIPT)}` : `systemd timer (or /etc/cron.d) slatebox-${answers.name}-backup`)
441
+ if (answers.address.port === null) plan.notes.push(`HTTPS: Slatebox gets and renews a certificate for ${new URL(answers.address.url).hostname} itself; point its DNS here and open ports 80 and 443.`)
442
+ else if (answers.address.url.startsWith('http:') && host.kind === 'ssh') plan.warnings.push('Plain HTTP: anyone on the network path can read what people type. Give --domain for HTTPS.')
443
+ if (host.kind === 'local' && answers.address.port !== null && ['0.0.0.0', '::'].includes(answers.address.listen)) {
444
+ plan.warnings.push(`Published on every network interface (--listen ${answers.address.listen}) over plain HTTP: anyone who can reach this computer can open the first-account page, and Docker's port rules bypass firewalls such as ufw.`)
445
+ }
446
+ if (host.kind === 'local' && scriptText) {
447
+ if ((ctx.platform || process.platform) === 'darwin') plan.notes.push('Backups run from cron, which skips a run while this computer sleeps; `slatebox status` says when the last backup is late.')
448
+ if (ctx.env.WSL_DISTRO_NAME) plan.warnings.push('WSL usually has no cron daemon running: start it (sudo service cron start) or scheduled backups will not run.')
449
+ }
450
+ if (host.kind === 'ssh' && (facts.ufw === 'active' || facts.firewalld === 'running')) {
451
+ plan.warnings.push(`A firewall (${facts.ufw === 'active' ? 'ufw' : 'firewalld'}) is on. Allow ${ports(answers).map(hostPort).join(', ')}/tcp yourself; the installer does not change firewall rules.`)
452
+ }
453
+ }
454
+ if (team) {
455
+ if (team.claim) {
456
+ plan.notes.unshift(`After you confirm, you sign in to Slatebox in your browser to claim ${team.host} for your account. Slatebox Cloud then sets up its secure tunnel and sends this install the tunnel token.`)
457
+ plan.files.push({ path: credentialsPath(ctx.home, answers.name), note: 'the team-address credential (mode 0600); it stays on this computer' })
458
+ } else if (!stored[TUNNEL_TOKEN] && !nothing) {
459
+ plan.notes.unshift(`The tunnel token for ${team.host} is fetched again from Slatebox Cloud with this computer's install credential.`)
460
+ }
461
+ }
462
+ if (nothing) plan.notes.push('The running install already matches these answers.')
463
+ ctx.emitPlan(plan)
464
+ if (planOnly) return { planned: true, plan }
465
+ if (nothing) {
466
+ await saveRecord(ctx, host, answers, image, settings, caps, record, true)
467
+ if (caps.commands.includes('setup-link')) await stillWaiting(ctx, args => host.docker(['exec', answers.name, SLATEBOX, ...args]))
468
+ return done(ctx, host, answers, image, { nothing: true })
469
+ }
470
+ await ctx.confirm(plan)
471
+
472
+ if (dockerMissing) {
473
+ out.step('docker', 'start', `Installing Docker Engine on ${host.where} (get.docker.com)`)
474
+ const installed = await host.remote(`${host.sudo}sh -c ${shq('curl -fsSL https://get.docker.com | sh')}`, { timeout: 20 * 60_000 })
475
+ const check = await host.docker(['version', '--format', '{{.Server.Version}}'])
476
+ if (installed.code !== 0 || check.code !== 0) throw new InstallError(EXIT.PRECONDITION, `Docker could not be installed or started on ${host.where}: ${lastLine(installed.stderr || check.stderr)}`)
477
+ out.step('docker', 'ok', `Docker ${check.stdout.trim()} on ${host.where}`)
478
+ }
479
+ if (team && !ctx.tunnelToken && !stored[TUNNEL_TOKEN]) {
480
+ // The claim is kept if anything after this fails: the next run reuses it.
481
+ await ensureTeamAddress(ctx, answers, team, stored)
482
+ await render()
483
+ }
484
+ if (!imageReady) {
485
+ image = await resolveImage(host.docker, { ref: imageRef || answers.image, archive, loadArchive: host.loadArchive, step: out.step.bind(out) })
486
+ await ready()
487
+ await render()
488
+ imageChanged = changedFrom()
489
+ if (existing.container.exists && !imageChanged && previousImage === image.id && !changes.some(change => !change.startsWith('the image '))) {
490
+ await saveRecord(ctx, host, answers, image, settings, caps, record, true)
491
+ if (caps.commands.includes('setup-link')) await stillWaiting(ctx, args => host.docker(['exec', answers.name, SLATEBOX, ...args]))
492
+ return done(ctx, host, answers, image, { nothing: true })
493
+ }
494
+ }
495
+
496
+ // Before an upgrade, a backup the rollback can restore.
497
+ let preUpgrade = null
498
+ if (imageChanged && existing.container.running) {
499
+ preUpgrade = join(backupsDir(host, answers), `pre-upgrade-${previousImage.slice(7, 19)}-${image.id.slice(7, 19)}.gz`)
500
+ out.step('backup', 'start', `Backing up before the upgrade to ${preUpgrade}`)
501
+ const backup = await host.backupToFile(answers.name, preUpgrade)
502
+ if (backup.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The backup before the upgrade failed, so nothing was changed: ${lastLine(backup.stderr)}`)
503
+ out.step('backup', 'ok', `Backed up to ${preUpgrade}`)
504
+ }
505
+
506
+ if (secretsText.includes(PENDING_TOKEN)) throw new Error('internal: the team address has no tunnel token yet')
507
+ const previous = { ...existing.files }
508
+ out.step('files', 'start', `Writing ${host.dir}`)
509
+ await host.writeFile(join(host.dir, MARKER), `${answers.name}\n`, 0o600)
510
+ await host.writeFile(secretsPath, secretsText, 0o600)
511
+ if (Object.keys(kept).length) await host.writeFile(join(host.dir, KEPT_FILE), envFileText(kept, 'Kept from an earlier image that accepted them.'), 0o600)
512
+ await host.writeFile(join(host.dir, SETTINGS_FILE), settingsText, 0o600)
513
+ await host.writeFile(join(host.dir, COMPOSE_FILE), composeText, 0o600)
514
+ if (scriptText) await host.writeFile(join(host.dir, BACKUP_SCRIPT), scriptText, 0o700)
515
+ out.step('files', 'ok', `Wrote ${host.dir}`)
516
+
517
+ out.step('start', 'start', `Starting Slatebox and waiting until it is healthy (up to ${ctx.healthTimeout}s)`)
518
+ const result = await startAndCheck(ctx, host, answers)
519
+ if (!result.ok) await rollback(ctx, host, answers, { fresh, previous, preUpgrade, why: result.why })
520
+ if (result.warning) out.step('health', 'warn', result.warning)
521
+ out.step('start', 'ok', answers.address.team ? `Slatebox is healthy on ${host.where}` : `Slatebox is healthy at ${answers.address.url}`)
522
+
523
+ // The first admin comes from the image's one-time setup link; an image without one keeps the old advice.
524
+ const inImage = args => host.docker(['exec', answers.name, SLATEBOX, ...args])
525
+ const linked = caps.commands.includes('setup-link') && await firstAdmin(ctx, inImage)
526
+ if (!linked && fresh) await firstAccount(ctx, host, answers, caps)
527
+ if (scriptText || previous[BACKUP_SCRIPT]) {
528
+ try {
529
+ const how = await scheduleBackups(ctx, host, answers, facts)
530
+ if (how !== 'unchanged') out.step('backups', 'ok', answers.backups.to === 'off' ? 'Backup schedule removed' : `Daily backups by ${how}`)
531
+ } catch (error) {
532
+ out.step('backups', 'warn', `The backup schedule could not be set up (${error.message}). Run ${join(host.dir, BACKUP_SCRIPT)} from your own scheduler.`)
533
+ }
534
+ }
535
+ await saveRecord(ctx, host, answers, image, settings, caps, record, false, previousImage)
536
+ return done(ctx, host, answers, image, { generated, fresh })
537
+ }
538
+
539
+ async function rollback(ctx, host, answers, { fresh, previous, preUpgrade, why }) {
540
+ const { out } = ctx
541
+ out.step('start', 'fail', `Slatebox did not become healthy: ${why}`)
542
+ if (fresh) {
543
+ await host.compose(['stop'])
544
+ throw new InstallError(EXIT.ROLLED_BACK, `Slatebox did not become healthy (${why}). It is stopped; its files and data volume are kept. See \`docker logs ${answers.name}\`${host.kind === 'ssh' ? ` on ${host.where}` : ''}, then run the installer again or \`slatebox uninstall --name ${answers.name}\`.`, {
545
+ commands: [`docker logs ${answers.name}`, `npx slatebox uninstall --name ${answers.name}`],
546
+ })
547
+ }
548
+ out.step('rollback', 'start', 'Putting the previous version back')
549
+ for (const file of [SECRETS_FILE, SETTINGS_FILE, COMPOSE_FILE, BACKUP_SCRIPT]) {
550
+ if (previous[file]) await host.writeFile(join(host.dir, file), previous[file], file === BACKUP_SCRIPT ? 0o700 : 0o600)
551
+ }
552
+ let back = await startAndCheck(ctx, host, answers)
553
+ if (back.ok && preUpgrade) {
554
+ // The new version may have changed the database before it failed: put back the copy taken just before.
555
+ out.step('rollback', 'start', `Restoring the backup taken before the upgrade (${preUpgrade})`)
556
+ const restored = await host.restoreFromFile(answers.name, preUpgrade)
557
+ back = restored.code === 0 ? await health(ctx, host, answers) : { ok: false, why: lastLine(restored.stderr) }
558
+ }
559
+ const manual = [
560
+ `cd ${shq(host.dir)} && docker compose -p ${answers.name} up -d`,
561
+ ...(preUpgrade ? [`docker exec -i ${answers.name} slatebox restore < ${shq(preUpgrade)}`] : []),
562
+ `docker logs ${answers.name}`,
563
+ ]
564
+ if (!back.ok) {
565
+ throw new InstallError(EXIT.ROLLBACK_FAILED, `The change failed (${why}) and putting the previous version back failed too (${back.why}). Your data volume ${answers.name}-data is untouched${preUpgrade ? ` and ${preUpgrade} holds a backup from just before` : ''}. Run these${host.kind === 'ssh' ? ` on ${host.where}` : ''}:\n ${manual.join('\n ')}`, { commands: manual })
566
+ }
567
+ out.step('rollback', 'ok', 'The previous version is running again')
568
+ throw new InstallError(EXIT.ROLLED_BACK, `The change failed (${why}), so the previous version was put back and is healthy.${preUpgrade ? ` Its data is as it was before the upgrade (${preUpgrade}).` : ''}`, { commands: [`docker logs ${answers.name}`] })
569
+ }
570
+
571
+ async function firstAccount(ctx, host, answers, caps) {
572
+ if (!answers.adminEmail) {
573
+ ctx.out.say(`\nOpen ${answers.address.url} and create the first account.`)
574
+ return
575
+ }
576
+ if (caps.commands.includes('admin')) {
577
+ const made = await host.docker(['exec', answers.name, SLATEBOX, 'admin', 'create', answers.adminEmail])
578
+ if (made.code === 0 && made.stdout.trim()) {
579
+ ctx.redactor.add(made.stdout.trim())
580
+ if (ctx.tty && !ctx.json) {
581
+ ctx.out.step('admin', 'ok', `Admin account ${answers.adminEmail} created; its one-time set-password link is printed below for this terminal only.`)
582
+ ctx.stderr.write(`\n Set your password: ${made.stdout.trim()}\n\n`)
583
+ } else {
584
+ // The link is a password: it never goes into JSON or a log. The person makes a fresh one at a terminal.
585
+ ctx.out.step('admin', 'ok', `Admin account ${answers.adminEmail} created. To set its password, run this at a terminal and open the link it prints: ${host.kind === 'ssh' ? `ssh ${host.where} ` : ''}docker exec ${answers.name} slatebox password-link ${answers.adminEmail}`)
586
+ }
587
+ return
588
+ }
589
+ }
590
+ ctx.out.say(`\nOpen ${answers.address.url} and create the first account with ${answers.adminEmail}.`)
591
+ ctx.out.say(`If anyone loses their password later: ${host.kind === 'ssh' ? `ssh ${host.where} ` : ''}docker exec ${answers.name} slatebox password-link <email>`)
592
+ }
593
+
594
+ async function saveRecord(ctx, host, answers, image, settings, caps, record, unchanged, previousImage) {
595
+ const now = new Date().toISOString()
596
+ const next = {
597
+ ...answers,
598
+ image: image.ref,
599
+ installedVersion: ctx.version,
600
+ imageRef: image.ref,
601
+ imageDigest: image.pinned,
602
+ imageId: image.id,
603
+ previousImageDigest: unchanged ? (record?.previousImageDigest ?? null) : (previousImage && previousImage !== image.id ? previousImage : record?.previousImageDigest ?? null),
604
+ secretRefs: settings.secrets,
605
+ secretsLocation: `${host.kind === 'ssh' ? `${host.where}:` : ''}${join(host.dir, SECRETS_FILE)}`,
606
+ lastHealthy: now,
607
+ installedAt: record?.installedAt || now,
608
+ state: 'installed',
609
+ }
610
+ if (host.kind === 'ssh') await host.writeFile(join(host.dir, 'install.yaml'), recordText(next), 0o600)
611
+ ctx.recordFile = writeRecord(ctx.home, next)
612
+ ctx.record = next
613
+ return ctx.recordFile
614
+ }
615
+
616
+ function done(ctx, host, answers, image, { nothing = false, generated = [], fresh = false } = {}) {
617
+ const secretsFile = `${host.kind === 'ssh' ? `${host.where}:` : ''}${join(host.dir, SECRETS_FILE)}`
618
+ return {
619
+ address: answers.address.url, name: answers.name, target: answers.target, version: image.labels?.['org.opencontainers.image.version'] || null,
620
+ imageDigest: image.pinned, installRecord: ctx.recordFile, secretsFile, nothingToChange: nothing,
621
+ keyGenerated: generated.includes('SLATEBOX_KEY_ENCRYPTION_KEY'), fresh,
622
+ ...(answers.address.team ? { teamAddress: answers.address.url, localAddress: `http://localhost:${answers.address.port}` } : {}),
623
+ }
624
+ }
625
+
626
+ // ------------------------------------------------------------------ day two
627
+
628
+ /** How old a backup may get before status calls it late: a day and a bit for a daily schedule, else a week and a bit. */
629
+ export function backupLate(record, lastBackup, now = Date.now()) {
630
+ if (record.backups.to === 'off' || record.backups.to.startsWith('s3://')) return null
631
+ const match = /^slatebox-(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})\.gz$/.exec(lastBackup || '')
632
+ if (!match) return null
633
+ const at = Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4], +match[5], +match[6])
634
+ const [, , dom, month, dow] = record.backups.schedule.split(' ')
635
+ const allowed = (dom === '*' && month === '*' && dow === '*' ? 26 : 8 * 24) * 3600_000
636
+ return { late: now - at > allowed, ageHours: Math.round((now - at) / 3600_000) }
637
+ }
638
+
639
+ export async function statusDocker(ctx, record) {
640
+ refuseWindows(ctx)
641
+ const host = hostFor(ctx, record)
642
+ try {
643
+ if (host.kind === 'ssh') {
644
+ const probe = await host.remote(remoteSudoProbe())
645
+ if (probe.stdout.includes('sudo')) host.sudo = 'sudo -n '
646
+ }
647
+ const inspected = await host.docker(['inspect', '--format', '{{json .State}}', record.name])
648
+ const state = inspected.code === 0 ? JSON.parse(inspected.stdout) : null
649
+ const version = state?.Running ? await host.docker(['exec', record.name, SLATEBOX, 'version']) : null
650
+ let lastBackup = null
651
+ if (host.kind === 'ssh') {
652
+ const list = `ls -1t ${shq(backupsDir(host, record))} 2>/dev/null | grep '^slatebox-.*\\.gz$' | head -1`
653
+ lastBackup = (await host.remote(`${host.sudo}sh -c ${shq(list)}`)).stdout.trim() || null
654
+ } else {
655
+ const dir = backupsDir(host, record)
656
+ // File names carry the UTC time they were taken, so the newest sorts last.
657
+ lastBackup = existsSync(dir) ? readdirSync(dir).filter(file => /^slatebox-\d{8}-\d{6}\.gz$/.test(file)).sort().pop() || null : null
658
+ }
659
+ const tunnel = record.address?.team && state?.Running ? await tunnelState(host, record.name) : null
660
+ const setup = state?.Running ? await setupState(args => host.docker(['exec', record.name, SLATEBOX, ...args])) : null
661
+ const age = backupLate(record, lastBackup)
662
+ if (age?.late) ctx.out.warn(`The last backup is ${age.ageHours} hours old, older than the schedule "${record.backups.schedule}" allows. See ${join(host.dir, 'backup.log')}${host.kind === 'ssh' ? ` on ${host.where}` : ''}.`)
663
+ return {
664
+ name: record.name, target: record.target, where: host.where, address: record.address.url,
665
+ running: Boolean(state?.Running), health: state?.Health?.Status || (state ? state.Status : 'missing'),
666
+ version: version?.code === 0 ? JSON.parse(version.stdout) : null, imageDigest: record.imageDigest,
667
+ ai: record.ai.mode === 'none' ? 'off' : record.ai.providers.map(provider => provider.id).join(', '),
668
+ sso: record.sso.enabled ? (record.sso.only ? 'on (only)' : 'on') : 'off',
669
+ lastBackup, backupLate: age ? age.late : null,
670
+ ...(record.address?.team ? { tunnel } : {}),
671
+ setup: setup ? (setup.setUp ? 'done' : 'waiting for the first admin') : null,
672
+ }
673
+ } finally {
674
+ await host.close?.()
675
+ }
676
+ }
677
+
678
+ const remoteSudoProbe = () => `[ "$(id -u)" = 0 ] && echo root || echo sudo`
679
+
680
+ async function withHost(ctx, record, fn) {
681
+ refuseWindows(ctx)
682
+ const host = hostFor(ctx, record)
683
+ try {
684
+ if (host.kind === 'ssh') {
685
+ const probe = await host.remote(remoteSudoProbe())
686
+ if (probe.code !== 0) throw new InstallError(EXIT.PRECONDITION, `Cannot reach ${host.where}: ${lastLine(probe.stderr)}`)
687
+ if (probe.stdout.includes('sudo')) host.sudo = 'sudo -n '
688
+ }
689
+ return await fn(host)
690
+ } finally {
691
+ await host.close?.()
692
+ }
693
+ }
694
+
695
+ export function backupDocker(ctx, record, { to }) {
696
+ return withHost(ctx, record, async host => {
697
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..*/, '').replace('T', '-')
698
+ if (to) {
699
+ const file = join(to.startsWith('/') ? to : join(process.cwd(), to), `slatebox-${stamp}.gz`)
700
+ const { mkdirSync, rmSync } = await import('node:fs')
701
+ mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 })
702
+ const result = await host.docker(['exec', record.name, SLATEBOX, 'backup'], { outputFile: file, timeout: 60 * 60_000 })
703
+ if (result.code !== 0) { rmSync(file, { force: true }); throw new InstallError(EXIT.PRECONDITION, `The backup failed: ${lastLine(result.stderr)}`) }
704
+ return { file, where: 'this computer' }
705
+ }
706
+ const file = join(backupsDir(host, record), `slatebox-${stamp}.gz`)
707
+ const result = await host.backupToFile(record.name, file)
708
+ if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The backup failed: ${lastLine(result.stderr)}`)
709
+ return { file, where: host.where }
710
+ })
711
+ }
712
+
713
+ export function restoreDocker(ctx, record, archive) {
714
+ return withHost(ctx, record, async host => {
715
+ const result = await host.restoreFromLocal(record.name, archive)
716
+ if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The restore failed: ${lastLine(result.stderr)}`)
717
+ return { restored: archive }
718
+ })
719
+ }
720
+
721
+ export function uninstallDocker(ctx, record, { deleteData }) {
722
+ return withHost(ctx, record, async host => {
723
+ if (deleteData && host.kind === 'ssh') {
724
+ // Only a folder this installer made for this install, and only its own files in it.
725
+ const marker = await host.readMarker()
726
+ if (marker !== record.name) {
727
+ throw new InstallError(EXIT.PRECONDITION, `${host.dir} on ${host.where} has no ${MARKER} naming "${record.name}", so the installer will not delete anything in it. Nothing was changed. Remove the container, the volume ${record.name}-data and the files yourself if this really is the install.`)
728
+ }
729
+ }
730
+ const down = await host.compose(['down'])
731
+ if (down.code !== 0 && !/no such file|not found|no configuration/i.test(down.stderr)) {
732
+ await host.docker(['rm', '-f', record.name])
733
+ }
734
+ const removed = { ...record, backups: { ...record.backups, to: 'off' } }
735
+ try { await scheduleBackups(ctx, host, removed, { systemd: 'yes' }) } catch { /* nothing scheduled */ }
736
+ if (deleteData) {
737
+ const volume = await host.docker(['volume', 'rm', `${record.name}-data`])
738
+ if (volume.code !== 0 && !/no such volume/i.test(volume.stderr)) throw new InstallError(EXIT.PRECONDITION, `The data volume could not be removed: ${lastLine(volume.stderr)}`)
739
+ const defaultBackups = record.backups.to === 'default' || record.backups.to === 'off' || record.backups.to.startsWith('s3://')
740
+ await host.removeInstall({ backups: defaultBackups ? join(host.dir, 'backups') : null })
741
+ return { dataDeleted: true }
742
+ }
743
+ return { dataDeleted: false, volume: `${record.name}-data`, secretsFile: join(host.dir, SECRETS_FILE) }
744
+ })
745
+ }
746
+
747
+ // The services' log lines carry their name: [app], [relay], [mongo], [proxy], [tunnel], [sso], [slatebox].
748
+ export const LOG_SERVICES = ['app', 'relay', 'mongo', 'proxy', 'tunnel', 'sso', 'slatebox']
749
+
750
+ /** docker logs for the install, optionally only one service's lines, optionally following. */
751
+ export function logsDocker(ctx, record, { follow = false, service, since } = {}) {
752
+ return withHost(ctx, record, async host => {
753
+ const args = ['logs', ...(since ? ['--since', since] : []), ...(follow ? ['--follow'] : ['--tail', '500']), record.name]
754
+ const keep = line => !service || line.startsWith(`[${service}] `) || (service === 'sso' && line.startsWith('[sso-setup] '))
755
+ const write = text => {
756
+ for (const line of text.split('\n')) if (line && keep(line)) ctx.stdout.write(`${ctx.redactor.redact(line)}\n`)
757
+ }
758
+ if (follow) {
759
+ if (host.kind !== 'local') throw new InstallError(EXIT.USAGE, `Following logs on ${host.where}: ssh ${host.where} ${host.sudo || ''}docker logs -f ${record.name}`)
760
+ // Streamed as it comes, each line through the redactor, until Ctrl-C.
761
+ const { spawn } = await import('node:child_process')
762
+ return new Promise(resolve => {
763
+ const child = (ctx.spawn || spawn)('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] })
764
+ let rest = ''
765
+ const onData = chunk => {
766
+ const text = rest + chunk
767
+ const cut = text.lastIndexOf('\n')
768
+ rest = cut < 0 ? text : text.slice(cut + 1)
769
+ if (cut >= 0) write(text.slice(0, cut))
770
+ }
771
+ child.stdout.on('data', onData)
772
+ child.stderr.on('data', onData)
773
+ child.on('error', () => resolve({ lines: false }))
774
+ child.on('close', () => { if (rest) write(rest); resolve({ lines: true }) })
775
+ })
776
+ }
777
+ const result = await host.docker(args, { timeout: 120_000 })
778
+ if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `docker logs failed: ${lastLine(result.stderr)}`)
779
+ // docker logs puts the container's stdout and stderr on its own two streams.
780
+ write(`${result.stdout}${result.stderr}`)
781
+ return { lines: true }
782
+ })
783
+ }
784
+
785
+ /** Run a script inside the container with node, the script on standard input (never in the arguments). */
786
+ export function execNode(ctx, record, script, args = []) {
787
+ return withHost(ctx, record, host => host.docker(['exec', '-i', record.name, 'node', '--input-type=module', '-', ...args], { input: script, timeout: 120_000 }))
788
+ }
789
+
790
+ /** A fresh one-time setup link from the install's container (setup-link.mjs makeSetupLink). */
791
+ export function setupLinkDocker(ctx, record) {
792
+ return withHost(ctx, record, host => makeSetupLink(ctx, args => host.docker(['exec', record.name, SLATEBOX, ...args])))
793
+ }
794
+
795
+ export function readSecretDocker(ctx, record, name) {
796
+ return withHost(ctx, record, async host => parseEnvFile(await host.readFile(join(host.dir, SECRETS_FILE)) || '')[name])
797
+ }