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