slatebox 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,285 @@
1
+ // A team address, https://<name>.slatebox.team, for any install target: check the name, sign in,
2
+ // claim it on Slatebox Cloud, keep the install credential on this computer, and hand the tunnel
3
+ // connector token to the target's secrets. The container's own cloudflared then connects out to
4
+ // Cloudflare: no DNS, no open ports, no certificates.
5
+ //
6
+ // Every function here is safe to run again: a claim retried with the same client key is the same
7
+ // claim, and an install that already has its token needs no network at all.
8
+ import { createHash } from 'node:crypto'
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+ import {
12
+ CloudError, cloudBase, cloudClient, credentialsPath, deviceLabel, newClientKey, readCredentials, removeCredentials,
13
+ signIn, TEAM_ADDRESS_RULE, teamAddressProblem, teamHost, writeCredentials,
14
+ } from '../cloud.mjs'
15
+ import { EXIT, InstallError } from '../errors.mjs'
16
+ import { installDir } from '../record.mjs'
17
+
18
+ export const TUNNEL_TOKEN = 'SLATEBOX_TUNNEL_TOKEN'
19
+ const PENDING_FILE = 'claim.json'
20
+ const E2E_PREFIX = 'e2e-'
21
+
22
+ function client(ctx, base) {
23
+ ctx.cloud ??= cloudClient(ctx, base || cloudBase(ctx))
24
+ return ctx.cloud
25
+ }
26
+
27
+ /**
28
+ * A team address that cannot be had: the same answer for taken and blocked names. A reserved name
29
+ * (Slatebox's own: www, admin, test, e2e-...) says so, in Slatebox Cloud's words.
30
+ */
31
+ function unavailable(name, suggestions = [], { reason, message } = {}) {
32
+ const free = suggestions?.length ? `\n Free right now: ${suggestions.join(', ')}` : ''
33
+ const why = reason === 'reserved' ? (message && /reserved/i.test(message) ? message.replace(/\s*Choose another name\.?$/, '') : `${teamHost(name)} is reserved for Slatebox itself.`) : `${teamHost(name)} isn't available.`
34
+ return new InstallError(EXIT.NEEDS_INPUT, `${why}${free}\n Choose another: --team-address <name>`, { id: 'address-unavailable', field: 'address.team', suggestions: suggestions || [], ...(reason ? { reason } : {}) })
35
+ }
36
+
37
+ function cloudFailure(error, name) {
38
+ if (error instanceof InstallError) return error
39
+ if (!(error instanceof CloudError)) return error
40
+ switch (error.code) {
41
+ case 'unavailable': return unavailable(name, error.suggestions, { reason: error.reason, message: error.message })
42
+ case 'invalid_name': return new InstallError(EXIT.USAGE, `"${name}" is not a team address: ${TEAM_ADDRESS_RULE}.`, { field: 'address.team' })
43
+ case 'limit_reached': return new InstallError(EXIT.PRECONDITION, `Your Slatebox account already has the most team addresses it may hold, or claimed too many today. ${error.message} Release one you no longer use (slatebox address release on that install), or use your own domain: --domain boards.example.com`, { id: 'address-limit' })
44
+ case 'rate_limited': return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud asks you to wait${error.retryAfter ? ` ${error.retryAfter} seconds` : ''} before trying again. Nothing was changed.`, { id: 'rate-limited', retryAfter: error.retryAfter })
45
+ case 'paused': return new InstallError(EXIT.PRECONDITION, 'New team addresses are paused on Slatebox Cloud right now. Nothing was changed. Try again later, or use --domain or --local.', { id: 'address-paused' })
46
+ case 'suspended': return new InstallError(EXIT.PRECONDITION, `${teamHost(name)} is suspended: ${error.notice || error.message}. Your Slatebox keeps running on this computer; contact abuse@slatebox.com about the address.`, { id: 'address-suspended' })
47
+ case 'upstream_unavailable': return new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud could not set up the secure tunnel just now (Cloudflare did not answer). Nothing was left half made; run the same command again in a minute.', { id: 'upstream-unavailable' })
48
+ case 'not_found': return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud no longer knows the team address of this install (${teamHost(name)}). It may have been released. Run slatebox install --team-address <name> to claim one again.`, { id: 'address-gone' })
49
+ default: return new InstallError(EXIT.PRECONDITION, `Slatebox Cloud answered: ${error.message} (${error.code}, HTTP ${error.status}).`, { id: 'cloud-error', code: error.code })
50
+ }
51
+ }
52
+
53
+ // ------------------------------------------------------------------ check
54
+
55
+ /**
56
+ * Before the plan: is the name ours already, or free to claim? Never signs in.
57
+ * @returns {Promise<{name: string, host: string, creds: object|null, claim: boolean}>}
58
+ */
59
+ export async function checkTeamAddress(ctx, answers) {
60
+ const name = answers.address.team
61
+ const problem = teamAddressProblem(name)
62
+ if (problem) throw new InstallError(EXIT.USAGE, `"${name}" is not a team address: ${problem}.`, { field: 'address.team' })
63
+ const creds = readCredentials(ctx.home, answers.name)
64
+ if (creds && creds.name !== name) {
65
+ throw new InstallError(EXIT.USAGE, `"${answers.name}" already has the team address ${teamHost(creds.name)}. To move it: slatebox rename ${name}${answers.name === 'slatebox' ? '' : ` --name ${answers.name}`}. For a second Slatebox, give it its own --name.`, { field: 'address.team' })
66
+ }
67
+ if (creds) {
68
+ ctx.redactor.add(creds.installCredential)
69
+ return { name, host: teamHost(name), creds, claim: false }
70
+ }
71
+ const cloud = client(ctx)
72
+ // e2e-<anything> belongs to the end-to-end test's accounts, which the Cloud knows only after
73
+ // the sign-in: a signed-out check always says no, so the claim itself is the check.
74
+ if (name.startsWith(E2E_PREFIX)) return { name, host: teamHost(name), creds: null, claim: true }
75
+ ctx.out.step('address', 'start', `Checking ${teamHost(name)}`)
76
+ let answer
77
+ try { answer = await cloud.availability(name) } catch (error) { throw cloudFailure(error, name) }
78
+ if (!answer?.available) throw unavailable(name, answer?.suggestions)
79
+ ctx.out.step('address', 'ok', `${teamHost(name)} is available`)
80
+ return { name, host: teamHost(name), creds: null, claim: true }
81
+ }
82
+
83
+ /** For the interview: the name if it is free, or the suggestions. Never signs in. */
84
+ export async function availability(ctx, name) {
85
+ try {
86
+ const answer = await client(ctx).availability(name)
87
+ return { available: Boolean(answer?.available), suggestions: answer?.suggestions || [] }
88
+ } catch (error) {
89
+ if (error instanceof CloudError && error.code === 'invalid_name') return { available: false, suggestions: [], invalid: true }
90
+ throw cloudFailure(error, name)
91
+ }
92
+ }
93
+
94
+ // ------------------------------------------------------------------ claim and attach
95
+
96
+ function pendingPath(ctx, install) { return join(installDir(ctx.home, install), PENDING_FILE) }
97
+
98
+ /** One client key per install and name, kept until the claim is done, so a retry is the same claim. */
99
+ function pendingKey(ctx, install, name) {
100
+ const path = pendingPath(ctx, install)
101
+ if (existsSync(path)) {
102
+ try {
103
+ const pending = JSON.parse(readFileSync(path, 'utf8'))
104
+ if (pending.name === name && pending.clientKey) return pending.clientKey
105
+ } catch { /* write a new one */ }
106
+ }
107
+ const clientKey = newClientKey()
108
+ mkdirSync(installDir(ctx.home, install), { recursive: true, mode: 0o700 })
109
+ writeFileSync(path, `${JSON.stringify({ name, clientKey })}\n`, { mode: 0o600 })
110
+ chmodSync(path, 0o600)
111
+ return clientKey
112
+ }
113
+
114
+ async function connectorToken(ctx, cloud, creds, { rotate = false } = {}) {
115
+ const answer = await cloud.connectorToken(creds.installCredential, { rotate })
116
+ if (!answer?.connectorToken) throw new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud sent no tunnel token.')
117
+ ctx.redactor.add(answer.connectorToken)
118
+ return answer.connectorToken
119
+ }
120
+
121
+ /**
122
+ * After the plan was approved: the tunnel token for this install. Claims the name (with a
123
+ * sign-in) if this computer holds no credential for it yet; otherwise uses the token already in
124
+ * the install's secrets, or fetches it again with the install credential.
125
+ * @param {{name: string, creds: object|null, claim: boolean}} check from checkTeamAddress
126
+ * @param {Record<string,string>} stored the install's current secrets
127
+ * @returns {Promise<string>} the connector token
128
+ */
129
+ export async function ensureTeamAddress(ctx, answers, check, stored = {}) {
130
+ if (ctx.tunnelToken) return ctx.tunnelToken
131
+ const { name } = check
132
+ if (check.creds && stored[TUNNEL_TOKEN]) {
133
+ ctx.redactor.add(stored[TUNNEL_TOKEN])
134
+ ctx.tunnelToken = stored[TUNNEL_TOKEN]
135
+ return ctx.tunnelToken
136
+ }
137
+ const cloud = client(ctx, check.creds?.cloudUrl)
138
+ if (check.creds) {
139
+ // The token file was lost (a new server, a wiped folder): fetch it again with the credential.
140
+ try {
141
+ ctx.tunnelToken = await connectorToken(ctx, cloud, check.creds)
142
+ ctx.out.step('address', 'ok', `Fetched the secure tunnel token for ${teamHost(name)} again`)
143
+ return ctx.tunnelToken
144
+ } catch (error) {
145
+ if (!(error instanceof CloudError && error.status === 401)) throw cloudFailure(error, name)
146
+ }
147
+ // The credential was revoked or replaced: sign in and mint a new one (this also rotates the tunnel secret).
148
+ const bearer = await signIn(ctx, cloud, { purpose: `reconnect ${teamHost(name)}` })
149
+ let minted
150
+ try { minted = await cloud.mintCredential(bearer, check.creds.claimId) } catch (error) { throw cloudFailure(error, name) }
151
+ const creds = { ...check.creds, installCredential: minted.installCredential, renewedAt: new Date().toISOString() }
152
+ ctx.redactor.add(creds.installCredential)
153
+ writeCredentials(ctx.home, answers.name, creds)
154
+ check.creds = creds
155
+ try { ctx.tunnelToken = minted.connectorToken || await connectorToken(ctx, cloud, creds) } catch (error) { throw cloudFailure(error, name) }
156
+ ctx.redactor.add(ctx.tunnelToken)
157
+ ctx.out.step('address', 'ok', `${teamHost(name)} has a new install credential`)
158
+ return ctx.tunnelToken
159
+ }
160
+
161
+ const clientKey = pendingKey(ctx, answers.name, name)
162
+ const bearer = await signIn(ctx, cloud)
163
+ ctx.out.step('address', 'start', `Claiming ${teamHost(name)}`)
164
+ let claimed
165
+ try {
166
+ claimed = await cloud.claim(bearer, {
167
+ name, clientKey, label: ctx.deviceLabel || deviceLabel(),
168
+ idempotencyKey: createHash('sha256').update(`${name}|${clientKey}`).digest('hex'),
169
+ })
170
+ } catch (error) {
171
+ throw cloudFailure(error, name)
172
+ }
173
+ const claim = claimed?.claim
174
+ if (!claim?.id) throw new InstallError(EXIT.PRECONDITION, 'Slatebox Cloud did not confirm the claim.')
175
+ let installCredential = claimed.installCredential
176
+ // A replayed claim (the first answer was lost) carries no credential: mint one.
177
+ if (!installCredential) {
178
+ try { installCredential = (await cloud.mintCredential(bearer, claim.id)).installCredential } catch (error) { throw cloudFailure(error, name) }
179
+ }
180
+ ctx.redactor.add(installCredential)
181
+ const creds = { claimId: claim.id, name: claim.name || name, host: claim.host || teamHost(name), cloudUrl: cloud.base, installCredential, claimedAt: new Date().toISOString() }
182
+ writeCredentials(ctx.home, answers.name, creds)
183
+ rmSync(pendingPath(ctx, answers.name), { force: true })
184
+ check.creds = creds
185
+ check.claim = false
186
+ const of = claimed.count && claimed.limit ? ` (${claimed.count} of ${claimed.limit} team addresses on this account)` : ''
187
+ ctx.out.step('address', 'ok', `Claimed ${creds.host}${of}`)
188
+ try {
189
+ ctx.tunnelToken = claimed.connectorToken || await connectorToken(ctx, cloud, creds)
190
+ } catch (error) {
191
+ throw cloudFailure(error, name)
192
+ }
193
+ ctx.redactor.add(ctx.tunnelToken)
194
+ return ctx.tunnelToken
195
+ }
196
+
197
+ // ------------------------------------------------------------------ day two
198
+
199
+ function requireCreds(ctx, record) {
200
+ const creds = readCredentials(ctx.home, record.name)
201
+ if (!creds) {
202
+ throw new InstallError(EXIT.PRECONDITION, `"${record.name}" has no team address on this computer (no ${credentialsPath(ctx.home, record.name)}).${record.address?.team ? ' Run slatebox install again to sign in and reconnect it.' : ' Add one with: slatebox install --team-address <name>'}`)
203
+ }
204
+ ctx.redactor.add(creds.installCredential)
205
+ return creds
206
+ }
207
+
208
+ /** The address as Slatebox Cloud sees it: active, suspended (with the notice), or unknown when offline. */
209
+ export async function teamStatus(ctx, record) {
210
+ const creds = readCredentials(ctx.home, record.name)
211
+ if (!creds) return { name: record.address.team, host: teamHost(record.address.team), status: 'no credential on this computer' }
212
+ ctx.redactor.add(creds.installCredential)
213
+ try {
214
+ const answer = await client(ctx, creds.cloudUrl).self(creds.installCredential)
215
+ // {claim: {id, name, host, status, suspension?}} (a flat claim is read the same way).
216
+ const self = answer?.claim || answer || {}
217
+ return { name: self.name || creds.name, host: self.host || creds.host, status: self.status || 'unknown', suspension: self.suspension || null }
218
+ } catch (error) {
219
+ if (error instanceof InstallError) return { name: creds.name, host: creds.host, status: 'unknown (Slatebox Cloud not reachable)' }
220
+ if (error instanceof CloudError && error.code === 'suspended') return { name: creds.name, host: creds.host, status: 'suspended', suspension: { notice: error.notice || error.message } }
221
+ return { name: creds.name, host: creds.host, status: `unknown (${error.code || error.message})` }
222
+ }
223
+ }
224
+
225
+ /** A new tunnel secret: every connector holding the old token is dropped. Returns the new token. */
226
+ export async function rotateTeamAddress(ctx, record) {
227
+ const creds = requireCreds(ctx, record)
228
+ try {
229
+ ctx.tunnelToken = await connectorToken(ctx, client(ctx, creds.cloudUrl), creds, { rotate: true })
230
+ } catch (error) {
231
+ throw cloudFailure(error, creds.name)
232
+ }
233
+ return ctx.tunnelToken
234
+ }
235
+
236
+ /** Move the address to a new name. The old name keeps working until renameComplete. */
237
+ export async function renameTeamAddress(ctx, record, next) {
238
+ const problem = teamAddressProblem(next)
239
+ if (problem) throw new InstallError(EXIT.USAGE, `"${next}" is not a team address: ${problem}.`, { field: 'address.team' })
240
+ const creds = requireCreds(ctx, record)
241
+ if (creds.name === next) throw new InstallError(EXIT.USAGE, `"${record.name}" is already at ${teamHost(next)}.`)
242
+ const cloud = client(ctx, creds.cloudUrl)
243
+ const bearer = await signIn(ctx, cloud, { purpose: `move ${teamHost(creds.name)} to ${teamHost(next)}` })
244
+ let answer
245
+ try { answer = await cloud.rename(bearer, creds.claimId, next) } catch (error) { throw cloudFailure(error, next) }
246
+ const renamed = { ...creds, previousName: creds.name, name: answer?.claim?.name || next, host: answer?.claim?.host || teamHost(next), renamedAt: new Date().toISOString() }
247
+ writeCredentials(ctx.home, record.name, renamed)
248
+ return renamed
249
+ }
250
+
251
+ /** After the install answers at the new name: drop the old one (its name is held for 30 days). */
252
+ export async function finishRename(ctx, record) {
253
+ const creds = requireCreds(ctx, record)
254
+ try {
255
+ await client(ctx, creds.cloudUrl).renameComplete(creds.installCredential)
256
+ } catch (error) {
257
+ if (error instanceof InstallError) return { done: false, why: error.message }
258
+ throw cloudFailure(error, creds.name)
259
+ }
260
+ const { previousName, ...rest } = creds
261
+ writeCredentials(ctx.home, record.name, rest)
262
+ return { done: true, previousName }
263
+ }
264
+
265
+ /**
266
+ * Give the address back. With offlineOk, an unreachable Cloud is not an error: the credential is
267
+ * kept so `slatebox address release` can finish later.
268
+ */
269
+ export async function releaseTeamAddress(ctx, record, { offlineOk = false } = {}) {
270
+ const creds = requireCreds(ctx, record)
271
+ try {
272
+ await client(ctx, creds.cloudUrl).releaseSelf(creds.installCredential)
273
+ } catch (error) {
274
+ if (error instanceof CloudError && (error.status === 404 || error.status === 401)) {
275
+ // Already released, or the credential was revoked by a release elsewhere.
276
+ } else if (offlineOk && error instanceof InstallError) {
277
+ return { released: false, host: creds.host, claimId: creds.claimId, why: error.message.split('\n')[0] }
278
+ } else {
279
+ throw cloudFailure(error, creds.name)
280
+ }
281
+ }
282
+ removeCredentials(ctx.home, record.name)
283
+ rmSync(pendingPath(ctx, record.name), { force: true })
284
+ return { released: true, host: creds.host, claimId: creds.claimId }
285
+ }