slatebox 0.1.0 → 0.2.1

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.
@@ -3,10 +3,12 @@
3
3
  //
4
4
  // preflight -> image -> plan -> confirm -> secrets -> files -> start -> health
5
5
  // -> (rollback on failure) -> first account -> backup schedule -> record
6
- import { existsSync, readdirSync } from 'node:fs'
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { homedir } from 'node:os'
7
8
  import { join } from 'node:path'
8
9
  import { EXIT, InstallError } from '../errors.mjs'
9
- import { checkArch, checkCpu, DEFAULT_IMAGE, FALLBACK_CAPABILITIES, inspectImage, normalArch, pinImage, probeImage, refreshTag, resolveImage } from '../image.mjs'
10
+ import { firstAdmin, makeSetupLink, setupState, stillWaiting } from '../setup-link.mjs'
11
+ import { checkArch, checkCpu, DEFAULT_IMAGE, FALLBACK_CAPABILITIES, inspectImage, isPinnedImage, knownCapabilities, normalArch, pinImage, probeImage, refreshTag, resolveImage } from '../image.mjs'
10
12
  import { emptyPlan } from '../plan.mjs'
11
13
  import { installDir, recordText, writeRecord } from '../record.mjs'
12
14
  import { COMPOSE_FILE, hostPort, ports, renderCompose, SECRETS_FILE, SETTINGS_FILE } from '../render/compose.mjs'
@@ -15,6 +17,8 @@ import { shq } from '../runner.mjs'
15
17
  import { secretValues } from '../secret-values.mjs'
16
18
  import { envFileText, parseEnvFile } from '../secrets.mjs'
17
19
  import { firstFreePort, localHost, MARKER, parseKeyValues, portFree, remotePreflightScript, sshHost, which } from './hosts.mjs'
20
+ import { checkTeamAddress, ensureTeamAddress, TUNNEL_TOKEN } from './address.mjs'
21
+ import { credentialsPath } from '../cloud.mjs'
18
22
 
19
23
  const SLATEBOX = '/opt/slatebox/bin/slatebox'
20
24
  const KEPT_FILE = 'secrets.kept.env'
@@ -33,6 +37,7 @@ export const backupsDir = (host, answers) =>
33
37
  : answers.backups.to
34
38
 
35
39
  const KEK = 'SLATEBOX_KEY_ENCRYPTION_KEY'
40
+ const PENDING_TOKEN = 'pending-team-address-claim'
36
41
 
37
42
  /** Native Windows has no sh, crontab or file modes; Docker Desktop's WSL 2 integration is the way there. */
38
43
  export function refuseWindows(ctx) {
@@ -188,6 +193,7 @@ async function start(host, timeout) {
188
193
  async function health(ctx, host, answers) {
189
194
  const deep = await host.docker(['exec', answers.name, SLATEBOX, 'health', '--deep', '--wait', '60'], { timeout: 120_000 })
190
195
  if (deep.code !== 0) return { ok: false, why: lastLine(deep.stderr) || 'slatebox health failed' }
196
+ if (answers.address.team) return teamHealth(ctx, host, answers)
191
197
  // From outside, the way a browser asks.
192
198
  const url = `${answers.address.url}/readyz`
193
199
  let outside = false
@@ -206,6 +212,41 @@ async function health(ctx, host, answers) {
206
212
  return { ok: true }
207
213
  }
208
214
 
215
+ /** The tunnel's connections, from inside the container; null when the image cannot say. */
216
+ export async function tunnelState(host, name, wait = 0) {
217
+ const result = await host.docker(['exec', name, SLATEBOX, 'tunnel', '--json', ...(wait ? ['--wait', String(wait)] : [])], { timeout: (wait + 30) * 1000 })
218
+ try { return JSON.parse(lastLine(result.stdout)) } catch { return null }
219
+ }
220
+
221
+ /**
222
+ * A team address is healthy when the container's cloudflared holds connections and the address
223
+ * answers from here through Cloudflare. A tunnel that is slow to come up is a warning, not a
224
+ * rollback: Slatebox itself is healthy, and the tunnel keeps trying on its own.
225
+ */
226
+ async function teamHealth(ctx, host, answers) {
227
+ const tunnel = await tunnelState(host, answers.name, 60)
228
+ if (tunnel?.ready) ctx.out.step('tunnel', 'ok', `Secure tunnel connected (${tunnel.connections} connection${tunnel.connections === 1 ? '' : 's'})`)
229
+ // A refused tunnel stays down until it gets a new token: no point probing the address.
230
+ if (tunnel?.state === 'failed') {
231
+ return { ok: true, warning: `Slatebox is healthy on this computer, but Cloudflare refused its secure tunnel (a revoked token or a suspended address), so ${answers.address.url} does not reach it. See slatebox status and slatebox logs --service tunnel; slatebox address rotate gets a new token.` }
232
+ }
233
+
234
+ const url = `${answers.address.url}/readyz`
235
+ const attempts = ctx.teamHealthAttempts ?? 30
236
+ for (let attempt = 0; attempt < attempts; attempt++) {
237
+ try {
238
+ const response = await ctx.fetch(url, { signal: AbortSignal.timeout(8000) })
239
+ if (response.ok && (await response.json().catch(() => null))?.ok === true) {
240
+ ctx.out.step('address', 'ok', `${answers.address.url} answers`)
241
+ return { ok: true }
242
+ }
243
+ } catch { /* retry */ }
244
+ if (attempt < attempts - 1) await new Promise(resolve => setTimeout(resolve, ctx.teamHealthDelay ?? 2000))
245
+ }
246
+ const why = tunnel?.ready ? `${answers.address.url} does not answer from here yet` : 'the secure tunnel has not connected yet'
247
+ return { ok: true, warning: `Slatebox is healthy on this computer, but ${why}. It keeps trying by itself; check with slatebox status and slatebox logs --service tunnel.` }
248
+ }
249
+
209
250
  async function startAndCheck(ctx, host, answers) {
210
251
  const started = await start(host, ctx.healthTimeout)
211
252
  if (!started.ok) return started
@@ -214,14 +255,14 @@ async function startAndCheck(ctx, host, answers) {
214
255
 
215
256
  // ------------------------------------------------------------------ backups
216
257
 
217
- function backupScript(host, answers, facts) {
258
+ function backupScript(ctx, host, answers, facts) {
218
259
  const to = answers.backups.to
219
260
  const s3 = to.startsWith('s3://')
220
261
  const dir = backupsDir(host, answers)
221
262
  const bucket = `${to.replace(/\/$/, '')}/`
222
263
  return `#!/bin/sh
223
264
  # Written by the slatebox installer: one backup of the Slatebox "${answers.name}",
224
- # keeping the last ${answers.backups.keep}. Run by ${host.kind === 'ssh' ? 'a systemd timer or cron' : 'cron'}; safe to run by hand.
265
+ # keeping the last ${answers.backups.keep}. Run by ${host.kind === 'ssh' ? 'a systemd timer or cron' : usesLaunchd(ctx, host, answers) ? 'a launchd agent' : 'cron'}; safe to run by hand.
225
266
  set -u
226
267
  umask 077
227
268
  docker=${shq(facts.docker_path || 'docker')}
@@ -246,10 +287,113 @@ ls -1t "$dir"/slatebox-*.gz 2>/dev/null | tail -n +${answers.backups.keep + 1} |
246
287
 
247
288
  const MARK = name => `# slatebox-installer:${name}`
248
289
 
290
+ // Every scheduler command gets this long. On macOS `crontab -` can wait for a permission prompt
291
+ // that a terminal never shows; nothing the installer runs after "healthy" may hang on it.
292
+ export const SCHEDULER_TIMEOUT_MS = 30_000
293
+
294
+ /** Why a scheduler command failed, in words: never an empty reason. */
295
+ function schedulerFailure(command, result, ctx) {
296
+ if (result.code === 124) {
297
+ const mac = (ctx.platform || process.platform) === 'darwin'
298
+ return `${command} did not finish within ${(ctx.schedulerTimeout ?? SCHEDULER_TIMEOUT_MS) / 1000}s and was stopped${mac ? ' (macOS may be waiting for permission for your terminal to change the crontab)' : ''}`
299
+ }
300
+ if (result.code === 127) return `${command} is not installed on this computer`
301
+ const said = lastLine(result.stderr) || lastLine(result.stdout)
302
+ return `${command} exited with code ${result.code}${said ? `: ${said}` : ' without saying why'}`
303
+ }
304
+
305
+ const schedulerRun = (ctx, cmd, args, options = {}) => ctx.run(cmd, args, { ...options, timeout: ctx.schedulerTimeout ?? SCHEDULER_TIMEOUT_MS })
306
+
307
+ // ---- macOS: a launchd agent, not cron. It needs no permission prompt (cron's crontab does, and can
308
+ // block on it), and a run missed while the Mac sleeps happens when it wakes.
309
+ export const launchAgentLabel = name => `com.slatebox.${name}.backup`
310
+ export const launchAgentPath = (ctx, name) => join(ctx.env?.HOME || homedir(), 'Library', 'LaunchAgents', `${launchAgentLabel(name)}.plist`)
311
+
312
+ /** A cron schedule launchd can say (each field * or one number), as StartCalendarInterval keys; else null. */
313
+ export function launchdInterval(schedule) {
314
+ const fields = String(schedule || '').trim().split(/\s+/)
315
+ if (fields.length !== 5) return null
316
+ const keys = ['Minute', 'Hour', 'Day', 'Month', 'Weekday']
317
+ const out = {}
318
+ for (const [i, field] of fields.entries()) {
319
+ if (field === '*') continue
320
+ if (!/^\d{1,2}$/.test(field)) return null
321
+ out[keys[i]] = Number(field)
322
+ }
323
+ return 'Minute' in out ? out : null
324
+ }
325
+
326
+ const xml = text => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
327
+
328
+ export function launchAgentText(label, script, log, interval) {
329
+ const calendar = Object.entries(interval).map(([key, value]) => ` <key>${key}</key><integer>${value}</integer>`).join('\n')
330
+ return `<?xml version="1.0" encoding="UTF-8"?>
331
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
332
+ <!-- Written by the slatebox installer: the backup schedule of a Slatebox on this Mac. -->
333
+ <plist version="1.0">
334
+ <dict>
335
+ <key>Label</key><string>${xml(label)}</string>
336
+ <key>ProgramArguments</key>
337
+ <array><string>/bin/sh</string><string>${xml(script)}</string></array>
338
+ <key>StartCalendarInterval</key>
339
+ <dict>
340
+ ${calendar}
341
+ </dict>
342
+ <key>StandardOutPath</key><string>${xml(log)}</string>
343
+ <key>StandardErrorPath</key><string>${xml(log)}</string>
344
+ </dict>
345
+ </plist>
346
+ `
347
+ }
348
+
349
+ /** Backups on this Mac go to launchd when the schedule fits it (a daily one always does). */
350
+ export const usesLaunchd = (ctx, host, answers) =>
351
+ host.kind === 'local' && (ctx.platform || process.platform) === 'darwin' && Boolean(launchdInterval(answers.backups.schedule))
352
+
353
+ /** Take the installer's own cron line out, if there is one (an install from before launchd). Never writes a crontab otherwise. */
354
+ async function removeCronLine(ctx, name) {
355
+ const listed = await schedulerRun(ctx, 'crontab', ['-l'])
356
+ if (listed.code !== 0 || !listed.stdout.split('\n').some(line => line.endsWith(MARK(name)))) return false
357
+ const others = listed.stdout.split('\n').filter(line => !line.endsWith(MARK(name)))
358
+ while (others.length && others.at(-1) === '') others.pop()
359
+ const written = await schedulerRun(ctx, 'crontab', ['-'], { input: others.length ? `${others.join('\n')}\n` : '' })
360
+ if (written.code !== 0) throw new Error(schedulerFailure('crontab', written, ctx))
361
+ return true
362
+ }
363
+
364
+ async function scheduleLaunchd(ctx, host, answers) {
365
+ const label = launchAgentLabel(answers.name)
366
+ const path = launchAgentPath(ctx, answers.name)
367
+ const domain = `gui/${ctx.uid ?? process.getuid?.() ?? 501}`
368
+ const existing = existsSync(path) ? readFileSync(path, 'utf8') : null
369
+ if (answers.backups.to === 'off') {
370
+ if (existing !== null) {
371
+ await schedulerRun(ctx, 'launchctl', ['bootout', `${domain}/${label}`])
372
+ rmSync(path, { force: true })
373
+ }
374
+ const cron = await removeCronLine(ctx, answers.name).catch(() => false)
375
+ return existing !== null || cron ? 'removed' : 'unchanged'
376
+ }
377
+ const text = launchAgentText(label, join(host.dir, BACKUP_SCRIPT), join(host.dir, 'backup.log'), launchdInterval(answers.backups.schedule))
378
+ const cron = await removeCronLine(ctx, answers.name).catch(() => false)
379
+ if (existing === text && !cron) return 'unchanged'
380
+ mkdirSync(join(path, '..'), { recursive: true })
381
+ writeFileSync(path, text, { mode: 0o644 })
382
+ // Load it again so a changed schedule takes effect; "not loaded" from bootout is fine.
383
+ await schedulerRun(ctx, 'launchctl', ['bootout', `${domain}/${label}`])
384
+ const loaded = await schedulerRun(ctx, 'launchctl', ['bootstrap', domain, path])
385
+ if (loaded.code !== 0) throw new Error(schedulerFailure('launchctl bootstrap', loaded, ctx))
386
+ return `a launchd agent (${label}; a run missed while the Mac sleeps happens when it wakes)`
387
+ }
388
+
249
389
  async function scheduleBackups(ctx, host, answers, facts) {
250
390
  const script = join(host.dir, BACKUP_SCRIPT)
391
+ if (host.kind === 'local' && (ctx.platform || process.platform) === 'darwin' && (answers.backups.to === 'off' || usesLaunchd(ctx, host, answers))) {
392
+ return scheduleLaunchd(ctx, host, answers)
393
+ }
251
394
  if (host.kind === 'local') {
252
- const listed = await ctx.run('crontab', ['-l'])
395
+ const listed = await schedulerRun(ctx, 'crontab', ['-l'])
396
+ if (listed.code === 124) throw new Error(schedulerFailure('crontab -l', listed, ctx))
253
397
  const current = listed.code === 0 ? listed.stdout : ''
254
398
  const lines = current.split('\n')
255
399
  const ours = lines.filter(line => line.endsWith(MARK(answers.name)))
@@ -259,8 +403,8 @@ async function scheduleBackups(ctx, host, answers, facts) {
259
403
  const others = lines.filter(line => !line.endsWith(MARK(answers.name)))
260
404
  while (others.length && others.at(-1) === '') others.pop()
261
405
  const next = [...others, ...want].length ? `${[...others, ...want].join('\n')}\n` : ''
262
- const written = await ctx.run('crontab', ['-'], { input: next })
263
- if (written.code !== 0) throw new Error(`crontab: ${lastLine(written.stderr)}`)
406
+ const written = await schedulerRun(ctx, 'crontab', ['-'], { input: next })
407
+ if (written.code !== 0) throw new Error(schedulerFailure('crontab', written, ctx))
264
408
  return answers.backups.to === 'off' ? 'removed' : 'cron'
265
409
  }
266
410
  const unit = `slatebox-${answers.name}-backup`
@@ -308,14 +452,19 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
308
452
  : await existingState(host, answers)
309
453
  await checkPorts(host, answers, facts, existing)
310
454
  out.step('preflight', 'ok', `${host.where}: Docker ${facts.docker || facts.docker_server || '(to be installed)'}`)
455
+ // Docker first, then the name: nobody claims a name on a machine that cannot run Slatebox.
456
+ const team = answers.address.team ? await checkTeamAddress(ctx, answers) : null
311
457
 
312
458
  // The image. Before a yes, only what is already on the host is looked at:
313
459
  // nothing is pulled or loaded (an upgrade fetches its tag first, because
314
- // whether it is newer is the question the plan answers).
460
+ // whether it is newer is the question the plan answers). An image that is not
461
+ // here yet is planned with what it is known to accept (this release's pinned
462
+ // image: its own list), and nothing is refused on a guess: after the yes it is
463
+ // pulled and probed first, and only then checked, before any claim or file.
315
464
  const dockerMissing = host.kind === 'ssh' && facts.needsDocker
316
465
  const wanted = imageRef || answers.image || DEFAULT_IMAGE
317
466
  let image = { ref: wanted, pinned: wanted, id: null }
318
- let caps = FALLBACK_CAPABILITIES
467
+ let caps = archive ? FALLBACK_CAPABILITIES : knownCapabilities(wanted)
319
468
  let imageReady = false
320
469
  const ready = async () => {
321
470
  caps = await probeImage(host.docker, image.id)
@@ -335,13 +484,16 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
335
484
  const stored = { ...parseEnvFile(existing.files[KEPT_FILE] || ''), ...parseEnvFile(existing.files[SECRETS_FILE] || '') }
336
485
  let settings, composeText, settingsText, scriptText, secretsText, generated, kept
337
486
  const render = async () => {
338
- settings = settingsFor(answers, caps)
487
+ settings = settingsFor(answers, caps, { deferred: !imageReady })
339
488
  guardKey(ctx, host, answers, stored, settings.secrets, existing)
340
489
  composeText = renderCompose(answers, { image: image.pinned, hostGateway: settings.hostGateway })
341
490
  settingsText = envFileText(settings.env, `Settings for the Slatebox "${answers.name}", written by the slatebox installer. No secrets.`)
342
- scriptText = answers.backups.to === 'off' ? null : backupScript(host, answers, facts)
343
- // The key encryption key is made once and then kept; referenced keys are read now.
344
- const secrets = await secretValues(ctx, settings.secrets, stored)
491
+ scriptText = answers.backups.to === 'off' ? null : backupScript(ctx, host, answers, facts)
492
+ // The key encryption key is made once and then kept; referenced keys are read now. Before
493
+ // the plan is approved, a team address that is still to be claimed has no token: the plan
494
+ // shows a stand-in, and nothing is written until the claim has brought the real one.
495
+ const pending = team && !ctx.tunnelToken && !stored[TUNNEL_TOKEN]
496
+ const secrets = await secretValues(pending ? { ...ctx, tunnelToken: PENDING_TOKEN } : ctx, settings.secrets, stored)
345
497
  generated = secrets.generated
346
498
  kept = Object.fromEntries(Object.entries(stored).filter(([name]) => !(name in secrets.values) && name === KEK))
347
499
  secretsText = envFileText(secrets.values, `Secrets for the Slatebox "${answers.name}". Keep a copy of SLATEBOX_KEY_ENCRYPTION_KEY with your backups.`)
@@ -378,7 +530,8 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
378
530
  }
379
531
  if (!imageReady) {
380
532
  plan.commands.push(archive ? `docker load < ${archive} (on ${host.where}, after you confirm)` : `docker pull ${wanted} (on ${host.where}, after you confirm)`)
381
- plan.notes.push(`${archive ? `The image is loaded from ${archive}` : `${wanted} is not on ${host.where} yet: it is pulled`} after you confirm, and checked before anything starts. Until then the plan assumes the current image's settings.`)
533
+ plan.notes.push(`${archive ? `The image is loaded from ${archive}` : `${wanted} is not on ${host.where} yet: it is downloaded`} after you confirm, and checked before anything is claimed, written or started. ${isPinnedImage(wanted) && !archive ? 'The plan uses the settings this release\'s image accepts.' : 'Until then the plan assumes the current image\'s settings.'}`)
534
+ if (settings.unchecked.length) plan.notes.push(`Checked once the image is here: that it supports ${settings.unchecked.join(', ')}.`)
382
535
  }
383
536
  if (!nothing) {
384
537
  plan.files.push(
@@ -392,25 +545,40 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
392
545
  plan.warnings.push(`The container is not running, so no backup can be taken before the ${imageChanged ? 'upgrade' : 'change'}: if it fails there is no copy to roll the data back to. Take one yourself first if you have an older backup to restore from (slatebox restore <file>).`)
393
546
  }
394
547
  plan.commands.push(`docker compose -p ${answers.name} up -d --wait`, `docker exec ${answers.name} slatebox health --deep`)
395
- if (scriptText) plan.commands.push(host.kind === 'local' ? `crontab: ${answers.backups.schedule} ${join(host.dir, BACKUP_SCRIPT)}` : `systemd timer (or /etc/cron.d) slatebox-${answers.name}-backup`)
548
+ if (scriptText) {
549
+ if (usesLaunchd(ctx, host, answers)) {
550
+ plan.files.push({ path: launchAgentPath(ctx, answers.name), note: `the launchd agent that runs ${BACKUP_SCRIPT} (${answers.backups.schedule})` })
551
+ plan.commands.push(`launchctl bootstrap gui/<you> ${launchAgentPath(ctx, answers.name)}`)
552
+ } else plan.commands.push(host.kind === 'local' ? `crontab: ${answers.backups.schedule} ${join(host.dir, BACKUP_SCRIPT)}` : `systemd timer (or /etc/cron.d) slatebox-${answers.name}-backup`)
553
+ }
396
554
  if (answers.address.port === null) plan.notes.push(`HTTPS: Slatebox gets and renews a certificate for ${new URL(answers.address.url).hostname} itself; point its DNS here and open ports 80 and 443.`)
397
555
  else if (answers.address.url.startsWith('http:') && host.kind === 'ssh') plan.warnings.push('Plain HTTP: anyone on the network path can read what people type. Give --domain for HTTPS.')
398
556
  if (host.kind === 'local' && answers.address.port !== null && ['0.0.0.0', '::'].includes(answers.address.listen)) {
399
557
  plan.warnings.push(`Published on every network interface (--listen ${answers.address.listen}) over plain HTTP: anyone who can reach this computer can open the first-account page, and Docker's port rules bypass firewalls such as ufw.`)
400
558
  }
401
559
  if (host.kind === 'local' && scriptText) {
402
- if ((ctx.platform || process.platform) === 'darwin') plan.notes.push('Backups run from cron, which skips a run while this computer sleeps; `slatebox status` says when the last backup is late.')
560
+ if (usesLaunchd(ctx, host, answers)) plan.notes.push('Backups run from a launchd agent (no permission prompt); a run missed while this Mac sleeps happens when it wakes. `slatebox status` says when the last backup is late.')
561
+ else if ((ctx.platform || process.platform) === 'darwin') plan.notes.push('Backups run from cron, which skips a run while this computer sleeps; `slatebox status` says when the last backup is late.')
403
562
  if (ctx.env.WSL_DISTRO_NAME) plan.warnings.push('WSL usually has no cron daemon running: start it (sudo service cron start) or scheduled backups will not run.')
404
563
  }
405
564
  if (host.kind === 'ssh' && (facts.ufw === 'active' || facts.firewalld === 'running')) {
406
565
  plan.warnings.push(`A firewall (${facts.ufw === 'active' ? 'ufw' : 'firewalld'}) is on. Allow ${ports(answers).map(hostPort).join(', ')}/tcp yourself; the installer does not change firewall rules.`)
407
566
  }
408
567
  }
568
+ if (team) {
569
+ if (team.claim) {
570
+ plan.notes.unshift(`After you confirm, you sign in to Slatebox in your browser to claim ${team.host} for your account. Slatebox Cloud then sets up its secure tunnel and sends this install the tunnel token.`)
571
+ plan.files.push({ path: credentialsPath(ctx.home, answers.name), note: 'the team-address credential (mode 0600); it stays on this computer' })
572
+ } else if (!stored[TUNNEL_TOKEN] && !nothing) {
573
+ plan.notes.unshift(`The tunnel token for ${team.host} is fetched again from Slatebox Cloud with this computer's install credential.`)
574
+ }
575
+ }
409
576
  if (nothing) plan.notes.push('The running install already matches these answers.')
410
577
  ctx.emitPlan(plan)
411
578
  if (planOnly) return { planned: true, plan }
412
579
  if (nothing) {
413
580
  await saveRecord(ctx, host, answers, image, settings, caps, record, true)
581
+ if (caps.commands.includes('setup-link')) await stillWaiting(ctx, args => host.docker(['exec', answers.name, SLATEBOX, ...args]))
414
582
  return done(ctx, host, answers, image, { nothing: true })
415
583
  }
416
584
  await ctx.confirm(plan)
@@ -422,6 +590,8 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
422
590
  if (installed.code !== 0 || check.code !== 0) throw new InstallError(EXIT.PRECONDITION, `Docker could not be installed or started on ${host.where}: ${lastLine(installed.stderr || check.stderr)}`)
423
591
  out.step('docker', 'ok', `Docker ${check.stdout.trim()} on ${host.where}`)
424
592
  }
593
+ // The image first: nobody claims a name, and nothing is written, for an image that cannot be
594
+ // had (offline) or that does not support what was asked for (render() refuses it now).
425
595
  if (!imageReady) {
426
596
  image = await resolveImage(host.docker, { ref: imageRef || answers.image, archive, loadArchive: host.loadArchive, step: out.step.bind(out) })
427
597
  await ready()
@@ -429,9 +599,15 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
429
599
  imageChanged = changedFrom()
430
600
  if (existing.container.exists && !imageChanged && previousImage === image.id && !changes.some(change => !change.startsWith('the image '))) {
431
601
  await saveRecord(ctx, host, answers, image, settings, caps, record, true)
602
+ if (caps.commands.includes('setup-link')) await stillWaiting(ctx, args => host.docker(['exec', answers.name, SLATEBOX, ...args]))
432
603
  return done(ctx, host, answers, image, { nothing: true })
433
604
  }
434
605
  }
606
+ if (team && !ctx.tunnelToken && !stored[TUNNEL_TOKEN]) {
607
+ // The claim is kept if anything after this fails: the next run reuses it.
608
+ await ensureTeamAddress(ctx, answers, team, stored)
609
+ await render()
610
+ }
435
611
 
436
612
  // Before an upgrade, a backup the rollback can restore.
437
613
  let preUpgrade = null
@@ -443,6 +619,7 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
443
619
  out.step('backup', 'ok', `Backed up to ${preUpgrade}`)
444
620
  }
445
621
 
622
+ if (secretsText.includes(PENDING_TOKEN)) throw new Error('internal: the team address has no tunnel token yet')
446
623
  const previous = { ...existing.files }
447
624
  out.step('files', 'start', `Writing ${host.dir}`)
448
625
  await host.writeFile(join(host.dir, MARKER), `${answers.name}\n`, 0o600)
@@ -457,9 +634,15 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
457
634
  const result = await startAndCheck(ctx, host, answers)
458
635
  if (!result.ok) await rollback(ctx, host, answers, { fresh, previous, preUpgrade, why: result.why })
459
636
  if (result.warning) out.step('health', 'warn', result.warning)
460
- out.step('start', 'ok', `Slatebox is healthy at ${answers.address.url}`)
461
-
462
- if (fresh) await firstAccount(ctx, host, answers, caps)
637
+ out.step('start', 'ok', answers.address.team ? `Slatebox is healthy on ${host.where}` : `Slatebox is healthy at ${answers.address.url}`)
638
+
639
+ // The first admin comes from the image's one-time setup link; an image without one keeps the old advice.
640
+ const inImage = args => host.docker(['exec', answers.name, SLATEBOX, ...args])
641
+ const linked = caps.commands.includes('setup-link') && await firstAdmin(ctx, inImage)
642
+ if (!linked && fresh) await firstAccount(ctx, host, answers, caps)
643
+ // The address and the setup link are what the person waits for: they are printed now, before
644
+ // the backup schedule, which only ever warns (and gives up after a timeout) if it cannot be set.
645
+ ctx.announce?.(done(ctx, host, answers, image, { generated, fresh }))
463
646
  if (scriptText || previous[BACKUP_SCRIPT]) {
464
647
  try {
465
648
  const how = await scheduleBackups(ctx, host, answers, facts)
@@ -555,6 +738,7 @@ function done(ctx, host, answers, image, { nothing = false, generated = [], fres
555
738
  address: answers.address.url, name: answers.name, target: answers.target, version: image.labels?.['org.opencontainers.image.version'] || null,
556
739
  imageDigest: image.pinned, installRecord: ctx.recordFile, secretsFile, nothingToChange: nothing,
557
740
  keyGenerated: generated.includes('SLATEBOX_KEY_ENCRYPTION_KEY'), fresh,
741
+ ...(answers.address.team ? { teamAddress: answers.address.url, localAddress: `http://localhost:${answers.address.port}` } : {}),
558
742
  }
559
743
  }
560
744
 
@@ -591,6 +775,8 @@ export async function statusDocker(ctx, record) {
591
775
  // File names carry the UTC time they were taken, so the newest sorts last.
592
776
  lastBackup = existsSync(dir) ? readdirSync(dir).filter(file => /^slatebox-\d{8}-\d{6}\.gz$/.test(file)).sort().pop() || null : null
593
777
  }
778
+ const tunnel = record.address?.team && state?.Running ? await tunnelState(host, record.name) : null
779
+ const setup = state?.Running ? await setupState(args => host.docker(['exec', record.name, SLATEBOX, ...args])) : null
594
780
  const age = backupLate(record, lastBackup)
595
781
  if (age?.late) ctx.out.warn(`The last backup is ${age.ageHours} hours old, older than the schedule "${record.backups.schedule}" allows. See ${join(host.dir, 'backup.log')}${host.kind === 'ssh' ? ` on ${host.where}` : ''}.`)
596
782
  return {
@@ -600,6 +786,8 @@ export async function statusDocker(ctx, record) {
600
786
  ai: record.ai.mode === 'none' ? 'off' : record.ai.providers.map(provider => provider.id).join(', '),
601
787
  sso: record.sso.enabled ? (record.sso.only ? 'on (only)' : 'on') : 'off',
602
788
  lastBackup, backupLate: age ? age.late : null,
789
+ ...(record.address?.team ? { tunnel } : {}),
790
+ setup: setup ? (setup.setUp ? 'done' : 'waiting for the first admin') : null,
603
791
  }
604
792
  } finally {
605
793
  await host.close?.()
@@ -675,11 +863,54 @@ export function uninstallDocker(ctx, record, { deleteData }) {
675
863
  })
676
864
  }
677
865
 
866
+ // The services' log lines carry their name: [app], [relay], [mongo], [proxy], [tunnel], [sso], [slatebox].
867
+ export const LOG_SERVICES = ['app', 'relay', 'mongo', 'proxy', 'tunnel', 'sso', 'slatebox']
868
+
869
+ /** docker logs for the install, optionally only one service's lines, optionally following. */
870
+ export function logsDocker(ctx, record, { follow = false, service, since } = {}) {
871
+ return withHost(ctx, record, async host => {
872
+ const args = ['logs', ...(since ? ['--since', since] : []), ...(follow ? ['--follow'] : ['--tail', '500']), record.name]
873
+ const keep = line => !service || line.startsWith(`[${service}] `) || (service === 'sso' && line.startsWith('[sso-setup] '))
874
+ const write = text => {
875
+ for (const line of text.split('\n')) if (line && keep(line)) ctx.stdout.write(`${ctx.redactor.redact(line)}\n`)
876
+ }
877
+ if (follow) {
878
+ if (host.kind !== 'local') throw new InstallError(EXIT.USAGE, `Following logs on ${host.where}: ssh ${host.where} ${host.sudo || ''}docker logs -f ${record.name}`)
879
+ // Streamed as it comes, each line through the redactor, until Ctrl-C.
880
+ const { spawn } = await import('node:child_process')
881
+ return new Promise(resolve => {
882
+ const child = (ctx.spawn || spawn)('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] })
883
+ let rest = ''
884
+ const onData = chunk => {
885
+ const text = rest + chunk
886
+ const cut = text.lastIndexOf('\n')
887
+ rest = cut < 0 ? text : text.slice(cut + 1)
888
+ if (cut >= 0) write(text.slice(0, cut))
889
+ }
890
+ child.stdout.on('data', onData)
891
+ child.stderr.on('data', onData)
892
+ child.on('error', () => resolve({ lines: false }))
893
+ child.on('close', () => { if (rest) write(rest); resolve({ lines: true }) })
894
+ })
895
+ }
896
+ const result = await host.docker(args, { timeout: 120_000 })
897
+ if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `docker logs failed: ${lastLine(result.stderr)}`)
898
+ // docker logs puts the container's stdout and stderr on its own two streams.
899
+ write(`${result.stdout}${result.stderr}`)
900
+ return { lines: true }
901
+ })
902
+ }
903
+
678
904
  /** Run a script inside the container with node, the script on standard input (never in the arguments). */
679
905
  export function execNode(ctx, record, script, args = []) {
680
906
  return withHost(ctx, record, host => host.docker(['exec', '-i', record.name, 'node', '--input-type=module', '-', ...args], { input: script, timeout: 120_000 }))
681
907
  }
682
908
 
909
+ /** A fresh one-time setup link from the install's container (setup-link.mjs makeSetupLink). */
910
+ export function setupLinkDocker(ctx, record) {
911
+ return withHost(ctx, record, host => makeSetupLink(ctx, args => host.docker(['exec', record.name, SLATEBOX, ...args])))
912
+ }
913
+
683
914
  export function readSecretDocker(ctx, record, name) {
684
915
  return withHost(ctx, record, async host => parseEnvFile(await host.readFile(join(host.dir, SECRETS_FILE)) || '')[name])
685
916
  }
@@ -5,7 +5,7 @@
5
5
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
6
6
  import { dirname, join, resolve } from 'node:path'
7
7
  import { EXIT, InstallError } from '../errors.mjs'
8
- import { DEFAULT_IMAGE, FALLBACK_CAPABILITIES, probeImage } from '../image.mjs'
8
+ import { DEFAULT_IMAGE, FALLBACK_CAPABILITIES, isPinnedImage, PINNED_CAPABILITIES, probeImage } from '../image.mjs'
9
9
  import { emptyPlan } from '../plan.mjs'
10
10
  import { renderCompose, SECRETS_FILE, SETTINGS_FILE } from '../render/compose.mjs'
11
11
  import { renderHelmChart } from '../render/helm.mjs'
@@ -27,6 +27,8 @@ export async function exportFiles(ctx, answers, { planOnly = false } = {}) {
27
27
  let caps = FALLBACK_CAPABILITIES
28
28
  if (image.local) {
29
29
  try { caps = await probeImage((args, o) => ctx.run('docker', args, o), image.id) } catch { warnings.push('The image did not list its settings; the current image\'s settings were assumed.') }
30
+ } else if (isPinnedImage(image.ref)) {
31
+ caps = PINNED_CAPABILITIES
30
32
  } else {
31
33
  warnings.push(`${image.ref} is not on this computer, so the files assume the current image's settings and are not pinned to a digest.`)
32
34
  }
@@ -6,12 +6,14 @@ import { mkdirSync, rmSync } from 'node:fs'
6
6
  import { join } from 'node:path'
7
7
  import { EXIT, InstallError } from '../errors.mjs'
8
8
  import { collect, resolveAnswers } from '../answers.mjs'
9
- import { checkArch, DEFAULT_IMAGE, FALLBACK_CAPABILITIES, hasRegistry, isTag, probeImage } from '../image.mjs'
9
+ import { checkArch, DEFAULT_IMAGE, FALLBACK_CAPABILITIES, hasRegistry, isPinnedImage, isTag, PINNED_CAPABILITIES, probeImage } from '../image.mjs'
10
10
  import { emptyPlan } from '../plan.mjs'
11
11
  import { installDir, recordText, writeRecord } from '../record.mjs'
12
12
  import { MANAGER, names, renderK8s, renderSecret } from '../render/k8s.mjs'
13
13
  import { settingsFor } from '../render/settings.mjs'
14
14
  import { secretValues } from '../secret-values.mjs'
15
+ import { firstAdmin, makeSetupLink, setupState, stillWaiting } from '../setup-link.mjs'
16
+ import { checkTeamAddress, ensureTeamAddress, TUNNEL_TOKEN } from './address.mjs'
15
17
  import { stringifyAll } from '../yaml.mjs'
16
18
 
17
19
  const SLATEBOX = '/opt/slatebox/bin/slatebox'
@@ -124,6 +126,8 @@ async function capabilities(ctx, image, warnings) {
124
126
  if (image.local) {
125
127
  try { return await probeImage((args, o) => ctx.run('docker', args, o), image.id || image.ref) } catch { /* fall through */ }
126
128
  }
129
+ // This release's own image: what it accepts is known without pulling it here (the cluster pulls it).
130
+ if (isPinnedImage(image.ref)) return PINNED_CAPABILITIES
127
131
  warnings.push(`The image was not on this computer, so its settings could not be read from it; the installer assumed the settings of the current image (pull ${image.ref} first to check).`)
128
132
  return FALLBACK_CAPABILITIES
129
133
  }
@@ -150,6 +154,16 @@ async function rollout(ctx, k, answers) {
150
154
  if (status.code !== 0) return { ok: false, why: lastLine(status.stderr) || 'rollout did not finish' }
151
155
  const deep = await k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'health', '--deep', '--wait', '60'], { timeout: 120_000 })
152
156
  if (deep.code !== 0) return { ok: false, why: lastLine(deep.stderr) || 'slatebox health failed' }
157
+ if (answers.address.team) {
158
+ for (let attempt = 0; attempt < (ctx.teamHealthAttempts ?? 30); attempt++) {
159
+ try {
160
+ const response = await ctx.fetch(`${answers.address.url}/readyz`, { signal: AbortSignal.timeout(8000) })
161
+ if (response.ok) return { ok: true }
162
+ } catch { /* retry */ }
163
+ await new Promise(resolve => setTimeout(resolve, ctx.teamHealthDelay ?? 2000))
164
+ }
165
+ return { ok: true, warning: `Slatebox is healthy in the cluster, but ${answers.address.url} does not answer from here yet: the secure tunnel keeps trying by itself (kubectl logs ${n.pod} -c slatebox | grep tunnel).` }
166
+ }
153
167
  if (answers.k8s.route !== 'none') {
154
168
  try {
155
169
  const response = await ctx.fetch(`${answers.address.url}/readyz`, { signal: AbortSignal.timeout(8000) })
@@ -172,6 +186,7 @@ export async function applyK8s(ctx, answers, { record, planOnly = false, imageRe
172
186
  out.step('preflight', 'start', `Checking kube context "${context}"`)
173
187
  const facts = await preflight(ctx, k, answers, context)
174
188
  out.step('preflight', 'ok', `Context "${context}", namespace ${answers.k8s.namespace}${facts.nsExists ? '' : ' (new)'}`)
189
+ const team = answers.address.team ? await checkTeamAddress(ctx, answers) : null
175
190
 
176
191
  const warnings = []
177
192
  const image = await clusterImage(ctx, imageRef || answers.image, { refresh })
@@ -187,7 +202,22 @@ export async function applyK8s(ctx, answers, { record, planOnly = false, imageRe
187
202
  throw new InstallError(EXIT.PRECONDITION, `Slatebox "${answers.name}" already has ${previous ? 'a StatefulSet' : 'a data volume'} in ${answers.k8s.namespace}, but its Secret ${names(answers).secret} holds no SLATEBOX_KEY_ENCRYPTION_KEY. A new key would make every AI and call key people saved unreadable. Nothing was changed. Put the Secret back from your backup, or add --new-encryption-key to start over with a new key.`, { needs: 'encryption-key' })
188
203
  }
189
204
  }
190
- const { values, generated } = await secretValues(ctx, settings.secrets, stored)
205
+ // The Secret is part of the server-side diff, so a team address still to be claimed is claimed
206
+ // (after its own yes) before the plan; a plan-only run shows a stand-in and claims nothing.
207
+ let secretCtx = ctx
208
+ if (team && !stored[TUNNEL_TOKEN]) {
209
+ if (planOnly) secretCtx = { ...ctx, tunnelToken: 'pending-team-address-claim' }
210
+ else {
211
+ if (team.claim) {
212
+ const claimPlan = emptyPlan({ action: 'claim', target: 'k8s', name: answers.name, where: 'Slatebox Cloud', address: answers.address.url,
213
+ notes: [`You sign in to Slatebox in your browser to claim ${team.host}. Its tunnel token goes into the Secret ${names(answers).secret}; the install credential stays on this computer (mode 0600).`] })
214
+ ctx.emitPlan(claimPlan)
215
+ await ctx.confirm(claimPlan)
216
+ }
217
+ await ensureTeamAddress(ctx, answers, team, stored)
218
+ }
219
+ }
220
+ const { values, generated } = await secretValues(secretCtx, settings.secrets, stored)
191
221
  const secretsHash = createHash('sha256').update(JSON.stringify(values)).digest('hex')
192
222
  const imageChanged = Boolean(previous && previous !== image.pinned)
193
223
 
@@ -222,6 +252,7 @@ export async function applyK8s(ctx, answers, { record, planOnly = false, imageRe
222
252
  if (nothing) {
223
253
  nextRecord.lastHealthy = new Date().toISOString()
224
254
  ctx.recordFile = writeRecord(ctx.home, nextRecord)
255
+ await stillWaiting(ctx, args => k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
225
256
  return {
226
257
  address: answers.address.url, name: answers.name, target: 'k8s', version: null, imageDigest: image.pinned,
227
258
  installRecord: ctx.recordFile, secretsFile: nextRecord.secretsLocation, nothingToChange: true, keyGenerated: false, fresh: false,
@@ -272,7 +303,9 @@ export async function applyK8s(ctx, answers, { record, planOnly = false, imageRe
272
303
  }
273
304
  if (result.warning) out.step('route', 'warn', result.warning)
274
305
  out.step('start', 'ok', `Slatebox is ready${answers.k8s.route === 'none' ? ' (port-forward to reach it)' : ` at ${answers.address.url}`}`)
275
- if (!previous) {
306
+ // The first admin comes from the image's one-time setup link; an image without one keeps the old advice.
307
+ const linked = await firstAdmin(ctx, args => k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
308
+ if (!linked && !previous) {
276
309
  out.say(`\n${answers.adminEmail ? `Open ${answers.address.url} and create the first account with ${answers.adminEmail}.` : `Open ${answers.address.url} and create the first account.`}`)
277
310
  }
278
311
  nextRecord.lastHealthy = new Date().toISOString()
@@ -313,12 +346,14 @@ export async function statusK8s(ctx, record) {
313
346
  const ready = info?.status?.containerStatuses?.find(item => item.name === 'slatebox')?.ready
314
347
  const version = ready ? await k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'version']) : null
315
348
  const backups = ready && record.backups.to !== 'off' ? await k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'backups', '--', 'sh', '-c', 'ls -1t /backups | head -1']) : null
349
+ const setup = ready ? await setupState(args => k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args])) : null
316
350
  return {
317
351
  name: record.name, target: 'k8s', where: `context ${record.k8s.context}, namespace ${record.k8s.namespace}`, address: record.address.url,
318
352
  running: Boolean(info), health: ready ? 'healthy' : info ? info.status.phase : 'missing',
319
353
  version: version?.code === 0 ? JSON.parse(version.stdout) : null, imageDigest: record.imageDigest,
320
354
  ai: record.ai.mode === 'none' ? 'off' : record.ai.providers.map(provider => provider.id).join(', '),
321
355
  sso: record.sso.enabled ? 'on' : 'off', lastBackup: backups?.stdout.trim() || null,
356
+ setup: setup ? (setup.setUp ? 'done' : 'waiting for the first admin') : null,
322
357
  }
323
358
  }
324
359
 
@@ -360,6 +395,12 @@ export function execNodeK8s(ctx, record, script, args = []) {
360
395
  return k(['exec', '-i', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', 'node', '--input-type=module', '-', ...args], { input: script, timeout: 120_000 })
361
396
  }
362
397
 
398
+ /** A fresh one-time setup link from the install's pod (setup-link.mjs makeSetupLink). */
399
+ export function setupLinkK8s(ctx, record) {
400
+ const k = kube(ctx, record.k8s.context)
401
+ return makeSetupLink(ctx, args => k(['exec', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
402
+ }
403
+
363
404
  export async function readSecretK8s(ctx, record, name) {
364
405
  const k = kube(ctx, record.k8s.context)
365
406
  return (await existingSecret(k, record))[name]