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.
package/src/cloud.mjs ADDED
@@ -0,0 +1,261 @@
1
+ // Slatebox Cloud, for team addresses (https://<name>.slatebox.team): the device-code sign-in
2
+ // (RFC 8628, like `gh auth login`), the team-address API, and the install credential that stays
3
+ // on this computer.
4
+ //
5
+ // What goes where:
6
+ // - The person's sign-in token lives in memory for one command and is never written anywhere.
7
+ // - The install credential (sbxi_…) is written to ~/.slatebox/installs/<name>/credentials.json,
8
+ // mode 0600 in a 0700 folder, and never leaves this computer (not to a server over SSH, not
9
+ // into a container). It can fetch this install's own tunnel token and release its own address,
10
+ // and nothing else.
11
+ // - The tunnel connector token goes only into the install's secrets (secrets.env or the
12
+ // Kubernetes Secret). Slatebox Cloud never stores it; it asks Cloudflare each time.
13
+ //
14
+ // The base URL is https://app.slatebox.com unless SLATEBOX_CLOUD_URL or --cloud-url says
15
+ // otherwise (a local claim service for tests). Plain http:// is accepted only for loopback.
16
+ import { spawn } from 'node:child_process'
17
+ import { randomBytes } from 'node:crypto'
18
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
19
+ import { hostname } from 'node:os'
20
+ import { join } from 'node:path'
21
+ import { EXIT, InstallError } from './errors.mjs'
22
+ import { installDir } from './record.mjs'
23
+
24
+ export const DEFAULT_CLOUD = 'https://app.slatebox.com'
25
+ export const TEAM_ZONE = 'slatebox.team'
26
+ export const CLI_CLIENT_ID = 'slatebox-cli'
27
+ export const TEAM_SCOPE = 'team-addresses'
28
+ export const CREDENTIALS_FILE = 'credentials.json'
29
+ const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'
30
+
31
+ // ------------------------------------------------------------------ names
32
+
33
+ // 3-32 characters, a-z 0-9 and hyphens, starting with a letter, not ending with a hyphen, and
34
+ // never two hyphens in a row (which also rules out xn-- punycode). The server holds the same rule
35
+ // plus the reserved and blocked lists; this is only so a typo is caught before any network call.
36
+ export const TEAM_ADDRESS_RULE = '3–32 characters: a–z, 0–9 and hyphens, starting with a letter, not ending with a hyphen (no two hyphens in a row)'
37
+ const TEAM_ADDRESS = /^[a-z][a-z0-9-]{1,30}[a-z0-9]$/
38
+
39
+ export function teamAddressProblem(name) {
40
+ const text = String(name ?? '')
41
+ if (!TEAM_ADDRESS.test(text) || text.includes('--')) return TEAM_ADDRESS_RULE
42
+ return null
43
+ }
44
+
45
+ export const teamHost = name => `${name}.${TEAM_ZONE}`
46
+ export const teamUrl = name => `https://${teamHost(name)}`
47
+
48
+ // ------------------------------------------------------------------ base URL
49
+
50
+ export function cloudBase(ctx) {
51
+ const raw = ctx.flags?.['cloud-url'] || ctx.env?.SLATEBOX_CLOUD_URL || DEFAULT_CLOUD
52
+ let url
53
+ try { url = new URL(raw) } catch { throw new InstallError(EXIT.USAGE, `SLATEBOX_CLOUD_URL (or --cloud-url) is not a URL: ${raw}`) }
54
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
55
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
56
+ throw new InstallError(EXIT.USAGE, 'SLATEBOX_CLOUD_URL must be https:// (plain http:// only for localhost).')
57
+ }
58
+ if (url.username || url.password || url.search || url.hash) throw new InstallError(EXIT.USAGE, 'SLATEBOX_CLOUD_URL is an origin, with nothing after the host.')
59
+ return url.origin
60
+ }
61
+
62
+ // ------------------------------------------------------------------ errors
63
+
64
+ /** An answer from Slatebox Cloud that is not a success: {error: {code, message}}. */
65
+ export class CloudError extends Error {
66
+ constructor(status, code, message, extra = {}) {
67
+ super(message || code || `HTTP ${status}`)
68
+ this.status = status
69
+ this.code = code || `http_${status}`
70
+ Object.assign(this, extra)
71
+ }
72
+ }
73
+
74
+ function offline(base, error) {
75
+ const host = new URL(base).host
76
+ const why = error?.cause?.code || error?.code || error?.name || error?.message || 'no answer'
77
+ return new InstallError(EXIT.PRECONDITION,
78
+ `Slatebox Cloud (${host}) can't be reached: ${why}.\n` +
79
+ ' A team address is claimed online. Nothing was changed.\n' +
80
+ ' Run this again when you\'re online, or install without one:\n' +
81
+ ' npx slatebox install --local\n' +
82
+ ' npx slatebox install --domain boards.example.com',
83
+ { id: 'cloud-unreachable', cloud: host })
84
+ }
85
+
86
+ // ------------------------------------------------------------------ client
87
+
88
+ /**
89
+ * @param {object} ctx run context: fetch, redactor
90
+ * @param {string} base Cloud origin
91
+ */
92
+ export function cloudClient(ctx, base) {
93
+ const fetchImpl = ctx.fetch || globalThis.fetch
94
+
95
+ async function call(method, path, { bearer, body, form, headers = {}, timeout = 20_000 } = {}) {
96
+ const init = { method, headers: { accept: 'application/json', 'user-agent': `slatebox-cli/${ctx.version || '0'}`, ...headers }, redirect: 'error', signal: AbortSignal.timeout(timeout) }
97
+ if (bearer) init.headers.authorization = `Bearer ${bearer}`
98
+ if (form) {
99
+ init.headers['content-type'] = 'application/x-www-form-urlencoded'
100
+ init.body = new URLSearchParams(form).toString()
101
+ } else if (body !== undefined) {
102
+ init.headers['content-type'] = 'application/json'
103
+ init.body = JSON.stringify(body)
104
+ }
105
+ let response
106
+ try {
107
+ response = await fetchImpl(`${base}${path}`, init)
108
+ } catch (error) {
109
+ throw offline(base, error)
110
+ }
111
+ let data = null
112
+ const text = typeof response.text === 'function' ? await response.text().catch(() => '') : JSON.stringify(await response.json?.().catch(() => null))
113
+ try { data = text ? JSON.parse(text) : null } catch { data = null }
114
+ if (response.status >= 200 && response.status < 300) return data ?? {}
115
+ // OAuth errors are {error: "code", error_description}; the API's are {error: {code, message}}.
116
+ const error = data?.error
117
+ const code = typeof error === 'string' ? error : error?.code
118
+ const message = typeof error === 'string' ? data?.error_description : error?.message
119
+ const retryAfter = Number(response.headers?.get?.('retry-after')) || undefined
120
+ throw new CloudError(response.status, code, message, { retryAfter, suggestions: data?.suggestions || error?.suggestions, notice: error?.notice })
121
+ }
122
+
123
+ const api = path => `/api/v1/team-addresses${path}`
124
+ const enc = encodeURIComponent
125
+
126
+ return {
127
+ base,
128
+ // --- sign-in (RFC 8628)
129
+ deviceAuthorize: (label, scope = TEAM_SCOPE) => call('POST', '/oauth/device_authorization', { form: { client_id: CLI_CLIENT_ID, scope, device_label: label } }),
130
+ deviceToken: deviceCode => call('POST', '/oauth/token', { form: { grant_type: DEVICE_GRANT, device_code: deviceCode, client_id: CLI_CLIENT_ID } }),
131
+ // --- the signed-in person's team addresses
132
+ availability: (name, bearer) => call('GET', api(`/availability?name=${enc(name)}`), { bearer }),
133
+ claim: (bearer, { name, clientKey, label, idempotencyKey }) => call('POST', api(''), { bearer, body: { name, clientKey, label }, headers: { 'idempotency-key': idempotencyKey }, timeout: 120_000 }),
134
+ list: bearer => call('GET', api(''), { bearer }),
135
+ rename: (bearer, id, name) => call('POST', api(`/${enc(id)}/rename`), { bearer, body: { name }, timeout: 120_000 }),
136
+ release: (bearer, id) => call('DELETE', api(`/${enc(id)}`), { bearer, timeout: 120_000 }),
137
+ mintCredential: (bearer, id) => call('POST', api(`/${enc(id)}/install-credential`), { bearer }),
138
+ // --- this install, with its install credential
139
+ self: credential => call('GET', api('/self'), { bearer: credential }),
140
+ connectorToken: (credential, { rotate = false } = {}) => call('POST', api('/self/connector-token'), { bearer: credential, body: { rotate }, timeout: 120_000 }),
141
+ renameComplete: credential => call('POST', api('/self/rename-complete'), { bearer: credential, body: {}, timeout: 120_000 }),
142
+ releaseSelf: credential => call('DELETE', api('/self'), { bearer: credential, timeout: 120_000 }),
143
+ }
144
+ }
145
+
146
+ // ------------------------------------------------------------------ sign-in
147
+
148
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
149
+
150
+ /** A short, printable name for this computer, shown on the consent page. */
151
+ export function deviceLabel() {
152
+ return hostname().replace(/[^\x20-\x7e]/g, '').slice(0, 64) || 'this computer'
153
+ }
154
+
155
+ /** Open a URL in the person's browser. Failure is fine: the code and link are printed anyway. */
156
+ export function openBrowser(url, platform = process.platform) {
157
+ const [cmd, args] = platform === 'darwin' ? ['open', [url]] : platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]]
158
+ try {
159
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true })
160
+ child.on('error', () => {})
161
+ child.unref()
162
+ } catch { /* printed anyway */ }
163
+ }
164
+
165
+ /**
166
+ * Sign in to Slatebox Cloud for one scope (team-addresses by default; a move asks for
167
+ * team:export and team:move). Returns an access token that lives
168
+ * 15 minutes and is kept in memory. There is no token shortcut: Slatebox Cloud gives the
169
+ * team-addresses scope only to this sign-in, never to a personal access token, so a person
170
+ * approves every claim, rename and credential in a browser.
171
+ */
172
+ export async function signIn(ctx, cloud, { purpose = 'claim a team address', scope = TEAM_SCOPE } = {}) {
173
+ const label = ctx.deviceLabel || deviceLabel()
174
+ const grant = await cloud.deviceAuthorize(label, scope).catch(error => { throw signInFailed(error, cloud) })
175
+ if (!grant?.device_code || !grant?.user_code || !grant?.verification_uri) throw new InstallError(EXIT.PRECONDITION, `Slatebox Cloud (${new URL(cloud.base).host}) did not start a sign-in.`)
176
+ ctx.redactor.add(grant.device_code)
177
+ // Only a link on the Cloud's own origin is opened or printed.
178
+ const sameOrigin = link => { try { return new URL(link).origin === cloud.base } catch { return false } }
179
+ const page = sameOrigin(grant.verification_uri) ? grant.verification_uri : `${cloud.base}/device`
180
+ const complete = sameOrigin(grant.verification_uri_complete) ? grant.verification_uri_complete : null
181
+ const minutes = Math.max(1, Math.round((grant.expires_in || 600) / 60))
182
+ ctx.out.event({ event: 'sign-in', status: 'waiting', verificationUri: page, userCode: grant.user_code, expiresIn: grant.expires_in || 600 })
183
+ const lines = ['', `Sign in to Slatebox to ${purpose}.`, ` Open: ${page}`, ` Code: ${grant.user_code}`]
184
+ if (ctx.interactive) {
185
+ lines.push(` (The code expires in ${minutes} minutes.)`)
186
+ ctx.stderr.write(`${lines.join('\n')}\n`)
187
+ if (await ctx.prompt.confirm('Open it in your browser now?', { default: true })) (ctx.openBrowser || openBrowser)(complete || page, ctx.platform)
188
+ } else {
189
+ lines.push(` (The code expires in ${minutes} minutes. Approve it in a browser where you are signed in to Slatebox.)`)
190
+ ctx.stderr.write(`${lines.join('\n')}\n`)
191
+ }
192
+ ctx.stderr.write('... waiting for approval\n')
193
+ let interval = Math.max(1, Number(grant.interval) || 5) * 1000
194
+ const deadline = Date.now() + (grant.expires_in || 600) * 1000
195
+ const wait = ctx.sleep || sleep
196
+ for (;;) {
197
+ await wait(interval)
198
+ try {
199
+ const token = await cloud.deviceToken(grant.device_code)
200
+ if (!token?.access_token) throw new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud approved the sign-in but sent no token.')
201
+ ctx.redactor.add(token.access_token)
202
+ ctx.out.event({ event: 'sign-in', status: 'ok' })
203
+ return token.access_token
204
+ } catch (error) {
205
+ if (!(error instanceof CloudError)) throw error
206
+ if (error.code === 'authorization_pending') { /* keep waiting */ } else if (error.code === 'slow_down') interval += 5000
207
+ else if (error.code === 'access_denied') throw new InstallError(EXIT.CANCELLED, 'The sign-in was denied in the browser. Nothing was changed.')
208
+ else if (error.code === 'expired_token') throw new InstallError(EXIT.PRECONDITION, 'The sign-in code expired before it was approved. Nothing was changed; run the command again for a new code.')
209
+ else throw signInFailed(error, cloud)
210
+ }
211
+ if (Date.now() > deadline) throw new InstallError(EXIT.PRECONDITION, 'The sign-in code expired before it was approved. Nothing was changed; run the command again for a new code.')
212
+ }
213
+ }
214
+
215
+ function signInFailed(error, cloud) {
216
+ if (error instanceof InstallError) return error
217
+ return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud (${new URL(cloud.base).host}) refused the sign-in: ${error.message}${error.code ? ` (${error.code})` : ''}.`)
218
+ }
219
+
220
+ // ------------------------------------------------------------------ credentials on disk
221
+
222
+ export const credentialsPath = (home, name) => join(installDir(home, name), CREDENTIALS_FILE)
223
+
224
+ /**
225
+ * The install's team-address credential, or null. A file or folder that others can read is
226
+ * refused with the command that fixes it, rather than used.
227
+ */
228
+ export function readCredentials(home, name) {
229
+ const path = credentialsPath(home, name)
230
+ if (!existsSync(path)) return null
231
+ if (process.platform !== 'win32') {
232
+ const fileMode = statSync(path).mode & 0o777
233
+ const dirMode = statSync(installDir(home, name)).mode & 0o777
234
+ if (fileMode & 0o077 || dirMode & 0o077) {
235
+ throw new InstallError(EXIT.PRECONDITION, `${path} can be read by other users of this computer (mode ${fileMode.toString(8)}, folder ${dirMode.toString(8)}), so it was not used. It holds the key to your team address. Fix it with: chmod 700 ${installDir(home, name)} && chmod 600 ${path}`)
236
+ }
237
+ }
238
+ let data
239
+ try { data = JSON.parse(readFileSync(path, 'utf8')) } catch { throw new InstallError(EXIT.PRECONDITION, `${path} is not readable JSON. Move it away and run slatebox install again to sign in and get a new one.`) }
240
+ if (!data?.claimId || !data?.installCredential || !data?.name) throw new InstallError(EXIT.PRECONDITION, `${path} is missing fields. Move it away and run slatebox install again.`)
241
+ return data
242
+ }
243
+
244
+ /** Written atomically, 0600 in a 0700 folder. */
245
+ export function writeCredentials(home, name, data) {
246
+ const dir = installDir(home, name)
247
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
248
+ chmodSync(dir, 0o700)
249
+ const path = credentialsPath(home, name)
250
+ writeFileSync(`${path}.tmp`, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 })
251
+ renameSync(`${path}.tmp`, path)
252
+ chmodSync(path, 0o600)
253
+ return path
254
+ }
255
+
256
+ export function removeCredentials(home, name) {
257
+ rmSync(credentialsPath(home, name), { force: true })
258
+ }
259
+
260
+ /** A random value that makes a retried claim from this computer the same claim. */
261
+ export const newClientKey = () => randomBytes(16).toString('base64url')
package/src/image.mjs CHANGED
@@ -10,8 +10,11 @@ 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
- export const PINNED_TAG = '0.1.0'
14
- export const PINNED_DIGEST = 'sha256:94f761bd8153ca9b9d9ef1ecd4af9faddf318427f7495c3af8492bb2a1d22d4f'
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
 
17
20
  /** Does this reference name a registry (so a digest reference can be pulled elsewhere)? */
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)