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.
- package/README.md +99 -15
- package/package.json +5 -2
- package/src/agent-prompt.mjs +18 -3
- package/src/answers.mjs +36 -9
- package/src/cli.mjs +339 -76
- package/src/cloud.mjs +265 -0
- package/src/image.mjs +57 -4
- package/src/interview.mjs +30 -1
- package/src/move.mjs +447 -0
- package/src/render/settings.mjs +20 -4
- package/src/secret-values.mjs +6 -1
- package/src/secrets.mjs +7 -2
- package/src/setup-link.mjs +88 -0
- package/src/targets/address.mjs +285 -0
- package/src/targets/docker.mjs +250 -19
- package/src/targets/export.mjs +3 -1
- package/src/targets/k8s.mjs +44 -3
package/src/cloud.mjs
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
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, reason: typeof error?.reason === 'string' ? error.reason : undefined })
|
|
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
|
+
// --yes asks nothing: the page is opened for the person, as Enter at the question would.
|
|
188
|
+
if (ctx.yes) {
|
|
189
|
+
ctx.stderr.write(' Opening it in your browser.\n')
|
|
190
|
+
;(ctx.openBrowser || openBrowser)(complete || page, ctx.platform)
|
|
191
|
+
} else if (await ctx.prompt.confirm('Open it in your browser now?', { default: true })) (ctx.openBrowser || openBrowser)(complete || page, ctx.platform)
|
|
192
|
+
} else {
|
|
193
|
+
lines.push(` (The code expires in ${minutes} minutes. Approve it in a browser where you are signed in to Slatebox.)`)
|
|
194
|
+
ctx.stderr.write(`${lines.join('\n')}\n`)
|
|
195
|
+
}
|
|
196
|
+
ctx.stderr.write('... waiting for approval\n')
|
|
197
|
+
let interval = Math.max(1, Number(grant.interval) || 5) * 1000
|
|
198
|
+
const deadline = Date.now() + (grant.expires_in || 600) * 1000
|
|
199
|
+
const wait = ctx.sleep || sleep
|
|
200
|
+
for (;;) {
|
|
201
|
+
await wait(interval)
|
|
202
|
+
try {
|
|
203
|
+
const token = await cloud.deviceToken(grant.device_code)
|
|
204
|
+
if (!token?.access_token) throw new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud approved the sign-in but sent no token.')
|
|
205
|
+
ctx.redactor.add(token.access_token)
|
|
206
|
+
ctx.out.event({ event: 'sign-in', status: 'ok' })
|
|
207
|
+
return token.access_token
|
|
208
|
+
} catch (error) {
|
|
209
|
+
if (!(error instanceof CloudError)) throw error
|
|
210
|
+
if (error.code === 'authorization_pending') { /* keep waiting */ } else if (error.code === 'slow_down') interval += 5000
|
|
211
|
+
else if (error.code === 'access_denied') throw new InstallError(EXIT.CANCELLED, 'The sign-in was denied in the browser. Nothing was changed.')
|
|
212
|
+
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.')
|
|
213
|
+
else throw signInFailed(error, cloud)
|
|
214
|
+
}
|
|
215
|
+
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.')
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function signInFailed(error, cloud) {
|
|
220
|
+
if (error instanceof InstallError) return error
|
|
221
|
+
return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud (${new URL(cloud.base).host}) refused the sign-in: ${error.message}${error.code ? ` (${error.code})` : ''}.`)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ------------------------------------------------------------------ credentials on disk
|
|
225
|
+
|
|
226
|
+
export const credentialsPath = (home, name) => join(installDir(home, name), CREDENTIALS_FILE)
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The install's team-address credential, or null. A file or folder that others can read is
|
|
230
|
+
* refused with the command that fixes it, rather than used.
|
|
231
|
+
*/
|
|
232
|
+
export function readCredentials(home, name) {
|
|
233
|
+
const path = credentialsPath(home, name)
|
|
234
|
+
if (!existsSync(path)) return null
|
|
235
|
+
if (process.platform !== 'win32') {
|
|
236
|
+
const fileMode = statSync(path).mode & 0o777
|
|
237
|
+
const dirMode = statSync(installDir(home, name)).mode & 0o777
|
|
238
|
+
if (fileMode & 0o077 || dirMode & 0o077) {
|
|
239
|
+
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}`)
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
let data
|
|
243
|
+
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.`) }
|
|
244
|
+
if (!data?.claimId || !data?.installCredential || !data?.name) throw new InstallError(EXIT.PRECONDITION, `${path} is missing fields. Move it away and run slatebox install again.`)
|
|
245
|
+
return data
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Written atomically, 0600 in a 0700 folder. */
|
|
249
|
+
export function writeCredentials(home, name, data) {
|
|
250
|
+
const dir = installDir(home, name)
|
|
251
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
252
|
+
chmodSync(dir, 0o700)
|
|
253
|
+
const path = credentialsPath(home, name)
|
|
254
|
+
writeFileSync(`${path}.tmp`, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 })
|
|
255
|
+
renameSync(`${path}.tmp`, path)
|
|
256
|
+
chmodSync(path, 0o600)
|
|
257
|
+
return path
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function removeCredentials(home, name) {
|
|
261
|
+
rmSync(credentialsPath(home, name), { force: true })
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** A random value that makes a retried claim from this computer the same claim. */
|
|
265
|
+
export const newClientKey = () => randomBytes(16).toString('base64url')
|
package/src/image.mjs
CHANGED
|
@@ -10,10 +10,32 @@ import { EXIT, InstallError } from './errors.mjs'
|
|
|
10
10
|
* build instead (self-host/build-image.sh).
|
|
11
11
|
*/
|
|
12
12
|
export const DEFAULT_REPOSITORY = 'ghcr.io/slatebox/slatebox'
|
|
13
|
-
|
|
14
|
-
|
|
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'
|
|
15
18
|
export const DEFAULT_IMAGE = PINNED_DIGEST ? `${DEFAULT_REPOSITORY}@${PINNED_DIGEST}` : `${DEFAULT_REPOSITORY}:${PINNED_TAG}`
|
|
16
19
|
|
|
20
|
+
// What the pinned image accepts: its own `slatebox settings --json` (self-host/rootfs/opt/slatebox/
|
|
21
|
+
// lib/settings.mjs at the revision it was built from). A plan for the pinned image on a machine
|
|
22
|
+
// that has not pulled it yet is then the real plan (a team address, several AI providers), not a
|
|
23
|
+
// guess from an older image. The image is still probed after it is pulled, and that answer wins.
|
|
24
|
+
export const PINNED_CAPABILITIES = Object.freeze({
|
|
25
|
+
settings: Object.freeze([
|
|
26
|
+
'SLATEBOX_URL', 'SLATEBOX_HTTPS', 'SLATEBOX_ACME_CA', 'SLATEBOX_MAIL_URL', 'SLATEBOX_MAIL_FROM',
|
|
27
|
+
'SLATEBOX_AI_KEY', 'SLATEBOX_AI_URL', 'SLATEBOX_AI_MODEL', 'SLATEBOX_AI_CONFIG',
|
|
28
|
+
'SLATEBOX_AI_PROVIDERS', 'SLATEBOX_AI_DEFAULT', 'SLATEBOX_AI_OWN_PROVIDERS', 'SLATEBOX_AI_PRIVATE_ENDPOINTS',
|
|
29
|
+
'SLATEBOX_SETTINGS', 'SLATEBOX_SSO', 'SLATEBOX_SSO_ONLY', 'SLATEBOX_SSO_ADMIN', 'SLATEBOX_KEY_ENCRYPTION_KEY',
|
|
30
|
+
'SLATEBOX_TUNNEL_TOKEN', 'SLATEBOX_LICENSE', 'SLATEBOX_LICENSE_FILE', 'MONGO_URL', 'MONGO_OPLOG_URL',
|
|
31
|
+
]),
|
|
32
|
+
commands: Object.freeze(['backup', 'restore', 'password-link', 'setup-link', 'health', 'version', 'sso', 'ai', 'settings', 'tunnel']),
|
|
33
|
+
source: 'pinned',
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
/** Is this reference the image this release pins (by digest, or by its tag while unpinned)? */
|
|
37
|
+
export const isPinnedImage = ref => Boolean(ref) && (ref === DEFAULT_IMAGE || (PINNED_DIGEST !== null && ref === `${DEFAULT_REPOSITORY}@${PINNED_DIGEST}`))
|
|
38
|
+
|
|
17
39
|
/** Does this reference name a registry (so a digest reference can be pulled elsewhere)? */
|
|
18
40
|
export function hasRegistry(ref) {
|
|
19
41
|
const first = ref.split('/')[0]
|
|
@@ -43,7 +65,18 @@ export function pinImage(wanted, info) {
|
|
|
43
65
|
return { ref: wanted, pinned, id, created: info.Created, labels: info.Config?.Labels || {}, architecture: info.Architecture || null }
|
|
44
66
|
}
|
|
45
67
|
|
|
68
|
+
// What docker pull says when this machine cannot reach the registry at all.
|
|
69
|
+
const OFFLINE = /no such host|dial tcp|i\/o timeout|network is unreachable|connection refused|TLS handshake timeout|temporary failure in name resolution|could not resolve|server misbehaving|Client\.Timeout/i
|
|
70
|
+
|
|
46
71
|
function unavailable(wanted, why) {
|
|
72
|
+
const registry = hasRegistry(wanted) ? wanted.split('/')[0] : 'Docker Hub'
|
|
73
|
+
if (OFFLINE.test(why || '')) {
|
|
74
|
+
return new InstallError(EXIT.PRECONDITION,
|
|
75
|
+
`The image ${wanted} could not be downloaded: this computer cannot reach ${registry} (${why}). Nothing was changed. ` +
|
|
76
|
+
'Check the internet connection (and any proxy or firewall), then run the same command again.' +
|
|
77
|
+
(wanted.startsWith(DEFAULT_REPOSITORY) ? ' To install a local build instead, give --image <name> or --image-archive <file.tar>.' : ''),
|
|
78
|
+
{ image: wanted, offline: true })
|
|
79
|
+
}
|
|
47
80
|
return new InstallError(EXIT.PRECONDITION,
|
|
48
81
|
`The image ${wanted} is not available: ${why}\n` +
|
|
49
82
|
(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.'),
|
|
@@ -95,8 +128,7 @@ export async function resolveImage(docker, { ref, archive, loadArchive, step })
|
|
|
95
128
|
}
|
|
96
129
|
let info = await inspectImage(docker, wanted)
|
|
97
130
|
if (!info) {
|
|
98
|
-
|
|
99
|
-
const pulled = await docker(['pull', wanted], { timeout: 60 * 60_000 })
|
|
131
|
+
const pulled = await pullWithProgress(docker, wanted, step)
|
|
100
132
|
if (pulled.code !== 0) throw unavailable(wanted, pulled.stderr.trim().split('\n').pop())
|
|
101
133
|
info = await inspectImage(docker, wanted)
|
|
102
134
|
if (!info) throw new InstallError(EXIT.PRECONDITION, `The image ${wanted} was pulled but cannot be inspected.`)
|
|
@@ -104,6 +136,27 @@ export async function resolveImage(docker, { ref, archive, loadArchive, step })
|
|
|
104
136
|
return pinImage(wanted, info)
|
|
105
137
|
}
|
|
106
138
|
|
|
139
|
+
/**
|
|
140
|
+
* docker pull, saying so first and then every so often while it runs (the first pull of the
|
|
141
|
+
* one-container image is about 1 GB), so a long download never looks like a hang.
|
|
142
|
+
*/
|
|
143
|
+
export async function pullWithProgress(docker, ref, step, { every = 15_000 } = {}) {
|
|
144
|
+
step('image', 'start', `Downloading ${ref} (about 1 GB the first time; later installs and upgrades fetch only what changed)`)
|
|
145
|
+
const started = Date.now()
|
|
146
|
+
const timer = setInterval(() => step('image', 'start', `Still downloading the image (${Math.round((Date.now() - started) / 1000)}s so far)`), every)
|
|
147
|
+
timer.unref?.()
|
|
148
|
+
try {
|
|
149
|
+
const pulled = await docker(['pull', ref], { timeout: 60 * 60_000 })
|
|
150
|
+
if (pulled.code === 0) step('image', 'ok', `Downloaded the image in ${Math.max(1, Math.round((Date.now() - started) / 1000))}s`)
|
|
151
|
+
return pulled
|
|
152
|
+
} finally {
|
|
153
|
+
clearInterval(timer)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** What an image is known to accept before it is on this machine: the pinned image's own list, else the oldest image's. */
|
|
158
|
+
export const knownCapabilities = ref => (isPinnedImage(ref || DEFAULT_IMAGE) ? PINNED_CAPABILITIES : FALLBACK_CAPABILITIES)
|
|
159
|
+
|
|
107
160
|
/** What the image accepts, read from the image (no network, nothing kept). */
|
|
108
161
|
export async function probeImage(docker, image) {
|
|
109
162
|
const base = ['run', '--rm', '--network', 'none']
|
package/src/interview.mjs
CHANGED
|
@@ -4,6 +4,21 @@
|
|
|
4
4
|
import { AI_CHOICES, QUESTIONS, SIZES } from './answers.mjs'
|
|
5
5
|
import { PRESETS } from './ai/settings-adapter.mjs'
|
|
6
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
|
+
}
|
|
7
22
|
|
|
8
23
|
const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/
|
|
9
24
|
const CLOUD = ['openai', 'anthropic', 'deepinfra', 'openrouter', 'groq', 'together', 'mistral']
|
|
@@ -84,7 +99,21 @@ export async function interview(ctx, partial) {
|
|
|
84
99
|
|
|
85
100
|
// Address
|
|
86
101
|
a.address ||= {}
|
|
87
|
-
if (!has(a.address, 'url') && !has(a.address, 'domain')) {
|
|
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'))) {
|
|
88
117
|
if (a.target === 'local' && !has(a.address, 'port')) {
|
|
89
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') })
|
|
90
119
|
a.address.port = Number(port)
|