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/move.mjs ADDED
@@ -0,0 +1,447 @@
1
+ // Moving a team between your own Slatebox and Slatebox Cloud, in either direction:
2
+ //
3
+ // slatebox migrate --to cloud your own server's team → Slatebox Cloud
4
+ // slatebox import --from cloud your Slatebox Cloud team → your own server
5
+ // slatebox export [--out <file>] a team export to a file (from either)
6
+ // slatebox import <file> [--to cloud] a team export file into a server
7
+ //
8
+ // Each move is: "Export everything" on the source (team.export, a team admin), the archive
9
+ // downloaded encrypted with a passphrase made here, then a move on the target (teamMove.start,
10
+ // the owner of their team there or someone in no team yet), the report shown, and the move
11
+ // confirmed (teamMove.confirm). Nothing is visible on the target until it is confirmed, and the
12
+ // other people are emailed only when the person says so.
13
+ //
14
+ // Credentials, never written anywhere and never printed:
15
+ // - Slatebox Cloud: SLATEBOX_CLOUD_TOKEN (a personal access token with "Move a team here" and
16
+ // "Export everything my team owns"), or else the browser sign-in with a code (device flow).
17
+ // - Your own server: SLATEBOX_API_TOKEN (the same token `slatebox exec` uses), or asked for
18
+ // with hidden input at a terminal. Its address: --from/--to, SLATEBOX_BASE_URL, or the install
19
+ // this computer made (--name).
20
+ // The archive is kept in ~/.slatebox/moves/ (0600 in a 0700 folder), its passphrase beside it in
21
+ // a .key file (0600). Once the move is live the person is asked whether to delete it (default no,
22
+ // and the command that deletes it is printed); --delete-archive deletes it without asking.
23
+ //
24
+ // The other people: once the move is live the person is asked once, "Send invitations to the N
25
+ // other members now?" (yes by default at a terminal); --invite / --no-invite answer it ahead, and
26
+ // a script (no terminal, or --yes) invites nobody unless --invite. Later: slatebox migrate invite
27
+ // <move id> --to cloud|<url>. Nobody gets an account without that email, and someone who already
28
+ // has an account on the target accepts an invitation to join there.
29
+ import { randomBytes, randomUUID } from 'node:crypto'
30
+ import { chmodSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
31
+ import { join } from 'node:path'
32
+ import { Readable } from 'node:stream'
33
+ import { pipeline } from 'node:stream/promises'
34
+ import { CloudError, cloudBase, cloudClient, signIn } from './cloud.mjs'
35
+ import { EXIT, InstallError } from './errors.mjs'
36
+ import { readRecord } from './record.mjs'
37
+ import { resolveRef } from './secrets.mjs'
38
+
39
+ export const MOVE_SCOPE = 'team:export team:move'
40
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
41
+
42
+ // ------------------------------------------------------------------ servers
43
+
44
+ /** An origin to send a token to: https, or plain http on this computer only. */
45
+ export function serverOrigin(raw, what = 'The server address') {
46
+ let url
47
+ try { url = new URL(raw) } catch { throw new InstallError(EXIT.USAGE, `${what} is not a URL: ${raw}`) }
48
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK.has(url.hostname)))
49
+ throw new InstallError(EXIT.USAGE, `${what} must be https:// (plain http:// only for localhost): ${url.origin}`)
50
+ if (url.username || url.password) throw new InstallError(EXIT.USAGE, `${what} must not carry a user name or password.`)
51
+ return url.origin
52
+ }
53
+
54
+ /**
55
+ * Where "cloud" or your own server is. spec: 'cloud', a URL, or undefined (your own server:
56
+ * SLATEBOX_BASE_URL, else the install this computer made).
57
+ */
58
+ export function resolveServer(ctx, spec) {
59
+ if (spec === 'cloud') return { kind: 'cloud', base: cloudBase(ctx), label: 'Slatebox Cloud' }
60
+ if (spec) return { kind: 'own', base: serverOrigin(spec), label: new URL(spec).host }
61
+ if (ctx.env.SLATEBOX_BASE_URL) return { kind: 'own', base: serverOrigin(ctx.env.SLATEBOX_BASE_URL, 'SLATEBOX_BASE_URL'), label: new URL(ctx.env.SLATEBOX_BASE_URL).host }
62
+ const name = ctx.flags.name || 'slatebox'
63
+ const record = readRecord(ctx.home, name)
64
+ const url = record?.address?.url
65
+ if (!url) throw new InstallError(EXIT.USAGE, `Which server? Give its address (--from https://boards.example.com, or --to), set SLATEBOX_BASE_URL, or install one here first (no install named "${name}" on this computer).`)
66
+ return { kind: 'own', base: serverOrigin(url), label: new URL(url).host, install: name }
67
+ }
68
+
69
+ async function tokenFor(ctx, server, purpose) {
70
+ if (server.token) return server.token
71
+ if (server.kind === 'cloud') {
72
+ const given = ctx.env.SLATEBOX_CLOUD_TOKEN
73
+ if (given) server.token = given
74
+ else {
75
+ try {
76
+ server.token = await signIn(ctx, cloudClient(ctx, server.base), { purpose, scope: MOVE_SCOPE })
77
+ } catch (error) {
78
+ if (error instanceof InstallError && /invalid_scope|unauthorized_client|not found|http_404/i.test(error.message))
79
+ throw new InstallError(EXIT.PRECONDITION, `${server.label} can't sign this computer in for a move yet. On ${server.base}, open Profile → Developer, make an access token with "Move a team here" and "Export everything my team owns", and run this again with SLATEBOX_CLOUD_TOKEN set to it (it is never written anywhere).`)
80
+ throw error
81
+ }
82
+ }
83
+ } else {
84
+ const given = ctx.env.SLATEBOX_API_TOKEN
85
+ if (given) server.token = given
86
+ else if (ctx.interactive) {
87
+ ctx.out.say(`\nAn access token for ${server.base} is needed: in Slatebox there, open Profile → Developer and make one with "Export everything my team owns" and "Move a team here". It is used for this command only and never written anywhere.`)
88
+ server.token = await ctx.prompt.secret(`Access token for ${server.label}`)
89
+ }
90
+ if (!server.token)
91
+ throw new InstallError(EXIT.NEEDS_INPUT, `An access token for ${server.base} is needed. Make one in Profile → Developer there ("Export everything my team owns", "Move a team here") and set SLATEBOX_API_TOKEN.`, { missing: [{ field: 'SLATEBOX_API_TOKEN', question: `An access token for ${server.base}` }] })
92
+ }
93
+ ctx.redactor.add(server.token)
94
+ return server.token
95
+ }
96
+
97
+ // ------------------------------------------------------------------ the API
98
+
99
+ /** The /api/v1 actions a move uses, on one server. */
100
+ export function moveApi(ctx, server) {
101
+ const fetchImpl = ctx.fetch || globalThis.fetch
102
+ const headers = (extra = {}) => ({ accept: 'application/json', 'user-agent': `slatebox-cli/${ctx.version || '0'}`, authorization: `Bearer ${server.token}`, ...extra })
103
+ const failed = (error) => {
104
+ const why = error?.cause?.code || error?.code || error?.name || error?.message || 'no answer'
105
+ return new InstallError(EXIT.PRECONDITION, `${server.label} (${server.base}) can't be reached: ${why}. Nothing was changed there.`)
106
+ }
107
+ async function readJson(response) {
108
+ const text = await response.text().catch(() => '')
109
+ try { return text ? JSON.parse(text) : {} } catch { return {} }
110
+ }
111
+ function refusal(response, data) {
112
+ const error = data?.error && typeof data.error === 'object' ? data.error : {}
113
+ const code = error.code || `http_${response.status}`
114
+ const hint = {
115
+ insufficient_scope: ' The access token needs the "Move a team here" and "Export everything my team owns" permissions.',
116
+ unauthorized: ' The access token is not valid there.',
117
+ team_owner_required: ' Only the owner of your team there can move a team into it. Sign in as the owner, or as someone in no team yet.',
118
+ team_admin_required: ' Only a team admin can export the team.',
119
+ move_pending: ' Run again with --replace-waiting to discard that move and start over.',
120
+ move_limit: ' Moves into a server are limited per person per day.',
121
+ // An older server than the archive: it says so in its own words, or (servers before this
122
+ // message) only that it does not know a section or version.
123
+ section_unknown: ` ${server.label} runs an older Slatebox than the archive needs: update that server to the latest Slatebox, then run this again.`,
124
+ version_unknown: ` ${server.label} runs an older Slatebox than the archive needs: update that server to the latest Slatebox, then run this again.`,
125
+ }[code] || ''
126
+ return new InstallError(EXIT.PRECONDITION, `${server.label} refused: ${error.message || `HTTP ${response.status}`} (${code}).${hint}`, { code, status: response.status })
127
+ }
128
+ async function call(method, path, body) {
129
+ const key = method === 'GET' ? null : randomUUID()
130
+ let confirm
131
+ for (let attempt = 0; attempt < 2; attempt++) {
132
+ let response
133
+ try {
134
+ response = await fetchImpl(`${server.base}/api/v1${path}`, {
135
+ method,
136
+ headers: headers({ ...(body !== undefined && { 'content-type': 'application/json' }), ...(key && { 'idempotency-key': key }), ...(confirm && { 'slatebox-confirm': confirm }) }),
137
+ ...(body !== undefined && { body: JSON.stringify(body) }),
138
+ redirect: 'error',
139
+ signal: AbortSignal.timeout(120_000),
140
+ })
141
+ } catch (error) {
142
+ throw failed(error)
143
+ }
144
+ const data = await readJson(response)
145
+ if (response.ok) return data
146
+ // A call held for the person's yes (an agent's token): ask, then send it again once.
147
+ if (response.status === 409 && data?.error?.code === 'confirmation_required' && !confirm) {
148
+ const reasons = (data.error.details?.reasons || []).map((reason) => reason.rule || reason).join(', ')
149
+ if (!ctx.yes && !(ctx.interactive && (await ctx.prompt.confirm(`${server.label} asks you to agree first${reasons ? ` (${reasons})` : ''}. Agree?`, { default: false }))))
150
+ throw new InstallError(ctx.interactive ? EXIT.CANCELLED : EXIT.NEEDS_INPUT, `${server.label} needs you to agree to this step; nothing more was changed.`)
151
+ confirm = data.error.details?.confirmationId
152
+ continue
153
+ }
154
+ throw refusal(response, data)
155
+ }
156
+ throw new InstallError(EXIT.PRECONDITION, `${server.label} did not take the confirmation.`)
157
+ }
158
+ // A one-time address the server handed out, always on the server's own origin: the path is
159
+ // what counts (the server may know itself by another address than this computer does).
160
+ const here = (address) => new URL(new URL(address).pathname, server.base).href
161
+
162
+ return {
163
+ exportTeam: () => call('POST', '/team/export', {}),
164
+ startMove: () => call('POST', '/team/moves', {}),
165
+ getMove: (id) => call('GET', `/team/moves/${encodeURIComponent(id)}`),
166
+ listMoves: () => call('GET', '/team/moves'),
167
+ discardMove: (id) => call('POST', `/team/moves/${encodeURIComponent(id)}/discard`, {}),
168
+ confirmMove: (id, invite) => call('POST', `/team/moves/${encodeURIComponent(id)}/confirm`, { invite }),
169
+ inviteMoved: (id, email) => call('POST', `/team/moves/${encodeURIComponent(id)}/invite`, email ? { email } : {}),
170
+ async download(address, passphrase, path) {
171
+ let response
172
+ try {
173
+ response = await fetchImpl(here(address), { method: 'POST', headers: { 'user-agent': `slatebox-cli/${ctx.version || '0'}`, ...(passphrase && { 'slatebox-export-passphrase': passphrase }) }, redirect: 'error' })
174
+ } catch (error) {
175
+ throw failed(error)
176
+ }
177
+ if (!response.ok) throw refusal(response, await readJson(response))
178
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(path, { mode: 0o600 }))
179
+ return statSync(path).size
180
+ },
181
+ async upload(address, path, passphrase) {
182
+ let response
183
+ try {
184
+ response = await fetchImpl(here(address), {
185
+ method: 'POST',
186
+ headers: { 'user-agent': `slatebox-cli/${ctx.version || '0'}`, 'content-type': 'application/octet-stream', 'content-length': String(statSync(path).size), ...(passphrase && { 'slatebox-export-passphrase-base64': Buffer.from(passphrase, 'utf8').toString('base64url') }) },
187
+ body: Readable.toWeb(createReadStream(path)),
188
+ duplex: 'half',
189
+ redirect: 'error',
190
+ })
191
+ } catch (error) {
192
+ throw failed(error)
193
+ }
194
+ const data = await readJson(response)
195
+ if (!response.ok) throw refusal(response, data)
196
+ return data
197
+ },
198
+ }
199
+ }
200
+
201
+ // ------------------------------------------------------------------ the archive on disk
202
+
203
+ export const movesDir = (home) => join(home, 'moves')
204
+
205
+ function archivePath(ctx, teamName, encrypted) {
206
+ const dir = movesDir(ctx.home)
207
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
208
+ chmodSync(dir, 0o700)
209
+ const slug = String(teamName || 'team').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'team'
210
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..*$/, '').replace('T', '-')
211
+ return join(dir, `${stamp}-${slug}.${encrypted ? 'sbxteam' : 'sbxteam.gz'}`)
212
+ }
213
+
214
+ const keyFile = (path) => `${path}.key`
215
+ function keepPassphrase(path, passphrase) {
216
+ writeFileSync(keyFile(path), `${passphrase}\n`, { mode: 0o600 })
217
+ chmodSync(keyFile(path), 0o600)
218
+ }
219
+ function forget(path) {
220
+ rmSync(path, { force: true })
221
+ rmSync(keyFile(path), { force: true })
222
+ }
223
+
224
+ /** A passphrase for an archive file: --passphrase env:NAME | file:/path | prompt, or <file>.key beside it. */
225
+ async function passphraseFor(ctx, file) {
226
+ const ref = ctx.flags.passphrase
227
+ if (ref) {
228
+ const value = await resolveRef(ref, { env: ctx.env, ask: ctx.interactive ? () => ctx.prompt.secret('Passphrase of the archive') : undefined })
229
+ if (!value) throw new InstallError(EXIT.NEEDS_INPUT, `The passphrase (${ref}) could not be read.`)
230
+ ctx.redactor.add(value)
231
+ return value
232
+ }
233
+ if (file && existsSync(keyFile(file))) {
234
+ const value = readFileSync(keyFile(file), 'utf8').trim()
235
+ ctx.redactor.add(value)
236
+ return value
237
+ }
238
+ return null
239
+ }
240
+
241
+ // ------------------------------------------------------------------ steps
242
+
243
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
244
+
245
+ function reportLines(report = {}, into) {
246
+ const sections = report.sections || {}
247
+ const created = (name) => sections[name]?.created || 0
248
+ const lines = [
249
+ ` Team: ${report.team?.name ?? '?'}${into === 'your_team' ? ' (joins the team you own)' : ' (becomes your team)'}`,
250
+ ` Slates: ${created('slates')} presentations: ${created('presentations')} comments: ${created('comments')} files: ${report.files?.created ?? 0}`,
251
+ ` People: ${plural((report.people || []).length, 'person', 'people')} (invited only if you say so)`,
252
+ ]
253
+ if ((report.library || []).length) lines.push(` Library: ${plural(report.library.length, 'item')} (sent to the review queue there; published once that server approves)`)
254
+ const needKeys = (report.ai?.imported || []).filter((item) => item.needsKey).map((item) => item.name)
255
+ if (needKeys.length) lines.push(` Agent keys: add the keys again for ${needKeys.join(', ')} (keys never move)`)
256
+ if ((report.tokens || []).length) lines.push(` Access tokens: make ${plural(report.tokens.length, 'token')} again (tokens never move)`)
257
+ if (report.rulesSwitchedOff) lines.push(` Board rules: ${report.rulesSwitchedOff} switched off until a team admin reviews them`)
258
+ const skipped = (report.skipped || []).length
259
+ if (skipped) lines.push(` Left out: ${skipped} (see --json for each and why)`)
260
+ return lines
261
+ }
262
+
263
+ async function agree(ctx, question, { fallback = true, flag } = {}) {
264
+ if (ctx.yes) return true
265
+ if (ctx.interactive) return ctx.prompt.confirm(question, { default: fallback })
266
+ throw new InstallError(EXIT.NEEDS_INPUT, `${question} Show this to the person; once they agree, run the same command with --yes${flag ? ` (${flag})` : ''}.`, { needsConfirmation: true })
267
+ }
268
+
269
+ // A move address on the target. A move already waiting there (one at a time) is discarded
270
+ // first only with --replace-waiting, or when the person agrees at a terminal.
271
+ async function startMove(ctx, target) {
272
+ const api = moveApi(ctx, target)
273
+ try {
274
+ return await api.startMove()
275
+ } catch (error) {
276
+ if (error.details?.code !== 'move_pending') throw error
277
+ const waiting = ((await api.listMoves()).moves || []).find((move) => ['pending', 'running'].includes(move.state))
278
+ if (!waiting) throw error
279
+ const replace = ctx.flags['replace-waiting'] || (ctx.interactive && !ctx.yes && (await ctx.prompt.confirm(`A move of ${waiting.teamName ?? 'a team'} is already waiting on ${target.label}. Discard it and start again?`, { default: false })))
280
+ if (!replace) throw error
281
+ await api.discardMove(waiting.importId)
282
+ ctx.out.step('discard', 'ok', `Discarded the move that was waiting on ${target.label}`)
283
+ return api.startMove()
284
+ }
285
+ }
286
+
287
+ // Upload an archive file to a server as a move, show the report, confirm it.
288
+ async function moveFileTo(ctx, target, path, passphrase, { started = null } = {}) {
289
+ const api = moveApi(ctx, target)
290
+ const ticket = started || (await startMove(ctx, target))
291
+ const size = statSync(path).size
292
+ ctx.out.step('upload', 'start', `Sending the archive to ${target.label} (${(size / 1024 / 1024).toFixed(1)} MB)`)
293
+ const result = await api.upload(ticket.uploadUrl, path, passphrase)
294
+ ctx.out.step('upload', 'ok', result.duplicate ? `${target.label} already has this archive: continuing that move` : `${target.label} has it, waiting for your confirmation (nobody else sees it)`)
295
+ const record = result.report ? result : await api.getMove(result.importId)
296
+ ctx.out.event({ event: 'move', status: record.state, importId: result.importId, into: ticket.into, report: record.report })
297
+ if (!ctx.json) for (const line of reportLines(record.report, ticket.into)) ctx.out.say(line)
298
+ if (record.state === 'confirmed') return { importId: result.importId, state: 'confirmed', duplicate: true }
299
+
300
+ if (!(await agree(ctx, `Make it live on ${target.label} now?`))) {
301
+ ctx.out.say(`Not confirmed. It waits on ${target.label} for 14 days (move ${result.importId}); run this command again to finish, or it is discarded then.`)
302
+ return { importId: result.importId, state: 'pending' }
303
+ }
304
+ const invite = await askInvite(ctx, record.report)
305
+ const done = await api.confirmMove(result.importId, invite)
306
+ ctx.out.step('confirm', 'ok', `The team is live on ${target.label}${done.merged ? ', in the team you own' : ', and you are its owner'}`)
307
+ if (!ctx.json) invitedLines(ctx, target, result.importId, invite, done.invited, otherMembers(record.report))
308
+ return { importId: result.importId, ...done }
309
+ }
310
+
311
+ // The people besides the mover (who takes one seat) that an invitation could reach.
312
+ export const otherMembers = (report) => Math.max(0, (report?.people || []).filter((person) => person.email).length - 1)
313
+
314
+ /** Asked once: --invite / --no-invite answer ahead; a terminal asks (yes by default); a script invites nobody. */
315
+ export async function askInvite(ctx, report) {
316
+ if (ctx.flags.invite === true) return true
317
+ if (ctx.flags.invite === false) return false
318
+ const others = otherMembers(report)
319
+ if (!others || !ctx.interactive || ctx.yes) return false
320
+ return ctx.prompt.confirm(`Send invitations to the ${plural(others, 'other member')} now?`, { default: true })
321
+ }
322
+
323
+ const targetFlag = (target) => (target.kind === 'cloud' ? 'cloud' : target.base)
324
+
325
+ function invitedLines(ctx, target, importId, asked, invited = {}, others = 0) {
326
+ if (!asked) {
327
+ if (others) ctx.out.say(`Nobody was invited yet. Invite the ${plural(others, 'other member')} later with: slatebox migrate invite ${importId} --to ${targetFlag(target)}`)
328
+ return
329
+ }
330
+ const parts = [`Invitations sent: ${invited.sent ?? 0}`]
331
+ if (invited.asked?.length) parts.push(`asked to join (they already have an account there and accept signed in): ${invited.asked.join(', ')}`)
332
+ if (invited.needsConsent?.length) parts.push(`not invited, they already have an account there: ${invited.needsConsent.join(', ')}`)
333
+ if (invited.unverified?.length) parts.push(`addresses to check first (then: slatebox migrate invite ${importId} --email <address> --to ${targetFlag(target)}): ${invited.unverified.join(', ')}`)
334
+ if (invited.mailDisabled) parts.push(`${invited.mailDisabled} not sent: ${target.label} cannot send email yet`)
335
+ ctx.out.say(`${parts.join('; ')}.`)
336
+ }
337
+
338
+ /** slatebox migrate invite <move id>: invite the moved people later (or one checked address with --email). */
339
+ export async function inviteMovedPeople(ctx, { id, to }) {
340
+ if (!id) throw new InstallError(EXIT.USAGE, 'Which move? slatebox migrate invite <move id> --to cloud|<url> (the move id is printed when the move goes live).')
341
+ const target = resolveServer(ctx, to)
342
+ await tokenFor(ctx, target, `invite your team's people on ${target.label}`)
343
+ const email = typeof ctx.flags.email === 'string' && ctx.flags.email ? ctx.flags.email : null
344
+ if (!(await agree(ctx, email ? `Email ${email} an invitation from ${target.label}?` : `Email the moved people nobody invited yet, from ${target.label}?`))) throw new InstallError(EXIT.CANCELLED, 'Cancelled; nobody was emailed.')
345
+ const done = await moveApi(ctx, target).inviteMoved(id, email)
346
+ ctx.out.event({ event: 'done', importId: id, to: target.base, ...done })
347
+ if (!ctx.json) {
348
+ if (email) ctx.out.say(`${email}: ${{ sent: 'invitation sent', asked: 'asked to join (they already have an account there)', needs_consent: 'not invited, they already have an account there', mail_disabled: `not sent, ${target.label} cannot send email yet`, already_invited: 'already invited' }[done.outcome] || done.outcome}.`)
349
+ else invitedLines(ctx, target, id, true, done.now || done.invited)
350
+ }
351
+ return 0
352
+ }
353
+
354
+ // After a move is live: the archive stays unless the person says to delete it (default no).
355
+ async function afterLive(ctx, path) {
356
+ const keep = () => ctx.out.say(`The archive is kept at ${path} (encrypted; passphrase in ${keyFile(path)}). To delete it: rm ${path} ${keyFile(path)}`)
357
+ if (ctx.flags['keep-archive']) return keep()
358
+ let remove = Boolean(ctx.flags['delete-archive'])
359
+ if (!remove && ctx.interactive && !ctx.yes) remove = await ctx.prompt.confirm('Delete the archive from this computer now? It is a full copy of the team.', { default: false })
360
+ if (!remove) return keep()
361
+ forget(path)
362
+ ctx.out.step('archive', 'ok', 'Deleted the archive from this computer')
363
+ }
364
+
365
+ /** Export the source's team to an encrypted archive in ~/.slatebox/moves. */
366
+ async function exportFrom(ctx, source, { out = null, passphrase = null, keyBeside = true, ticket: given = null } = {}) {
367
+ const api = moveApi(ctx, source)
368
+ const ticket = given || (await api.exportTeam())
369
+ const secret = passphrase === null ? randomBytes(24).toString('base64url') : passphrase
370
+ if (secret) ctx.redactor.add(secret)
371
+ const path = out || archivePath(ctx, ticket.team?.name, Boolean(secret))
372
+ ctx.out.step('export', 'start', `Exporting ${ticket.team?.name ?? 'your team'} from ${source.label} (${plural(ticket.slates ?? 0, 'slate')}, ${plural(ticket.members ?? 0, 'person', 'people')})`)
373
+ if (secret && keyBeside) keepPassphrase(path, secret)
374
+ const bytes = await api.download(ticket.downloadUrl, secret, path)
375
+ ctx.out.step('export', 'ok', `Exported ${(bytes / 1024 / 1024).toFixed(1)} MB${secret ? ', encrypted' : ''}`)
376
+ return { path, passphrase: secret, team: ticket.team, members: ticket.members, slates: ticket.slates }
377
+ }
378
+
379
+ /** slatebox migrate --to cloud | import --from cloud: the whole move, source to target. */
380
+ export async function moveTeam(ctx, { from, to }) {
381
+ const source = resolveServer(ctx, from)
382
+ const target = resolveServer(ctx, to)
383
+ if (source.base === target.base) throw new InstallError(EXIT.USAGE, `The team is already on ${source.base}: give a different --from or --to.`)
384
+ await tokenFor(ctx, source, `move your team from ${source.label}`)
385
+ await tokenFor(ctx, target, `move your team to ${target.label}`)
386
+
387
+ // Ask both sides first, so a refusal (not a team admin there, not an owner here, a move
388
+ // already waiting) comes before anything is downloaded.
389
+ const sourceApi = moveApi(ctx, source)
390
+ const preflight = await sourceApi.exportTeam()
391
+ const started = await startMove(ctx, target)
392
+ const plan = {
393
+ action: 'move', from: source.base, to: target.base, team: preflight.team?.name, slates: preflight.slates, people: preflight.members,
394
+ into: started.into, leavesCopy: true,
395
+ }
396
+ ctx.out.event({ event: 'plan', ...plan })
397
+ if (!ctx.json)
398
+ ctx.out.say([
399
+ '', `Move ${preflight.team?.name ?? 'your team'} (${plural(preflight.slates ?? 0, 'slate')}, ${plural(preflight.members ?? 0, 'person', 'people')})`,
400
+ ` from ${source.base}`, ` to ${target.base}${started.into === 'your_team' ? ' (into the team you own there)' : ' (as a new team you own there)'}`,
401
+ ' What moves: slates and boards, smart components, versions, comments, presentations, files, brand kit, library items (to the review queue there), people (invited only if you say so).',
402
+ ' What stays: passwords, keys, access tokens, connected agents and integrations. The team stays on the source too until you remove it there.', '',
403
+ ].join('\n'))
404
+ if (!(await agree(ctx, 'Start the move?'))) throw new InstallError(EXIT.CANCELLED, 'Cancelled; nothing was changed.')
405
+
406
+ const exported = await exportFrom(ctx, source, { ticket: preflight })
407
+ let done
408
+ try {
409
+ done = await moveFileTo(ctx, target, exported.path, exported.passphrase, { started })
410
+ } catch (error) {
411
+ ctx.out.warn(`The archive is kept at ${exported.path} (encrypted; its passphrase is in ${keyFile(exported.path)}). Finish with: slatebox import ${exported.path} --to ${to === 'cloud' ? 'cloud' : target.base}`)
412
+ throw error
413
+ }
414
+ if (done.state === 'confirmed') await afterLive(ctx, exported.path)
415
+ else ctx.out.say(`The archive is kept at ${exported.path} (encrypted; passphrase in ${keyFile(exported.path)}).`)
416
+ ctx.out.event({ event: 'done', moved: done.state === 'confirmed', ...done, archive: existsSync(exported.path) ? exported.path : null, from: source.base, to: target.base })
417
+ if (done.state === 'confirmed' && !ctx.json) {
418
+ ctx.out.say(`\nDone. Open ${target.base} to see the team.`)
419
+ ctx.out.say('Next: add your agent keys again, make new access tokens, and reconnect integrations there. The team is still on the source until you remove it.')
420
+ }
421
+ return 0
422
+ }
423
+
424
+ /** slatebox export: a team export to a file. */
425
+ export async function exportTeamFile(ctx, { from, out }) {
426
+ const source = resolveServer(ctx, from)
427
+ await tokenFor(ctx, source, `export your team from ${source.label}`)
428
+ const passphrase = ctx.flags.passphrase ? await passphraseFor(ctx, null) : null
429
+ const exported = await exportFrom(ctx, source, { out: out || null, passphrase: passphrase ?? '', keyBeside: false })
430
+ ctx.out.event({ event: 'done', file: exported.path, encrypted: Boolean(passphrase), team: exported.team })
431
+ ctx.out.say(`Wrote ${exported.path}${passphrase ? ' (encrypted with your passphrase)' : ' (signed, not encrypted: keep it private, it holds every slate)'}.`)
432
+ return 0
433
+ }
434
+
435
+ /** slatebox import <file>: an archive file into a server, as a move. */
436
+ export async function importTeamFile(ctx, { file, to }) {
437
+ if (!existsSync(file)) throw new InstallError(EXIT.USAGE, `There is no file ${file}.`)
438
+ const target = resolveServer(ctx, to)
439
+ await tokenFor(ctx, target, `move your team to ${target.label}`)
440
+ const passphrase = await passphraseFor(ctx, file)
441
+ const done = await moveFileTo(ctx, target, file, passphrase)
442
+ ctx.out.event({ event: 'done', moved: done.state === 'confirmed', ...done, to: target.base })
443
+ if (done.state === 'confirmed' && !ctx.json) ctx.out.say(`\nDone. Open ${target.base} to see the team. Keys, access tokens and integrations are added again there.`)
444
+ return 0
445
+ }
446
+
447
+ export { CloudError }
@@ -25,6 +25,13 @@ export function settingsFor(answers, caps) {
25
25
  env.SLATEBOX_URL = answers.address.url
26
26
  // Behind an Ingress or a Gateway, HTTPS ends at the edge.
27
27
  if (k8s && answers.k8s?.route !== 'none' && answers.address.url?.startsWith('https:')) env.SLATEBOX_HTTPS = 'off'
28
+ // A team address: Cloudflare ends HTTPS and the container's cloudflared connects out with the
29
+ // tunnel token, which is a secret like any other (never in slatebox.env or a ConfigMap).
30
+ if (answers.address.team) {
31
+ require('SLATEBOX_TUNNEL_TOKEN', 'a team address (https://<name>.slatebox.team)')
32
+ env.SLATEBOX_HTTPS = 'off'
33
+ notes.push(`${answers.address.url} reaches Slatebox through an outbound Cloudflare Tunnel from the container: no DNS, no open ports, no certificates. Only 127.0.0.1 is published here.`)
34
+ }
28
35
  if (answers.acmeCa) { require('SLATEBOX_ACME_CA', 'a custom certificate authority'); env.SLATEBOX_ACME_CA = answers.acmeCa }
29
36
 
30
37
  if (answers.mail?.urlFrom) {
@@ -53,6 +60,7 @@ export function settingsFor(answers, caps) {
53
60
  if (known.has('SLATEBOX_KEY_ENCRYPTION_KEY')) secrets.SLATEBOX_KEY_ENCRYPTION_KEY = 'generate'
54
61
  else warnings.push('This image does not accept SLATEBOX_KEY_ENCRYPTION_KEY, so people cannot save their own AI and call keys on it. A newer image can.')
55
62
  Object.assign(secrets, ai.secrets)
63
+ if (answers.address.team) secrets.SLATEBOX_TUNNEL_TOKEN = 'tunnel'
56
64
  if (answers.mail?.urlFrom) secrets.SLATEBOX_MAIL_URL = answers.mail.urlFrom
57
65
 
58
66
  return { env, secrets, warnings, notes, hostGateway: ai.hostGateway }
@@ -19,7 +19,12 @@ export async function secretValues(ctx, wanted, stored = {}) {
19
19
  const generated = []
20
20
  const missing = []
21
21
  for (const [name, ref] of Object.entries(wanted)) {
22
- if (ref === 'generate') {
22
+ if (ref === 'tunnel') {
23
+ // The team address's tunnel token: fetched from Slatebox Cloud for this run, or the one stored.
24
+ const value = ctx.tunnelToken ?? stored[name]
25
+ if (value) values[name] = value
26
+ else missing.push({ field: name, question: 'the team address has no tunnel token yet: run slatebox install to sign in and fetch it', flag: '--team-address <name>', default: null })
27
+ } else if (ref === 'generate') {
23
28
  if (stored[name]) values[name] = stored[name]
24
29
  else {
25
30
  values[name] = generateKek()
package/src/secrets.mjs CHANGED
@@ -10,7 +10,7 @@ export function generateKek() {
10
10
  return randomBytes(32).toString('base64')
11
11
  }
12
12
 
13
- export const REF = /^(env:[A-Za-z_][A-Za-z0-9_]*|file:.+|prompt|none|stored)$/
13
+ export const REF = /^(env:[A-Za-z_][A-Za-z0-9_]*|file:.+|prompt|none|stored|tunnel)$/
14
14
 
15
15
  // Prefixes that API keys and tokens start with (and AWS access key IDs).
16
16
  const KEY_PREFIX = /^(gsk_|ghp_|gho_|ghu_|ghs_|ghr_|github_pat_|glpat|hf_|r8_|xox[abprs]|sk_|rk_|pk_live|pk_test|nvapi|AKIA[0-9A-Z]{12}|ASIA[0-9A-Z]{12})/
@@ -39,7 +39,7 @@ export function isRef(value) {
39
39
  */
40
40
  export async function resolveRef(ref, { env = process.env, ask } = {}) {
41
41
  if (!isRef(ref)) throw new InstallError(2, 'A key must be given as a reference (env:NAME, file:/path or prompt), never as its value.')
42
- if (ref === 'none' || ref === 'stored') return undefined
42
+ if (ref === 'none' || ref === 'stored' || ref === 'tunnel') return undefined
43
43
  if (ref === 'prompt') return ask ? ask() : undefined
44
44
  if (ref.startsWith('env:')) {
45
45
  const value = env[ref.slice(4)]
@@ -88,6 +88,10 @@ export function parseEnvFile(text) {
88
88
  // ------------------------------------------------------------ redaction
89
89
 
90
90
  const MIN_SECRET = 6
91
+ // Shapes that are secrets whatever their value: a team-address install credential, a
92
+ // Cloudflare tunnel connector token (base64 of {"a":…,"t":…,"s":…}), and a setup link's token.
93
+ // A self-hosted server's one-time setup link (/setup/<32 bytes base64url>) is as good as an admin password.
94
+ export const SECRET_SHAPES = [/sbxi_[A-Za-z0-9]+_[A-Za-z0-9_-]+/g, /eyJhIjoi[A-Za-z0-9+/_-]{16,}={0,2}/g, /(?<=\/setup\/)[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g]
91
95
 
92
96
  /** Every secret the installer has seen is replaced by *** in anything it prints or logs. */
93
97
  export class Redactor {
@@ -110,6 +114,7 @@ export class Redactor {
110
114
 
111
115
  redact(text) {
112
116
  let out = String(text)
117
+ for (const shape of SECRET_SHAPES) out = out.replace(shape, '***')
113
118
  // Longest first, so a value that contains another is removed whole.
114
119
  for (const value of [...this.values].sort((a, b) => b.length - a.length)) {
115
120
  if (out.includes(value)) out = out.split(value).join('***')
@@ -0,0 +1,88 @@
1
+ // The first admin. Nobody can sign up on a new self-hosted Slatebox until its one-time setup link
2
+ // is used: the person who opens it creates the first account, the server administrator and the
3
+ // owner of the first team. The image makes the link (`slatebox setup-link` in the container: single
4
+ // use, 24 hours, only its hash kept, a new one replaces the old).
5
+ //
6
+ // The link is as good as an admin password, so the installer prints it only to a terminal, on
7
+ // stderr, never into --json or a pipe (`slatebox setup-link --force-stdout` is the one way to pipe
8
+ // it), and its token is added to the redactor the moment it is known.
9
+
10
+ const lastJson = text => {
11
+ try { return JSON.parse(String(text || '').trim().split('\n').pop()) } catch { return null }
12
+ }
13
+
14
+ /** Whether this run may print a setup link: a person at a terminal, not --json. */
15
+ export const showsSetupLink = ctx => Boolean(ctx.tty) && !ctx.json
16
+
17
+ /**
18
+ * The image's setup state through exec(args) (docker exec or kubectl exec of the in-image
19
+ * `slatebox`): { setUp, linkExpiresAt }, or null when the image has no setup links (before 0.2.0).
20
+ */
21
+ export async function setupState(exec) {
22
+ const result = await exec(['setup-link', '--check'])
23
+ if (result.code !== 0) return null
24
+ const state = lastJson(result.stdout)
25
+ return state && typeof state.setUp === 'boolean' ? state : null
26
+ }
27
+
28
+ /** A fresh link ({ url, expiresAt }), { setUp: true } when there is nothing to set up, or { error }. */
29
+ export async function makeSetupLink(ctx, exec) {
30
+ const result = await exec(['setup-link', '--json'])
31
+ if (result.code === 3) return { setUp: true }
32
+ const link = result.code === 0 ? lastJson(result.stdout) : null
33
+ if (!link?.url) return { error: String(result.stderr || '').trim().split('\n').pop() || `exit ${result.code}` }
34
+ const token = link.url.split('/setup/')[1]
35
+ ctx.redactor.add(token)
36
+ return link
37
+ }
38
+
39
+ /**
40
+ * After an install or change is healthy: when the server still waits for its first admin, make a
41
+ * link if this run may print it (ctx.setupLink = { url, expiresAt }), else note that one is
42
+ * needed (ctx.setupLink = { pending: true }). Images without setup links are left alone.
43
+ */
44
+ export async function firstAdmin(ctx, exec) {
45
+ const state = await setupState(exec)
46
+ if (!state) return false
47
+ if (state.setUp) return true
48
+ if (!showsSetupLink(ctx)) {
49
+ ctx.setupLink = { pending: true }
50
+ return true
51
+ }
52
+ const link = await makeSetupLink(ctx, exec)
53
+ if (link.url) ctx.setupLink = link
54
+ else if (!link.setUp) {
55
+ ctx.out.step('setup', 'warn', `The one-time setup link could not be made (${link.error}). Run slatebox setup-link to try again.`)
56
+ ctx.setupLink = { pending: true }
57
+ }
58
+ return true
59
+ }
60
+
61
+ /**
62
+ * A run that changed nothing (a re-run, an upgrade with no newer image) on a server still waiting
63
+ * for its first admin: say how to get a link, but make none, since a new link would silently end
64
+ * the one the person may already hold (the same rule as `slatebox status`).
65
+ */
66
+ export async function stillWaiting(ctx, exec) {
67
+ const state = await setupState(exec)
68
+ if (state && !state.setUp) ctx.setupLink = { pending: true }
69
+ }
70
+
71
+ const command = name => `slatebox setup-link${name === 'slatebox' ? '' : ` --name ${name}`}`
72
+
73
+ /**
74
+ * The closing lines about the first admin. A line { terminal: text } carries the link itself and is
75
+ * written straight to the terminal (stderr), past the redactor that would hide it.
76
+ */
77
+ export function setupLines(ctx, name) {
78
+ const link = ctx.setupLink
79
+ if (!link) return []
80
+ if (link.pending) {
81
+ return ['', 'Nobody can sign up until the first admin exists. Get the one-time setup link at a terminal:',
82
+ ` ${command(name)}`, 'Open it to create the first account: the server administrator and the owner of the first team.']
83
+ }
84
+ return ['', 'Create the first account (the server administrator) with this one-time setup link.',
85
+ 'It works once and expires in 24 hours; nobody can sign up before it is used:',
86
+ { terminal: ` ${link.url} (printed to this terminal only)` },
87
+ `Lost it? ${command(name)} prints a new one and ends this one.`]
88
+ }