slatebox 0.0.0-stage → 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 }
package/src/output.mjs ADDED
@@ -0,0 +1,51 @@
1
+ // Everything the installer prints goes through here, and through the redactor.
2
+ // With --json (or in agent mode) stdout carries one JSON event per line and
3
+ // people's text goes to stderr; otherwise people's text goes to stdout.
4
+
5
+ export class Output {
6
+ /**
7
+ * @param {{stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, json: boolean, debug: boolean, redactor: import('./secrets.mjs').Redactor}} options
8
+ */
9
+ constructor({ stdout, stderr, json, debug, redactor }) {
10
+ this.stdout = stdout
11
+ this.stderr = stderr
12
+ this.json = json
13
+ this.debugOn = debug
14
+ this.redactor = redactor
15
+ }
16
+
17
+ #text(stream, text) {
18
+ stream.write(this.redactor.redact(text) + (text.endsWith('\n') ? '' : '\n'))
19
+ }
20
+
21
+ /** A line for people. */
22
+ say(text = '') {
23
+ this.#text(this.json ? this.stderr : this.stdout, text)
24
+ }
25
+
26
+ /** A warning for people, always on stderr. */
27
+ warn(text) {
28
+ this.#text(this.stderr, `! ${text}`)
29
+ }
30
+
31
+ debug(text) {
32
+ if (this.debugOn) this.#text(this.stderr, `[debug] ${text}`)
33
+ }
34
+
35
+ /** A machine-readable event: {"event":"plan"|"step"|"done"|"error", ...}. Only with --json. */
36
+ event(event) {
37
+ if (!this.json) return
38
+ this.stdout.write(this.redactor.redact(JSON.stringify(event)) + '\n')
39
+ }
40
+
41
+ /** A step in progress, for both audiences. */
42
+ step(id, status, detail = '') {
43
+ this.event({ event: 'step', id, status, ...(detail ? { detail } : {}) })
44
+ if (!this.json || this.debugOn) {
45
+ const mark = { start: '…', ok: '✓', skip: '–', warn: '!', fail: '✗' }[status] || '·'
46
+ this.#text(this.json ? this.stderr : this.stdout, `${mark} ${detail || id}`)
47
+ } else if (status === 'fail' || status === 'warn') {
48
+ this.#text(this.stderr, `${status === 'fail' ? '✗' : '!'} ${detail || id}`)
49
+ }
50
+ }
51
+ }
package/src/plan.mjs ADDED
@@ -0,0 +1,51 @@
1
+ // The plan: everything an install will write, run and create, shown before
2
+ // anything changes. It names where secrets go, never what they are.
3
+
4
+ /**
5
+ * @typedef {{
6
+ * action: 'install'|'upgrade'|'change'|'uninstall'|'restore'|'export'|'nothing',
7
+ * target: string, name: string, where: string, address: string|null,
8
+ * image?: {ref: string, pinned: string, previous?: string},
9
+ * files: {path: string, note?: string}[], commands: string[], objects: string[],
10
+ * ports: string[], secretsLocation: string|null, warnings: string[], notes: string[],
11
+ * changes: string[],
12
+ * }} Plan
13
+ */
14
+
15
+ export function emptyPlan(fields) {
16
+ return { files: [], commands: [], objects: [], ports: [], secretsLocation: null, warnings: [], notes: [], changes: [], ...fields }
17
+ }
18
+
19
+ export function formatPlan(plan) {
20
+ const lines = []
21
+ const title = {
22
+ install: `Plan: install Slatebox "${plan.name}" on ${plan.where}`,
23
+ upgrade: `Plan: upgrade Slatebox "${plan.name}" on ${plan.where}`,
24
+ change: `Plan: change Slatebox "${plan.name}" on ${plan.where}`,
25
+ uninstall: `Plan: remove Slatebox "${plan.name}" from ${plan.where}`,
26
+ restore: `Plan: restore Slatebox "${plan.name}" on ${plan.where} from a backup`,
27
+ export: `Plan: write the files for Slatebox "${plan.name}"`,
28
+ nothing: `Slatebox "${plan.name}" on ${plan.where}: nothing to change`,
29
+ }[plan.action]
30
+ lines.push(title, '')
31
+ if (plan.address) lines.push(` Address: ${plan.address}`)
32
+ if (plan.image) {
33
+ lines.push(` Image: ${plan.image.ref}`)
34
+ if (plan.image.pinned !== plan.image.ref) lines.push(` pinned as ${plan.image.pinned}`)
35
+ if (plan.image.previous && plan.image.previous !== plan.image.pinned) lines.push(` replacing ${plan.image.previous}`)
36
+ }
37
+ if (plan.ports.length) lines.push(` Ports: ${plan.ports.join(', ')}`)
38
+ if (plan.secretsLocation) lines.push(` Secrets: ${plan.secretsLocation}`)
39
+ const section = (label, items) => {
40
+ if (!items.length) return
41
+ lines.push('', ` ${label}:`)
42
+ for (const item of items) lines.push(` - ${item}`)
43
+ }
44
+ section('Changes', plan.changes)
45
+ section('Files', plan.files.map(file => (file.note ? `${file.path} (${file.note})` : file.path)))
46
+ section('Commands', plan.commands)
47
+ section('Objects', plan.objects)
48
+ section('Notes', plan.notes)
49
+ section('Warnings', plan.warnings)
50
+ return lines.join('\n')
51
+ }
package/src/prompt.mjs ADDED
@@ -0,0 +1,87 @@
1
+ // Questions for people: short, each with a default that Enter accepts.
2
+ // Only used when there is a person at a terminal; agents get exit code 3 and
3
+ // the list of questions instead.
4
+ import { createInterface } from 'node:readline'
5
+ import { EXIT, InstallError } from './errors.mjs'
6
+
7
+ export function createPrompt({ input, output }) {
8
+ // One reader for the whole run, with lines queued, so answers typed (or
9
+ // piped) ahead of their question are not lost.
10
+ const rl = createInterface({ input, terminal: false })
11
+ const queue = []
12
+ const waiting = []
13
+ let closed = false
14
+ rl.on('line', line => (waiting.length ? waiting.shift()(line) : queue.push(line)))
15
+ rl.on('close', () => { closed = true; while (waiting.length) waiting.shift()(null) })
16
+ const nextLine = () => (queue.length ? Promise.resolve(queue.shift()) : closed ? Promise.resolve(null) : new Promise(resolve => waiting.push(resolve)))
17
+
18
+ async function line(prompt) {
19
+ output.write(prompt)
20
+ const answer = await nextLine()
21
+ if (answer === null) throw new InstallError(EXIT.CANCELLED, 'Cancelled.')
22
+ return answer.trim()
23
+ }
24
+
25
+ return {
26
+ async text(question, { default: fallback = '', validate, optional = false } = {}) {
27
+ for (;;) {
28
+ const answer = (await line(`? ${question}${fallback ? ` (${fallback})` : optional ? ' (Enter skips)' : ''}: `)) || fallback
29
+ if (!answer && optional) return ''
30
+ const problem = !answer ? 'An answer is needed.' : validate?.(answer)
31
+ if (!problem) return answer
32
+ output.write(` ${problem}\n`)
33
+ }
34
+ },
35
+ async choose(question, choices, { default: fallback = null } = {}) {
36
+ output.write(`? ${question}\n`)
37
+ choices.forEach((choice, index) => output.write(` ${index + 1}) ${choice.label}${choice.value === fallback ? ' [default]' : ''}\n`))
38
+ for (;;) {
39
+ const answer = await line(` Choose 1-${choices.length}${fallback ? ' (Enter for the default)' : ''}: `)
40
+ if (!answer && fallback) return fallback
41
+ const index = Number(answer) - 1
42
+ if (Number.isInteger(index) && choices[index]) return choices[index].value
43
+ const named = choices.find(choice => choice.value === answer)
44
+ if (named) return named.value
45
+ output.write(' Type the number of a choice.\n')
46
+ }
47
+ },
48
+ async confirm(question, { default: fallback = false } = {}) {
49
+ const answer = (await line(`? ${question} [${fallback ? 'Y/n' : 'y/N'}]: `)).toLowerCase()
50
+ if (!answer) return fallback
51
+ return answer === 'y' || answer === 'yes'
52
+ },
53
+ /** Hidden input: nothing is echoed while the key is typed. */
54
+ async secret(question) {
55
+ output.write(`? ${question}: `)
56
+ const tty = input.isTTY && typeof input.setRawMode === 'function'
57
+ if (!tty) {
58
+ const answer = await nextLine()
59
+ output.write('\n')
60
+ return answer?.trim() || undefined
61
+ }
62
+ rl.pause()
63
+ input.setRawMode(true)
64
+ input.resume()
65
+ let value = ''
66
+ try {
67
+ await new Promise((resolve, reject) => {
68
+ const onData = chunk => {
69
+ for (const char of chunk.toString('utf8')) {
70
+ if (char === '\r' || char === '\n') { input.off('data', onData); resolve(); return }
71
+ if (char === '\u0003') { input.off('data', onData); reject(new InstallError(EXIT.CANCELLED, 'Cancelled.')); return }
72
+ if (char === '\u007f') value = value.slice(0, -1)
73
+ else value += char
74
+ }
75
+ }
76
+ input.on('data', onData)
77
+ })
78
+ } finally {
79
+ input.setRawMode(false)
80
+ output.write('\n')
81
+ rl.resume()
82
+ }
83
+ return value || undefined
84
+ },
85
+ close: () => rl.close(),
86
+ }
87
+ }