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,73 @@
1
+ // Export only: write the compose file, the Kubernetes manifests or a Helm
2
+ // chart for GitOps, with placeholders where secrets go. Nothing is applied and
3
+ // no host or cluster is contacted (the local Docker is asked for the image's
4
+ // digest and settings when it has the image).
5
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
6
+ import { dirname, join, resolve } from 'node:path'
7
+ import { EXIT, InstallError } from '../errors.mjs'
8
+ import { DEFAULT_IMAGE, FALLBACK_CAPABILITIES, probeImage } from '../image.mjs'
9
+ import { emptyPlan } from '../plan.mjs'
10
+ import { renderCompose, SECRETS_FILE, SETTINGS_FILE } from '../render/compose.mjs'
11
+ import { renderHelmChart } from '../render/helm.mjs'
12
+ import { names, renderK8s, renderSecret } from '../render/k8s.mjs'
13
+ import { settingsFor } from '../render/settings.mjs'
14
+ import { envFileText } from '../secrets.mjs'
15
+ import { stringify, stringifyAll } from '../yaml.mjs'
16
+ import { clusterImage } from './k8s.mjs'
17
+
18
+ function placeholder(name, ref) {
19
+ if (ref === 'generate') return '<32 random bytes in base64: openssl rand -base64 32; keep it with your backups>'
20
+ return `<the value of ${ref}>`
21
+ }
22
+
23
+ export async function exportFiles(ctx, answers, { planOnly = false } = {}) {
24
+ const dir = resolve(answers.export.dir)
25
+ const warnings = []
26
+ const image = await clusterImage(ctx, answers.image || DEFAULT_IMAGE)
27
+ let caps = FALLBACK_CAPABILITIES
28
+ if (image.local) {
29
+ try { caps = await probeImage((args, o) => ctx.run('docker', args, o), image.id) } catch { warnings.push('The image did not list its settings; the current image\'s settings were assumed.') }
30
+ } else {
31
+ warnings.push(`${image.ref} is not on this computer, so the files assume the current image's settings and are not pinned to a digest.`)
32
+ }
33
+ const settings = settingsFor(answers, caps)
34
+ const placeholders = Object.fromEntries(Object.entries(settings.secrets).map(([name, ref]) => [name, placeholder(name, ref)]))
35
+ const files = {}
36
+ if (answers.export.format === 'compose') {
37
+ files['compose.yaml'] = renderCompose(answers, { image: image.pinned, hostGateway: settings.hostGateway, pullPolicy: null })
38
+ files[SETTINGS_FILE] = envFileText(settings.env, 'Settings for Slatebox. No secrets.')
39
+ files[`${SECRETS_FILE}.example`] = envFileText(placeholders, `Copy to ${SECRETS_FILE} (mode 0600) and fill in. Never commit the real file.`)
40
+ files['README.md'] = `# Slatebox "${answers.name}"\n\n1. \`cp ${SECRETS_FILE}.example ${SECRETS_FILE} && chmod 600 ${SECRETS_FILE}\` and fill in each value.\n2. \`docker compose up -d --wait\`\n3. Open ${answers.address.url}\n\nBack up with \`docker exec ${answers.name} slatebox backup > slatebox-backup.gz\`, and keep SLATEBOX_KEY_ENCRYPTION_KEY with your backups: they do not contain it.\n`
41
+ } else {
42
+ const record = stringify({ ...answers, imageDigest: image.pinned, secretRefs: settings.secrets, state: 'exported' })
43
+ const secret = renderSecret(answers, placeholders)
44
+ if (answers.export.format === 'manifests') {
45
+ files['slatebox.yaml'] = `# Slatebox "${answers.name}". Apply with: kubectl apply --server-side -f slatebox.yaml (after the Secret).\n${stringifyAll(renderK8s(answers, { image: image.pinned, env: settings.env, record }))}`
46
+ } else {
47
+ const version = ctx.version
48
+ for (const [path, text] of Object.entries(renderHelmChart(answers, { image: image.pinned, env: settings.env, version, appVersion: image.pinned.split(/[@:]/).pop().slice(0, 19) }))) {
49
+ files[join('slatebox', path)] = text
50
+ }
51
+ }
52
+ files['secret.example.yaml'] = `# Fill in, then: kubectl apply -n ${answers.k8s.namespace} -f secret.yaml (never commit the filled-in file)\n${stringify(secret)}`
53
+ files['README.md'] = `# Slatebox "${answers.name}" on Kubernetes\n\n1. Copy secret.example.yaml to secret.yaml, fill in each value, apply it.\n2. ${answers.export.format === 'helm' ? `helm upgrade --install ${answers.name} ./slatebox -n ${answers.k8s.namespace} --create-namespace` : 'kubectl apply --server-side -f slatebox.yaml'}\n3. Open ${answers.address.url}${answers.k8s.route === 'none' ? ` after kubectl -n ${answers.k8s.namespace} port-forward svc/${names(answers).service} 7070:7070` : ''}\n`
54
+ }
55
+ const plan = emptyPlan({
56
+ action: 'export', target: 'export', name: answers.name, where: dir, address: answers.address.url,
57
+ image: { ref: image.ref, pinned: image.pinned }, files: Object.keys(files).map(path => ({ path: join(dir, path) })),
58
+ warnings: [...warnings, ...settings.warnings], notes: settings.notes,
59
+ })
60
+ ctx.emitPlan(plan)
61
+ if (planOnly) return { planned: true, plan }
62
+ const clashes = Object.keys(files).filter(path => existsSync(join(dir, path)) && !ctx.yes)
63
+ if (clashes.length && !ctx.interactive) {
64
+ throw new InstallError(EXIT.NEEDS_INPUT, `${dir} already has ${clashes.join(', ')}. Run again with --yes to overwrite them.`, { needsConfirmation: true })
65
+ }
66
+ if (clashes.length) await ctx.confirm({ ...plan, action: 'export' })
67
+ for (const [path, text] of Object.entries(files)) {
68
+ const full = join(dir, path)
69
+ mkdirSync(dirname(full), { recursive: true })
70
+ writeFileSync(full, text)
71
+ }
72
+ return { address: answers.address.url, name: answers.name, target: 'export', format: answers.export.format, dir, files: Object.keys(files), imageDigest: image.pinned }
73
+ }
@@ -0,0 +1,202 @@
1
+ // A Docker host: this computer, or a Linux server reached over SSH. The
2
+ // install flow (docker.mjs) is the same for both; only these primitives differ.
3
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync, chmodSync } from 'node:fs'
4
+ import { createServer } from 'node:net'
5
+ import { dirname, join } from 'node:path'
6
+ import { EXIT, InstallError } from '../errors.mjs'
7
+ import { shq } from '../runner.mjs'
8
+
9
+ function bindable(port, address) {
10
+ return new Promise(resolve => {
11
+ const server = createServer()
12
+ server.once('error', error => resolve(['EADDRNOTAVAIL', 'EAFNOSUPPORT'].includes(error.code) ? 'n/a' : false))
13
+ server.listen({ port, host: address, exclusive: true }, () => server.close(() => resolve(true)))
14
+ })
15
+ }
16
+
17
+ /**
18
+ * Is a TCP port free on this computer? Bind it on every interface, as Docker
19
+ * would, and on the loopback addresses too: on macOS a dev server on
20
+ * 127.0.0.1 or ::1 does not stop a bind on 0.0.0.0, yet it answers
21
+ * http://localhost:<port> first.
22
+ */
23
+ export async function portFree(port) {
24
+ for (const address of ['0.0.0.0', '127.0.0.1', '::1']) {
25
+ if ((await bindable(port, address)) === false) return false
26
+ }
27
+ return true
28
+ }
29
+
30
+ /** The absolute path of a program on PATH, or null (cron runs with a short PATH, so scripts name it in full). */
31
+ export function which(name, path = process.env.PATH || '') {
32
+ for (const dir of path.split(':').filter(Boolean)) {
33
+ const candidate = join(dir, name)
34
+ try {
35
+ accessSync(candidate, constants.X_OK)
36
+ if (statSync(candidate).isFile()) return candidate
37
+ } catch { /* not here */ }
38
+ }
39
+ return null
40
+ }
41
+
42
+ // The files an install writes into its folder; deleting data removes these and nothing else.
43
+ export const MARKER = '.slatebox-install'
44
+ export const INSTALL_FILES = ['compose.yaml', 'slatebox.env', 'secrets.env', 'secrets.kept.env', 'backup.sh', 'backup.log', 'install.yaml', MARKER]
45
+ const BACKUP_FILES = ['slatebox-*.gz', 'pre-upgrade-*.gz', '*.gz.part']
46
+
47
+ export async function firstFreePort(from = 7070, tries = 100) {
48
+ for (let port = from; port < from + tries; port++) if (await portFree(port)) return port
49
+ return null
50
+ }
51
+
52
+ export function localHost(ctx, { dir, name }) {
53
+ const docker = (args, options) => ctx.run('docker', args, options)
54
+ return {
55
+ kind: 'local',
56
+ where: 'this computer',
57
+ dir,
58
+ name,
59
+ docker,
60
+ compose: (args, options) => docker(['compose', '--project-directory', dir, '-f', join(dir, 'compose.yaml'), '-p', name, ...args], options),
61
+ async readFile(path) {
62
+ return existsSync(path) ? readFileSync(path, 'utf8') : null
63
+ },
64
+ async writeFile(path, content, mode = 0o600) {
65
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
66
+ writeFileSync(`${path}.tmp`, content, { mode })
67
+ chmodSync(`${path}.tmp`, mode)
68
+ renameSync(`${path}.tmp`, path)
69
+ },
70
+ async readMarker() {
71
+ const path = join(dir, MARKER)
72
+ return existsSync(path) ? readFileSync(path, 'utf8').trim() : null
73
+ },
74
+ async removeInstall({ backups }) {
75
+ for (const file of INSTALL_FILES) rmSync(join(dir, file), { force: true })
76
+ if (backups && existsSync(backups)) {
77
+ const { readdirSync } = await import('node:fs')
78
+ for (const file of readdirSync(backups)) if (/^(slatebox-|pre-upgrade-).*\.gz(\.part)?$/.test(file)) rmSync(join(backups, file), { force: true })
79
+ try { rmdirSync(backups) } catch { /* not empty: someone else's files */ }
80
+ }
81
+ try { rmdirSync(dir) } catch { /* not empty */ }
82
+ },
83
+ loadArchive: file => docker(['load', '-i', file], { timeout: 60 * 60_000 }),
84
+ /** A complete backup into a file on this host (the image writes nothing until the archive checks out). */
85
+ async backupToFile(container, path) {
86
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
87
+ const result = await docker(['exec', container, '/opt/slatebox/bin/slatebox', 'backup'], { outputFile: path, timeout: 60 * 60_000 })
88
+ if (result.code !== 0) rmSync(path, { force: true })
89
+ return result
90
+ },
91
+ restoreFromFile: (container, path) => docker(['exec', '-i', container, '/opt/slatebox/bin/slatebox', 'restore'], { inputFile: path, timeout: 60 * 60_000 }),
92
+ restoreFromLocal(container, path) { return this.restoreFromFile(container, path) },
93
+ sh: (script, options) => ctx.run('sh', ['-s'], { input: script, ...options }),
94
+ }
95
+ }
96
+
97
+ /**
98
+ * A server over SSH, with the system ssh (so ~/.ssh/config, ProxyJump, agents
99
+ * and hardware keys work). One multiplexed connection; every step is a small
100
+ * script on standard input, never left on the server.
101
+ */
102
+ export function sshHost(ctx, ssh, { name, home }) {
103
+ const controlDir = join(home, 'cm')
104
+ const multiplex = controlDir.length < 50
105
+ if (multiplex) mkdirSync(controlDir, { recursive: true, mode: 0o700 })
106
+ const base = [
107
+ '-o', 'BatchMode=yes',
108
+ ...(multiplex ? ['-o', 'ControlMaster=auto', '-o', `ControlPath=${join(controlDir, '%C')}`, '-o', 'ControlPersist=120'] : []),
109
+ '-p', String(ssh.port),
110
+ ...(ssh.identity ? ['-i', ssh.identity.replace(/^~(?=\/)/, ctx.env.HOME || '')] : []),
111
+ ...ssh.options.flatMap(option => ['-o', option]),
112
+ ssh.user ? `${ssh.user}@${ssh.host}` : ssh.host,
113
+ ]
114
+ const host = {
115
+ kind: 'ssh',
116
+ where: `${ssh.user ? `${ssh.user}@` : ''}${ssh.host}`,
117
+ dir: ssh.dir,
118
+ name,
119
+ sudo: '',
120
+ remote: (command, options) => ctx.run('ssh', [...base, command], options),
121
+ docker: (args, options) => host.remote(`${host.sudo}docker ${args.map(shq).join(' ')}`, options),
122
+ // The directory is root's (mode 0700): compose reads it under sudo, never through a cd as the login user.
123
+ compose: (args, options) => host.remote(`${host.sudo}docker compose --project-directory ${shq(ssh.dir)} -f ${shq(join(ssh.dir, 'compose.yaml'))} -p ${shq(name)} ${args.map(shq).join(' ')}`, options),
124
+ /** The file's text; null only when it does not exist. Any other failure is an error, never "no file". */
125
+ async readFile(path) {
126
+ const script = `if [ -e ${shq(path)} ]; then cat ${shq(path)}; else exit 3; fi`
127
+ const result = await host.remote(`${host.sudo}sh -c ${shq(script)}`)
128
+ if (result.code === 0) return result.stdout
129
+ if (result.code === 3) return null
130
+ throw new InstallError(EXIT.PRECONDITION, `Could not read ${path} on ${host.where}: ${result.stderr.trim().split('\n').pop() || `exit ${result.code}`}. Nothing was changed.`)
131
+ },
132
+ async writeFile(path, content, mode = 0o600) {
133
+ const octal = mode.toString(8)
134
+ const script = `umask 077; mkdir -p ${shq(dirname(path))} && cat > ${shq(`${path}.tmp`)} && chmod ${octal} ${shq(`${path}.tmp`)} && mv ${shq(`${path}.tmp`)} ${shq(path)}`
135
+ const result = await host.remote(`${host.sudo}sh -c ${shq(script)}`, { input: content })
136
+ if (result.code !== 0) throw new Error(`Could not write ${path} on ${host.where}: ${result.stderr.trim()}`)
137
+ },
138
+ async readMarker() {
139
+ const result = await host.remote(`${host.sudo}cat ${shq(join(ssh.dir, MARKER))}`)
140
+ return result.code === 0 ? result.stdout.trim() : null
141
+ },
142
+ async removeInstall({ backups }) {
143
+ const files = INSTALL_FILES.map(file => shq(join(ssh.dir, file))).join(' ')
144
+ const old = backups ? BACKUP_FILES.map(glob => `${shq(backups)}/${glob}`).join(' ') : ''
145
+ const script = `rm -f ${files}${backups ? `; rm -f ${old}; rmdir ${shq(backups)} 2>/dev/null` : ''}; rmdir ${shq(ssh.dir)} 2>/dev/null; true`
146
+ const result = await host.remote(`${host.sudo}sh -c ${shq(script)}`)
147
+ if (result.code !== 0) throw new Error(`Could not remove the install files on ${host.where}: ${result.stderr.trim()}`)
148
+ },
149
+ loadArchive: file => host.remote(`${host.sudo}docker load`, { inputFile: file, timeout: 60 * 60_000 }),
150
+ async backupToFile(container, path) {
151
+ const script = `umask 077; mkdir -p ${shq(dirname(path))} && if docker exec ${shq(container)} /opt/slatebox/bin/slatebox backup > ${shq(`${path}.part`)}; then mv ${shq(`${path}.part`)} ${shq(path)}; else rm -f ${shq(`${path}.part`)}; exit 1; fi`
152
+ return host.remote(`${host.sudo}sh -c ${shq(script)}`, { timeout: 60 * 60_000 })
153
+ },
154
+ restoreFromFile: (container, path) => host.remote(`${host.sudo}sh -c ${shq(`docker exec -i ${shq(container)} /opt/slatebox/bin/slatebox restore < ${shq(path)}`)}`, { timeout: 60 * 60_000 }),
155
+ restoreFromLocal: (container, file) => host.remote(`${host.sudo}docker exec -i ${shq(container)} /opt/slatebox/bin/slatebox restore`, { inputFile: file, timeout: 60 * 60_000 }),
156
+ sh: (script, options) => host.remote(`${host.sudo}sh -s`, { input: script, ...options }),
157
+ close: () => (multiplex ? ctx.run('ssh', ['-O', 'exit', ...base], { timeout: 10_000 }) : null),
158
+ }
159
+ return host
160
+ }
161
+
162
+ /** What the server is, before anything is changed on it. One round trip. */
163
+ export function remotePreflightScript(ports) {
164
+ return `
165
+ set -u
166
+ uid=$(id -u)
167
+ echo "uid=$uid"
168
+ S=""
169
+ if [ "$uid" != 0 ]; then
170
+ if sudo -n true 2>/dev/null; then echo "sudo=yes"; S="sudo -n "; else echo "sudo=no"; fi
171
+ fi
172
+ echo "arch=$(uname -m)"
173
+ if [ -r /etc/os-release ]; then . /etc/os-release; echo "os=\${ID:-unknown} \${VERSION_ID:-}"; fi
174
+ d=$(command -v docker 2>/dev/null || true)
175
+ echo "docker_path=$d"
176
+ if [ -n "$d" ]; then
177
+ echo "docker_server=$($S docker version --format '{{.Server.Version}}' 2>/dev/null || true)"
178
+ echo "compose=$($S docker compose version --short 2>/dev/null || true)"
179
+ fi
180
+ echo "systemd=$([ -d /run/systemd/system ] && echo yes || echo no)"
181
+ echo "cron=$([ -d /etc/cron.d ] && echo yes || echo no)"
182
+ echo "disk_kb=$(df -Pk / 2>/dev/null | awk 'NR==2{print $4}')"
183
+ echo "mem_kb=$(awk '/MemTotal/{print $2}' /proc/meminfo 2>/dev/null)"
184
+ if command -v ss >/dev/null 2>&1; then
185
+ echo "listening=$(ss -ltnH 2>/dev/null | awk '{print $4}' | sed 's/.*://' | sort -un | tr '\\n' ' ')"
186
+ else
187
+ l=""; for p in ${ports.join(' ')}; do (exec 3<>/dev/tcp/127.0.0.1/$p) 2>/dev/null && l="$l $p"; done; echo "listening=$l"
188
+ fi
189
+ if command -v ufw >/dev/null 2>&1; then echo "ufw=$($S ufw status 2>/dev/null | head -1 | awk '{print $2}')"; fi
190
+ if command -v firewall-cmd >/dev/null 2>&1; then echo "firewalld=$($S firewall-cmd --state 2>/dev/null || true)"; fi
191
+ echo "addresses=$(hostname -I 2>/dev/null || true)"
192
+ `
193
+ }
194
+
195
+ export function parseKeyValues(text) {
196
+ const out = {}
197
+ for (const line of text.split('\n')) {
198
+ const at = line.indexOf('=')
199
+ if (at > 0) out[line.slice(0, at).trim()] = line.slice(at + 1).trim()
200
+ }
201
+ return out
202
+ }