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.
package/src/cloud.mjs ADDED
@@ -0,0 +1,261 @@
1
+ // Slatebox Cloud, for team addresses (https://<name>.slatebox.team): the device-code sign-in
2
+ // (RFC 8628, like `gh auth login`), the team-address API, and the install credential that stays
3
+ // on this computer.
4
+ //
5
+ // What goes where:
6
+ // - The person's sign-in token lives in memory for one command and is never written anywhere.
7
+ // - The install credential (sbxi_…) is written to ~/.slatebox/installs/<name>/credentials.json,
8
+ // mode 0600 in a 0700 folder, and never leaves this computer (not to a server over SSH, not
9
+ // into a container). It can fetch this install's own tunnel token and release its own address,
10
+ // and nothing else.
11
+ // - The tunnel connector token goes only into the install's secrets (secrets.env or the
12
+ // Kubernetes Secret). Slatebox Cloud never stores it; it asks Cloudflare each time.
13
+ //
14
+ // The base URL is https://app.slatebox.com unless SLATEBOX_CLOUD_URL or --cloud-url says
15
+ // otherwise (a local claim service for tests). Plain http:// is accepted only for loopback.
16
+ import { spawn } from 'node:child_process'
17
+ import { randomBytes } from 'node:crypto'
18
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
19
+ import { hostname } from 'node:os'
20
+ import { join } from 'node:path'
21
+ import { EXIT, InstallError } from './errors.mjs'
22
+ import { installDir } from './record.mjs'
23
+
24
+ export const DEFAULT_CLOUD = 'https://app.slatebox.com'
25
+ export const TEAM_ZONE = 'slatebox.team'
26
+ export const CLI_CLIENT_ID = 'slatebox-cli'
27
+ export const TEAM_SCOPE = 'team-addresses'
28
+ export const CREDENTIALS_FILE = 'credentials.json'
29
+ const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'
30
+
31
+ // ------------------------------------------------------------------ names
32
+
33
+ // 3-32 characters, a-z 0-9 and hyphens, starting with a letter, not ending with a hyphen, and
34
+ // never two hyphens in a row (which also rules out xn-- punycode). The server holds the same rule
35
+ // plus the reserved and blocked lists; this is only so a typo is caught before any network call.
36
+ export const TEAM_ADDRESS_RULE = '3–32 characters: a–z, 0–9 and hyphens, starting with a letter, not ending with a hyphen (no two hyphens in a row)'
37
+ const TEAM_ADDRESS = /^[a-z][a-z0-9-]{1,30}[a-z0-9]$/
38
+
39
+ export function teamAddressProblem(name) {
40
+ const text = String(name ?? '')
41
+ if (!TEAM_ADDRESS.test(text) || text.includes('--')) return TEAM_ADDRESS_RULE
42
+ return null
43
+ }
44
+
45
+ export const teamHost = name => `${name}.${TEAM_ZONE}`
46
+ export const teamUrl = name => `https://${teamHost(name)}`
47
+
48
+ // ------------------------------------------------------------------ base URL
49
+
50
+ export function cloudBase(ctx) {
51
+ const raw = ctx.flags?.['cloud-url'] || ctx.env?.SLATEBOX_CLOUD_URL || DEFAULT_CLOUD
52
+ let url
53
+ try { url = new URL(raw) } catch { throw new InstallError(EXIT.USAGE, `SLATEBOX_CLOUD_URL (or --cloud-url) is not a URL: ${raw}`) }
54
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
55
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
56
+ throw new InstallError(EXIT.USAGE, 'SLATEBOX_CLOUD_URL must be https:// (plain http:// only for localhost).')
57
+ }
58
+ if (url.username || url.password || url.search || url.hash) throw new InstallError(EXIT.USAGE, 'SLATEBOX_CLOUD_URL is an origin, with nothing after the host.')
59
+ return url.origin
60
+ }
61
+
62
+ // ------------------------------------------------------------------ errors
63
+
64
+ /** An answer from Slatebox Cloud that is not a success: {error: {code, message}}. */
65
+ export class CloudError extends Error {
66
+ constructor(status, code, message, extra = {}) {
67
+ super(message || code || `HTTP ${status}`)
68
+ this.status = status
69
+ this.code = code || `http_${status}`
70
+ Object.assign(this, extra)
71
+ }
72
+ }
73
+
74
+ function offline(base, error) {
75
+ const host = new URL(base).host
76
+ const why = error?.cause?.code || error?.code || error?.name || error?.message || 'no answer'
77
+ return new InstallError(EXIT.PRECONDITION,
78
+ `Slatebox Cloud (${host}) can't be reached: ${why}.\n` +
79
+ ' A team address is claimed online. Nothing was changed.\n' +
80
+ ' Run this again when you\'re online, or install without one:\n' +
81
+ ' npx slatebox install --local\n' +
82
+ ' npx slatebox install --domain boards.example.com',
83
+ { id: 'cloud-unreachable', cloud: host })
84
+ }
85
+
86
+ // ------------------------------------------------------------------ client
87
+
88
+ /**
89
+ * @param {object} ctx run context: fetch, redactor
90
+ * @param {string} base Cloud origin
91
+ */
92
+ export function cloudClient(ctx, base) {
93
+ const fetchImpl = ctx.fetch || globalThis.fetch
94
+
95
+ async function call(method, path, { bearer, body, form, headers = {}, timeout = 20_000 } = {}) {
96
+ const init = { method, headers: { accept: 'application/json', 'user-agent': `slatebox-cli/${ctx.version || '0'}`, ...headers }, redirect: 'error', signal: AbortSignal.timeout(timeout) }
97
+ if (bearer) init.headers.authorization = `Bearer ${bearer}`
98
+ if (form) {
99
+ init.headers['content-type'] = 'application/x-www-form-urlencoded'
100
+ init.body = new URLSearchParams(form).toString()
101
+ } else if (body !== undefined) {
102
+ init.headers['content-type'] = 'application/json'
103
+ init.body = JSON.stringify(body)
104
+ }
105
+ let response
106
+ try {
107
+ response = await fetchImpl(`${base}${path}`, init)
108
+ } catch (error) {
109
+ throw offline(base, error)
110
+ }
111
+ let data = null
112
+ const text = typeof response.text === 'function' ? await response.text().catch(() => '') : JSON.stringify(await response.json?.().catch(() => null))
113
+ try { data = text ? JSON.parse(text) : null } catch { data = null }
114
+ if (response.status >= 200 && response.status < 300) return data ?? {}
115
+ // OAuth errors are {error: "code", error_description}; the API's are {error: {code, message}}.
116
+ const error = data?.error
117
+ const code = typeof error === 'string' ? error : error?.code
118
+ const message = typeof error === 'string' ? data?.error_description : error?.message
119
+ const retryAfter = Number(response.headers?.get?.('retry-after')) || undefined
120
+ throw new CloudError(response.status, code, message, { retryAfter, suggestions: data?.suggestions || error?.suggestions, notice: error?.notice })
121
+ }
122
+
123
+ const api = path => `/api/v1/team-addresses${path}`
124
+ const enc = encodeURIComponent
125
+
126
+ return {
127
+ base,
128
+ // --- sign-in (RFC 8628)
129
+ deviceAuthorize: (label, scope = TEAM_SCOPE) => call('POST', '/oauth/device_authorization', { form: { client_id: CLI_CLIENT_ID, scope, device_label: label } }),
130
+ deviceToken: deviceCode => call('POST', '/oauth/token', { form: { grant_type: DEVICE_GRANT, device_code: deviceCode, client_id: CLI_CLIENT_ID } }),
131
+ // --- the signed-in person's team addresses
132
+ availability: (name, bearer) => call('GET', api(`/availability?name=${enc(name)}`), { bearer }),
133
+ claim: (bearer, { name, clientKey, label, idempotencyKey }) => call('POST', api(''), { bearer, body: { name, clientKey, label }, headers: { 'idempotency-key': idempotencyKey }, timeout: 120_000 }),
134
+ list: bearer => call('GET', api(''), { bearer }),
135
+ rename: (bearer, id, name) => call('POST', api(`/${enc(id)}/rename`), { bearer, body: { name }, timeout: 120_000 }),
136
+ release: (bearer, id) => call('DELETE', api(`/${enc(id)}`), { bearer, timeout: 120_000 }),
137
+ mintCredential: (bearer, id) => call('POST', api(`/${enc(id)}/install-credential`), { bearer }),
138
+ // --- this install, with its install credential
139
+ self: credential => call('GET', api('/self'), { bearer: credential }),
140
+ connectorToken: (credential, { rotate = false } = {}) => call('POST', api('/self/connector-token'), { bearer: credential, body: { rotate }, timeout: 120_000 }),
141
+ renameComplete: credential => call('POST', api('/self/rename-complete'), { bearer: credential, body: {}, timeout: 120_000 }),
142
+ releaseSelf: credential => call('DELETE', api('/self'), { bearer: credential, timeout: 120_000 }),
143
+ }
144
+ }
145
+
146
+ // ------------------------------------------------------------------ sign-in
147
+
148
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
149
+
150
+ /** A short, printable name for this computer, shown on the consent page. */
151
+ export function deviceLabel() {
152
+ return hostname().replace(/[^\x20-\x7e]/g, '').slice(0, 64) || 'this computer'
153
+ }
154
+
155
+ /** Open a URL in the person's browser. Failure is fine: the code and link are printed anyway. */
156
+ export function openBrowser(url, platform = process.platform) {
157
+ const [cmd, args] = platform === 'darwin' ? ['open', [url]] : platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]]
158
+ try {
159
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true })
160
+ child.on('error', () => {})
161
+ child.unref()
162
+ } catch { /* printed anyway */ }
163
+ }
164
+
165
+ /**
166
+ * Sign in to Slatebox Cloud for one scope (team-addresses by default; a move asks for
167
+ * team:export and team:move). Returns an access token that lives
168
+ * 15 minutes and is kept in memory. There is no token shortcut: Slatebox Cloud gives the
169
+ * team-addresses scope only to this sign-in, never to a personal access token, so a person
170
+ * approves every claim, rename and credential in a browser.
171
+ */
172
+ export async function signIn(ctx, cloud, { purpose = 'claim a team address', scope = TEAM_SCOPE } = {}) {
173
+ const label = ctx.deviceLabel || deviceLabel()
174
+ const grant = await cloud.deviceAuthorize(label, scope).catch(error => { throw signInFailed(error, cloud) })
175
+ if (!grant?.device_code || !grant?.user_code || !grant?.verification_uri) throw new InstallError(EXIT.PRECONDITION, `Slatebox Cloud (${new URL(cloud.base).host}) did not start a sign-in.`)
176
+ ctx.redactor.add(grant.device_code)
177
+ // Only a link on the Cloud's own origin is opened or printed.
178
+ const sameOrigin = link => { try { return new URL(link).origin === cloud.base } catch { return false } }
179
+ const page = sameOrigin(grant.verification_uri) ? grant.verification_uri : `${cloud.base}/device`
180
+ const complete = sameOrigin(grant.verification_uri_complete) ? grant.verification_uri_complete : null
181
+ const minutes = Math.max(1, Math.round((grant.expires_in || 600) / 60))
182
+ ctx.out.event({ event: 'sign-in', status: 'waiting', verificationUri: page, userCode: grant.user_code, expiresIn: grant.expires_in || 600 })
183
+ const lines = ['', `Sign in to Slatebox to ${purpose}.`, ` Open: ${page}`, ` Code: ${grant.user_code}`]
184
+ if (ctx.interactive) {
185
+ lines.push(` (The code expires in ${minutes} minutes.)`)
186
+ ctx.stderr.write(`${lines.join('\n')}\n`)
187
+ if (await ctx.prompt.confirm('Open it in your browser now?', { default: true })) (ctx.openBrowser || openBrowser)(complete || page, ctx.platform)
188
+ } else {
189
+ lines.push(` (The code expires in ${minutes} minutes. Approve it in a browser where you are signed in to Slatebox.)`)
190
+ ctx.stderr.write(`${lines.join('\n')}\n`)
191
+ }
192
+ ctx.stderr.write('... waiting for approval\n')
193
+ let interval = Math.max(1, Number(grant.interval) || 5) * 1000
194
+ const deadline = Date.now() + (grant.expires_in || 600) * 1000
195
+ const wait = ctx.sleep || sleep
196
+ for (;;) {
197
+ await wait(interval)
198
+ try {
199
+ const token = await cloud.deviceToken(grant.device_code)
200
+ if (!token?.access_token) throw new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud approved the sign-in but sent no token.')
201
+ ctx.redactor.add(token.access_token)
202
+ ctx.out.event({ event: 'sign-in', status: 'ok' })
203
+ return token.access_token
204
+ } catch (error) {
205
+ if (!(error instanceof CloudError)) throw error
206
+ if (error.code === 'authorization_pending') { /* keep waiting */ } else if (error.code === 'slow_down') interval += 5000
207
+ else if (error.code === 'access_denied') throw new InstallError(EXIT.CANCELLED, 'The sign-in was denied in the browser. Nothing was changed.')
208
+ else if (error.code === 'expired_token') throw new InstallError(EXIT.PRECONDITION, 'The sign-in code expired before it was approved. Nothing was changed; run the command again for a new code.')
209
+ else throw signInFailed(error, cloud)
210
+ }
211
+ if (Date.now() > deadline) throw new InstallError(EXIT.PRECONDITION, 'The sign-in code expired before it was approved. Nothing was changed; run the command again for a new code.')
212
+ }
213
+ }
214
+
215
+ function signInFailed(error, cloud) {
216
+ if (error instanceof InstallError) return error
217
+ return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud (${new URL(cloud.base).host}) refused the sign-in: ${error.message}${error.code ? ` (${error.code})` : ''}.`)
218
+ }
219
+
220
+ // ------------------------------------------------------------------ credentials on disk
221
+
222
+ export const credentialsPath = (home, name) => join(installDir(home, name), CREDENTIALS_FILE)
223
+
224
+ /**
225
+ * The install's team-address credential, or null. A file or folder that others can read is
226
+ * refused with the command that fixes it, rather than used.
227
+ */
228
+ export function readCredentials(home, name) {
229
+ const path = credentialsPath(home, name)
230
+ if (!existsSync(path)) return null
231
+ if (process.platform !== 'win32') {
232
+ const fileMode = statSync(path).mode & 0o777
233
+ const dirMode = statSync(installDir(home, name)).mode & 0o777
234
+ if (fileMode & 0o077 || dirMode & 0o077) {
235
+ throw new InstallError(EXIT.PRECONDITION, `${path} can be read by other users of this computer (mode ${fileMode.toString(8)}, folder ${dirMode.toString(8)}), so it was not used. It holds the key to your team address. Fix it with: chmod 700 ${installDir(home, name)} && chmod 600 ${path}`)
236
+ }
237
+ }
238
+ let data
239
+ try { data = JSON.parse(readFileSync(path, 'utf8')) } catch { throw new InstallError(EXIT.PRECONDITION, `${path} is not readable JSON. Move it away and run slatebox install again to sign in and get a new one.`) }
240
+ if (!data?.claimId || !data?.installCredential || !data?.name) throw new InstallError(EXIT.PRECONDITION, `${path} is missing fields. Move it away and run slatebox install again.`)
241
+ return data
242
+ }
243
+
244
+ /** Written atomically, 0600 in a 0700 folder. */
245
+ export function writeCredentials(home, name, data) {
246
+ const dir = installDir(home, name)
247
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
248
+ chmodSync(dir, 0o700)
249
+ const path = credentialsPath(home, name)
250
+ writeFileSync(`${path}.tmp`, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 })
251
+ renameSync(`${path}.tmp`, path)
252
+ chmodSync(path, 0o600)
253
+ return path
254
+ }
255
+
256
+ export function removeCredentials(home, name) {
257
+ rmSync(credentialsPath(home, name), { force: true })
258
+ }
259
+
260
+ /** A random value that makes a retried claim from this computer the same claim. */
261
+ export const newClientKey = () => randomBytes(16).toString('base64url')
package/src/errors.mjs ADDED
@@ -0,0 +1,23 @@
1
+ // Exit codes, as documented in README.md and printed by `slatebox --help`.
2
+ export const EXIT = Object.freeze({
3
+ OK: 0,
4
+ USAGE: 2, // bad flags or answers; details list each field
5
+ NEEDS_INPUT: 3, // a missing answer or a confirmation, and nobody to ask
6
+ PRECONDITION: 4, // no Docker, no kube context, CPU, port taken, image unavailable, not available yet
7
+ ROLLED_BACK: 5, // changes applied, health failed, rolled back cleanly
8
+ ROLLBACK_FAILED: 6, // a person must act; details carry the commands
9
+ CANCELLED: 7,
10
+ })
11
+
12
+ export class InstallError extends Error {
13
+ /**
14
+ * @param {number} exitCode one of EXIT
15
+ * @param {string} message what happened and what to do, in plain words
16
+ * @param {object} [details] machine-readable extras for --json (fields, missing, commands)
17
+ */
18
+ constructor(exitCode, message, details = {}) {
19
+ super(message)
20
+ this.exitCode = exitCode
21
+ this.details = details
22
+ }
23
+ }
package/src/image.mjs ADDED
@@ -0,0 +1,141 @@
1
+ // Which image to run, pinned to something that cannot change underneath an
2
+ // install, and what that image accepts.
3
+ import { capabilitiesFromProbe, LEGACY_SETTINGS } from './ai/settings-adapter.mjs'
4
+ import { EXIT, InstallError } from './errors.mjs'
5
+
6
+ /**
7
+ * Each release of this package installs one image: the public multi-arch
8
+ * index on GHCR, by its digest, so `npx slatebox@x.y.z install` always
9
+ * installs the same bytes. Give --image or --image-archive to install a local
10
+ * build instead (self-host/build-image.sh).
11
+ */
12
+ export const DEFAULT_REPOSITORY = 'ghcr.io/slatebox/slatebox'
13
+ // 0.2.0 added the team-address tunnel (cloudflared); 0.2.1 adds the self-host fixes and team
14
+ // moves. PINNED_DIGEST is the published multi-arch index of ghcr.io/slatebox/slatebox:0.2.1
15
+ // (linux/amd64 and linux/arm64); `npm publish` refuses to run without it.
16
+ export const PINNED_TAG = '0.2.1'
17
+ export const PINNED_DIGEST = 'sha256:208d4bfc460ed2feedc435ccc22231177929e8885ab5f856933c67e6831ca5b5'
18
+ export const DEFAULT_IMAGE = PINNED_DIGEST ? `${DEFAULT_REPOSITORY}@${PINNED_DIGEST}` : `${DEFAULT_REPOSITORY}:${PINNED_TAG}`
19
+
20
+ /** Does this reference name a registry (so a digest reference can be pulled elsewhere)? */
21
+ export function hasRegistry(ref) {
22
+ const first = ref.split('/')[0]
23
+ return ref.includes('/') && (first.includes('.') || first.includes(':') || first === 'localhost')
24
+ }
25
+
26
+ export const repositoryOf = ref => ref.replace(/@sha256:[a-f0-9]{64}$/, '').replace(/:[^/:]+$/, '')
27
+
28
+ /** A tag (it can move), as opposed to a digest reference or an image ID. */
29
+ export const isTag = ref => !ref.includes('@sha256:') && !/^sha256:[a-f0-9]{64}$/.test(ref)
30
+
31
+ /** The image as it is on the host now, or null. Never pulls. */
32
+ export async function inspectImage(docker, ref) {
33
+ const inspected = await docker(['image', 'inspect', '--format', '{{json .}}', ref])
34
+ return inspected.code === 0 ? JSON.parse(inspected.stdout) : null
35
+ }
36
+
37
+ /** The pinned description of an inspected image. */
38
+ export function pinImage(wanted, info) {
39
+ const id = info.Id
40
+ let pinned = id
41
+ if (wanted.includes('@sha256:')) pinned = wanted
42
+ else if (hasRegistry(wanted)) {
43
+ const repository = repositoryOf(wanted)
44
+ pinned = (info.RepoDigests || []).find(digest => digest.startsWith(`${repository}@`)) || id
45
+ }
46
+ return { ref: wanted, pinned, id, created: info.Created, labels: info.Config?.Labels || {}, architecture: info.Architecture || null }
47
+ }
48
+
49
+ function unavailable(wanted, why) {
50
+ return new InstallError(EXIT.PRECONDITION,
51
+ `The image ${wanted} is not available: ${why}\n` +
52
+ (wanted.startsWith(DEFAULT_REPOSITORY) ? 'The public image needs no login: check that this machine can reach ghcr.io (or that the --to version exists), then try again. To install a local build instead, give --image <name> or --image-archive <file.tar>.' : 'Check the name, or log in to its registry with docker login.'),
53
+ { image: wanted })
54
+ }
55
+
56
+ /**
57
+ * For an upgrade: fetch a tag again, because a cached tag says nothing about
58
+ * what the registry has now. When the registry cannot be reached and a copy is
59
+ * already on the host, that copy is used and the person is told.
60
+ */
61
+ export async function refreshTag(docker, ref, step) {
62
+ if (!isTag(ref)) return
63
+ step('image', 'start', `Fetching ${ref} to see whether it is newer`)
64
+ const pulled = await docker(['pull', ref], { timeout: 60 * 60_000 })
65
+ if (pulled.code === 0) return
66
+ const why = pulled.stderr.trim().split('\n').pop()
67
+ if (!(await inspectImage(docker, ref))) throw unavailable(ref, why)
68
+ step('image', 'warn', `${ref} could not be pulled (${why}); using the copy already on the host.`)
69
+ }
70
+
71
+ const ARCH = { x86_64: 'amd64', amd64: 'amd64', aarch64: 'arm64', arm64: 'arm64' }
72
+ export const normalArch = arch => ARCH[String(arch || '').trim()] || String(arch || '').trim() || null
73
+
74
+ /** Refuse an image built for another processor than the host's (or the cluster nodes'). */
75
+ export function checkArch(image, hostArch, where) {
76
+ const want = normalArch(image.architecture)
77
+ const have = [].concat(hostArch || []).map(normalArch).filter(Boolean)
78
+ if (!want || !have.length || have.includes(want)) return
79
+ throw new InstallError(EXIT.PRECONDITION, `The image ${image.ref} is built for ${want}, but ${where} is ${[...new Set(have)].join(' and ')}. Use an image built for ${[...new Set(have)].join(' or ')} (docker buildx build --platform linux/${have[0]}).`)
80
+ }
81
+
82
+ /**
83
+ * Make the image available to a Docker host and pin it.
84
+ * @param {(args: string[], options?: object) => Promise<{code:number,stdout:string,stderr:string}>} docker docker on the target host
85
+ * @param {{ref?: string, archive?: string, loadArchive?: (file: string) => Promise<{code:number,stdout:string,stderr:string}>, step: Function}} options
86
+ * @returns {Promise<{ref: string, pinned: string, id: string, created?: string, labels: object}>}
87
+ */
88
+ export async function resolveImage(docker, { ref, archive, loadArchive, step }) {
89
+ let wanted = ref || DEFAULT_IMAGE
90
+ if (archive) {
91
+ step('image', 'start', `Loading the image from ${archive}`)
92
+ const loaded = await loadArchive(archive)
93
+ if (loaded.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The image archive ${archive} could not be loaded: ${loaded.stderr.trim()}`)
94
+ const named = /Loaded image: (\S+)/.exec(loaded.stdout)
95
+ const id = /Loaded image ID: (sha256:[a-f0-9]{64})/.exec(loaded.stdout)
96
+ if (!ref) wanted = named?.[1] || id?.[1]
97
+ if (!wanted) throw new InstallError(EXIT.PRECONDITION, `The image archive ${archive} did not name an image.`)
98
+ }
99
+ let info = await inspectImage(docker, wanted)
100
+ if (!info) {
101
+ step('image', 'start', `Pulling ${wanted}`)
102
+ const pulled = await docker(['pull', wanted], { timeout: 60 * 60_000 })
103
+ if (pulled.code !== 0) throw unavailable(wanted, pulled.stderr.trim().split('\n').pop())
104
+ info = await inspectImage(docker, wanted)
105
+ if (!info) throw new InstallError(EXIT.PRECONDITION, `The image ${wanted} was pulled but cannot be inspected.`)
106
+ }
107
+ return pinImage(wanted, info)
108
+ }
109
+
110
+ /** What the image accepts, read from the image (no network, nothing kept). */
111
+ export async function probeImage(docker, image) {
112
+ const base = ['run', '--rm', '--network', 'none']
113
+ const settingsJson = await docker([...base, '--entrypoint', '/opt/slatebox/bin/slatebox', image, 'settings', '--json'])
114
+ if (settingsJson.code === 0) {
115
+ const caps = capabilitiesFromProbe({ settingsJson: settingsJson.stdout })
116
+ if (caps) return caps
117
+ }
118
+ // Older images: the usage text lists the commands, and configure.mjs refuses
119
+ // an unknown SLATEBOX_ name with the list of every name it accepts.
120
+ const usage = settingsJson.stderr
121
+ const configure = await docker([...base, '-e', 'SLATEBOX_INSTALLER_PROBE=1', '--entrypoint', 'node', image, '/opt/slatebox/lib/configure.mjs'])
122
+ const caps = capabilitiesFromProbe({ configureOutput: configure.stdout + configure.stderr, usage })
123
+ if (!caps) {
124
+ throw new InstallError(EXIT.PRECONDITION, `${image} does not look like a Slatebox image (it does not list its settings). Give the one-container image, ghcr.io/slatebox/slatebox.`)
125
+ }
126
+ return caps
127
+ }
128
+
129
+ /** MongoDB 8.0 needs AVX (x86-64) or ARMv8.2-A; the image's own mongod is the authority. */
130
+ export async function checkCpu(docker, image) {
131
+ const result = await docker(['run', '--rm', '--network', 'none', '--entrypoint', 'mongod', image, '--version'])
132
+ if (/exec format error/i.test(result.stderr)) {
133
+ throw new InstallError(EXIT.PRECONDITION, `${image} is built for another processor architecture than this host ("exec format error"). Use an image built for this host's architecture.`)
134
+ }
135
+ if (result.code === 132 || /Illegal instruction/i.test(result.stderr)) {
136
+ throw new InstallError(EXIT.PRECONDITION, 'This processor cannot run MongoDB 8.0, which Slatebox includes: it needs AVX on Intel/AMD (2011 or newer) or ARMv8.2-A on ARM (Raspberry Pi 5, Graviton 2, Apple silicon).')
137
+ }
138
+ return result.code === 0
139
+ }
140
+
141
+ export const FALLBACK_CAPABILITIES = Object.freeze({ settings: [...LEGACY_SETTINGS], commands: ['backup', 'restore', 'password-link', 'health', 'version', 'sso'], source: 'assumed' })
@@ -0,0 +1,199 @@
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
+ import { teamAddressProblem, teamHost } from './cloud.mjs'
8
+ import { availability } from './targets/address.mjs'
9
+
10
+ /** Ask for a team address until one is free. Taken, reserved and blocked names get the same answer. */
11
+ export async function askTeamAddress(ctx, p) {
12
+ for (;;) {
13
+ const name = (await p.text('Team address', { validate: v => teamAddressProblem(v.toLowerCase()) })).toLowerCase()
14
+ const answer = await availability(ctx, name)
15
+ if (answer.available) {
16
+ ctx.stderr.write(`[ok] ${teamHost(name)} is available\n`)
17
+ return name
18
+ }
19
+ ctx.stderr.write(`[!!] ${teamHost(name)} isn't available.${answer.suggestions.length ? `\n Free right now: ${answer.suggestions.join(', ')}` : ''}\n`)
20
+ }
21
+ }
22
+
23
+ const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/
24
+ const CLOUD = ['openai', 'anthropic', 'deepinfra', 'openrouter', 'groq', 'together', 'mistral']
25
+
26
+ async function listModels(ctx, baseUrl) {
27
+ try {
28
+ const response = await ctx.fetch(`${baseUrl.replace(/\/$/, '')}/models`, { signal: AbortSignal.timeout(3000) })
29
+ if (!response.ok) return []
30
+ return ((await response.json()).data || []).map(model => model.id).filter(Boolean).slice(0, 20)
31
+ } catch { return [] }
32
+ }
33
+
34
+ const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
35
+ // Never repeat what was typed: it may be the key.
36
+ 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.'
37
+ const variableName = optional => v => (looksLikeKey(v) ? KEY_TYPED : VARIABLE.test(v) ? null : `A variable name, like OPENAI_API_KEY${optional ? ', or Enter for none' : ''}`)
38
+
39
+ async function keyRef(p, label) {
40
+ // Two steps, so that nobody pastes a key where a name is asked for.
41
+ const how = await p.choose(`How will you give the ${label} key?`, [
42
+ { value: 'env', label: 'It is in an environment variable (I will give its name)' },
43
+ { value: 'prompt', label: 'Type it now, hidden; it goes only into the secrets file' },
44
+ ], { default: 'env' })
45
+ if (how === 'prompt') return 'prompt'
46
+ const name = await p.text(`Name of the environment variable that holds the ${label} key`, { validate: variableName(false) })
47
+ return `env:${name}`
48
+ }
49
+
50
+ async function provider(ctx, p, kind, ids) {
51
+ const preset = PRESETS[kind]
52
+ let id = kind
53
+ for (let n = 2; ids.includes(id); n++) id = `${kind}-${n}`
54
+ if (preset.kind === 'deepinfra') return { id, kind: 'deepinfra', keyFrom: await keyRef(p, 'DeepInfra') }
55
+ if (kind === 'openai-compatible') {
56
+ 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' } } })
57
+ const models = await listModels(ctx, baseUrl)
58
+ const model = models.length
59
+ ? await p.choose(`Model at ${baseUrl}`, models.map(value => ({ value, label: value })), { default: models[0] })
60
+ : await p.text('Model name the endpoint serves (for example qwen3:8b)')
61
+ const token = await p.text('Name of the environment variable that holds its token (Enter if it needs none)', { optional: true, validate: variableName(true) })
62
+ return { id: ids.includes('local') ? `local-${ids.length + 1}` : 'local', kind: 'openai-compatible', baseUrl, model, keyFrom: token ? `env:${token}` : 'none' }
63
+ }
64
+ const model = await p.text(`${kind} model to use`)
65
+ return { id, kind, model, keyFrom: await keyRef(p, kind) }
66
+ }
67
+
68
+ /**
69
+ * @param {object} ctx run context (prompt, fetch, freePort, currentContext)
70
+ * @param {object} partial collected answers
71
+ * @returns {Promise<object>} partial with the person's answers added
72
+ */
73
+ export async function interview(ctx, partial) {
74
+ const p = ctx.prompt
75
+ const a = structuredClone(partial)
76
+ const has = (object, key) => object && object[key] !== undefined && object[key] !== null
77
+ ctx.stderr.write('\nSlatebox installer. Enter accepts the default in brackets; Ctrl-C stops without changing anything.\n\n')
78
+
79
+ if (!has(a, 'target')) {
80
+ const choices = QUESTIONS.target.choices.map(choice => choice.value === 'k8s' && ctx.currentContext ? { ...choice, label: `Kubernetes (current context: ${ctx.currentContext})` } : choice)
81
+ a.target = await p.choose(QUESTIONS.target.question, choices, { default: 'local' })
82
+ }
83
+ if (a.target === 'ssh') {
84
+ a.ssh ||= {}
85
+ if (!has(a.ssh, 'host')) {
86
+ const spec = await p.text(QUESTIONS['ssh.host'].question)
87
+ const at = spec.indexOf('@')
88
+ if (at > 0) { a.ssh.user = spec.slice(0, at); a.ssh.host = spec.slice(at + 1) } else a.ssh.host = spec
89
+ }
90
+ }
91
+ if (a.target === 'export') {
92
+ a.export ||= {}
93
+ if (!has(a.export, 'format')) a.export.format = await p.choose('Which files?', [
94
+ { value: 'compose', label: 'Docker Compose file' }, { value: 'manifests', label: 'Kubernetes manifests' }, { value: 'helm', label: 'Helm chart' },
95
+ ], { default: 'compose' })
96
+ if (!has(a.export, 'dir')) a.export.dir = await p.text('Write them to', { default: './slatebox-deploy' })
97
+ }
98
+ const kube = a.target === 'k8s' || ['manifests', 'helm'].includes(a.export?.format)
99
+
100
+ // Address
101
+ a.address ||= {}
102
+ if (!has(a.address, 'url') && !has(a.address, 'domain') && a.address.team === undefined && !has(a.address, 'port') && (a.target === 'local' || a.target === 'ssh')) {
103
+ const where = await p.choose('Where should your team open Slatebox?', [
104
+ { value: 'team', label: 'A free team address, https://<name>.slatebox.team (recommended: no DNS, ports or certificates)' },
105
+ { value: 'domain', label: 'My own domain (I point DNS at this server, or I run a proxy)' },
106
+ { value: 'local', label: a.target === 'local' ? `Only this computer, http://localhost:${ctx.freePort}` : `Plain http://${a.ssh?.host || '<server>'}:7070, no HTTPS` },
107
+ ], { default: 'team' })
108
+ if (where === 'team') a.address.team = await askTeamAddress(ctx, p)
109
+ else if (where === 'domain') a.address.domain = await p.text('Domain name, pointed at this server (for example boards.example.com)')
110
+ else {
111
+ a.address.team = null
112
+ if (a.target === 'local') a.address.port = ctx.freePort
113
+ else a.address.port = 7070
114
+ }
115
+ }
116
+ if (!has(a.address, 'url') && !has(a.address, 'domain') && !a.address.team && !(a.address.team === null && has(a.address, 'port'))) {
117
+ if (a.target === 'local' && !has(a.address, 'port')) {
118
+ 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') })
119
+ a.address.port = Number(port)
120
+ } else if (a.target === 'ssh' || (a.target === 'export' && !kube)) {
121
+ const domain = await p.text(`Domain name for HTTPS, pointed at the server (Enter for plain http://${a.ssh?.host || '<server>'}:7070)`, { optional: true })
122
+ if (domain) a.address.domain = domain
123
+ } else if (kube) {
124
+ a.k8s ||= {}
125
+ if (!has(a.k8s, 'route')) a.k8s.route = await p.choose('How does traffic reach it?', [
126
+ { value: 'ingress', label: 'An Ingress (ingress-nginx, Traefik, ...)' }, { value: 'gateway', label: 'Gateway API (an HTTPRoute on an existing Gateway)' },
127
+ { value: 'none', label: 'Nothing for now (kubectl port-forward)' },
128
+ ], { default: 'ingress' })
129
+ if (a.k8s.route !== 'none') {
130
+ a.address.domain = await p.text('Host name people will use (for example boards.example.com)')
131
+ if (a.k8s.route === 'ingress' && !has(a.k8s, 'ingressClass')) a.k8s.ingressClass = (await p.text('IngressClass', { optional: true })) || null
132
+ if (a.k8s.route === 'gateway' && !has(a.k8s, 'gatewayRef')) a.k8s.gatewayRef = await p.text('Gateway, as namespace/name')
133
+ if (!has(a.k8s, 'tlsIssuer')) {
134
+ const issuer = await p.text('cert-manager issuer for TLS, as ClusterIssuer/name or Issuer/name', { optional: true })
135
+ if (issuer) { const [kind, name] = issuer.includes('/') ? issuer.split('/') : ['ClusterIssuer', issuer]; a.k8s.tlsIssuer = { kind, name } }
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ if (!has(a, 'adminEmail')) {
142
+ const optional = a.target === 'local' || a.target === 'export'
143
+ const email = await p.text(QUESTIONS.adminEmail.question, { optional, validate: v => (EMAIL.test(v) ? null : 'An email address') })
144
+ if (email) a.adminEmail = email
145
+ }
146
+
147
+ // AI: nothing is pre-selected.
148
+ a.ai ||= {}
149
+ if (!has(a.ai, 'mode')) {
150
+ const choice = await p.choose(QUESTIONS['ai.mode'].question, AI_CHOICES)
151
+ if (choice === 'none') a.ai = { mode: 'none' }
152
+ else {
153
+ const providers = []
154
+ if (choice === 'cloud' || choice === 'both') {
155
+ do {
156
+ const kind = await p.choose('Which provider?', CLOUD.map(value => ({ value, label: value })))
157
+ providers.push(await provider(ctx, p, kind, providers.map(item => item.id)))
158
+ } while (await p.confirm('Add another cloud provider?', { default: false }))
159
+ }
160
+ if (choice === 'endpoint' || choice === 'both') providers.push(await provider(ctx, p, 'openai-compatible', providers.map(item => item.id)))
161
+ a.ai = { mode: 'providers', providers }
162
+ 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})` })))
163
+ }
164
+ }
165
+
166
+ a.sso ||= {}
167
+ if (!has(a.sso, 'enabled')) {
168
+ a.sso.enabled = await p.confirm('Single sign-on (bundled Keycloak: Entra ID, Okta, Google Workspace, SAML, LDAP)?', { default: false })
169
+ if (a.sso.enabled) {
170
+ a.sso.only = await p.confirm('Single sign-on only (no passwords, no guests)?', { default: false })
171
+ a.sso.adminConsole = (await p.confirm('Close Keycloak\'s admin console on the public address?', { default: false })) ? 'closed' : 'open'
172
+ }
173
+ }
174
+
175
+ a.backups ||= {}
176
+ if (!has(a.backups, 'to')) {
177
+ const where = await p.choose('Backups', kube
178
+ ? [{ value: 'default', label: 'Daily at 03:00 UTC to a volume in the namespace, keep 14' }, { value: 'off', label: 'Off' }]
179
+ : [{ 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' }],
180
+ { default: 'default' })
181
+ a.backups.to = where === 'dir' ? await p.text('Folder') : where === 's3' ? await p.text('S3 URL (s3://bucket/prefix)') : where
182
+ }
183
+
184
+ if (!has(a, 'size')) {
185
+ 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' })
186
+ }
187
+
188
+ a.mail ||= {}
189
+ if (!has(a.mail, 'urlFrom')) {
190
+ 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:/, '')) })
191
+ if (name) {
192
+ a.mail.urlFrom = `env:${name.replace(/^env:/, '')}`
193
+ a.mail.from = (await p.text('Send mail from (for example Slatebox <boards@example.com>)', { optional: true })) || null
194
+ } else {
195
+ 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`)
196
+ }
197
+ }
198
+ return a
199
+ }