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.
- package/LICENSE.md +21 -0
- package/README.md +151 -2
- package/bin/slatebox.mjs +9 -0
- package/package.json +41 -4
- package/src/agent-prompt.mjs +64 -0
- package/src/ai/settings-adapter.mjs +198 -0
- package/src/answers.mjs +489 -0
- package/src/cli.mjs +477 -0
- package/src/errors.mjs +23 -0
- package/src/image.mjs +138 -0
- package/src/interview.mjs +170 -0
- package/src/output.mjs +51 -0
- package/src/plan.mjs +51 -0
- package/src/prompt.mjs +87 -0
- package/src/record.mjs +46 -0
- package/src/render/compose.mjs +47 -0
- package/src/render/helm.mjs +78 -0
- package/src/render/k8s.mjs +204 -0
- package/src/render/settings.mjs +59 -0
- package/src/runner.mjs +50 -0
- package/src/secret-values.mjs +40 -0
- package/src/secrets.mjs +119 -0
- package/src/targets/docker.mjs +685 -0
- package/src/targets/export.mjs +73 -0
- package/src/targets/hosts.mjs +202 -0
- package/src/targets/k8s.mjs +366 -0
- package/src/yaml.mjs +293 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// The questions a person is asked, in order, for whatever the flags, the
|
|
2
|
+
// answers file and an earlier install did not already say. Each answer lands
|
|
3
|
+
// in the same fields an answers file uses.
|
|
4
|
+
import { AI_CHOICES, QUESTIONS, SIZES } from './answers.mjs'
|
|
5
|
+
import { PRESETS } from './ai/settings-adapter.mjs'
|
|
6
|
+
import { looksLikeKey } from './secrets.mjs'
|
|
7
|
+
|
|
8
|
+
const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/
|
|
9
|
+
const CLOUD = ['openai', 'anthropic', 'deepinfra', 'openrouter', 'groq', 'together', 'mistral']
|
|
10
|
+
|
|
11
|
+
async function listModels(ctx, baseUrl) {
|
|
12
|
+
try {
|
|
13
|
+
const response = await ctx.fetch(`${baseUrl.replace(/\/$/, '')}/models`, { signal: AbortSignal.timeout(3000) })
|
|
14
|
+
if (!response.ok) return []
|
|
15
|
+
return ((await response.json()).data || []).map(model => model.id).filter(Boolean).slice(0, 20)
|
|
16
|
+
} catch { return [] }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
20
|
+
// Never repeat what was typed: it may be the key.
|
|
21
|
+
const KEY_TYPED = 'That looks like a key, not a variable name. It was not saved or shown. Type the NAME of the variable that holds it, like GROQ_API_KEY.'
|
|
22
|
+
const variableName = optional => v => (looksLikeKey(v) ? KEY_TYPED : VARIABLE.test(v) ? null : `A variable name, like OPENAI_API_KEY${optional ? ', or Enter for none' : ''}`)
|
|
23
|
+
|
|
24
|
+
async function keyRef(p, label) {
|
|
25
|
+
// Two steps, so that nobody pastes a key where a name is asked for.
|
|
26
|
+
const how = await p.choose(`How will you give the ${label} key?`, [
|
|
27
|
+
{ value: 'env', label: 'It is in an environment variable (I will give its name)' },
|
|
28
|
+
{ value: 'prompt', label: 'Type it now, hidden; it goes only into the secrets file' },
|
|
29
|
+
], { default: 'env' })
|
|
30
|
+
if (how === 'prompt') return 'prompt'
|
|
31
|
+
const name = await p.text(`Name of the environment variable that holds the ${label} key`, { validate: variableName(false) })
|
|
32
|
+
return `env:${name}`
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function provider(ctx, p, kind, ids) {
|
|
36
|
+
const preset = PRESETS[kind]
|
|
37
|
+
let id = kind
|
|
38
|
+
for (let n = 2; ids.includes(id); n++) id = `${kind}-${n}`
|
|
39
|
+
if (preset.kind === 'deepinfra') return { id, kind: 'deepinfra', keyFrom: await keyRef(p, 'DeepInfra') }
|
|
40
|
+
if (kind === 'openai-compatible') {
|
|
41
|
+
const baseUrl = await p.text('Endpoint URL (OpenAI-compatible)', { default: 'http://localhost:11434/v1', validate: v => { try { new URL(v); return null } catch { return 'A URL, like http://ollama:11434/v1' } } })
|
|
42
|
+
const models = await listModels(ctx, baseUrl)
|
|
43
|
+
const model = models.length
|
|
44
|
+
? await p.choose(`Model at ${baseUrl}`, models.map(value => ({ value, label: value })), { default: models[0] })
|
|
45
|
+
: await p.text('Model name the endpoint serves (for example qwen3:8b)')
|
|
46
|
+
const token = await p.text('Name of the environment variable that holds its token (Enter if it needs none)', { optional: true, validate: variableName(true) })
|
|
47
|
+
return { id: ids.includes('local') ? `local-${ids.length + 1}` : 'local', kind: 'openai-compatible', baseUrl, model, keyFrom: token ? `env:${token}` : 'none' }
|
|
48
|
+
}
|
|
49
|
+
const model = await p.text(`${kind} model to use`)
|
|
50
|
+
return { id, kind, model, keyFrom: await keyRef(p, kind) }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {object} ctx run context (prompt, fetch, freePort, currentContext)
|
|
55
|
+
* @param {object} partial collected answers
|
|
56
|
+
* @returns {Promise<object>} partial with the person's answers added
|
|
57
|
+
*/
|
|
58
|
+
export async function interview(ctx, partial) {
|
|
59
|
+
const p = ctx.prompt
|
|
60
|
+
const a = structuredClone(partial)
|
|
61
|
+
const has = (object, key) => object && object[key] !== undefined && object[key] !== null
|
|
62
|
+
ctx.stderr.write('\nSlatebox installer. Enter accepts the default in brackets; Ctrl-C stops without changing anything.\n\n')
|
|
63
|
+
|
|
64
|
+
if (!has(a, 'target')) {
|
|
65
|
+
const choices = QUESTIONS.target.choices.map(choice => choice.value === 'k8s' && ctx.currentContext ? { ...choice, label: `Kubernetes (current context: ${ctx.currentContext})` } : choice)
|
|
66
|
+
a.target = await p.choose(QUESTIONS.target.question, choices, { default: 'local' })
|
|
67
|
+
}
|
|
68
|
+
if (a.target === 'ssh') {
|
|
69
|
+
a.ssh ||= {}
|
|
70
|
+
if (!has(a.ssh, 'host')) {
|
|
71
|
+
const spec = await p.text(QUESTIONS['ssh.host'].question)
|
|
72
|
+
const at = spec.indexOf('@')
|
|
73
|
+
if (at > 0) { a.ssh.user = spec.slice(0, at); a.ssh.host = spec.slice(at + 1) } else a.ssh.host = spec
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (a.target === 'export') {
|
|
77
|
+
a.export ||= {}
|
|
78
|
+
if (!has(a.export, 'format')) a.export.format = await p.choose('Which files?', [
|
|
79
|
+
{ value: 'compose', label: 'Docker Compose file' }, { value: 'manifests', label: 'Kubernetes manifests' }, { value: 'helm', label: 'Helm chart' },
|
|
80
|
+
], { default: 'compose' })
|
|
81
|
+
if (!has(a.export, 'dir')) a.export.dir = await p.text('Write them to', { default: './slatebox-deploy' })
|
|
82
|
+
}
|
|
83
|
+
const kube = a.target === 'k8s' || ['manifests', 'helm'].includes(a.export?.format)
|
|
84
|
+
|
|
85
|
+
// Address
|
|
86
|
+
a.address ||= {}
|
|
87
|
+
if (!has(a.address, 'url') && !has(a.address, 'domain')) {
|
|
88
|
+
if (a.target === 'local' && !has(a.address, 'port')) {
|
|
89
|
+
const port = await p.text('Port on this computer', { default: String(ctx.freePort), validate: v => (/^\d+$/.test(v) && Number(v) < 65536 ? null : 'A port number') })
|
|
90
|
+
a.address.port = Number(port)
|
|
91
|
+
} else if (a.target === 'ssh' || (a.target === 'export' && !kube)) {
|
|
92
|
+
const domain = await p.text(`Domain name for HTTPS, pointed at the server (Enter for plain http://${a.ssh?.host || '<server>'}:7070)`, { optional: true })
|
|
93
|
+
if (domain) a.address.domain = domain
|
|
94
|
+
} else if (kube) {
|
|
95
|
+
a.k8s ||= {}
|
|
96
|
+
if (!has(a.k8s, 'route')) a.k8s.route = await p.choose('How does traffic reach it?', [
|
|
97
|
+
{ value: 'ingress', label: 'An Ingress (ingress-nginx, Traefik, ...)' }, { value: 'gateway', label: 'Gateway API (an HTTPRoute on an existing Gateway)' },
|
|
98
|
+
{ value: 'none', label: 'Nothing for now (kubectl port-forward)' },
|
|
99
|
+
], { default: 'ingress' })
|
|
100
|
+
if (a.k8s.route !== 'none') {
|
|
101
|
+
a.address.domain = await p.text('Host name people will use (for example boards.example.com)')
|
|
102
|
+
if (a.k8s.route === 'ingress' && !has(a.k8s, 'ingressClass')) a.k8s.ingressClass = (await p.text('IngressClass', { optional: true })) || null
|
|
103
|
+
if (a.k8s.route === 'gateway' && !has(a.k8s, 'gatewayRef')) a.k8s.gatewayRef = await p.text('Gateway, as namespace/name')
|
|
104
|
+
if (!has(a.k8s, 'tlsIssuer')) {
|
|
105
|
+
const issuer = await p.text('cert-manager issuer for TLS, as ClusterIssuer/name or Issuer/name', { optional: true })
|
|
106
|
+
if (issuer) { const [kind, name] = issuer.includes('/') ? issuer.split('/') : ['ClusterIssuer', issuer]; a.k8s.tlsIssuer = { kind, name } }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (!has(a, 'adminEmail')) {
|
|
113
|
+
const optional = a.target === 'local' || a.target === 'export'
|
|
114
|
+
const email = await p.text(QUESTIONS.adminEmail.question, { optional, validate: v => (EMAIL.test(v) ? null : 'An email address') })
|
|
115
|
+
if (email) a.adminEmail = email
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// AI: nothing is pre-selected.
|
|
119
|
+
a.ai ||= {}
|
|
120
|
+
if (!has(a.ai, 'mode')) {
|
|
121
|
+
const choice = await p.choose(QUESTIONS['ai.mode'].question, AI_CHOICES)
|
|
122
|
+
if (choice === 'none') a.ai = { mode: 'none' }
|
|
123
|
+
else {
|
|
124
|
+
const providers = []
|
|
125
|
+
if (choice === 'cloud' || choice === 'both') {
|
|
126
|
+
do {
|
|
127
|
+
const kind = await p.choose('Which provider?', CLOUD.map(value => ({ value, label: value })))
|
|
128
|
+
providers.push(await provider(ctx, p, kind, providers.map(item => item.id)))
|
|
129
|
+
} while (await p.confirm('Add another cloud provider?', { default: false }))
|
|
130
|
+
}
|
|
131
|
+
if (choice === 'endpoint' || choice === 'both') providers.push(await provider(ctx, p, 'openai-compatible', providers.map(item => item.id)))
|
|
132
|
+
a.ai = { mode: 'providers', providers }
|
|
133
|
+
if (providers.length > 1) a.ai.default = await p.choose('Which one is the default?', providers.map(item => ({ value: item.id, label: `${item.id} (${item.model || item.kind})` })))
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
a.sso ||= {}
|
|
138
|
+
if (!has(a.sso, 'enabled')) {
|
|
139
|
+
a.sso.enabled = await p.confirm('Single sign-on (bundled Keycloak: Entra ID, Okta, Google Workspace, SAML, LDAP)?', { default: false })
|
|
140
|
+
if (a.sso.enabled) {
|
|
141
|
+
a.sso.only = await p.confirm('Single sign-on only (no passwords, no guests)?', { default: false })
|
|
142
|
+
a.sso.adminConsole = (await p.confirm('Close Keycloak\'s admin console on the public address?', { default: false })) ? 'closed' : 'open'
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
a.backups ||= {}
|
|
147
|
+
if (!has(a.backups, 'to')) {
|
|
148
|
+
const where = await p.choose('Backups', kube
|
|
149
|
+
? [{ value: 'default', label: 'Daily at 03:00 UTC to a volume in the namespace, keep 14' }, { value: 'off', label: 'Off' }]
|
|
150
|
+
: [{ value: 'default', label: 'Daily at 03:00, keep 14, next to the install' }, { value: 'dir', label: 'Daily to another folder' }, { value: 's3', label: 'Daily to S3 (needs the aws command on the host)' }, { value: 'off', label: 'Off' }],
|
|
151
|
+
{ default: 'default' })
|
|
152
|
+
a.backups.to = where === 'dir' ? await p.text('Folder') : where === 's3' ? await p.text('S3 URL (s3://bucket/prefix)') : where
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (!has(a, 'size')) {
|
|
156
|
+
a.size = await p.choose('Size', Object.entries(SIZES).map(([value, size]) => ({ value, label: `${value}: ${size.memory} memory, ${size.cpu} CPU, ${size.storage} storage${a.sso?.enabled ? ' (+0.5 GB for SSO)' : ''}` })), { default: 'small' })
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
a.mail ||= {}
|
|
160
|
+
if (!has(a.mail, 'urlFrom')) {
|
|
161
|
+
const name = await p.text('Mail: name of the environment variable that holds your SMTP URL (smtp://user:pass@host:587)', { optional: true, validate: v => variableName(true)(v.replace(/^env:/, '')) })
|
|
162
|
+
if (name) {
|
|
163
|
+
a.mail.urlFrom = `env:${name.replace(/^env:/, '')}`
|
|
164
|
+
a.mail.from = (await p.text('Send mail from (for example Slatebox <boards@example.com>)', { optional: true })) || null
|
|
165
|
+
} else {
|
|
166
|
+
ctx.stderr.write(` Without mail, someone who forgets a password gets a one-time link from you: docker exec ${a.name || 'slatebox'} slatebox password-link <email>\n`)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return a
|
|
170
|
+
}
|
package/src/output.mjs
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Everything the installer prints goes through here, and through the redactor.
|
|
2
|
+
// With --json (or in agent mode) stdout carries one JSON event per line and
|
|
3
|
+
// people's text goes to stderr; otherwise people's text goes to stdout.
|
|
4
|
+
|
|
5
|
+
export class Output {
|
|
6
|
+
/**
|
|
7
|
+
* @param {{stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, json: boolean, debug: boolean, redactor: import('./secrets.mjs').Redactor}} options
|
|
8
|
+
*/
|
|
9
|
+
constructor({ stdout, stderr, json, debug, redactor }) {
|
|
10
|
+
this.stdout = stdout
|
|
11
|
+
this.stderr = stderr
|
|
12
|
+
this.json = json
|
|
13
|
+
this.debugOn = debug
|
|
14
|
+
this.redactor = redactor
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
#text(stream, text) {
|
|
18
|
+
stream.write(this.redactor.redact(text) + (text.endsWith('\n') ? '' : '\n'))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A line for people. */
|
|
22
|
+
say(text = '') {
|
|
23
|
+
this.#text(this.json ? this.stderr : this.stdout, text)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A warning for people, always on stderr. */
|
|
27
|
+
warn(text) {
|
|
28
|
+
this.#text(this.stderr, `! ${text}`)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
debug(text) {
|
|
32
|
+
if (this.debugOn) this.#text(this.stderr, `[debug] ${text}`)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A machine-readable event: {"event":"plan"|"step"|"done"|"error", ...}. Only with --json. */
|
|
36
|
+
event(event) {
|
|
37
|
+
if (!this.json) return
|
|
38
|
+
this.stdout.write(this.redactor.redact(JSON.stringify(event)) + '\n')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A step in progress, for both audiences. */
|
|
42
|
+
step(id, status, detail = '') {
|
|
43
|
+
this.event({ event: 'step', id, status, ...(detail ? { detail } : {}) })
|
|
44
|
+
if (!this.json || this.debugOn) {
|
|
45
|
+
const mark = { start: '…', ok: '✓', skip: '–', warn: '!', fail: '✗' }[status] || '·'
|
|
46
|
+
this.#text(this.json ? this.stderr : this.stdout, `${mark} ${detail || id}`)
|
|
47
|
+
} else if (status === 'fail' || status === 'warn') {
|
|
48
|
+
this.#text(this.stderr, `${status === 'fail' ? '✗' : '!'} ${detail || id}`)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/plan.mjs
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// The plan: everything an install will write, run and create, shown before
|
|
2
|
+
// anything changes. It names where secrets go, never what they are.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @typedef {{
|
|
6
|
+
* action: 'install'|'upgrade'|'change'|'uninstall'|'restore'|'export'|'nothing',
|
|
7
|
+
* target: string, name: string, where: string, address: string|null,
|
|
8
|
+
* image?: {ref: string, pinned: string, previous?: string},
|
|
9
|
+
* files: {path: string, note?: string}[], commands: string[], objects: string[],
|
|
10
|
+
* ports: string[], secretsLocation: string|null, warnings: string[], notes: string[],
|
|
11
|
+
* changes: string[],
|
|
12
|
+
* }} Plan
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export function emptyPlan(fields) {
|
|
16
|
+
return { files: [], commands: [], objects: [], ports: [], secretsLocation: null, warnings: [], notes: [], changes: [], ...fields }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function formatPlan(plan) {
|
|
20
|
+
const lines = []
|
|
21
|
+
const title = {
|
|
22
|
+
install: `Plan: install Slatebox "${plan.name}" on ${plan.where}`,
|
|
23
|
+
upgrade: `Plan: upgrade Slatebox "${plan.name}" on ${plan.where}`,
|
|
24
|
+
change: `Plan: change Slatebox "${plan.name}" on ${plan.where}`,
|
|
25
|
+
uninstall: `Plan: remove Slatebox "${plan.name}" from ${plan.where}`,
|
|
26
|
+
restore: `Plan: restore Slatebox "${plan.name}" on ${plan.where} from a backup`,
|
|
27
|
+
export: `Plan: write the files for Slatebox "${plan.name}"`,
|
|
28
|
+
nothing: `Slatebox "${plan.name}" on ${plan.where}: nothing to change`,
|
|
29
|
+
}[plan.action]
|
|
30
|
+
lines.push(title, '')
|
|
31
|
+
if (plan.address) lines.push(` Address: ${plan.address}`)
|
|
32
|
+
if (plan.image) {
|
|
33
|
+
lines.push(` Image: ${plan.image.ref}`)
|
|
34
|
+
if (plan.image.pinned !== plan.image.ref) lines.push(` pinned as ${plan.image.pinned}`)
|
|
35
|
+
if (plan.image.previous && plan.image.previous !== plan.image.pinned) lines.push(` replacing ${plan.image.previous}`)
|
|
36
|
+
}
|
|
37
|
+
if (plan.ports.length) lines.push(` Ports: ${plan.ports.join(', ')}`)
|
|
38
|
+
if (plan.secretsLocation) lines.push(` Secrets: ${plan.secretsLocation}`)
|
|
39
|
+
const section = (label, items) => {
|
|
40
|
+
if (!items.length) return
|
|
41
|
+
lines.push('', ` ${label}:`)
|
|
42
|
+
for (const item of items) lines.push(` - ${item}`)
|
|
43
|
+
}
|
|
44
|
+
section('Changes', plan.changes)
|
|
45
|
+
section('Files', plan.files.map(file => (file.note ? `${file.path} (${file.note})` : file.path)))
|
|
46
|
+
section('Commands', plan.commands)
|
|
47
|
+
section('Objects', plan.objects)
|
|
48
|
+
section('Notes', plan.notes)
|
|
49
|
+
section('Warnings', plan.warnings)
|
|
50
|
+
return lines.join('\n')
|
|
51
|
+
}
|
package/src/prompt.mjs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Questions for people: short, each with a default that Enter accepts.
|
|
2
|
+
// Only used when there is a person at a terminal; agents get exit code 3 and
|
|
3
|
+
// the list of questions instead.
|
|
4
|
+
import { createInterface } from 'node:readline'
|
|
5
|
+
import { EXIT, InstallError } from './errors.mjs'
|
|
6
|
+
|
|
7
|
+
export function createPrompt({ input, output }) {
|
|
8
|
+
// One reader for the whole run, with lines queued, so answers typed (or
|
|
9
|
+
// piped) ahead of their question are not lost.
|
|
10
|
+
const rl = createInterface({ input, terminal: false })
|
|
11
|
+
const queue = []
|
|
12
|
+
const waiting = []
|
|
13
|
+
let closed = false
|
|
14
|
+
rl.on('line', line => (waiting.length ? waiting.shift()(line) : queue.push(line)))
|
|
15
|
+
rl.on('close', () => { closed = true; while (waiting.length) waiting.shift()(null) })
|
|
16
|
+
const nextLine = () => (queue.length ? Promise.resolve(queue.shift()) : closed ? Promise.resolve(null) : new Promise(resolve => waiting.push(resolve)))
|
|
17
|
+
|
|
18
|
+
async function line(prompt) {
|
|
19
|
+
output.write(prompt)
|
|
20
|
+
const answer = await nextLine()
|
|
21
|
+
if (answer === null) throw new InstallError(EXIT.CANCELLED, 'Cancelled.')
|
|
22
|
+
return answer.trim()
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return {
|
|
26
|
+
async text(question, { default: fallback = '', validate, optional = false } = {}) {
|
|
27
|
+
for (;;) {
|
|
28
|
+
const answer = (await line(`? ${question}${fallback ? ` (${fallback})` : optional ? ' (Enter skips)' : ''}: `)) || fallback
|
|
29
|
+
if (!answer && optional) return ''
|
|
30
|
+
const problem = !answer ? 'An answer is needed.' : validate?.(answer)
|
|
31
|
+
if (!problem) return answer
|
|
32
|
+
output.write(` ${problem}\n`)
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
async choose(question, choices, { default: fallback = null } = {}) {
|
|
36
|
+
output.write(`? ${question}\n`)
|
|
37
|
+
choices.forEach((choice, index) => output.write(` ${index + 1}) ${choice.label}${choice.value === fallback ? ' [default]' : ''}\n`))
|
|
38
|
+
for (;;) {
|
|
39
|
+
const answer = await line(` Choose 1-${choices.length}${fallback ? ' (Enter for the default)' : ''}: `)
|
|
40
|
+
if (!answer && fallback) return fallback
|
|
41
|
+
const index = Number(answer) - 1
|
|
42
|
+
if (Number.isInteger(index) && choices[index]) return choices[index].value
|
|
43
|
+
const named = choices.find(choice => choice.value === answer)
|
|
44
|
+
if (named) return named.value
|
|
45
|
+
output.write(' Type the number of a choice.\n')
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
async confirm(question, { default: fallback = false } = {}) {
|
|
49
|
+
const answer = (await line(`? ${question} [${fallback ? 'Y/n' : 'y/N'}]: `)).toLowerCase()
|
|
50
|
+
if (!answer) return fallback
|
|
51
|
+
return answer === 'y' || answer === 'yes'
|
|
52
|
+
},
|
|
53
|
+
/** Hidden input: nothing is echoed while the key is typed. */
|
|
54
|
+
async secret(question) {
|
|
55
|
+
output.write(`? ${question}: `)
|
|
56
|
+
const tty = input.isTTY && typeof input.setRawMode === 'function'
|
|
57
|
+
if (!tty) {
|
|
58
|
+
const answer = await nextLine()
|
|
59
|
+
output.write('\n')
|
|
60
|
+
return answer?.trim() || undefined
|
|
61
|
+
}
|
|
62
|
+
rl.pause()
|
|
63
|
+
input.setRawMode(true)
|
|
64
|
+
input.resume()
|
|
65
|
+
let value = ''
|
|
66
|
+
try {
|
|
67
|
+
await new Promise((resolve, reject) => {
|
|
68
|
+
const onData = chunk => {
|
|
69
|
+
for (const char of chunk.toString('utf8')) {
|
|
70
|
+
if (char === '\r' || char === '\n') { input.off('data', onData); resolve(); return }
|
|
71
|
+
if (char === '\u0003') { input.off('data', onData); reject(new InstallError(EXIT.CANCELLED, 'Cancelled.')); return }
|
|
72
|
+
if (char === '\u007f') value = value.slice(0, -1)
|
|
73
|
+
else value += char
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
input.on('data', onData)
|
|
77
|
+
})
|
|
78
|
+
} finally {
|
|
79
|
+
input.setRawMode(false)
|
|
80
|
+
output.write('\n')
|
|
81
|
+
rl.resume()
|
|
82
|
+
}
|
|
83
|
+
return value || undefined
|
|
84
|
+
},
|
|
85
|
+
close: () => rl.close(),
|
|
86
|
+
}
|
|
87
|
+
}
|
package/src/record.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// The install record: the resolved answers of a successful install (secret
|
|
2
|
+
// references stay references), plus what the installer needs for upgrades.
|
|
3
|
+
// On this computer it lives in ~/.slatebox/installs/<name>/install.yaml; an
|
|
4
|
+
// SSH install keeps the same file on the server, and Kubernetes keeps it in a
|
|
5
|
+
// ConfigMap. Every target also keeps a copy here, so `slatebox status` and
|
|
6
|
+
// `upgrade` know where each install is.
|
|
7
|
+
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
8
|
+
import { homedir } from 'node:os'
|
|
9
|
+
import { join } from 'node:path'
|
|
10
|
+
import { parse, stringify } from './yaml.mjs'
|
|
11
|
+
|
|
12
|
+
export function slateboxHome(env = process.env, flag) {
|
|
13
|
+
return flag || env.SLATEBOX_INSTALL_HOME || join(env.HOME || homedir(), '.slatebox')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const installDir = (home, name) => join(home, 'installs', name)
|
|
17
|
+
export const recordPath = (home, name) => join(installDir(home, name), 'install.yaml')
|
|
18
|
+
|
|
19
|
+
export function readRecord(home, name) {
|
|
20
|
+
const path = recordPath(home, name)
|
|
21
|
+
if (!existsSync(path)) return null
|
|
22
|
+
return parse(readFileSync(path, 'utf8'))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function recordText(record) {
|
|
26
|
+
return `# The slatebox installer's record of the install "${record.name}". It holds no secrets.\n${stringify(record)}`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Write atomically, readable only by this user (it names where the secrets are). */
|
|
30
|
+
export function writeRecord(home, record) {
|
|
31
|
+
const dir = installDir(home, record.name)
|
|
32
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
33
|
+
const path = recordPath(home, record.name)
|
|
34
|
+
writeFileSync(`${path}.tmp`, recordText(record), { mode: 0o600 })
|
|
35
|
+
renameSync(`${path}.tmp`, path)
|
|
36
|
+
chmodSync(path, 0o600)
|
|
37
|
+
return path
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function listRecords(home) {
|
|
41
|
+
const dir = join(home, 'installs')
|
|
42
|
+
if (!existsSync(dir)) return []
|
|
43
|
+
return readdirSync(dir).sort().map(name => {
|
|
44
|
+
try { return readRecord(home, name) } catch { return { name, state: 'unreadable' } }
|
|
45
|
+
}).filter(Boolean)
|
|
46
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// The Docker Compose file for this computer and for a server over SSH. It is
|
|
2
|
+
// also what `slatebox install export --format compose` writes.
|
|
3
|
+
import { stringify } from '../yaml.mjs'
|
|
4
|
+
|
|
5
|
+
export const COMPOSE_FILE = 'compose.yaml'
|
|
6
|
+
export const SETTINGS_FILE = 'slatebox.env'
|
|
7
|
+
export const SECRETS_FILE = 'secrets.env'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Published ports. This computer publishes on 127.0.0.1 unless --listen says
|
|
11
|
+
* otherwise: Docker's port rules go around host firewalls such as ufw, so a
|
|
12
|
+
* bare "7070:7070" on a VPS would put the first-account page on the internet.
|
|
13
|
+
*/
|
|
14
|
+
export function ports(answers) {
|
|
15
|
+
if (answers.address.port === null) return ['80:80', '443:443']
|
|
16
|
+
const listen = answers.address.listen && !['0.0.0.0', '::'].includes(answers.address.listen) ? `${answers.address.listen.includes(':') ? `[${answers.address.listen}]` : answers.address.listen}:` : ''
|
|
17
|
+
return [`${listen}${answers.address.port}:7070`]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The host port of a published mapping ("127.0.0.1:7070:7070" -> 7070). */
|
|
21
|
+
export const hostPort = mapping => Number(mapping.split(':').at(-2))
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {object} answers
|
|
25
|
+
* @param {{image: string, hostGateway?: boolean, pullPolicy?: string|null}} options image: an immutable
|
|
26
|
+
* reference (repo@sha256:… or an image ID). pullPolicy null for exported files, where compose must pull.
|
|
27
|
+
*/
|
|
28
|
+
export function renderCompose(answers, { image, hostGateway = false, pullPolicy = 'never' }) {
|
|
29
|
+
const service = {
|
|
30
|
+
image,
|
|
31
|
+
container_name: answers.name,
|
|
32
|
+
restart: 'unless-stopped',
|
|
33
|
+
// The installer pulls (or loads) the image itself before it starts anything,
|
|
34
|
+
// so an upgrade never fetches behind its back. Exported files leave it out.
|
|
35
|
+
...(pullPolicy ? { pull_policy: pullPolicy } : {}),
|
|
36
|
+
ports: ports(answers),
|
|
37
|
+
volumes: ['data:/data'],
|
|
38
|
+
env_file: [SETTINGS_FILE, SECRETS_FILE],
|
|
39
|
+
labels: { 'com.slatebox.install': answers.name, 'app.kubernetes.io/managed-by': 'slatebox-installer' },
|
|
40
|
+
}
|
|
41
|
+
if (hostGateway) service.extra_hosts = ['host.docker.internal:host-gateway']
|
|
42
|
+
const compose = { name: answers.name, services: { slatebox: service }, volumes: { data: { name: `${answers.name}-data` } } }
|
|
43
|
+
return `# Written by the slatebox installer for the install "${answers.name}".
|
|
44
|
+
# Change it with \`npx slatebox install --name ${answers.name} ...\` (or \`slatebox ai ...\`) rather than by hand:
|
|
45
|
+
# the installer keeps its answers in install.yaml and writes this file again.
|
|
46
|
+
${stringify(compose)}`
|
|
47
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// `export --format helm`: the same objects renderK8s makes, wrapped as a chart
|
|
2
|
+
// for GitOps. The objects are rendered once with marker values, and each
|
|
3
|
+
// marker becomes a template expression, so the chart cannot drift from what
|
|
4
|
+
// `install k8s` applies. The Secret is not in the chart: it names an existing
|
|
5
|
+
// one (create it with your secret manager, or from secret.example.yaml).
|
|
6
|
+
import { names, renderK8s } from './k8s.mjs'
|
|
7
|
+
import { stringify } from '../yaml.mjs'
|
|
8
|
+
|
|
9
|
+
const MARK = {
|
|
10
|
+
image: '__SBX_IMAGE__', namespace: '__SBX_NAMESPACE__', memory: '__SBX_MEMORY__', cpu: '__SBX_CPU__',
|
|
11
|
+
storage: '__SBX_STORAGE__', host: '__sbx-host__.invalid', secret: '__SBX_SECRET__', storageClass: '__SBX_STORAGE_CLASS__',
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const EXPR = {
|
|
15
|
+
[MARK.image]: '{{ .Values.image | quote }}',
|
|
16
|
+
[MARK.namespace]: '{{ .Release.Namespace | quote }}',
|
|
17
|
+
[MARK.memory]: '{{ .Values.resources.memory | quote }}',
|
|
18
|
+
[MARK.cpu]: '{{ .Values.resources.cpu | quote }}',
|
|
19
|
+
[MARK.storage]: '{{ .Values.storage.size | quote }}',
|
|
20
|
+
[MARK.host]: '{{ .Values.host | quote }}',
|
|
21
|
+
[MARK.secret]: '{{ .Values.existingSecret | quote }}',
|
|
22
|
+
[MARK.storageClass]: '{{ .Values.storage.className | quote }}',
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function templated(object) {
|
|
26
|
+
let text = stringify(object)
|
|
27
|
+
for (const [mark, expression] of Object.entries(EXPR)) text = text.split(mark).join(expression)
|
|
28
|
+
return text
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @returns {Record<string, string>} chart files by path, relative to the chart directory
|
|
33
|
+
*/
|
|
34
|
+
export function renderHelmChart(answers, { image, env, version, appVersion }) {
|
|
35
|
+
const n = names(answers)
|
|
36
|
+
const host = answers.address.url ? new URL(answers.address.url).hostname : null
|
|
37
|
+
const marked = structuredClone(answers)
|
|
38
|
+
marked.k8s = { ...marked.k8s, namespace: MARK.namespace, storageClass: answers.k8s.storageClass ? MARK.storageClass : null }
|
|
39
|
+
marked.size = { memory: MARK.memory, cpu: MARK.cpu, storage: MARK.storage }
|
|
40
|
+
if (answers.k8s.route !== 'none') marked.address = { url: `https://${MARK.host}` }
|
|
41
|
+
const objects = renderK8s(marked, { image: MARK.image, env: {}, record: '' })
|
|
42
|
+
.filter(object => object.kind !== 'Namespace' && object.metadata.name !== n.record && object.metadata.name !== n.config)
|
|
43
|
+
const files = {}
|
|
44
|
+
files['Chart.yaml'] = stringify({
|
|
45
|
+
apiVersion: 'v2', name: 'slatebox', description: 'Slatebox: the app, live collaboration and its database in one pod.',
|
|
46
|
+
type: 'application', version, appVersion: String(appVersion),
|
|
47
|
+
})
|
|
48
|
+
const values = {
|
|
49
|
+
image,
|
|
50
|
+
host,
|
|
51
|
+
existingSecret: n.secret,
|
|
52
|
+
resources: { memory: answers.size.memory, cpu: answers.size.cpu },
|
|
53
|
+
storage: { size: answers.size.storage, className: answers.k8s.storageClass || '' },
|
|
54
|
+
settings: { ...env },
|
|
55
|
+
}
|
|
56
|
+
files['values.yaml'] = `# Values for the Slatebox chart, written by \`slatebox install export --format helm\`.\n# The Secret "${n.secret}" must exist: see secret.example.yaml next to this chart.\n${stringify(values)}`
|
|
57
|
+
files['templates/configmap.yaml'] = `apiVersion: v1
|
|
58
|
+
kind: ConfigMap
|
|
59
|
+
metadata:
|
|
60
|
+
name: ${n.config}
|
|
61
|
+
namespace: {{ .Release.Namespace | quote }}
|
|
62
|
+
labels:
|
|
63
|
+
${Object.entries(objects[0].metadata.labels).map(([key, value]) => ` ${key}: ${value}`).join('\n')}
|
|
64
|
+
data:
|
|
65
|
+
{{- range $key, $value := .Values.settings }}
|
|
66
|
+
{{ $key }}: {{ $value | quote }}
|
|
67
|
+
{{- end }}
|
|
68
|
+
`
|
|
69
|
+
for (const object of objects) {
|
|
70
|
+
let text = templated(object)
|
|
71
|
+
if (object.kind === 'StatefulSet') {
|
|
72
|
+
text = text.replace(/slatebox\.com\/config-hash: \S+/, `slatebox.com/config-hash: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum | trunc 16 | quote }}`)
|
|
73
|
+
text = text.replace(`name: ${n.secret}`, `name: ${EXPR[MARK.secret]}`)
|
|
74
|
+
}
|
|
75
|
+
files[`templates/${object.kind.toLowerCase()}-${object.metadata.name}.yaml`] = text
|
|
76
|
+
}
|
|
77
|
+
return files
|
|
78
|
+
}
|