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/README.md +95 -15
- package/package.json +5 -2
- package/src/agent-prompt.mjs +18 -3
- package/src/answers.mjs +29 -5
- package/src/cli.mjs +306 -72
- package/src/cloud.mjs +261 -0
- package/src/image.mjs +5 -2
- package/src/interview.mjs +30 -1
- package/src/move.mjs +447 -0
- package/src/render/settings.mjs +8 -0
- package/src/secret-values.mjs +6 -1
- package/src/secrets.mjs +7 -2
- package/src/setup-link.mjs +88 -0
- package/src/targets/address.mjs +281 -0
- package/src/targets/docker.mjs +116 -4
- package/src/targets/k8s.mjs +41 -2
package/src/cli.mjs
CHANGED
|
@@ -1,57 +1,88 @@
|
|
|
1
|
-
// `slatebox`:
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
|
|
6
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
7
|
-
import {
|
|
8
|
-
import { fileURLToPath } from 'node:url'
|
|
1
|
+
// `slatebox`: the one Slatebox command. It installs and runs your own Slatebox (with a free team
|
|
2
|
+
// address, your own domain, or this computer only), and runs agent scripts against any Slatebox
|
|
3
|
+
// (exec, describe and the MCP server, from the slatebox-mcp package, in this same process).
|
|
4
|
+
// main() takes its streams and environment as arguments and returns the exit code, so tests run
|
|
5
|
+
// it in process.
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
9
8
|
import { parseArgs } from 'node:util'
|
|
10
9
|
import { AGENT_PROMPT } from './agent-prompt.mjs'
|
|
11
10
|
import { aiEnv, aiTestScript, normalizeProvider } from './ai/settings-adapter.mjs'
|
|
12
11
|
import { ANSWER_FLAGS, collect, flagsFromEnv, parseProviderSpec, resolveAnswers } from './answers.mjs'
|
|
12
|
+
import { CREDENTIALS_FILE, readCredentials, teamHost } from './cloud.mjs'
|
|
13
13
|
import { EXIT, InstallError } from './errors.mjs'
|
|
14
14
|
import { interview } from './interview.mjs'
|
|
15
15
|
import { Output } from './output.mjs'
|
|
16
16
|
import { DEFAULT_IMAGE, DEFAULT_REPOSITORY, isTag } from './image.mjs'
|
|
17
17
|
import { formatPlan } from './plan.mjs'
|
|
18
18
|
import { createPrompt } from './prompt.mjs'
|
|
19
|
-
import { listRecords, readRecord, slateboxHome, writeRecord } from './record.mjs'
|
|
19
|
+
import { installDir, listRecords, readRecord, slateboxHome, writeRecord } from './record.mjs'
|
|
20
20
|
import { makeRunner } from './runner.mjs'
|
|
21
21
|
import { Redactor } from './secrets.mjs'
|
|
22
|
-
import {
|
|
22
|
+
import { finishRename, releaseTeamAddress, renameTeamAddress, rotateTeamAddress, teamStatus } from './targets/address.mjs'
|
|
23
|
+
import { applyDocker, backupDocker, defaultLocalPort, execNode, LOG_SERVICES, logsDocker, readSecretDocker, restoreDocker, setupLinkDocker, statusDocker, uninstallDocker } from './targets/docker.mjs'
|
|
23
24
|
import { exportFiles } from './targets/export.mjs'
|
|
24
|
-
import { applyK8s, backupK8s, execNodeK8s, readSecretK8s, restoreK8s, statusK8s, uninstallK8s } from './targets/k8s.mjs'
|
|
25
|
+
import { applyK8s, backupK8s, execNodeK8s, readSecretK8s, restoreK8s, setupLinkK8s, statusK8s, uninstallK8s } from './targets/k8s.mjs'
|
|
26
|
+
import { setupLines } from './setup-link.mjs'
|
|
27
|
+
import { exportTeamFile, importTeamFile, inviteMovedPeople, moveTeam } from './move.mjs'
|
|
25
28
|
import { parse as parseYaml } from './yaml.mjs'
|
|
26
29
|
|
|
27
30
|
const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
28
31
|
|
|
29
|
-
|
|
32
|
+
// Every word `slatebox` takes. An unknown word is exit 2 with a suggestion; nothing is fetched or
|
|
33
|
+
// run for it.
|
|
34
|
+
export const COMMANDS = Object.freeze([
|
|
35
|
+
{ name: 'install', usage: 'install [--team-address <name> | --domain <host> | --local] [target]', summary: 'install, or change, your own Slatebox (safe to run again)' },
|
|
36
|
+
{ name: 'status', usage: 'status [--json]', summary: 'health, address, tunnel, setup, version, AI and SSO, last backup' },
|
|
37
|
+
{ name: 'setup-link', usage: 'setup-link', summary: 'a new one-time link that creates the first admin (ends the last one)' },
|
|
38
|
+
{ name: 'logs', usage: 'logs [-f] [--service app|relay|mongo|proxy|tunnel|sso] [--since 10m]', summary: 'the container\'s log' },
|
|
39
|
+
{ name: 'upgrade', usage: 'upgrade [--to <image>]', summary: 'back up, upgrade, check health, roll back on failure' },
|
|
40
|
+
{ name: 'rename', usage: 'rename <new-name>', summary: 'move the team address to https://<new-name>.slatebox.team' },
|
|
41
|
+
{ name: 'address', usage: 'address [release | rotate]', summary: 'the team address: show it, give it back, or get a new tunnel token' },
|
|
42
|
+
{ name: 'uninstall', usage: 'uninstall [--keep-address] [--delete-data --confirm <name>]', summary: 'stop and remove (alias: remove); data is kept unless you say otherwise' },
|
|
43
|
+
{ name: 'backup', usage: 'backup [--to <dir>]', summary: 'a complete backup now' },
|
|
44
|
+
{ name: 'restore', usage: 'restore <file.gz>', summary: 'replace everything with a backup' },
|
|
45
|
+
{ name: 'ai', usage: 'ai list | add "<spec>" | remove <id> | use <id> | off | test [id]', summary: 'agent providers for this install' },
|
|
46
|
+
{ name: 'migrate', usage: 'migrate --to cloud | --from cloud [--invite|--no-invite] [--keep-archive|--delete-archive] | migrate invite <move id> --to cloud|<url>', summary: 'move your team between your own Slatebox and Slatebox Cloud' },
|
|
47
|
+
{ name: 'import', usage: 'import --from cloud | <file> [--to cloud|<url>]', summary: 'bring a team in (from Slatebox Cloud, or a team export file)' },
|
|
48
|
+
{ name: 'export', usage: 'export [--from cloud|<url>] [--out <file>]', summary: 'a team export file of everything your team owns' },
|
|
49
|
+
{ name: 'secrets', usage: 'secrets path | reveal <NAME>', summary: 'where secrets are kept; reveal prints one to a terminal' },
|
|
50
|
+
{ name: 'installs', usage: 'installs', summary: 'the installs this computer made' },
|
|
51
|
+
{ name: 'plan', usage: 'plan [install flags]', summary: 'print the plan only; changes nothing' },
|
|
52
|
+
{ name: 'agent-prompt', usage: 'agent-prompt', summary: 'instructions for a coding agent to install it for you' },
|
|
53
|
+
{ name: 'exec', usage: 'exec <file> | - | -e <code> [--preview] [--remote]', summary: 'run an agent script against your Slatebox (SLATEBOX_API_TOKEN)' },
|
|
54
|
+
{ name: 'describe', usage: 'describe [query] [--method <name>]', summary: 'the methods an exec script can call' },
|
|
55
|
+
{ name: 'mcp', usage: 'mcp [--http --port <n>]', summary: 'start the MCP server (the same as slatebox-mcp)' },
|
|
56
|
+
{ name: 'help', usage: 'help', summary: 'this text' },
|
|
57
|
+
])
|
|
58
|
+
const ALIASES = Object.freeze({ remove: 'uninstall' })
|
|
59
|
+
const SLATE_COMMANDS = new Set(['exec', 'describe', 'mcp'])
|
|
60
|
+
const COMMAND_NAMES = new Set(COMMANDS.map(command => command.name))
|
|
30
61
|
|
|
31
|
-
|
|
62
|
+
const commandList = () => COMMANDS.map(({ usage, summary }) => {
|
|
63
|
+
const left = ` slatebox ${usage}`
|
|
64
|
+
return left.length < 40 ? `${left.padEnd(41)}${summary}` : `${left}\n${' '.repeat(41)}${summary}`
|
|
65
|
+
}).join('\n')
|
|
32
66
|
|
|
33
|
-
|
|
34
|
-
|
|
67
|
+
export const HELP = `slatebox ${PKG.version}: run your own Slatebox, and work with any Slatebox from a script.
|
|
68
|
+
|
|
69
|
+
npx slatebox install asks where your team opens it (a free team address at
|
|
70
|
+
https://<name>.slatebox.team, your own domain, or this
|
|
71
|
+
computer only), shows a plan, installs
|
|
72
|
+
npx slatebox install --team-address acme --yes the same without questions (you still sign
|
|
73
|
+
in once in your browser to claim the address)
|
|
74
|
+
npx slatebox install --domain boards.example.com your own domain (Caddy HTTPS, or --url and your proxy)
|
|
35
75
|
npx slatebox --dry-run the questions and the plan only; nothing changes
|
|
36
76
|
npx slatebox agent-prompt instructions for a coding agent to do it for you
|
|
37
77
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
slatebox plan [same flags] print the plan only; changes nothing
|
|
41
|
-
slatebox status address, version, health, AI and SSO, last backup
|
|
42
|
-
slatebox upgrade [--to <image>] fetch the install's image tag again (or --to), back up,
|
|
43
|
-
upgrade, check health, roll back on failure
|
|
44
|
-
slatebox backup [--to <dir>] a complete backup now
|
|
45
|
-
slatebox restore <file.gz>
|
|
46
|
-
slatebox uninstall [--delete-data --confirm <name>] data is kept unless you say otherwise
|
|
47
|
-
slatebox ai list | add "<spec>" | remove <id> | use <id> | off | test [id]
|
|
48
|
-
slatebox secrets path | reveal <NAME> where secrets are kept; reveal prints one to a terminal
|
|
49
|
-
slatebox installs the installs this computer made
|
|
50
|
-
slatebox agent-prompt
|
|
78
|
+
Commands:
|
|
79
|
+
${commandList()}
|
|
51
80
|
|
|
52
81
|
Install flags (each also SLATEBOX_INSTALL_<NAME> in the environment; flags win,
|
|
53
82
|
then --answers, then the environment. Consent never comes from the environment:
|
|
54
83
|
--yes, --install-docker and --new-encryption-key are typed each time):
|
|
84
|
+
--team-address <name> claim https://<name>.slatebox.team (3-32 characters: a-z, 0-9, hyphens)
|
|
85
|
+
--local this computer only (http://localhost), no team address
|
|
55
86
|
--name <id> several installs can live side by side (default slatebox)
|
|
56
87
|
--answers <file> YAML or JSON answers (see agent-prompt); never holds secrets
|
|
57
88
|
--target local|ssh|k8s|export --host user@host --ssh-port N --identity <key>
|
|
@@ -72,15 +103,28 @@ then --answers, then the environment. Consent never comes from the environment:
|
|
|
72
103
|
--new-encryption-key replace a lost SLATEBOX_KEY_ENCRYPTION_KEY over existing data
|
|
73
104
|
(keys people saved become unreadable; refused without it)
|
|
74
105
|
|
|
106
|
+
Moving a team (slatebox migrate --to cloud | --from cloud, import, export): your own server's
|
|
107
|
+
address is --from/--to <url>, SLATEBOX_BASE_URL, or the install made here (--name); its access
|
|
108
|
+
token is SLATEBOX_API_TOKEN (asked for at a terminal). Slatebox Cloud signs you in with a code in
|
|
109
|
+
your browser (it asks to "move your team"), or takes SLATEBOX_CLOUD_TOKEN. Nothing is visible on
|
|
110
|
+
the other side until you confirm. Then you are asked once to send invitations to the other members
|
|
111
|
+
(yes by default; --invite / --no-invite answer ahead; a script sends none without --invite; later:
|
|
112
|
+
slatebox migrate invite <move id> --to cloud|<url>), and whether to delete the archive from this
|
|
113
|
+
computer (no by default; --delete-archive, --keep-archive). --replace-waiting discards a move
|
|
114
|
+
already waiting.
|
|
115
|
+
|
|
116
|
+
Team addresses: the sign-in is a code you approve in your browser (Slatebox Cloud), every time
|
|
117
|
+
a name is claimed, moved or reconnected. SLATEBOX_CLOUD_URL or --cloud-url points at another
|
|
118
|
+
Slatebox Cloud. The install credential stays in
|
|
119
|
+
~/.slatebox/installs/<name>/credentials.json (mode 0600).
|
|
120
|
+
|
|
75
121
|
Global: --yes (after a person approved the plan) --json (NDJSON events on stdout)
|
|
76
122
|
--agent auto|yes|no --debug --health-timeout <seconds> (default 600)
|
|
77
123
|
|
|
78
124
|
Exit codes: 0 done or nothing to change; 2 bad flags or answers; 3 an answer or a
|
|
79
125
|
confirmation is needed and nobody can be asked; 4 a precondition failed;
|
|
80
126
|
5 the change failed and was rolled back; 6 the rollback failed too (commands
|
|
81
|
-
attached); 7 cancelled.
|
|
82
|
-
|
|
83
|
-
Slates (from slatebox-mcp, fetched when first used): slatebox exec | describe
|
|
127
|
+
attached); 7 cancelled. (exec has its own: slatebox exec --help.)
|
|
84
128
|
`
|
|
85
129
|
|
|
86
130
|
// Agents that announce themselves in the environment.
|
|
@@ -97,6 +141,10 @@ function parse(argv) {
|
|
|
97
141
|
answers: { type: 'string' }, home: { type: 'string' }, 'image-archive': { type: 'string' }, 'health-timeout': { type: 'string' },
|
|
98
142
|
'dry-run': { type: 'boolean' }, 'show-secrets': { type: 'boolean' }, 'delete-data': { type: 'boolean' }, confirm: { type: 'string' },
|
|
99
143
|
to: { type: 'string' }, 'force-stdout': { type: 'boolean' }, 'new-encryption-key': { type: 'boolean' },
|
|
144
|
+
'cloud-url': { type: 'string' }, 'keep-address': { type: 'boolean' }, follow: { type: 'boolean', short: 'f' },
|
|
145
|
+
service: { type: 'string' }, since: { type: 'string' },
|
|
146
|
+
from: { type: 'string' }, out: { type: 'string' }, invite: { type: 'boolean' }, 'keep-archive': { type: 'boolean' },
|
|
147
|
+
passphrase: { type: 'string' }, 'replace-waiting': { type: 'boolean' }, 'delete-archive': { type: 'boolean' }, email: { type: 'string' },
|
|
100
148
|
}
|
|
101
149
|
for (const [flag, type] of Object.entries(ANSWER_FLAGS)) {
|
|
102
150
|
options[flag] = type === 'multiple' ? { type: 'string', multiple: true } : { type }
|
|
@@ -104,35 +152,68 @@ function parse(argv) {
|
|
|
104
152
|
return parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true, strict: true })
|
|
105
153
|
}
|
|
106
154
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
155
|
+
/** The closest command to a mistyped word, for "did you mean". */
|
|
156
|
+
export function suggest(word) {
|
|
157
|
+
const distance = (a, b) => {
|
|
158
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i)
|
|
159
|
+
for (let i = 1; i <= a.length; i++) {
|
|
160
|
+
let previous = row[0]
|
|
161
|
+
row[0] = i
|
|
162
|
+
for (let j = 1; j <= b.length; j++) {
|
|
163
|
+
const current = row[j]
|
|
164
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1))
|
|
165
|
+
previous = current
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return row[b.length]
|
|
169
|
+
}
|
|
170
|
+
const names = [...COMMAND_NAMES, ...Object.keys(ALIASES)]
|
|
171
|
+
const best = names.map(name => ({ name, d: distance(word.toLowerCase(), name) })).sort((a, b) => a.d - b.d)[0]
|
|
172
|
+
return best && best.d <= Math.max(1, Math.floor(word.length / 3)) ? best.name : null
|
|
118
173
|
}
|
|
119
174
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
175
|
+
// exec, describe and mcp are slatebox-mcp's, a dependency of this package, run in this process.
|
|
176
|
+
async function slateCommand(argv, io) {
|
|
177
|
+
let commands
|
|
178
|
+
try {
|
|
179
|
+
commands = argv[0] === 'mcp' ? await import('slatebox-mcp/mcp') : await import('slatebox-mcp/commands')
|
|
180
|
+
} catch (error) {
|
|
181
|
+
io.stderr.write(`slatebox ${argv[0]} needs the slatebox-mcp package next to this one, and it could not be loaded (${error.code || error.message}). Reinstall: npm i -g slatebox\n`)
|
|
182
|
+
return EXIT.PRECONDITION
|
|
183
|
+
}
|
|
184
|
+
if (argv[0] === 'mcp') {
|
|
185
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
186
|
+
io.stdout.write('Usage: slatebox mcp [--base-url ORIGIN] [--typed-tools on|off] [--http [--port N]]\nThe same as slatebox-mcp: SLATEBOX_API_TOKEN is your personal access token.\n')
|
|
187
|
+
return 0
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
await commands.startMcp(argv.slice(1), { env: io.env, stderr: io.stderr })
|
|
191
|
+
return 0
|
|
192
|
+
} catch (error) {
|
|
193
|
+
io.stderr.write(`Slatebox MCP could not start: ${error.message}\n`)
|
|
194
|
+
return error.name === 'UsageError' || error.constructor?.name === 'UsageError' ? EXIT.USAGE : 1
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return commands.run(argv, { env: io.env, stdin: io.stdin, stdout: io.stdout, stderr: io.stderr, name: 'slatebox' })
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Plain `slatebox`: the commands, and at a terminal an offer to install. Never installs unasked. */
|
|
201
|
+
async function bare(io) {
|
|
202
|
+
const tty = Boolean(io.stdin.isTTY && io.stderr.isTTY) && !detectAgent(io.env)
|
|
203
|
+
const text = `slatebox ${PKG.version}: one container with the app, live editing and the database.\n\nCommands:\n${commandList()}\n\nMore: slatebox help\n`
|
|
204
|
+
if (!tty) {
|
|
205
|
+
io.stdout.write(text)
|
|
206
|
+
return 0
|
|
207
|
+
}
|
|
208
|
+
io.stderr.write(`${text}\n`)
|
|
209
|
+
const prompt = createPrompt({ input: io.stdin, output: io.stderr })
|
|
210
|
+
let yes
|
|
211
|
+
try { yes = await prompt.confirm('Install Slatebox on this computer?', { default: true }) } catch { yes = false } finally { prompt.close() }
|
|
212
|
+
if (!yes) {
|
|
213
|
+
io.stderr.write('Nothing was changed. When you are ready: npx slatebox install\n')
|
|
214
|
+
return 0
|
|
215
|
+
}
|
|
216
|
+
return main(['install'], io)
|
|
136
217
|
}
|
|
137
218
|
|
|
138
219
|
function readAnswersFile(path) {
|
|
@@ -158,8 +239,17 @@ export async function main(argv, io = {}) {
|
|
|
158
239
|
io = { env: process.env, stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, ...io }
|
|
159
240
|
io.platform ??= process.platform
|
|
160
241
|
io.cwd ??= process.cwd()
|
|
242
|
+
if (!argv.length) return bare(io)
|
|
243
|
+
if (ALIASES[argv[0]]) argv = [ALIASES[argv[0]], ...argv.slice(1)]
|
|
161
244
|
const [command] = argv
|
|
162
|
-
if (
|
|
245
|
+
if (SLATE_COMMANDS.has(command)) return slateCommand(argv, io)
|
|
246
|
+
if (command && !command.startsWith('-') && !COMMAND_NAMES.has(command)) {
|
|
247
|
+
const near = suggest(command)
|
|
248
|
+
const message = `Unknown command ${command}.${near ? ` Did you mean slatebox ${near}?` : ''} See slatebox help.`
|
|
249
|
+
io.stderr.write(`${message}\n`)
|
|
250
|
+
if (argv.includes('--json')) io.stdout.write(JSON.stringify({ event: 'error', id: 'usage', status: 'failed', exitCode: EXIT.USAGE, message, ...(near ? { suggestion: near } : {}) }) + '\n')
|
|
251
|
+
return EXIT.USAGE
|
|
252
|
+
}
|
|
163
253
|
let parsed
|
|
164
254
|
try {
|
|
165
255
|
parsed = parse(argv)
|
|
@@ -173,7 +263,7 @@ export async function main(argv, io = {}) {
|
|
|
173
263
|
const positionals = parsed.positionals
|
|
174
264
|
if (flags.version) { io.stdout.write(`${PKG.version}\n`); return 0 }
|
|
175
265
|
if (flags.help || positionals[0] === 'help') { io.stdout.write(HELP); return 0 }
|
|
176
|
-
//
|
|
266
|
+
// Flags with no command (`npx slatebox --dry-run`, `--answers x --yes`) are the install.
|
|
177
267
|
if (!positionals.length) positionals.unshift('install')
|
|
178
268
|
|
|
179
269
|
const agentMode = flags.agent === 'yes' || (flags.agent !== 'no' && detectAgent(io.env))
|
|
@@ -187,6 +277,8 @@ export async function main(argv, io = {}) {
|
|
|
187
277
|
home: slateboxHome(io.env, flags.home), redactor, out, run: io.run || makeRunner(out), fetch: io.fetch || globalThis.fetch,
|
|
188
278
|
interactive, tty, agentMode, json, yes: Boolean(flags.yes), healthTimeout: Number(flags['health-timeout'] || 600),
|
|
189
279
|
cliFlags: parsed.values, platform: io.platform, cwd: io.cwd,
|
|
280
|
+
openBrowser: io.openBrowser, sleep: io.sleep, deviceLabel: io.deviceLabel, spawn: io.spawn,
|
|
281
|
+
teamHealthAttempts: io.teamHealthAttempts, teamHealthDelay: io.teamHealthDelay,
|
|
190
282
|
}
|
|
191
283
|
if (interactive) ctx.prompt = createPrompt({ input: io.stdin, output: io.stderr })
|
|
192
284
|
ctx.emitPlan = plan => {
|
|
@@ -254,7 +346,11 @@ function upgradeImage(record, flags) {
|
|
|
254
346
|
|
|
255
347
|
function finish(ctx, done, lines = []) {
|
|
256
348
|
ctx.out.event({ event: 'done', ...done })
|
|
257
|
-
|
|
349
|
+
// { terminal } lines carry a setup link: straight to the terminal, past the redactor (setup-link.mjs).
|
|
350
|
+
for (const line of lines) {
|
|
351
|
+
if (typeof line === 'string') ctx.out.say(line)
|
|
352
|
+
else ctx.stderr.write(`${line.terminal}\n`)
|
|
353
|
+
}
|
|
258
354
|
return 0
|
|
259
355
|
}
|
|
260
356
|
|
|
@@ -287,17 +383,34 @@ async function applyTarget(ctx, answers, options) {
|
|
|
287
383
|
}
|
|
288
384
|
|
|
289
385
|
function closing(ctx, done) {
|
|
290
|
-
if (done.nothingToChange) return [`Nothing to change: ${done.name} is running at ${done.address}
|
|
386
|
+
if (done.nothingToChange) return [`Nothing to change: ${done.name} is running at ${done.address}.${done.teamAddress ? ' (slatebox upgrade gets a newer image.)' : ''}`, ...setupLines(ctx, done.name)]
|
|
291
387
|
if (done.target === 'export') return [`Wrote ${done.files.length} files to ${done.dir}. Nothing was applied.`]
|
|
292
|
-
const lines = ['', `Slatebox is running at
|
|
388
|
+
const lines = ['', `Slatebox is running at ${done.address}`, ...setupLines(ctx, done.name)]
|
|
389
|
+
if (done.teamAddress) {
|
|
390
|
+
lines.push('', `On this computer it also answers at ${done.localAddress}.`,
|
|
391
|
+
'', `Keep a copy of ${installDir(ctx.home, done.name)}/ (keys and the team-address credential).`)
|
|
392
|
+
}
|
|
293
393
|
if (done.keyGenerated) {
|
|
294
394
|
lines.push('', `Your key encryption key is stored in ${done.secretsFile}. Back it up with your password manager now.`,
|
|
295
395
|
'Backups do not contain it, and without it people\'s saved AI keys cannot be read after a restore.')
|
|
296
396
|
}
|
|
297
|
-
lines.push(`Install record: ${done.installRecord}`, `
|
|
397
|
+
lines.push(`Install record: ${done.installRecord}`, `Next: slatebox status slatebox logs slatebox upgrade slatebox uninstall${done.name === 'slatebox' ? '' : ` (--name ${done.name})`}`)
|
|
298
398
|
return lines
|
|
299
399
|
}
|
|
300
400
|
|
|
401
|
+
// install --from cloud: the server is new and has no admin yet, so the team comes over once the
|
|
402
|
+
// person has made the first account (the setup link above) and an access token there.
|
|
403
|
+
function fromCloudLines(done) {
|
|
404
|
+
if (done.target === 'export') return []
|
|
405
|
+
return [
|
|
406
|
+
'', 'To bring your team over from Slatebox Cloud:',
|
|
407
|
+
' 1. Open the setup link above and create your account.',
|
|
408
|
+
` 2. In ${done.address}, open Profile → Developer and make an access token with "Move a team here".`,
|
|
409
|
+
` 3. Run: SLATEBOX_API_TOKEN=<that token> npx slatebox import --from cloud${done.name === 'slatebox' ? '' : ` --name ${done.name}`}`,
|
|
410
|
+
' (you sign in to Slatebox Cloud in your browser; nothing is copied until you confirm)',
|
|
411
|
+
]
|
|
412
|
+
}
|
|
413
|
+
|
|
301
414
|
async function showSecretOnce(ctx, record, name) {
|
|
302
415
|
if (ctx.json || !(ctx.stdout.isTTY || ctx.flags['force-stdout'])) {
|
|
303
416
|
throw new InstallError(EXIT.USAGE, 'Secrets are printed only to a terminal, never with --json or into a pipe (add --force-stdout if you really mean to).')
|
|
@@ -313,6 +426,19 @@ async function dispatch(ctx, positionals, flags) {
|
|
|
313
426
|
case 'agent-prompt':
|
|
314
427
|
ctx.stdout.write(AGENT_PROMPT)
|
|
315
428
|
return 0
|
|
429
|
+
case 'migrate': {
|
|
430
|
+
if (sub === 'invite') return inviteMovedPeople(ctx, { id: rest[0], to: flags.to })
|
|
431
|
+
if (sub) throw new InstallError(EXIT.USAGE, `Unknown: slatebox migrate ${sub}. Use slatebox migrate --to cloud, --from cloud, or slatebox migrate invite <move id> --to cloud|<url>.`)
|
|
432
|
+
if (!flags.to && !flags.from) throw new InstallError(EXIT.USAGE, 'Say which way: slatebox migrate --to cloud (your own server to Slatebox Cloud) or slatebox migrate --from cloud (Slatebox Cloud to your own server).')
|
|
433
|
+
return moveTeam(ctx, { from: flags.from, to: flags.to })
|
|
434
|
+
}
|
|
435
|
+
case 'import': {
|
|
436
|
+
if (sub) return importTeamFile(ctx, { file: sub, to: flags.to })
|
|
437
|
+
if (!flags.from) throw new InstallError(EXIT.USAGE, 'Import from where? slatebox import --from cloud, or slatebox import <file.sbxteam>.')
|
|
438
|
+
return moveTeam(ctx, { from: flags.from, to: flags.to })
|
|
439
|
+
}
|
|
440
|
+
case 'export':
|
|
441
|
+
return exportTeamFile(ctx, { from: flags.from, out: flags.out })
|
|
316
442
|
case 'installs': {
|
|
317
443
|
const records = listRecords(ctx.home)
|
|
318
444
|
ctx.out.event({ event: 'done', installs: records.map(record => ({ name: record.name, target: record.target, address: record.address?.url, state: record.state })) })
|
|
@@ -330,7 +456,7 @@ async function dispatch(ctx, positionals, flags) {
|
|
|
330
456
|
if (!ctx.json) ctx.out.say(`Nothing was changed. To apply: slatebox install ${flags.answers ? `--answers ${flags.answers} ` : ''}... (the same answers)${ctx.interactive ? '' : ' --yes'}`)
|
|
331
457
|
return 0
|
|
332
458
|
}
|
|
333
|
-
finish(ctx, done, closing(ctx, done))
|
|
459
|
+
finish(ctx, done, [...closing(ctx, done), ...(flags.from === 'cloud' ? fromCloudLines(done) : [])])
|
|
334
460
|
if (flags['show-secrets'] && done.keyGenerated) await showSecretOnce(ctx, ctx.record, 'SLATEBOX_KEY_ENCRYPTION_KEY')
|
|
335
461
|
return 0
|
|
336
462
|
}
|
|
@@ -345,14 +471,29 @@ async function dispatch(ctx, positionals, flags) {
|
|
|
345
471
|
case 'status': {
|
|
346
472
|
const record = requireRecord(ctx, flags)
|
|
347
473
|
const status = record.target === 'k8s' ? await statusK8s(ctx, record) : await statusDocker(ctx, record)
|
|
474
|
+
if (record.address?.team) status.teamAddress = await teamStatus(ctx, record)
|
|
348
475
|
ctx.out.event({ event: 'done', ...status })
|
|
349
476
|
if (!ctx.json) {
|
|
350
|
-
for (const [label, value] of Object.entries({ Name: status.name, Where: status.where, Address: status.address, Health: status.health, Version: status.version ? `app ${status.version.app}, engine ${status.version.engine}` : '-', Image: status.imageDigest, AI: status.ai, SSO: status.sso, 'Last backup': status.lastBackup || 'none yet' })) {
|
|
477
|
+
for (const [label, value] of Object.entries({ Name: status.name, Where: status.where, Address: status.address, ...(status.teamAddress ? { 'Team address': teamLine(status) } : {}), Health: status.health, ...(status.setup === 'waiting for the first admin' ? { Setup: `waiting for the first admin: ${record.name === 'slatebox' ? 'slatebox setup-link' : `slatebox setup-link --name ${record.name}`} prints a one-time link` } : {}), Version: status.version ? `app ${status.version.app}, engine ${status.version.engine}` : '-', Image: status.imageDigest, AI: status.ai, SSO: status.sso, 'Last backup': status.lastBackup || 'none yet' })) {
|
|
351
478
|
ctx.out.say(`${label.padEnd(12)} ${value}`)
|
|
352
479
|
}
|
|
480
|
+
if (status.tunnel?.connectors > 1) ctx.out.warn(`The tunnel has ${status.tunnel.connectors} connectors. If you did not start a second copy of this install, someone may hold its tunnel token: slatebox address rotate`)
|
|
353
481
|
}
|
|
354
482
|
return status.health === 'healthy' ? 0 : EXIT.PRECONDITION
|
|
355
483
|
}
|
|
484
|
+
case 'setup-link': {
|
|
485
|
+
const record = requireRecord(ctx, flags)
|
|
486
|
+
// As good as an admin password: a terminal only, never --json or a pipe, unless --force-stdout.
|
|
487
|
+
if (ctx.json || !(ctx.stdout.isTTY || flags['force-stdout'])) {
|
|
488
|
+
throw new InstallError(EXIT.USAGE, 'The setup link is printed only to a terminal, never with --json or into a pipe (add --force-stdout if you really mean to).')
|
|
489
|
+
}
|
|
490
|
+
const link = record.target === 'k8s' ? await setupLinkK8s(ctx, record) : await setupLinkDocker(ctx, record)
|
|
491
|
+
if (link.setUp) throw new InstallError(EXIT.PRECONDITION, `"${record.name}" is already set up: its administrator invites people from the Team page. A lost password: docker exec ${record.name} slatebox password-link <email>`)
|
|
492
|
+
if (!link.url) throw new InstallError(EXIT.PRECONDITION, `No setup link could be made (${link.error}). Is "${record.name}" running an image from 0.2.0 on? slatebox status; slatebox upgrade`)
|
|
493
|
+
ctx.stdout.write(`${link.url}\n`)
|
|
494
|
+
ctx.stderr.write('Open it to create the first account: the server administrator and the owner of the first team.\nIt works once, expires in 24 hours, and the link before it no longer works.\n')
|
|
495
|
+
return 0
|
|
496
|
+
}
|
|
356
497
|
case 'backup': {
|
|
357
498
|
const record = requireRecord(ctx, flags)
|
|
358
499
|
const result = record.target === 'k8s' ? await backupK8s(ctx, record, { to: flags.to }) : await backupDocker(ctx, record, { to: flags.to })
|
|
@@ -372,23 +513,96 @@ async function dispatch(ctx, positionals, flags) {
|
|
|
372
513
|
case 'uninstall': {
|
|
373
514
|
const record = requireRecord(ctx, flags)
|
|
374
515
|
const deleteData = Boolean(flags['delete-data'])
|
|
516
|
+
const release = Boolean(record.address?.team) && !flags['keep-address'] && Boolean(readCredentials(ctx.home, record.name))
|
|
375
517
|
if (deleteData) {
|
|
376
518
|
let typed = flags.confirm
|
|
377
519
|
if (!typed && ctx.interactive) typed = await ctx.prompt.text(`This deletes every slate and account of "${record.name}". Type its name to confirm`, { optional: true })
|
|
378
520
|
if (typed !== record.name) throw new InstallError(ctx.interactive ? EXIT.CANCELLED : EXIT.NEEDS_INPUT, `Deleting data needs the install's name typed back: --confirm ${record.name}. Nothing was changed.`, { needsConfirmation: true })
|
|
379
521
|
}
|
|
380
|
-
const plan = { action: 'uninstall', target: record.target, name: record.name, where: record.target === 'ssh' ? record.ssh.host : record.target === 'k8s' ? record.k8s.context : 'this computer', address: record.address.url, files: [], commands: [], objects: [], ports: [], secretsLocation: record.secretsLocation, warnings: deleteData ? ['Data, secrets and backups next to the install will be deleted.'] : [], notes: deleteData ? [] : ['The data volume and the secrets are kept; install again with the same --name to get it back.'], changes: [] }
|
|
522
|
+
const plan = { action: 'uninstall', target: record.target, name: record.name, where: record.target === 'ssh' ? record.ssh.host : record.target === 'k8s' ? record.k8s.context : 'this computer', address: record.address.url, files: [], commands: [], objects: [], ports: [], secretsLocation: record.secretsLocation, warnings: [...(deleteData ? ['Data, secrets and backups next to the install will be deleted.'] : []), ...(release ? [`${teamHost(record.address.team)} is released (held for your account for 30 days, then anyone may claim it). Keep it with --keep-address.`] : [])], notes: deleteData ? [] : ['The data volume and the secrets are kept; install again with the same --name to get it back.'], changes: [] }
|
|
381
523
|
ctx.emitPlan(plan)
|
|
382
524
|
await ctx.confirm(plan)
|
|
383
525
|
const result = record.target === 'k8s' ? await uninstallK8s(ctx, record, { deleteData }) : await uninstallDocker(ctx, record, { deleteData })
|
|
526
|
+
let released = null
|
|
527
|
+
if (release) {
|
|
528
|
+
released = await releaseTeamAddress(ctx, record, { offlineOk: true })
|
|
529
|
+
if (released.released) ctx.out.step('address', 'ok', `Released ${released.host} (held for your account for 30 days, then anyone may claim it)`)
|
|
530
|
+
else ctx.out.step('address', 'warn', `${released.why} ${released.host} is still yours; release it later with: slatebox address release${record.name === 'slatebox' ? '' : ` --name ${record.name}`} (the credential is kept for that). Unused addresses are released by Slatebox Cloud after 24 hours without a connection anyway.`)
|
|
531
|
+
}
|
|
532
|
+
const keepCredential = released && !released.released
|
|
384
533
|
if (deleteData) {
|
|
385
|
-
const
|
|
386
|
-
|
|
387
|
-
|
|
534
|
+
const dir = installDir(ctx.home, record.name)
|
|
535
|
+
if (keepCredential) {
|
|
536
|
+
for (const entry of existsSync(dir) ? readdirSync(dir) : []) if (entry !== CREDENTIALS_FILE) rmSync(join(dir, entry), { recursive: true, force: true })
|
|
537
|
+
} else rmSync(dir, { recursive: true, force: true })
|
|
388
538
|
} else {
|
|
389
|
-
writeRecord(ctx.home, { ...record, state: 'uninstalled' })
|
|
539
|
+
writeRecord(ctx.home, { ...record, ...(released?.released ? { address: localAddress(record) } : {}), state: 'uninstalled' })
|
|
540
|
+
}
|
|
541
|
+
const summary = { name: record.name, ...result, ...(released ? { addressReleased: released.released } : {}) }
|
|
542
|
+
return finish(ctx, summary, [deleteData ? `Removed "${record.name}" and its data.` : `Removed "${record.name}". Kept: ${result.volume} and ${result.secretsFile}. To delete them too: slatebox uninstall --name ${record.name} --delete-data --confirm ${record.name}`])
|
|
543
|
+
}
|
|
544
|
+
case 'logs': {
|
|
545
|
+
const record = requireRecord(ctx, flags)
|
|
546
|
+
if (flags.service && !LOG_SERVICES.includes(flags.service)) throw new InstallError(EXIT.USAGE, `--service is one of ${LOG_SERVICES.join(', ')}.`)
|
|
547
|
+
if (flags.since && !/^\d+[smhd]?$|^\d{4}-\d{2}-\d{2}/.test(flags.since)) throw new InstallError(EXIT.USAGE, '--since is a duration like 10m or 2h, or a date.')
|
|
548
|
+
if (record.target === 'k8s') {
|
|
549
|
+
const args = ['--context', record.k8s.context, 'logs', '-n', record.k8s.namespace, `${record.name}-0`, '-c', 'slatebox', ...(flags.since ? ['--since', flags.since] : ['--tail', '500'])]
|
|
550
|
+
const result = await ctx.run('kubectl', args, { timeout: 120_000 })
|
|
551
|
+
if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `kubectl logs failed: ${result.stderr.trim().split('\n').pop()}`)
|
|
552
|
+
for (const line of result.stdout.split('\n')) if (line && (!flags.service || line.startsWith(`[${flags.service}] `))) ctx.stdout.write(`${ctx.redactor.redact(line)}\n`)
|
|
553
|
+
return 0
|
|
554
|
+
}
|
|
555
|
+
await logsDocker(ctx, record, { follow: Boolean(flags.follow), service: flags.service, since: flags.since })
|
|
556
|
+
return 0
|
|
557
|
+
}
|
|
558
|
+
case 'rename': {
|
|
559
|
+
const record = requireRecord(ctx, flags)
|
|
560
|
+
if (!record.address?.team) throw new InstallError(EXIT.USAGE, `"${record.name}" has no team address. Add one with: slatebox install --team-address <name>`)
|
|
561
|
+
if (!sub) throw new InstallError(EXIT.USAGE, 'Name the new address: slatebox rename <new-name>')
|
|
562
|
+
const renamed = await renameTeamAddress(ctx, record, sub.toLowerCase())
|
|
563
|
+
ctx.out.step('address', 'ok', `${renamed.host} is yours; moving "${record.name}" to it`)
|
|
564
|
+
const done = await reapply(ctx, { ...record, address: { ...record.address, team: renamed.name, url: undefined } })
|
|
565
|
+
const finished = await finishRename(ctx, { ...record, address: { ...record.address, team: renamed.name } })
|
|
566
|
+
if (finished.done) ctx.out.step('address', 'ok', `${teamHost(renamed.previousName)} no longer points here (held for your account for 30 days)`)
|
|
567
|
+
else ctx.out.step('address', 'warn', `Could not tell Slatebox Cloud the move is done (${finished.why}); the old address is dropped by itself within 24 hours.`)
|
|
568
|
+
return finish(ctx, { ...done, previousAddress: `https://${teamHost(renamed.previousName)}` }, ['', `Slatebox is now at ${done.address}`])
|
|
569
|
+
}
|
|
570
|
+
case 'address': {
|
|
571
|
+
const record = readRecord(ctx.home, flags.name || 'slatebox')
|
|
572
|
+
if (!sub || sub === 'status') {
|
|
573
|
+
const current = requireRecord(ctx, flags)
|
|
574
|
+
if (!current.address?.team) {
|
|
575
|
+
ctx.out.event({ event: 'done', name: current.name, teamAddress: null, address: current.address.url })
|
|
576
|
+
ctx.out.say(`"${current.name}" has no team address; it is at ${current.address.url}. Add one with: slatebox install --team-address <name>`)
|
|
577
|
+
return 0
|
|
578
|
+
}
|
|
579
|
+
const team = await teamStatus(ctx, current)
|
|
580
|
+
ctx.out.event({ event: 'done', name: current.name, teamAddress: team })
|
|
581
|
+
if (!ctx.json) ctx.out.say(`${team.host}: ${team.status}${team.suspension?.notice ? ` (${team.suspension.notice})` : ''}`)
|
|
582
|
+
return team.status === 'active' ? 0 : EXIT.PRECONDITION
|
|
583
|
+
}
|
|
584
|
+
if (sub === 'release') {
|
|
585
|
+
// Works from the credential alone, so an address left over after an offline uninstall can still be given back.
|
|
586
|
+
const target = record || { name: flags.name || 'slatebox', address: {} }
|
|
587
|
+
const released = await releaseTeamAddress(ctx, target)
|
|
588
|
+
ctx.out.step('address', 'ok', `Released ${released.host} (held for your account for 30 days, then anyone may claim it)`)
|
|
589
|
+
if (record && record.state !== 'uninstalled' && record.address?.team) {
|
|
590
|
+
const done = await reapply(ctx, { ...record, address: localAddress(record) })
|
|
591
|
+
return finish(ctx, { ...done, addressReleased: true }, ['', `"${record.name}" now answers only at ${done.address}.`])
|
|
592
|
+
}
|
|
593
|
+
if (record?.address?.team) writeRecord(ctx.home, { ...record, address: localAddress(record) })
|
|
594
|
+
if (!record && existsSync(installDir(ctx.home, target.name)) && !readdirSync(installDir(ctx.home, target.name)).length) rmSync(installDir(ctx.home, target.name), { recursive: true, force: true })
|
|
595
|
+
return finish(ctx, { name: target.name, addressReleased: true }, [])
|
|
596
|
+
}
|
|
597
|
+
if (sub === 'rotate') {
|
|
598
|
+
const current = requireRecord(ctx, flags)
|
|
599
|
+
if (!current.address?.team) throw new InstallError(EXIT.USAGE, `"${current.name}" has no team address.`)
|
|
600
|
+
await rotateTeamAddress(ctx, current)
|
|
601
|
+
ctx.out.step('address', 'ok', 'New tunnel secret: every connector holding the old token was dropped')
|
|
602
|
+
const done = await reapply(ctx, current)
|
|
603
|
+
return finish(ctx, { ...done, rotated: true }, ['', `${done.address} now uses the new tunnel token.`])
|
|
390
604
|
}
|
|
391
|
-
|
|
605
|
+
throw new InstallError(EXIT.USAGE, 'Usage: slatebox address [status | release | rotate]')
|
|
392
606
|
}
|
|
393
607
|
case 'ai':
|
|
394
608
|
return aiCommand(ctx, flags, sub, rest)
|
|
@@ -408,6 +622,26 @@ async function dispatch(ctx, positionals, flags) {
|
|
|
408
622
|
}
|
|
409
623
|
}
|
|
410
624
|
|
|
625
|
+
function teamLine(status) {
|
|
626
|
+
const team = status.teamAddress
|
|
627
|
+
const connections = status.tunnel?.ready ? `, ${status.tunnel.connections} connection${status.tunnel.connections === 1 ? '' : 's'}` : status.tunnel?.state === 'failed' ? ', tunnel refused by Cloudflare' : status.tunnel ? ', tunnel not connected' : ''
|
|
628
|
+
return `https://${team.host} (${team.status}${connections})${team.suspension?.notice ? `: ${team.suspension.notice}` : ''}`
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** The install's address without its team address: this computer only (or the server's own address). */
|
|
632
|
+
function localAddress(record) {
|
|
633
|
+
if (record.target === 'k8s') return { url: `http://localhost:7070` }
|
|
634
|
+
const port = record.address?.port ?? 7070
|
|
635
|
+
return { url: undefined, port, listen: record.address?.listen ?? '127.0.0.1', team: null }
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** Apply an install record again (same image), after its address or tunnel token changed. */
|
|
639
|
+
async function reapply(ctx, record) {
|
|
640
|
+
const { answers, errors } = resolveAnswers(collect({ record }), {})
|
|
641
|
+
if (errors.length) throw new InstallError(EXIT.USAGE, `The install record is not valid: ${errors.map(error => `${error.field} (${error.message})`).join('; ')}`, { fields: errors })
|
|
642
|
+
return applyTarget(ctx, answers, { record, imageRef: record.imageRef, explicitContext: true })
|
|
643
|
+
}
|
|
644
|
+
|
|
411
645
|
// ------------------------------------------------------------------ ai
|
|
412
646
|
|
|
413
647
|
async function aiCommand(ctx, flags, sub, rest) {
|