slatebox 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,281 @@
1
+ // A team address, https://<name>.slatebox.team, for any install target: check the name, sign in,
2
+ // claim it on Slatebox Cloud, keep the install credential on this computer, and hand the tunnel
3
+ // connector token to the target's secrets. The container's own cloudflared then connects out to
4
+ // Cloudflare: no DNS, no open ports, no certificates.
5
+ //
6
+ // Every function here is safe to run again: a claim retried with the same client key is the same
7
+ // claim, and an install that already has its token needs no network at all.
8
+ import { createHash } from 'node:crypto'
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+ import {
12
+ CloudError, cloudBase, cloudClient, credentialsPath, deviceLabel, newClientKey, readCredentials, removeCredentials,
13
+ signIn, TEAM_ADDRESS_RULE, teamAddressProblem, teamHost, writeCredentials,
14
+ } from '../cloud.mjs'
15
+ import { EXIT, InstallError } from '../errors.mjs'
16
+ import { installDir } from '../record.mjs'
17
+
18
+ export const TUNNEL_TOKEN = 'SLATEBOX_TUNNEL_TOKEN'
19
+ const PENDING_FILE = 'claim.json'
20
+ const E2E_PREFIX = 'e2e-'
21
+
22
+ function client(ctx, base) {
23
+ ctx.cloud ??= cloudClient(ctx, base || cloudBase(ctx))
24
+ return ctx.cloud
25
+ }
26
+
27
+ /** A team address that cannot be had: the same answer for taken, reserved and blocked names. */
28
+ function unavailable(name, suggestions = []) {
29
+ const free = suggestions?.length ? `\n Free right now: ${suggestions.join(', ')}` : ''
30
+ return new InstallError(EXIT.NEEDS_INPUT, `${teamHost(name)} isn't available.${free}\n Choose another: --team-address <name>`, { id: 'address-unavailable', field: 'address.team', suggestions: suggestions || [] })
31
+ }
32
+
33
+ function cloudFailure(error, name) {
34
+ if (error instanceof InstallError) return error
35
+ if (!(error instanceof CloudError)) return error
36
+ switch (error.code) {
37
+ case 'unavailable': return unavailable(name, error.suggestions)
38
+ case 'invalid_name': return new InstallError(EXIT.USAGE, `"${name}" is not a team address: ${TEAM_ADDRESS_RULE}.`, { field: 'address.team' })
39
+ case 'limit_reached': return new InstallError(EXIT.PRECONDITION, `Your Slatebox account already has the most team addresses it may hold, or claimed too many today. ${error.message} Release one you no longer use (slatebox address release on that install), or use your own domain: --domain boards.example.com`, { id: 'address-limit' })
40
+ case 'rate_limited': return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud asks you to wait${error.retryAfter ? ` ${error.retryAfter} seconds` : ''} before trying again. Nothing was changed.`, { id: 'rate-limited', retryAfter: error.retryAfter })
41
+ case 'paused': return new InstallError(EXIT.PRECONDITION, 'New team addresses are paused on Slatebox Cloud right now. Nothing was changed. Try again later, or use --domain or --local.', { id: 'address-paused' })
42
+ case 'suspended': return new InstallError(EXIT.PRECONDITION, `${teamHost(name)} is suspended: ${error.notice || error.message}. Your Slatebox keeps running on this computer; contact abuse@slatebox.com about the address.`, { id: 'address-suspended' })
43
+ case 'upstream_unavailable': return new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud could not set up the secure tunnel just now (Cloudflare did not answer). Nothing was left half made; run the same command again in a minute.', { id: 'upstream-unavailable' })
44
+ case 'not_found': return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud no longer knows the team address of this install (${teamHost(name)}). It may have been released. Run slatebox install --team-address <name> to claim one again.`, { id: 'address-gone' })
45
+ default: return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud answered: ${error.message} (${error.code}, HTTP ${error.status}).`, { id: 'cloud-error', code: error.code })
46
+ }
47
+ }
48
+
49
+ // ------------------------------------------------------------------ check
50
+
51
+ /**
52
+ * Before the plan: is the name ours already, or free to claim? Never signs in.
53
+ * @returns {Promise<{name: string, host: string, creds: object|null, claim: boolean}>}
54
+ */
55
+ export async function checkTeamAddress(ctx, answers) {
56
+ const name = answers.address.team
57
+ const problem = teamAddressProblem(name)
58
+ if (problem) throw new InstallError(EXIT.USAGE, `"${name}" is not a team address: ${problem}.`, { field: 'address.team' })
59
+ const creds = readCredentials(ctx.home, answers.name)
60
+ if (creds && creds.name !== name) {
61
+ throw new InstallError(EXIT.USAGE, `"${answers.name}" already has the team address ${teamHost(creds.name)}. To move it: slatebox rename ${name}${answers.name === 'slatebox' ? '' : ` --name ${answers.name}`}. For a second Slatebox, give it its own --name.`, { field: 'address.team' })
62
+ }
63
+ if (creds) {
64
+ ctx.redactor.add(creds.installCredential)
65
+ return { name, host: teamHost(name), creds, claim: false }
66
+ }
67
+ const cloud = client(ctx)
68
+ // e2e-<anything> belongs to the end-to-end test's accounts, which the Cloud knows only after
69
+ // the sign-in: a signed-out check always says no, so the claim itself is the check.
70
+ if (name.startsWith(E2E_PREFIX)) return { name, host: teamHost(name), creds: null, claim: true }
71
+ ctx.out.step('address', 'start', `Checking ${teamHost(name)}`)
72
+ let answer
73
+ try { answer = await cloud.availability(name) } catch (error) { throw cloudFailure(error, name) }
74
+ if (!answer?.available) throw unavailable(name, answer?.suggestions)
75
+ ctx.out.step('address', 'ok', `${teamHost(name)} is available`)
76
+ return { name, host: teamHost(name), creds: null, claim: true }
77
+ }
78
+
79
+ /** For the interview: the name if it is free, or the suggestions. Never signs in. */
80
+ export async function availability(ctx, name) {
81
+ try {
82
+ const answer = await client(ctx).availability(name)
83
+ return { available: Boolean(answer?.available), suggestions: answer?.suggestions || [] }
84
+ } catch (error) {
85
+ if (error instanceof CloudError && error.code === 'invalid_name') return { available: false, suggestions: [], invalid: true }
86
+ throw cloudFailure(error, name)
87
+ }
88
+ }
89
+
90
+ // ------------------------------------------------------------------ claim and attach
91
+
92
+ function pendingPath(ctx, install) { return join(installDir(ctx.home, install), PENDING_FILE) }
93
+
94
+ /** One client key per install and name, kept until the claim is done, so a retry is the same claim. */
95
+ function pendingKey(ctx, install, name) {
96
+ const path = pendingPath(ctx, install)
97
+ if (existsSync(path)) {
98
+ try {
99
+ const pending = JSON.parse(readFileSync(path, 'utf8'))
100
+ if (pending.name === name && pending.clientKey) return pending.clientKey
101
+ } catch { /* write a new one */ }
102
+ }
103
+ const clientKey = newClientKey()
104
+ mkdirSync(installDir(ctx.home, install), { recursive: true, mode: 0o700 })
105
+ writeFileSync(path, `${JSON.stringify({ name, clientKey })}\n`, { mode: 0o600 })
106
+ chmodSync(path, 0o600)
107
+ return clientKey
108
+ }
109
+
110
+ async function connectorToken(ctx, cloud, creds, { rotate = false } = {}) {
111
+ const answer = await cloud.connectorToken(creds.installCredential, { rotate })
112
+ if (!answer?.connectorToken) throw new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud sent no tunnel token.')
113
+ ctx.redactor.add(answer.connectorToken)
114
+ return answer.connectorToken
115
+ }
116
+
117
+ /**
118
+ * After the plan was approved: the tunnel token for this install. Claims the name (with a
119
+ * sign-in) if this computer holds no credential for it yet; otherwise uses the token already in
120
+ * the install's secrets, or fetches it again with the install credential.
121
+ * @param {{name: string, creds: object|null, claim: boolean}} check from checkTeamAddress
122
+ * @param {Record<string,string>} stored the install's current secrets
123
+ * @returns {Promise<string>} the connector token
124
+ */
125
+ export async function ensureTeamAddress(ctx, answers, check, stored = {}) {
126
+ if (ctx.tunnelToken) return ctx.tunnelToken
127
+ const { name } = check
128
+ if (check.creds && stored[TUNNEL_TOKEN]) {
129
+ ctx.redactor.add(stored[TUNNEL_TOKEN])
130
+ ctx.tunnelToken = stored[TUNNEL_TOKEN]
131
+ return ctx.tunnelToken
132
+ }
133
+ const cloud = client(ctx, check.creds?.cloudUrl)
134
+ if (check.creds) {
135
+ // The token file was lost (a new server, a wiped folder): fetch it again with the credential.
136
+ try {
137
+ ctx.tunnelToken = await connectorToken(ctx, cloud, check.creds)
138
+ ctx.out.step('address', 'ok', `Fetched the secure tunnel token for ${teamHost(name)} again`)
139
+ return ctx.tunnelToken
140
+ } catch (error) {
141
+ if (!(error instanceof CloudError && error.status === 401)) throw cloudFailure(error, name)
142
+ }
143
+ // The credential was revoked or replaced: sign in and mint a new one (this also rotates the tunnel secret).
144
+ const bearer = await signIn(ctx, cloud, { purpose: `reconnect ${teamHost(name)}` })
145
+ let minted
146
+ try { minted = await cloud.mintCredential(bearer, check.creds.claimId) } catch (error) { throw cloudFailure(error, name) }
147
+ const creds = { ...check.creds, installCredential: minted.installCredential, renewedAt: new Date().toISOString() }
148
+ ctx.redactor.add(creds.installCredential)
149
+ writeCredentials(ctx.home, answers.name, creds)
150
+ check.creds = creds
151
+ try { ctx.tunnelToken = minted.connectorToken || await connectorToken(ctx, cloud, creds) } catch (error) { throw cloudFailure(error, name) }
152
+ ctx.redactor.add(ctx.tunnelToken)
153
+ ctx.out.step('address', 'ok', `${teamHost(name)} has a new install credential`)
154
+ return ctx.tunnelToken
155
+ }
156
+
157
+ const clientKey = pendingKey(ctx, answers.name, name)
158
+ const bearer = await signIn(ctx, cloud)
159
+ ctx.out.step('address', 'start', `Claiming ${teamHost(name)}`)
160
+ let claimed
161
+ try {
162
+ claimed = await cloud.claim(bearer, {
163
+ name, clientKey, label: ctx.deviceLabel || deviceLabel(),
164
+ idempotencyKey: createHash('sha256').update(`${name}|${clientKey}`).digest('hex'),
165
+ })
166
+ } catch (error) {
167
+ throw cloudFailure(error, name)
168
+ }
169
+ const claim = claimed?.claim
170
+ if (!claim?.id) throw new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud did not confirm the claim.')
171
+ let installCredential = claimed.installCredential
172
+ // A replayed claim (the first answer was lost) carries no credential: mint one.
173
+ if (!installCredential) {
174
+ try { installCredential = (await cloud.mintCredential(bearer, claim.id)).installCredential } catch (error) { throw cloudFailure(error, name) }
175
+ }
176
+ ctx.redactor.add(installCredential)
177
+ const creds = { claimId: claim.id, name: claim.name || name, host: claim.host || teamHost(name), cloudUrl: cloud.base, installCredential, claimedAt: new Date().toISOString() }
178
+ writeCredentials(ctx.home, answers.name, creds)
179
+ rmSync(pendingPath(ctx, answers.name), { force: true })
180
+ check.creds = creds
181
+ check.claim = false
182
+ const of = claimed.count && claimed.limit ? ` (${claimed.count} of ${claimed.limit} team addresses on this account)` : ''
183
+ ctx.out.step('address', 'ok', `Claimed ${creds.host}${of}`)
184
+ try {
185
+ ctx.tunnelToken = claimed.connectorToken || await connectorToken(ctx, cloud, creds)
186
+ } catch (error) {
187
+ throw cloudFailure(error, name)
188
+ }
189
+ ctx.redactor.add(ctx.tunnelToken)
190
+ return ctx.tunnelToken
191
+ }
192
+
193
+ // ------------------------------------------------------------------ day two
194
+
195
+ function requireCreds(ctx, record) {
196
+ const creds = readCredentials(ctx.home, record.name)
197
+ if (!creds) {
198
+ throw new InstallError(EXIT.PRECONDITION, `"${record.name}" has no team address on this computer (no ${credentialsPath(ctx.home, record.name)}).${record.address?.team ? ' Run slatebox install again to sign in and reconnect it.' : ' Add one with: slatebox install --team-address <name>'}`)
199
+ }
200
+ ctx.redactor.add(creds.installCredential)
201
+ return creds
202
+ }
203
+
204
+ /** The address as Slatebox Cloud sees it: active, suspended (with the notice), or unknown when offline. */
205
+ export async function teamStatus(ctx, record) {
206
+ const creds = readCredentials(ctx.home, record.name)
207
+ if (!creds) return { name: record.address.team, host: teamHost(record.address.team), status: 'no credential on this computer' }
208
+ ctx.redactor.add(creds.installCredential)
209
+ try {
210
+ const answer = await client(ctx, creds.cloudUrl).self(creds.installCredential)
211
+ // {claim: {id, name, host, status, suspension?}} (a flat claim is read the same way).
212
+ const self = answer?.claim || answer || {}
213
+ return { name: self.name || creds.name, host: self.host || creds.host, status: self.status || 'unknown', suspension: self.suspension || null }
214
+ } catch (error) {
215
+ if (error instanceof InstallError) return { name: creds.name, host: creds.host, status: 'unknown (Slatebox Cloud not reachable)' }
216
+ if (error instanceof CloudError && error.code === 'suspended') return { name: creds.name, host: creds.host, status: 'suspended', suspension: { notice: error.notice || error.message } }
217
+ return { name: creds.name, host: creds.host, status: `unknown (${error.code || error.message})` }
218
+ }
219
+ }
220
+
221
+ /** A new tunnel secret: every connector holding the old token is dropped. Returns the new token. */
222
+ export async function rotateTeamAddress(ctx, record) {
223
+ const creds = requireCreds(ctx, record)
224
+ try {
225
+ ctx.tunnelToken = await connectorToken(ctx, client(ctx, creds.cloudUrl), creds, { rotate: true })
226
+ } catch (error) {
227
+ throw cloudFailure(error, creds.name)
228
+ }
229
+ return ctx.tunnelToken
230
+ }
231
+
232
+ /** Move the address to a new name. The old name keeps working until renameComplete. */
233
+ export async function renameTeamAddress(ctx, record, next) {
234
+ const problem = teamAddressProblem(next)
235
+ if (problem) throw new InstallError(EXIT.USAGE, `"${next}" is not a team address: ${problem}.`, { field: 'address.team' })
236
+ const creds = requireCreds(ctx, record)
237
+ if (creds.name === next) throw new InstallError(EXIT.USAGE, `"${record.name}" is already at ${teamHost(next)}.`)
238
+ const cloud = client(ctx, creds.cloudUrl)
239
+ const bearer = await signIn(ctx, cloud, { purpose: `move ${teamHost(creds.name)} to ${teamHost(next)}` })
240
+ let answer
241
+ try { answer = await cloud.rename(bearer, creds.claimId, next) } catch (error) { throw cloudFailure(error, next) }
242
+ const renamed = { ...creds, previousName: creds.name, name: answer?.claim?.name || next, host: answer?.claim?.host || teamHost(next), renamedAt: new Date().toISOString() }
243
+ writeCredentials(ctx.home, record.name, renamed)
244
+ return renamed
245
+ }
246
+
247
+ /** After the install answers at the new name: drop the old one (its name is held for 30 days). */
248
+ export async function finishRename(ctx, record) {
249
+ const creds = requireCreds(ctx, record)
250
+ try {
251
+ await client(ctx, creds.cloudUrl).renameComplete(creds.installCredential)
252
+ } catch (error) {
253
+ if (error instanceof InstallError) return { done: false, why: error.message }
254
+ throw cloudFailure(error, creds.name)
255
+ }
256
+ const { previousName, ...rest } = creds
257
+ writeCredentials(ctx.home, record.name, rest)
258
+ return { done: true, previousName }
259
+ }
260
+
261
+ /**
262
+ * Give the address back. With offlineOk, an unreachable Cloud is not an error: the credential is
263
+ * kept so `slatebox address release` can finish later.
264
+ */
265
+ export async function releaseTeamAddress(ctx, record, { offlineOk = false } = {}) {
266
+ const creds = requireCreds(ctx, record)
267
+ try {
268
+ await client(ctx, creds.cloudUrl).releaseSelf(creds.installCredential)
269
+ } catch (error) {
270
+ if (error instanceof CloudError && (error.status === 404 || error.status === 401)) {
271
+ // Already released, or the credential was revoked by a release elsewhere.
272
+ } else if (offlineOk && error instanceof InstallError) {
273
+ return { released: false, host: creds.host, claimId: creds.claimId, why: error.message.split('\n')[0] }
274
+ } else {
275
+ throw cloudFailure(error, creds.name)
276
+ }
277
+ }
278
+ removeCredentials(ctx.home, record.name)
279
+ rmSync(pendingPath(ctx, record.name), { force: true })
280
+ return { released: true, host: creds.host, claimId: creds.claimId }
281
+ }
@@ -6,6 +6,7 @@
6
6
  import { existsSync, readdirSync } from 'node:fs'
7
7
  import { join } from 'node:path'
8
8
  import { EXIT, InstallError } from '../errors.mjs'
9
+ import { firstAdmin, makeSetupLink, setupState, stillWaiting } from '../setup-link.mjs'
9
10
  import { checkArch, checkCpu, DEFAULT_IMAGE, FALLBACK_CAPABILITIES, inspectImage, normalArch, pinImage, probeImage, refreshTag, resolveImage } from '../image.mjs'
10
11
  import { emptyPlan } from '../plan.mjs'
11
12
  import { installDir, recordText, writeRecord } from '../record.mjs'
@@ -15,6 +16,8 @@ import { shq } from '../runner.mjs'
15
16
  import { secretValues } from '../secret-values.mjs'
16
17
  import { envFileText, parseEnvFile } from '../secrets.mjs'
17
18
  import { firstFreePort, localHost, MARKER, parseKeyValues, portFree, remotePreflightScript, sshHost, which } from './hosts.mjs'
19
+ import { checkTeamAddress, ensureTeamAddress, TUNNEL_TOKEN } from './address.mjs'
20
+ import { credentialsPath } from '../cloud.mjs'
18
21
 
19
22
  const SLATEBOX = '/opt/slatebox/bin/slatebox'
20
23
  const KEPT_FILE = 'secrets.kept.env'
@@ -33,6 +36,7 @@ export const backupsDir = (host, answers) =>
33
36
  : answers.backups.to
34
37
 
35
38
  const KEK = 'SLATEBOX_KEY_ENCRYPTION_KEY'
39
+ const PENDING_TOKEN = 'pending-team-address-claim'
36
40
 
37
41
  /** Native Windows has no sh, crontab or file modes; Docker Desktop's WSL 2 integration is the way there. */
38
42
  export function refuseWindows(ctx) {
@@ -188,6 +192,7 @@ async function start(host, timeout) {
188
192
  async function health(ctx, host, answers) {
189
193
  const deep = await host.docker(['exec', answers.name, SLATEBOX, 'health', '--deep', '--wait', '60'], { timeout: 120_000 })
190
194
  if (deep.code !== 0) return { ok: false, why: lastLine(deep.stderr) || 'slatebox health failed' }
195
+ if (answers.address.team) return teamHealth(ctx, host, answers)
191
196
  // From outside, the way a browser asks.
192
197
  const url = `${answers.address.url}/readyz`
193
198
  let outside = false
@@ -206,6 +211,41 @@ async function health(ctx, host, answers) {
206
211
  return { ok: true }
207
212
  }
208
213
 
214
+ /** The tunnel's connections, from inside the container; null when the image cannot say. */
215
+ export async function tunnelState(host, name, wait = 0) {
216
+ const result = await host.docker(['exec', name, SLATEBOX, 'tunnel', '--json', ...(wait ? ['--wait', String(wait)] : [])], { timeout: (wait + 30) * 1000 })
217
+ try { return JSON.parse(lastLine(result.stdout)) } catch { return null }
218
+ }
219
+
220
+ /**
221
+ * A team address is healthy when the container's cloudflared holds connections and the address
222
+ * answers from here through Cloudflare. A tunnel that is slow to come up is a warning, not a
223
+ * rollback: Slatebox itself is healthy, and the tunnel keeps trying on its own.
224
+ */
225
+ async function teamHealth(ctx, host, answers) {
226
+ const tunnel = await tunnelState(host, answers.name, 60)
227
+ if (tunnel?.ready) ctx.out.step('tunnel', 'ok', `Secure tunnel connected (${tunnel.connections} connection${tunnel.connections === 1 ? '' : 's'})`)
228
+ // A refused tunnel stays down until it gets a new token: no point probing the address.
229
+ if (tunnel?.state === 'failed') {
230
+ 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.` }
231
+ }
232
+
233
+ const url = `${answers.address.url}/readyz`
234
+ const attempts = ctx.teamHealthAttempts ?? 30
235
+ for (let attempt = 0; attempt < attempts; attempt++) {
236
+ try {
237
+ const response = await ctx.fetch(url, { signal: AbortSignal.timeout(8000) })
238
+ if (response.ok && (await response.json().catch(() => null))?.ok === true) {
239
+ ctx.out.step('address', 'ok', `${answers.address.url} answers`)
240
+ return { ok: true }
241
+ }
242
+ } catch { /* retry */ }
243
+ if (attempt < attempts - 1) await new Promise(resolve => setTimeout(resolve, ctx.teamHealthDelay ?? 2000))
244
+ }
245
+ const why = tunnel?.ready ? `${answers.address.url} does not answer from here yet` : 'the secure tunnel has not connected yet'
246
+ 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.` }
247
+ }
248
+
209
249
  async function startAndCheck(ctx, host, answers) {
210
250
  const started = await start(host, ctx.healthTimeout)
211
251
  if (!started.ok) return started
@@ -308,6 +348,8 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
308
348
  : await existingState(host, answers)
309
349
  await checkPorts(host, answers, facts, existing)
310
350
  out.step('preflight', 'ok', `${host.where}: Docker ${facts.docker || facts.docker_server || '(to be installed)'}`)
351
+ // Docker first, then the name: nobody claims a name on a machine that cannot run Slatebox.
352
+ const team = answers.address.team ? await checkTeamAddress(ctx, answers) : null
311
353
 
312
354
  // The image. Before a yes, only what is already on the host is looked at:
313
355
  // nothing is pulled or loaded (an upgrade fetches its tag first, because
@@ -340,8 +382,11 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
340
382
  composeText = renderCompose(answers, { image: image.pinned, hostGateway: settings.hostGateway })
341
383
  settingsText = envFileText(settings.env, `Settings for the Slatebox "${answers.name}", written by the slatebox installer. No secrets.`)
342
384
  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)
385
+ // The key encryption key is made once and then kept; referenced keys are read now. Before
386
+ // the plan is approved, a team address that is still to be claimed has no token: the plan
387
+ // shows a stand-in, and nothing is written until the claim has brought the real one.
388
+ const pending = team && !ctx.tunnelToken && !stored[TUNNEL_TOKEN]
389
+ const secrets = await secretValues(pending ? { ...ctx, tunnelToken: PENDING_TOKEN } : ctx, settings.secrets, stored)
345
390
  generated = secrets.generated
346
391
  kept = Object.fromEntries(Object.entries(stored).filter(([name]) => !(name in secrets.values) && name === KEK))
347
392
  secretsText = envFileText(secrets.values, `Secrets for the Slatebox "${answers.name}". Keep a copy of SLATEBOX_KEY_ENCRYPTION_KEY with your backups.`)
@@ -406,11 +451,20 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
406
451
  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
452
  }
408
453
  }
454
+ if (team) {
455
+ if (team.claim) {
456
+ 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.`)
457
+ plan.files.push({ path: credentialsPath(ctx.home, answers.name), note: 'the team-address credential (mode 0600); it stays on this computer' })
458
+ } else if (!stored[TUNNEL_TOKEN] && !nothing) {
459
+ plan.notes.unshift(`The tunnel token for ${team.host} is fetched again from Slatebox Cloud with this computer's install credential.`)
460
+ }
461
+ }
409
462
  if (nothing) plan.notes.push('The running install already matches these answers.')
410
463
  ctx.emitPlan(plan)
411
464
  if (planOnly) return { planned: true, plan }
412
465
  if (nothing) {
413
466
  await saveRecord(ctx, host, answers, image, settings, caps, record, true)
467
+ if (caps.commands.includes('setup-link')) await stillWaiting(ctx, args => host.docker(['exec', answers.name, SLATEBOX, ...args]))
414
468
  return done(ctx, host, answers, image, { nothing: true })
415
469
  }
416
470
  await ctx.confirm(plan)
@@ -422,6 +476,11 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
422
476
  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
477
  out.step('docker', 'ok', `Docker ${check.stdout.trim()} on ${host.where}`)
424
478
  }
479
+ if (team && !ctx.tunnelToken && !stored[TUNNEL_TOKEN]) {
480
+ // The claim is kept if anything after this fails: the next run reuses it.
481
+ await ensureTeamAddress(ctx, answers, team, stored)
482
+ await render()
483
+ }
425
484
  if (!imageReady) {
426
485
  image = await resolveImage(host.docker, { ref: imageRef || answers.image, archive, loadArchive: host.loadArchive, step: out.step.bind(out) })
427
486
  await ready()
@@ -429,6 +488,7 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
429
488
  imageChanged = changedFrom()
430
489
  if (existing.container.exists && !imageChanged && previousImage === image.id && !changes.some(change => !change.startsWith('the image '))) {
431
490
  await saveRecord(ctx, host, answers, image, settings, caps, record, true)
491
+ if (caps.commands.includes('setup-link')) await stillWaiting(ctx, args => host.docker(['exec', answers.name, SLATEBOX, ...args]))
432
492
  return done(ctx, host, answers, image, { nothing: true })
433
493
  }
434
494
  }
@@ -443,6 +503,7 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
443
503
  out.step('backup', 'ok', `Backed up to ${preUpgrade}`)
444
504
  }
445
505
 
506
+ if (secretsText.includes(PENDING_TOKEN)) throw new Error('internal: the team address has no tunnel token yet')
446
507
  const previous = { ...existing.files }
447
508
  out.step('files', 'start', `Writing ${host.dir}`)
448
509
  await host.writeFile(join(host.dir, MARKER), `${answers.name}\n`, 0o600)
@@ -457,9 +518,12 @@ async function applyOn(ctx, host, answers, { record, planOnly = false, imageRef,
457
518
  const result = await startAndCheck(ctx, host, answers)
458
519
  if (!result.ok) await rollback(ctx, host, answers, { fresh, previous, preUpgrade, why: result.why })
459
520
  if (result.warning) out.step('health', 'warn', result.warning)
460
- out.step('start', 'ok', `Slatebox is healthy at ${answers.address.url}`)
521
+ out.step('start', 'ok', answers.address.team ? `Slatebox is healthy on ${host.where}` : `Slatebox is healthy at ${answers.address.url}`)
461
522
 
462
- if (fresh) await firstAccount(ctx, host, answers, caps)
523
+ // The first admin comes from the image's one-time setup link; an image without one keeps the old advice.
524
+ const inImage = args => host.docker(['exec', answers.name, SLATEBOX, ...args])
525
+ const linked = caps.commands.includes('setup-link') && await firstAdmin(ctx, inImage)
526
+ if (!linked && fresh) await firstAccount(ctx, host, answers, caps)
463
527
  if (scriptText || previous[BACKUP_SCRIPT]) {
464
528
  try {
465
529
  const how = await scheduleBackups(ctx, host, answers, facts)
@@ -555,6 +619,7 @@ function done(ctx, host, answers, image, { nothing = false, generated = [], fres
555
619
  address: answers.address.url, name: answers.name, target: answers.target, version: image.labels?.['org.opencontainers.image.version'] || null,
556
620
  imageDigest: image.pinned, installRecord: ctx.recordFile, secretsFile, nothingToChange: nothing,
557
621
  keyGenerated: generated.includes('SLATEBOX_KEY_ENCRYPTION_KEY'), fresh,
622
+ ...(answers.address.team ? { teamAddress: answers.address.url, localAddress: `http://localhost:${answers.address.port}` } : {}),
558
623
  }
559
624
  }
560
625
 
@@ -591,6 +656,8 @@ export async function statusDocker(ctx, record) {
591
656
  // File names carry the UTC time they were taken, so the newest sorts last.
592
657
  lastBackup = existsSync(dir) ? readdirSync(dir).filter(file => /^slatebox-\d{8}-\d{6}\.gz$/.test(file)).sort().pop() || null : null
593
658
  }
659
+ const tunnel = record.address?.team && state?.Running ? await tunnelState(host, record.name) : null
660
+ const setup = state?.Running ? await setupState(args => host.docker(['exec', record.name, SLATEBOX, ...args])) : null
594
661
  const age = backupLate(record, lastBackup)
595
662
  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
663
  return {
@@ -600,6 +667,8 @@ export async function statusDocker(ctx, record) {
600
667
  ai: record.ai.mode === 'none' ? 'off' : record.ai.providers.map(provider => provider.id).join(', '),
601
668
  sso: record.sso.enabled ? (record.sso.only ? 'on (only)' : 'on') : 'off',
602
669
  lastBackup, backupLate: age ? age.late : null,
670
+ ...(record.address?.team ? { tunnel } : {}),
671
+ setup: setup ? (setup.setUp ? 'done' : 'waiting for the first admin') : null,
603
672
  }
604
673
  } finally {
605
674
  await host.close?.()
@@ -675,11 +744,54 @@ export function uninstallDocker(ctx, record, { deleteData }) {
675
744
  })
676
745
  }
677
746
 
747
+ // The services' log lines carry their name: [app], [relay], [mongo], [proxy], [tunnel], [sso], [slatebox].
748
+ export const LOG_SERVICES = ['app', 'relay', 'mongo', 'proxy', 'tunnel', 'sso', 'slatebox']
749
+
750
+ /** docker logs for the install, optionally only one service's lines, optionally following. */
751
+ export function logsDocker(ctx, record, { follow = false, service, since } = {}) {
752
+ return withHost(ctx, record, async host => {
753
+ const args = ['logs', ...(since ? ['--since', since] : []), ...(follow ? ['--follow'] : ['--tail', '500']), record.name]
754
+ const keep = line => !service || line.startsWith(`[${service}] `) || (service === 'sso' && line.startsWith('[sso-setup] '))
755
+ const write = text => {
756
+ for (const line of text.split('\n')) if (line && keep(line)) ctx.stdout.write(`${ctx.redactor.redact(line)}\n`)
757
+ }
758
+ if (follow) {
759
+ if (host.kind !== 'local') throw new InstallError(EXIT.USAGE, `Following logs on ${host.where}: ssh ${host.where} ${host.sudo || ''}docker logs -f ${record.name}`)
760
+ // Streamed as it comes, each line through the redactor, until Ctrl-C.
761
+ const { spawn } = await import('node:child_process')
762
+ return new Promise(resolve => {
763
+ const child = (ctx.spawn || spawn)('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] })
764
+ let rest = ''
765
+ const onData = chunk => {
766
+ const text = rest + chunk
767
+ const cut = text.lastIndexOf('\n')
768
+ rest = cut < 0 ? text : text.slice(cut + 1)
769
+ if (cut >= 0) write(text.slice(0, cut))
770
+ }
771
+ child.stdout.on('data', onData)
772
+ child.stderr.on('data', onData)
773
+ child.on('error', () => resolve({ lines: false }))
774
+ child.on('close', () => { if (rest) write(rest); resolve({ lines: true }) })
775
+ })
776
+ }
777
+ const result = await host.docker(args, { timeout: 120_000 })
778
+ if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `docker logs failed: ${lastLine(result.stderr)}`)
779
+ // docker logs puts the container's stdout and stderr on its own two streams.
780
+ write(`${result.stdout}${result.stderr}`)
781
+ return { lines: true }
782
+ })
783
+ }
784
+
678
785
  /** Run a script inside the container with node, the script on standard input (never in the arguments). */
679
786
  export function execNode(ctx, record, script, args = []) {
680
787
  return withHost(ctx, record, host => host.docker(['exec', '-i', record.name, 'node', '--input-type=module', '-', ...args], { input: script, timeout: 120_000 }))
681
788
  }
682
789
 
790
+ /** A fresh one-time setup link from the install's container (setup-link.mjs makeSetupLink). */
791
+ export function setupLinkDocker(ctx, record) {
792
+ return withHost(ctx, record, host => makeSetupLink(ctx, args => host.docker(['exec', record.name, SLATEBOX, ...args])))
793
+ }
794
+
683
795
  export function readSecretDocker(ctx, record, name) {
684
796
  return withHost(ctx, record, async host => parseEnvFile(await host.readFile(join(host.dir, SECRETS_FILE)) || '')[name])
685
797
  }
@@ -12,6 +12,8 @@ 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'
@@ -150,6 +152,16 @@ async function rollout(ctx, k, answers) {
150
152
  if (status.code !== 0) return { ok: false, why: lastLine(status.stderr) || 'rollout did not finish' }
151
153
  const deep = await k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'health', '--deep', '--wait', '60'], { timeout: 120_000 })
152
154
  if (deep.code !== 0) return { ok: false, why: lastLine(deep.stderr) || 'slatebox health failed' }
155
+ if (answers.address.team) {
156
+ for (let attempt = 0; attempt < (ctx.teamHealthAttempts ?? 30); attempt++) {
157
+ try {
158
+ const response = await ctx.fetch(`${answers.address.url}/readyz`, { signal: AbortSignal.timeout(8000) })
159
+ if (response.ok) return { ok: true }
160
+ } catch { /* retry */ }
161
+ await new Promise(resolve => setTimeout(resolve, ctx.teamHealthDelay ?? 2000))
162
+ }
163
+ 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).` }
164
+ }
153
165
  if (answers.k8s.route !== 'none') {
154
166
  try {
155
167
  const response = await ctx.fetch(`${answers.address.url}/readyz`, { signal: AbortSignal.timeout(8000) })
@@ -172,6 +184,7 @@ export async function applyK8s(ctx, answers, { record, planOnly = false, imageRe
172
184
  out.step('preflight', 'start', `Checking kube context "${context}"`)
173
185
  const facts = await preflight(ctx, k, answers, context)
174
186
  out.step('preflight', 'ok', `Context "${context}", namespace ${answers.k8s.namespace}${facts.nsExists ? '' : ' (new)'}`)
187
+ const team = answers.address.team ? await checkTeamAddress(ctx, answers) : null
175
188
 
176
189
  const warnings = []
177
190
  const image = await clusterImage(ctx, imageRef || answers.image, { refresh })
@@ -187,7 +200,22 @@ export async function applyK8s(ctx, answers, { record, planOnly = false, imageRe
187
200
  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
201
  }
189
202
  }
190
- const { values, generated } = await secretValues(ctx, settings.secrets, stored)
203
+ // The Secret is part of the server-side diff, so a team address still to be claimed is claimed
204
+ // (after its own yes) before the plan; a plan-only run shows a stand-in and claims nothing.
205
+ let secretCtx = ctx
206
+ if (team && !stored[TUNNEL_TOKEN]) {
207
+ if (planOnly) secretCtx = { ...ctx, tunnelToken: 'pending-team-address-claim' }
208
+ else {
209
+ if (team.claim) {
210
+ const claimPlan = emptyPlan({ action: 'claim', target: 'k8s', name: answers.name, where: 'Slatebox Cloud', address: answers.address.url,
211
+ 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).`] })
212
+ ctx.emitPlan(claimPlan)
213
+ await ctx.confirm(claimPlan)
214
+ }
215
+ await ensureTeamAddress(ctx, answers, team, stored)
216
+ }
217
+ }
218
+ const { values, generated } = await secretValues(secretCtx, settings.secrets, stored)
191
219
  const secretsHash = createHash('sha256').update(JSON.stringify(values)).digest('hex')
192
220
  const imageChanged = Boolean(previous && previous !== image.pinned)
193
221
 
@@ -222,6 +250,7 @@ export async function applyK8s(ctx, answers, { record, planOnly = false, imageRe
222
250
  if (nothing) {
223
251
  nextRecord.lastHealthy = new Date().toISOString()
224
252
  ctx.recordFile = writeRecord(ctx.home, nextRecord)
253
+ await stillWaiting(ctx, args => k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
225
254
  return {
226
255
  address: answers.address.url, name: answers.name, target: 'k8s', version: null, imageDigest: image.pinned,
227
256
  installRecord: ctx.recordFile, secretsFile: nextRecord.secretsLocation, nothingToChange: true, keyGenerated: false, fresh: false,
@@ -272,7 +301,9 @@ export async function applyK8s(ctx, answers, { record, planOnly = false, imageRe
272
301
  }
273
302
  if (result.warning) out.step('route', 'warn', result.warning)
274
303
  out.step('start', 'ok', `Slatebox is ready${answers.k8s.route === 'none' ? ' (port-forward to reach it)' : ` at ${answers.address.url}`}`)
275
- if (!previous) {
304
+ // The first admin comes from the image's one-time setup link; an image without one keeps the old advice.
305
+ const linked = await firstAdmin(ctx, args => k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
306
+ if (!linked && !previous) {
276
307
  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
308
  }
278
309
  nextRecord.lastHealthy = new Date().toISOString()
@@ -313,12 +344,14 @@ export async function statusK8s(ctx, record) {
313
344
  const ready = info?.status?.containerStatuses?.find(item => item.name === 'slatebox')?.ready
314
345
  const version = ready ? await k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'version']) : null
315
346
  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
347
+ const setup = ready ? await setupState(args => k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args])) : null
316
348
  return {
317
349
  name: record.name, target: 'k8s', where: `context ${record.k8s.context}, namespace ${record.k8s.namespace}`, address: record.address.url,
318
350
  running: Boolean(info), health: ready ? 'healthy' : info ? info.status.phase : 'missing',
319
351
  version: version?.code === 0 ? JSON.parse(version.stdout) : null, imageDigest: record.imageDigest,
320
352
  ai: record.ai.mode === 'none' ? 'off' : record.ai.providers.map(provider => provider.id).join(', '),
321
353
  sso: record.sso.enabled ? 'on' : 'off', lastBackup: backups?.stdout.trim() || null,
354
+ setup: setup ? (setup.setUp ? 'done' : 'waiting for the first admin') : null,
322
355
  }
323
356
  }
324
357
 
@@ -360,6 +393,12 @@ export function execNodeK8s(ctx, record, script, args = []) {
360
393
  return k(['exec', '-i', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', 'node', '--input-type=module', '-', ...args], { input: script, timeout: 120_000 })
361
394
  }
362
395
 
396
+ /** A fresh one-time setup link from the install's pod (setup-link.mjs makeSetupLink). */
397
+ export function setupLinkK8s(ctx, record) {
398
+ const k = kube(ctx, record.k8s.context)
399
+ return makeSetupLink(ctx, args => k(['exec', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
400
+ }
401
+
363
402
  export async function readSecretK8s(ctx, record, name) {
364
403
  const k = kube(ctx, record.k8s.context)
365
404
  return (await existingSecret(k, record))[name]