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,489 @@
1
+ // Answers: what to install and how. They come from four places, lowest first:
2
+ // the install record of an earlier run, exported SLATEBOX_INSTALL_* variables,
3
+ // an answers file (--answers), and flags. Secrets are never answers: a key is
4
+ // given as a reference (env:NAME, file:/path, prompt) and read only when used.
5
+ import { isAbsolute, join, normalize, resolve as resolvePath } from 'node:path'
6
+ import { isRef, looksLikeKey } from './secrets.mjs'
7
+ import { normalizeProvider, PROVIDER_KINDS } from './ai/settings-adapter.mjs'
8
+
9
+ export const TARGETS = ['local', 'ssh', 'k8s', 'export']
10
+ export const SIZES = Object.freeze({
11
+ small: Object.freeze({ memory: '1Gi', cpu: '1', storage: '10Gi' }),
12
+ team: Object.freeze({ memory: '2Gi', cpu: '2', storage: '20Gi' }),
13
+ large: Object.freeze({ memory: '4Gi', cpu: '4', storage: '50Gi' }),
14
+ })
15
+ export const DEFAULT_PORT = 7070
16
+
17
+ // Every flag the install, plan and upgrade commands take, with its type. The
18
+ // same names in capitals under SLATEBOX_INSTALL_ are read from the environment,
19
+ // except consent (see ARGV_ONLY).
20
+ export const ANSWER_FLAGS = {
21
+ target: 'string', host: 'string', 'ssh-port': 'string', identity: 'string', 'install-docker': 'boolean', sudo: 'string',
22
+ dir: 'string', 'ssh-option': 'multiple', url: 'string', domain: 'string', port: 'string', listen: 'string', 'admin-email': 'string',
23
+ ai: 'string', 'ai-provider': 'multiple', 'ai-default': 'string', sso: 'boolean', 'sso-only': 'boolean', 'sso-admin': 'string',
24
+ 'mail-url-from': 'string', 'mail-from': 'string', backups: 'string', 'backup-schedule': 'string', 'backup-keep': 'string',
25
+ size: 'string', 'k8s-context': 'string', namespace: 'string', route: 'string', 'ingress-class': 'string',
26
+ 'gateway-ref': 'string', 'tls-issuer': 'string', 'storage-class': 'string', format: 'string', out: 'string',
27
+ image: 'string', name: 'string', 'acme-ca': 'string', settings: 'string',
28
+ }
29
+ // Global flags that also have an environment form.
30
+ const GLOBAL_ENV_FLAGS = { answers: 'string', json: 'boolean', agent: 'string', 'image-archive': 'string', home: 'string', debug: 'boolean', 'health-timeout': 'string' }
31
+
32
+ const isObject = value => value && typeof value === 'object' && !Array.isArray(value)
33
+
34
+ function deepMerge(base, extra) {
35
+ const out = { ...base }
36
+ for (const [key, value] of Object.entries(extra || {})) {
37
+ if (value === undefined) continue
38
+ out[key] = isObject(value) && isObject(out[key]) ? deepMerge(out[key], value) : value
39
+ }
40
+ return out
41
+ }
42
+
43
+ const truthy = value => /^(1|true|yes|on)$/i.test(String(value))
44
+
45
+ // Consent is typed on the command line, each time: a variable left exported in
46
+ // a shell, a CI job or an agent's environment must never approve a plan,
47
+ // install Docker on a server or replace the key encryption key.
48
+ export const ARGV_ONLY = new Set(['yes', 'install-docker', 'new-encryption-key', 'delete-data', 'confirm'])
49
+
50
+ /** SLATEBOX_INSTALL_ADMIN_EMAIL=x becomes { 'admin-email': 'x' }. Only exported variables count. */
51
+ export function flagsFromEnv(env) {
52
+ const out = {}
53
+ const known = { ...ANSWER_FLAGS, ...GLOBAL_ENV_FLAGS }
54
+ for (const [flag, type] of Object.entries(known)) {
55
+ if (ARGV_ONLY.has(flag)) continue
56
+ const value = env[`SLATEBOX_INSTALL_${flag.toUpperCase().replace(/-/g, '_')}`]
57
+ if (value === undefined || value === '') continue
58
+ out[flag] = type === 'boolean' ? truthy(value) : type === 'multiple' ? value.split(/\s*;\s*/).filter(Boolean) : value
59
+ }
60
+ return out
61
+ }
62
+
63
+ /** "id=local,kind=ollama,url=http://...,model=qwen3:8b,key=env:NAME" */
64
+ export function parseProviderSpec(spec) {
65
+ const fields = {}
66
+ for (const part of String(spec).split(',')) {
67
+ const at = part.indexOf('=')
68
+ if (at < 1) continue
69
+ fields[part.slice(0, at).trim()] = part.slice(at + 1).trim()
70
+ }
71
+ const out = { id: fields.id || fields.kind, kind: fields.kind }
72
+ if (fields.url || fields.baseUrl) out.baseUrl = fields.url || fields.baseUrl
73
+ if (fields.model) out.model = fields.model
74
+ out.keyFrom = fields.key || fields.keyFrom || 'none'
75
+ if (fields.toolChoice || fields['tool-choice']) out.toolChoice = fields.toolChoice || fields['tool-choice']
76
+ return out
77
+ }
78
+
79
+ function splitHost(spec) {
80
+ const match = /^(?:([^@]+)@)?(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(spec)
81
+ if (!match) return { host: spec }
82
+ return { user: match[1], host: match[2], port: match[3] ? Number(match[3]) : undefined }
83
+ }
84
+
85
+ /** The answers that a set of flags gives, and nothing more. */
86
+ export function answersFromFlags(flags) {
87
+ const out = {}
88
+ const set = (path, value) => {
89
+ if (value === undefined) return
90
+ const keys = path.split('.')
91
+ let node = out
92
+ for (const key of keys.slice(0, -1)) node = node[key] ||= {}
93
+ node[keys.at(-1)] = value
94
+ }
95
+ set('name', flags.name)
96
+ set('target', flags.target)
97
+ set('image', flags.image)
98
+ set('acmeCa', flags['acme-ca'])
99
+ if (flags.host) {
100
+ const { user, host, port } = splitHost(flags.host)
101
+ set('ssh.host', host)
102
+ set('ssh.user', user)
103
+ set('ssh.port', port)
104
+ }
105
+ if (flags['ssh-port']) set('ssh.port', Number(flags['ssh-port']))
106
+ set('ssh.identity', flags.identity)
107
+ set('ssh.installDocker', flags['install-docker'])
108
+ set('ssh.sudo', flags.sudo)
109
+ set('ssh.dir', flags.dir)
110
+ set('ssh.options', flags['ssh-option'])
111
+ set('address.url', flags.url)
112
+ set('address.domain', flags.domain)
113
+ set('address.listen', flags.listen)
114
+ if (flags.port !== undefined) set('address.port', Number(flags.port))
115
+ set('adminEmail', flags['admin-email'])
116
+ if (flags.ai !== undefined) set('ai.mode', flags.ai)
117
+ if (flags['ai-provider']?.length) {
118
+ set('ai.mode', 'providers')
119
+ set('ai.providers', flags['ai-provider'].map(parseProviderSpec))
120
+ }
121
+ set('ai.default', flags['ai-default'])
122
+ set('sso.enabled', flags.sso)
123
+ if (flags['sso-only'] !== undefined) {
124
+ set('sso.only', flags['sso-only'])
125
+ if (flags['sso-only']) set('sso.enabled', true)
126
+ }
127
+ set('sso.adminConsole', flags['sso-admin'])
128
+ set('mail.urlFrom', flags['mail-url-from'])
129
+ set('mail.from', flags['mail-from'])
130
+ set('backups.to', flags.backups)
131
+ set('backups.schedule', flags['backup-schedule'])
132
+ if (flags['backup-keep'] !== undefined) set('backups.keep', Number(flags['backup-keep']))
133
+ set('size', flags.size)
134
+ set('k8s.context', flags['k8s-context'])
135
+ set('k8s.namespace', flags.namespace)
136
+ set('k8s.route', flags.route)
137
+ set('k8s.ingressClass', flags['ingress-class'])
138
+ set('k8s.gatewayRef', flags['gateway-ref'])
139
+ if (flags['tls-issuer']) {
140
+ const [kind, name] = flags['tls-issuer'].includes('/') ? flags['tls-issuer'].split('/') : ['ClusterIssuer', flags['tls-issuer']]
141
+ set('k8s.tlsIssuer', { kind, name })
142
+ }
143
+ set('k8s.storageClass', flags['storage-class'])
144
+ set('export.format', flags.format)
145
+ set('export.dir', flags.out)
146
+ if (flags.settings !== undefined) {
147
+ try { set('settings', JSON.parse(flags.settings)) } catch { set('settings', flags.settings) }
148
+ }
149
+ return out
150
+ }
151
+
152
+ /** Merge the four sources: record < environment < answers file < flags. */
153
+ export function collect({ record, env = {}, file, flags = {} }) {
154
+ let out = {}
155
+ if (record) out = deepMerge(out, stripRecord(record))
156
+ out = deepMerge(out, answersFromFlags(flagsFromEnv(env)))
157
+ // An answers file is data from elsewhere: it cannot give consent either.
158
+ if (file?.ssh && 'installDocker' in file.ssh) file = { ...file, ssh: Object.fromEntries(Object.entries(file.ssh).filter(([key]) => key !== 'installDocker')) }
159
+ if (file) out = deepMerge(out, file)
160
+ out = deepMerge(out, answersFromFlags(flags))
161
+ return out
162
+ }
163
+
164
+ // What an install record adds beyond the answers is not an answer.
165
+ function stripRecord(record) {
166
+ const { installedVersion, imageDigest, previousImageDigest, imageRef, lastHealthy, secretsLocation, state, installedAt, capabilities, ...answers } = record
167
+ return answers
168
+ }
169
+
170
+ // ------------------------------------------------------------ questions
171
+
172
+ export const AI_CHOICES = [
173
+ { value: 'none', label: 'None for now (the usual choice; add a provider later with `slatebox ai add`)' },
174
+ { value: 'cloud', label: 'Cloud provider key(s): OpenAI, Anthropic, DeepInfra, OpenRouter, Groq, Together, Mistral' },
175
+ { value: 'endpoint', label: 'An endpoint I run: Ollama, vLLM, LM Studio or any OpenAI-compatible URL, and its model' },
176
+ { value: 'both', label: 'Both' },
177
+ ]
178
+
179
+ export const QUESTIONS = {
180
+ target: {
181
+ question: 'Where should Slatebox run?',
182
+ choices: [
183
+ { value: 'local', label: 'This computer, with Docker' },
184
+ { value: 'ssh', label: 'A Linux server over SSH' },
185
+ { value: 'k8s', label: 'Kubernetes (the current kube context)' },
186
+ { value: 'export', label: 'Just write the files (compose file or manifests) for GitOps' },
187
+ ],
188
+ flag: '--target',
189
+ },
190
+ 'ssh.host': { question: 'Server (user@host or a name from ~/.ssh/config)', flag: '--host' },
191
+ adminEmail: { question: 'Admin email (the first account, and the HTTPS certificate contact)', flag: '--admin-email' },
192
+ 'ai.mode': {
193
+ question: 'AI for drafts and the canvas assistant. Slatebox works with any provider, and none is chosen for you.',
194
+ choices: AI_CHOICES,
195
+ flag: '--ai none | --ai-provider kind=<openai|anthropic|deepinfra|openrouter|groq|together|mistral|ollama|lmstudio|openai-compatible>,model=<model>,url=<endpoint>,key=env:<VAR> (repeat for several, then --ai-default <id>)',
196
+ },
197
+ }
198
+
199
+ function question(field, extra = {}) {
200
+ const q = QUESTIONS[field] || {}
201
+ return { field, question: q.question || field, ...(q.choices ? { choices: q.choices } : {}), flag: q.flag, default: null, ...extra }
202
+ }
203
+
204
+ // ------------------------------------------------------------ resolve
205
+
206
+ // Never repeat the value: it may be the key itself.
207
+ const KEY_IN_NAME = 'this looks like a key, not the name of an environment variable. It was not saved or shown. Export the key in a variable (export GROQ_API_KEY=...) and give env:GROQ_API_KEY'
208
+ const refLooksLikeKey = ref => typeof ref === 'string' && ref.startsWith('env:') && looksLikeKey(ref.slice(4))
209
+
210
+ const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/
211
+ const NAME = /^[a-z][a-z0-9-]{0,30}$/
212
+ const QUANTITY = /^[0-9]+(\.[0-9]+)?(Mi|Gi|Ti|M|G|T)?$/
213
+ const DAILY_CRON = /^([0-5]?[0-9]) ([01]?[0-9]|2[0-3]) \* \* \*$/
214
+ const CRON_FIELD = /^[0-9A-Za-z*,/-]+$/
215
+ // Image references go to docker and kubectl as arguments: no option-looking or shell-looking ones.
216
+ const IMAGE_REF = /^[A-Za-z0-9][A-Za-z0-9._/:@-]*$/
217
+ // What ssh gets from an answers file. Never a ProxyCommand, LocalCommand or
218
+ // anything else that runs a program here, and never host-key checking off.
219
+ const SSH_HOST = /^(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9_][A-Za-z0-9_.:-]*)$/
220
+ const SSH_USER = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/
221
+ const SSH_DIR = /^\/[A-Za-z0-9._/-]+$/
222
+ const SSH_OPTIONS = {
223
+ ConnectTimeout: /^[0-9]{1,4}$/,
224
+ ServerAliveInterval: /^[0-9]{1,4}$/,
225
+ ServerAliveCountMax: /^[0-9]{1,3}$/,
226
+ StrictHostKeyChecking: /^(yes|accept-new|ask)$/,
227
+ UserKnownHostsFile: /^[A-Za-z0-9._/~-]+$/,
228
+ IdentitiesOnly: /^(yes|no)$/,
229
+ IdentityAgent: /^[A-Za-z0-9._/~-]+$/,
230
+ ProxyJump: /^([A-Za-z0-9_][A-Za-z0-9_.-]*@)?[A-Za-z0-9_][A-Za-z0-9_.-]*(:[0-9]{1,5})?(,([A-Za-z0-9_][A-Za-z0-9_.-]*@)?[A-Za-z0-9_][A-Za-z0-9_.-]*(:[0-9]{1,5})?)*$/,
231
+ HostKeyAlias: /^[A-Za-z0-9_.-]+$/,
232
+ AddressFamily: /^(any|inet|inet6)$/,
233
+ Compression: /^(yes|no)$/,
234
+ }
235
+ const S3_URL = /^s3:\/\/[a-z0-9][a-z0-9.-]{1,61}[a-z0-9](\/[A-Za-z0-9._/-]*)?$/
236
+ const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i
237
+
238
+ export function sshOptionProblem(option) {
239
+ const match = /^([A-Za-z]+)[= ](.+)$/.exec(String(option))
240
+ if (!match) return 'Key=Value'
241
+ const check = SSH_OPTIONS[match[1]]
242
+ if (!check) return `${match[1]} is not allowed (allowed: ${Object.keys(SSH_OPTIONS).join(', ')}); put anything else in ~/.ssh/config`
243
+ if (!check.test(match[2])) return `${match[1]} has a value that is not allowed${match[1] === 'StrictHostKeyChecking' ? ' (yes, accept-new or ask: checking host keys is never turned off)' : ''}`
244
+ return null
245
+ }
246
+
247
+ /** RFC 1123 host name, or an IP address. */
248
+ export function hostnameProblem(hostname) {
249
+ if (/^\[[0-9a-f:.]+\]$/i.test(hostname) || /^[0-9.]+$/.test(hostname)) return null
250
+ if (hostname.length > 253 || !hostname.split('.').every(label => LABEL.test(label))) return 'a host name: letters, digits and dashes in dot-separated labels'
251
+ return null
252
+ }
253
+
254
+ function toMi(quantity) {
255
+ const match = /^([0-9.]+)(Mi|Gi|Ti|M|G|T)?$/.exec(quantity)
256
+ const n = Number(match[1])
257
+ return { Mi: n, Gi: n * 1024, Ti: n * 1024 * 1024, M: n / 1.048576, G: n * 953.674, T: n * 953674 }[match[2] || 'Mi'] ?? n / (1024 * 1024)
258
+ }
259
+
260
+ function httpUrl(value) {
261
+ try {
262
+ const url = new URL(value)
263
+ if (!['http:', 'https:'].includes(url.protocol)) return null
264
+ if (url.username || url.password || url.pathname !== '/' || url.search || url.hash) return null
265
+ return url
266
+ } catch { return null }
267
+ }
268
+
269
+ /**
270
+ * Fill in defaults and check everything.
271
+ * @param {object} partial from collect()
272
+ * @param {{freePort?: number}} ctx
273
+ * @returns {{answers: object, missing: object[], errors: {field: string, message: string}[]}}
274
+ */
275
+ export function resolveAnswers(partial, ctx = {}) {
276
+ const errors = []
277
+ const missing = []
278
+ const err = (field, message) => errors.push({ field, message })
279
+ const p = structuredClone(partial || {})
280
+ const a = { version: 1 }
281
+
282
+ a.name = p.name ?? 'slatebox'
283
+ if (!NAME.test(a.name)) err('name', 'lowercase letters, digits and dashes, starting with a letter, at most 31 characters')
284
+ a.target = p.target ?? 'local'
285
+ if (!TARGETS.includes(a.target)) err('target', `one of ${TARGETS.join(', ')}`)
286
+ if (p.image) a.image = p.image
287
+ if (a.image !== undefined && (typeof a.image !== 'string' || !IMAGE_REF.test(a.image))) err('image', 'an image reference, like ghcr.io/slatebox/slatebox:latest')
288
+ if (p.acmeCa) a.acmeCa = p.acmeCa
289
+
290
+ // --- target-specific sections
291
+ if (a.target === 'ssh') {
292
+ const s = p.ssh || {}
293
+ a.ssh = {
294
+ host: s.host ?? null, user: s.user ?? 'root', port: s.port ?? 22, identity: s.identity ?? null,
295
+ sudo: s.sudo ?? 'auto', installDocker: Boolean(s.installDocker), dir: s.dir ?? '/opt/slatebox', options: s.options ?? [],
296
+ }
297
+ if (!a.ssh.host) missing.push(question('ssh.host'))
298
+ else if (!SSH_HOST.test(a.ssh.host)) err('ssh.host', 'a host name, an IP address or a name from ~/.ssh/config (not starting with -)')
299
+ if (!a.ssh.user) a.ssh.user = 'root'
300
+ if (!SSH_USER.test(a.ssh.user)) err('ssh.user', 'a user name (letters, digits, . _ -, not starting with -)')
301
+ if (!Number.isInteger(a.ssh.port) || a.ssh.port < 1 || a.ssh.port > 65535) err('ssh.port', 'a port number')
302
+ if (!['auto', 'yes', 'no'].includes(a.ssh.sudo)) err('ssh.sudo', 'auto, yes or no')
303
+ if (typeof a.ssh.dir !== 'string' || !SSH_DIR.test(a.ssh.dir) || a.ssh.dir.split('/').includes('..') || normalize(a.ssh.dir) === '/') err('ssh.dir', 'an absolute path on the server: letters, digits and . _ - / only')
304
+ if (a.ssh.identity !== null && (typeof a.ssh.identity !== 'string' || a.ssh.identity.startsWith('-'))) err('ssh.identity', 'the path of a private key')
305
+ if (!Array.isArray(a.ssh.options)) err('ssh.options', 'a list of Key=Value')
306
+ else {
307
+ const problems = a.ssh.options.map(sshOptionProblem).filter(Boolean)
308
+ if (problems.length) err('ssh.options', problems.join('; '))
309
+ }
310
+ }
311
+ if (a.target === 'k8s' || (a.target === 'export' && ['manifests', 'helm'].includes(p.export?.format))) {
312
+ const k = p.k8s || {}
313
+ a.k8s = {
314
+ context: k.context ?? null, namespace: k.namespace ?? 'slatebox', route: k.route ?? 'none',
315
+ ingressClass: k.ingressClass ?? null, gatewayRef: k.gatewayRef ?? null, tlsIssuer: k.tlsIssuer ?? null, storageClass: k.storageClass ?? null,
316
+ }
317
+ if (!['none', 'ingress', 'gateway'].includes(a.k8s.route)) err('k8s.route', 'none, ingress or gateway')
318
+ if (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(a.k8s.namespace)) err('k8s.namespace', 'a valid namespace name')
319
+ if (a.k8s.route === 'gateway' && !/^[a-z0-9-]+\/[a-z0-9-]+$/.test(a.k8s.gatewayRef || '')) err('k8s.gatewayRef', 'namespace/name of the Gateway')
320
+ if (a.k8s.tlsIssuer && (!['ClusterIssuer', 'Issuer'].includes(a.k8s.tlsIssuer.kind) || !a.k8s.tlsIssuer.name)) err('k8s.tlsIssuer', 'ClusterIssuer/<name> or Issuer/<name>')
321
+ }
322
+ if (a.target === 'export') {
323
+ a.export = { format: p.export?.format ?? 'compose', dir: p.export?.dir ?? './slatebox-deploy' }
324
+ if (!['compose', 'manifests', 'helm'].includes(a.export.format)) err('export.format', 'compose, manifests or helm')
325
+ }
326
+
327
+ // --- address
328
+ const given = p.address || {}
329
+ const k8s = a.target === 'k8s' || Boolean(a.k8s)
330
+ if (given.domain && given.url) err('address.url', 'give a domain or a URL, not both')
331
+ let url = given.domain ? `https://${given.domain}` : given.url
332
+ if (k8s) {
333
+ if (a.k8s.route === 'none') {
334
+ url ??= `http://localhost:${DEFAULT_PORT}`
335
+ } else if (!url || !httpUrl(url) || httpUrl(url).protocol !== 'https:') {
336
+ err('address.url', `a route (${a.k8s.route}) needs the host name people will use, given as --domain`)
337
+ url = null
338
+ }
339
+ a.address = { url }
340
+ } else {
341
+ let port = given.port
342
+ if (url && httpUrl(url)?.protocol === 'https:') {
343
+ port = null // built-in HTTPS: ports 80 and 443
344
+ } else {
345
+ port ??= a.target === 'local' ? (ctx.freePort ?? DEFAULT_PORT) : DEFAULT_PORT
346
+ if (!Number.isInteger(port) || port < 1 || port > 65535) err('address.port', 'a port number')
347
+ if (url) {
348
+ const parsed = httpUrl(url)
349
+ const urlPort = parsed ? Number(parsed.port || 80) : null
350
+ if (parsed && urlPort !== port) err('address.url', `the address must use the published port ${port} (it says ${urlPort})`)
351
+ } else {
352
+ const host = a.target === 'ssh' ? (!SSH_HOST.test(a.ssh.host || '') ? null : a.ssh.host.includes(':') && !a.ssh.host.startsWith('[') ? `[${a.ssh.host}]` : a.ssh.host) : 'localhost'
353
+ url = host ? `http://${host}:${port}` : null
354
+ }
355
+ }
356
+ const listen = given.listen ?? (a.target === 'local' && port !== null ? '127.0.0.1' : '0.0.0.0')
357
+ if (!['127.0.0.1', '0.0.0.0', '::1', '::'].includes(listen) && !/^[0-9]{1,3}(\.[0-9]{1,3}){3}$/.test(listen)) err('address.listen', 'an IP address of this host to publish on: 127.0.0.1 (this computer only) or 0.0.0.0 (every network interface)')
358
+ a.address = { url, port, listen }
359
+ }
360
+ if (a.address.url && !httpUrl(a.address.url)) {
361
+ if (!errors.some(error => error.field === 'address.url')) err('address.url', 'an http:// or https:// address with nothing after the host, for example https://boards.example.com')
362
+ } else if (a.address.url) {
363
+ const parsed = httpUrl(a.address.url)
364
+ const problem = hostnameProblem(parsed.hostname)
365
+ if (problem) err('address.url', problem)
366
+ else a.address.url = parsed.origin
367
+ }
368
+
369
+ // --- people
370
+ a.adminEmail = p.adminEmail ?? null
371
+ if (a.adminEmail && !EMAIL.test(a.adminEmail)) err('adminEmail', 'an email address')
372
+ if (!a.adminEmail && (a.target === 'ssh' || a.target === 'k8s')) missing.push(question('adminEmail'))
373
+
374
+ // --- AI: never a default
375
+ const ai = p.ai || {}
376
+ if (ai.mode === undefined || ai.mode === null) {
377
+ missing.push(question('ai.mode'))
378
+ a.ai = { mode: null }
379
+ } else if (ai.mode === 'none') {
380
+ a.ai = { mode: 'none' }
381
+ } else if (ai.mode === 'providers') {
382
+ const providers = (ai.providers || []).map((provider, index) => {
383
+ if (!provider?.kind || !PROVIDER_KINDS.includes(provider.kind)) {
384
+ err(`ai.providers[${index}].kind`, `one of ${PROVIDER_KINDS.join(', ')}`)
385
+ return provider
386
+ }
387
+ const normalized = normalizeProvider(provider)
388
+ if (refLooksLikeKey(normalized.keyFrom)) {
389
+ err(`ai.providers[${index}].keyFrom`, KEY_IN_NAME)
390
+ normalized.keyFrom = 'none'
391
+ return normalized
392
+ }
393
+ const literal = !isRef(normalized.keyFrom)
394
+ if (literal) {
395
+ err(`ai.providers[${index}].keyFrom`, 'a reference: env:NAME, file:/path, prompt or none (never the key itself)')
396
+ normalized.keyFrom = 'none'
397
+ }
398
+ if (literal) {
399
+ // already reported
400
+ } else if (normalized.kind === 'openai-compatible') {
401
+ try { new URL(normalized.baseUrl) } catch { err(`ai.providers[${index}].baseUrl`, 'the endpoint URL, for example http://ollama:11434/v1') }
402
+ if (!normalized.model) err(`ai.providers[${index}].model`, 'the model name the endpoint serves')
403
+ } else if (normalized.keyFrom === 'none') {
404
+ err(`ai.providers[${index}].keyFrom`, 'DeepInfra needs a key: env:NAME, file:/path or prompt')
405
+ }
406
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(normalized.id || '')) err(`ai.providers[${index}].id`, 'lowercase letters, digits and dashes')
407
+ return normalized
408
+ })
409
+ if (!providers.length) err('ai.providers', 'at least one provider, or --ai none')
410
+ const ids = providers.map(provider => provider?.id)
411
+ if (new Set(ids).size !== ids.length) err('ai.providers', 'each provider needs its own id')
412
+ a.ai = { mode: 'providers', providers, default: ai.default ?? (providers.length === 1 ? providers[0]?.id : null) }
413
+ if (providers.length > 1 && !ai.default) err('ai.default', 'several providers: say which one is the default (--ai-default <id>)')
414
+ else if (a.ai.default && !ids.includes(a.ai.default)) err('ai.default', `one of ${ids.join(', ')}`)
415
+ } else {
416
+ err('ai.mode', 'none or providers (with --ai-provider)')
417
+ a.ai = { mode: null }
418
+ }
419
+
420
+ // --- single sign-on, mail
421
+ const sso = p.sso || {}
422
+ a.sso = { enabled: Boolean(sso.enabled), only: Boolean(sso.only), adminConsole: sso.adminConsole ?? 'open' }
423
+ if (!['open', 'closed'].includes(a.sso.adminConsole)) err('sso.adminConsole', 'open or closed')
424
+ if (a.sso.only && !a.sso.enabled) err('sso.only', 'needs single sign-on on')
425
+ const mail = p.mail || {}
426
+ a.mail = { urlFrom: mail.urlFrom ?? null, from: mail.from ?? null }
427
+ if (refLooksLikeKey(a.mail.urlFrom)) {
428
+ err('mail.urlFrom', KEY_IN_NAME)
429
+ a.mail.urlFrom = null
430
+ } else if (a.mail.urlFrom && !isRef(a.mail.urlFrom)) {
431
+ err('mail.urlFrom', 'a reference to the SMTP URL: env:NAME or file:/path (it holds a password)')
432
+ a.mail.urlFrom = null
433
+ }
434
+ if (a.mail.from && !a.mail.urlFrom) err('mail.from', 'only applies with a mail URL')
435
+
436
+ // --- backups
437
+ const b = p.backups || {}
438
+ a.backups = { schedule: b.schedule ?? '0 3 * * *', to: b.to ?? 'default', keep: b.keep ?? 14 }
439
+ if (!Number.isInteger(a.backups.keep) || a.backups.keep < 1) err('backups.keep', 'how many backups to keep, at least 1')
440
+ if (a.backups.to !== 'off' && (typeof a.backups.schedule !== 'string' || a.backups.schedule.split(' ').length !== 5 || !a.backups.schedule.split(' ').every(field => CRON_FIELD.test(field)))) err('backups.schedule', 'a cron schedule, for example "0 3 * * *"')
441
+ if (typeof a.backups.to !== 'string' || /[\0\r\n]/.test(a.backups.to)) {
442
+ err('backups.to', 'default, off, a folder or s3://bucket/prefix')
443
+ a.backups.to = 'off'
444
+ } else if (a.backups.to.startsWith('s3:')) {
445
+ if (!S3_URL.test(a.backups.to)) err('backups.to', 's3://bucket/prefix (letters, digits and . _ - / in the prefix)')
446
+ } else if (!['default', 'off', 'pvc'].includes(a.backups.to) && !k8s) {
447
+ // A folder, made absolute once here so the stored answer does not depend on where the installer runs.
448
+ let to = a.backups.to
449
+ if (to === '~' || to.startsWith('~/')) to = a.target === 'ssh' ? to : join(ctx.home || '~', to.slice(1))
450
+ if (!isAbsolute(to)) {
451
+ if (a.target === 'ssh' || a.target === 'export') err('backups.to', 'an absolute folder on the server')
452
+ else if (ctx.cwd) to = resolvePath(ctx.cwd, to)
453
+ }
454
+ a.backups.to = to
455
+ }
456
+ if (k8s && a.backups.to !== 'off') {
457
+ if (!['default', 'pvc'].includes(a.backups.to)) err('backups.to', 'on Kubernetes backups go to a volume in the namespace (default) or off; S3 is not supported there yet')
458
+ if (!DAILY_CRON.test(a.backups.schedule)) err('backups.schedule', 'on Kubernetes a daily time, "M H * * *" (UTC)')
459
+ } else if (a.backups.to.startsWith('s3://') && a.target !== 'local' && a.target !== 'ssh') {
460
+ err('backups.to', 'S3 backups need the aws command on a Docker host')
461
+ }
462
+
463
+ // --- size
464
+ if (typeof p.size === 'string' || p.size === undefined) {
465
+ const named = SIZES[p.size ?? 'small']
466
+ if (!named) {
467
+ err('size', `small, team, large, or { memory, cpu, storage }`)
468
+ a.size = { ...SIZES.small }
469
+ } else {
470
+ a.size = { ...named }
471
+ if (a.sso.enabled) a.size.memory = `${toMi(named.memory) + 512}Mi`
472
+ }
473
+ } else if (isObject(p.size)) {
474
+ a.size = { memory: String(p.size.memory), cpu: String(p.size.cpu), storage: String(p.size.storage) }
475
+ if (!QUANTITY.test(a.size.memory) || !QUANTITY.test(a.size.storage) || !/^[0-9]+(\.[0-9]+)?m?$/.test(a.size.cpu)) err('size', 'memory and storage like 2Gi, cpu like 2 or 500m')
476
+ } else {
477
+ err('size', 'small, team, large, or { memory, cpu, storage }')
478
+ }
479
+
480
+ a.settings = p.settings ?? {}
481
+ if (!isObject(a.settings)) err('settings', 'a JSON object (no secrets: those go in references)')
482
+ if (a.acmeCa && !/^https:\/\/\S+$/.test(a.acmeCa)) err('acmeCa', 'an https:// ACME directory URL')
483
+ return { answers: a, missing, errors }
484
+ }
485
+
486
+ /** The answers as they are stored in an install record and in exported answers files. */
487
+ export function recordable(answers) {
488
+ return structuredClone(answers)
489
+ }