layerbase 0.1.2 → 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/cli.tsx → dist/cli.js} +36 -35
- package/dist/cli.js.map +1 -0
- package/dist/commands/alias.js +27 -0
- package/dist/commands/alias.js.map +1 -0
- package/dist/commands/connect.js +51 -0
- package/dist/commands/connect.js.map +1 -0
- package/dist/commands/connection-string.js +43 -0
- package/dist/commands/connection-string.js.map +1 -0
- package/dist/commands/interactive.js +125 -0
- package/dist/commands/interactive.js.map +1 -0
- package/dist/commands/login.js +61 -0
- package/dist/commands/login.js.map +1 -0
- package/dist/commands/logout.js +25 -0
- package/dist/commands/logout.js.map +1 -0
- package/dist/commands/ls.js +60 -0
- package/dist/commands/ls.js.map +1 -0
- package/dist/commands/whoami.js +49 -0
- package/dist/commands/whoami.js.map +1 -0
- package/dist/lib/alias.js +68 -0
- package/dist/lib/alias.js.map +1 -0
- package/dist/lib/browser-login.js +78 -0
- package/dist/lib/browser-login.js.map +1 -0
- package/dist/lib/cloud-api.js +44 -0
- package/dist/lib/cloud-api.js.map +1 -0
- package/dist/lib/config.js +32 -0
- package/dist/lib/config.js.map +1 -0
- package/dist/lib/engines.js +89 -0
- package/dist/lib/engines.js.map +1 -0
- package/dist/lib/format.js +38 -0
- package/dist/lib/format.js.map +1 -0
- package/dist/lib/launch.js +43 -0
- package/dist/lib/launch.js.map +1 -0
- package/dist/lib/open-browser.js +18 -0
- package/dist/lib/open-browser.js.map +1 -0
- package/dist/lib/run-spindb.js +49 -0
- package/dist/lib/run-spindb.js.map +1 -0
- package/dist/lib/token.js +15 -0
- package/dist/lib/token.js.map +1 -0
- package/dist/ui/app.js +27 -0
- package/dist/ui/app.js.map +1 -0
- package/dist/ui/brand.js +8 -0
- package/dist/ui/brand.js.map +1 -0
- package/dist/ui/connecting.js +7 -0
- package/dist/ui/connecting.js.map +1 -0
- package/dist/ui/menu.js +33 -0
- package/dist/ui/menu.js.map +1 -0
- package/dist/ui/press-enter.js +13 -0
- package/dist/ui/press-enter.js.map +1 -0
- package/dist/ui/unknown.js +12 -0
- package/dist/ui/unknown.js.map +1 -0
- package/package.json +15 -9
- package/bin/layerbase.mjs +0 -5
- package/src/commands/alias.tsx +0 -28
- package/src/commands/connect.tsx +0 -66
- package/src/commands/connection-string.tsx +0 -49
- package/src/commands/interactive.tsx +0 -168
- package/src/commands/login.tsx +0 -103
- package/src/commands/logout.tsx +0 -27
- package/src/commands/ls.tsx +0 -99
- package/src/commands/whoami.tsx +0 -64
- package/src/lib/alias.ts +0 -84
- package/src/lib/browser-login.ts +0 -115
- package/src/lib/cloud-api.ts +0 -96
- package/src/lib/config.ts +0 -45
- package/src/lib/engines.ts +0 -124
- package/src/lib/format.ts +0 -47
- package/src/lib/launch.ts +0 -47
- package/src/lib/open-browser.ts +0 -20
- package/src/lib/run-spindb.ts +0 -51
- package/src/lib/token.ts +0 -19
- package/src/ui/app.tsx +0 -38
- package/src/ui/brand.tsx +0 -15
- package/src/ui/connecting.tsx +0 -13
- package/src/ui/menu.tsx +0 -56
- package/src/ui/press-enter.tsx +0 -11
- package/src/ui/unknown.tsx +0 -17
package/src/commands/whoami.tsx
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { useEffect, useState } from 'react'
|
|
2
|
-
import { Text, useApp } from 'ink'
|
|
3
|
-
import { loadCredentials } from '../lib/config'
|
|
4
|
-
import { decodeTokenClaims } from '../lib/token'
|
|
5
|
-
|
|
6
|
-
type State =
|
|
7
|
-
| { kind: 'loading' }
|
|
8
|
-
| { kind: 'out' }
|
|
9
|
-
| { kind: 'in'; email: string; apiUrl: string; expiresAtMs: number | null }
|
|
10
|
-
|
|
11
|
-
// Offline: reads the stored token and decodes it. No network, so it works even
|
|
12
|
-
// before the cloud endpoints are deployed. It reports the cached identity, not
|
|
13
|
-
// a live session check (use any cloud command to confirm the token still works).
|
|
14
|
-
export function Whoami({ json }: { json: boolean }) {
|
|
15
|
-
const { exit } = useApp()
|
|
16
|
-
const [state, setState] = useState<State>({ kind: 'loading' })
|
|
17
|
-
|
|
18
|
-
useEffect(() => {
|
|
19
|
-
async function fetchAndSetWhoami() {
|
|
20
|
-
const creds = await loadCredentials()
|
|
21
|
-
if (!creds) {
|
|
22
|
-
if (json) {
|
|
23
|
-
process.stdout.write(`${JSON.stringify({ loggedIn: false })}\n`)
|
|
24
|
-
}
|
|
25
|
-
process.exitCode = 1
|
|
26
|
-
setState({ kind: 'out' })
|
|
27
|
-
return
|
|
28
|
-
}
|
|
29
|
-
const claims = decodeTokenClaims(creds.token)
|
|
30
|
-
const email = claims?.email ?? 'unknown'
|
|
31
|
-
const expiresAtMs = claims?.exp ? claims.exp * 1000 : null
|
|
32
|
-
if (json) {
|
|
33
|
-
process.stdout.write(
|
|
34
|
-
`${JSON.stringify({ loggedIn: true, email, apiUrl: creds.apiUrl, expiresAt: expiresAtMs })}\n`,
|
|
35
|
-
)
|
|
36
|
-
}
|
|
37
|
-
setState({ kind: 'in', email, apiUrl: creds.apiUrl, expiresAtMs })
|
|
38
|
-
}
|
|
39
|
-
fetchAndSetWhoami()
|
|
40
|
-
}, [json])
|
|
41
|
-
|
|
42
|
-
useEffect(() => {
|
|
43
|
-
if (state.kind !== 'loading') {
|
|
44
|
-
exit()
|
|
45
|
-
}
|
|
46
|
-
}, [state, exit])
|
|
47
|
-
|
|
48
|
-
if (state.kind === 'loading' || json) {
|
|
49
|
-
return null
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
if (state.kind === 'out') {
|
|
53
|
-
return <Text color="yellow">Not logged in. Run `layerbase login`.</Text>
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
const expiry = state.expiresAtMs
|
|
57
|
-
? ` Token expires ${new Date(state.expiresAtMs).toISOString().slice(0, 10)}.`
|
|
58
|
-
: ''
|
|
59
|
-
return (
|
|
60
|
-
<Text color="green">
|
|
61
|
-
Signed in as {state.email} at {state.apiUrl}.{expiry}
|
|
62
|
-
</Text>
|
|
63
|
-
)
|
|
64
|
-
}
|
package/src/lib/alias.ts
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import { existsSync, symlinkSync, writeFileSync } from 'node:fs'
|
|
2
|
-
import { join, delimiter, dirname } from 'node:path'
|
|
3
|
-
|
|
4
|
-
const isWin = process.platform === 'win32'
|
|
5
|
-
|
|
6
|
-
function findOnPath(name: string): string | null {
|
|
7
|
-
const exts = isWin ? ['.cmd', '.exe', '.bat', ''] : ['']
|
|
8
|
-
for (const dir of (process.env.PATH ?? '').split(delimiter)) {
|
|
9
|
-
if (!dir) continue
|
|
10
|
-
for (const ext of exts) {
|
|
11
|
-
const full = join(dir, `${name}${ext}`)
|
|
12
|
-
if (existsSync(full)) return full
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
return null
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
// `lb` is a grabby two-character name (e.g. Debian live-build ships `lb`), so
|
|
19
|
-
// we only ever claim it when it is genuinely free, and only next to our own
|
|
20
|
-
// `layerbase` bin. Everything keys off where `layerbase` itself resolves.
|
|
21
|
-
export type LbStatus =
|
|
22
|
-
| { state: 'available'; binDir: string; layerbasePath: string }
|
|
23
|
-
| { state: 'ours'; path: string }
|
|
24
|
-
| { state: 'taken'; path: string }
|
|
25
|
-
| { state: 'unknown' }
|
|
26
|
-
|
|
27
|
-
export function lbStatus(): LbStatus {
|
|
28
|
-
const layerbasePath = findOnPath('layerbase')
|
|
29
|
-
if (!layerbasePath) return { state: 'unknown' }
|
|
30
|
-
|
|
31
|
-
const binDir = dirname(layerbasePath)
|
|
32
|
-
const lbPath = findOnPath('lb')
|
|
33
|
-
if (lbPath) {
|
|
34
|
-
// Already ours if it lives next to layerbase; otherwise it belongs to
|
|
35
|
-
// another tool and we leave it alone.
|
|
36
|
-
return dirname(lbPath) === binDir
|
|
37
|
-
? { state: 'ours', path: lbPath }
|
|
38
|
-
: { state: 'taken', path: lbPath }
|
|
39
|
-
}
|
|
40
|
-
return { state: 'available', binDir, layerbasePath }
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export type SetupResult =
|
|
44
|
-
| { ok: true; path: string }
|
|
45
|
-
| { ok: false; reason: string }
|
|
46
|
-
|
|
47
|
-
export function setupLb(): SetupResult {
|
|
48
|
-
const status = lbStatus()
|
|
49
|
-
|
|
50
|
-
if (status.state === 'ours') {
|
|
51
|
-
return { ok: true, path: status.path }
|
|
52
|
-
}
|
|
53
|
-
if (status.state === 'taken') {
|
|
54
|
-
return {
|
|
55
|
-
ok: false,
|
|
56
|
-
reason: `\`lb\` is already used by ${status.path}, so I left it alone. Your other tool wins.`,
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
if (status.state === 'unknown') {
|
|
60
|
-
return {
|
|
61
|
-
ok: false,
|
|
62
|
-
reason:
|
|
63
|
-
'Could not find a global `layerbase` on your PATH (running locally or via npx?). ' +
|
|
64
|
-
'Add `alias lb=layerbase` to your shell profile instead.',
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const lbPath = join(status.binDir, isWin ? 'lb.cmd' : 'lb')
|
|
69
|
-
try {
|
|
70
|
-
if (isWin) {
|
|
71
|
-
writeFileSync(lbPath, '@layerbase %*\r\n')
|
|
72
|
-
} else {
|
|
73
|
-
symlinkSync(status.layerbasePath, lbPath)
|
|
74
|
-
}
|
|
75
|
-
return { ok: true, path: lbPath }
|
|
76
|
-
} catch (error) {
|
|
77
|
-
return {
|
|
78
|
-
ok: false,
|
|
79
|
-
reason:
|
|
80
|
-
`Could not create \`lb\` in ${status.binDir}: ${(error as Error).message}. ` +
|
|
81
|
-
'Add `alias lb=layerbase` to your shell profile instead.',
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
}
|
package/src/lib/browser-login.ts
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import { createServer } from 'node:http'
|
|
2
|
-
import { randomBytes } from 'node:crypto'
|
|
3
|
-
import type { AddressInfo } from 'node:net'
|
|
4
|
-
import { openBrowser } from './open-browser'
|
|
5
|
-
|
|
6
|
-
export type LoginPhase =
|
|
7
|
-
| { kind: 'starting' }
|
|
8
|
-
| { kind: 'waiting'; authUrl: string }
|
|
9
|
-
|
|
10
|
-
export type BrowserLoginResult = { token: string }
|
|
11
|
-
|
|
12
|
-
// Standard CLI OAuth-handoff: bind a loopback server on a random port, open the
|
|
13
|
-
// browser to the web /auth/cli page with that loopback as the redirect, and
|
|
14
|
-
// wait for the web callback to bounce back the freshly-minted token. A state
|
|
15
|
-
// nonce ties the request to this process so a stray request can't inject a token.
|
|
16
|
-
export async function runBrowserLogin(options: {
|
|
17
|
-
apiUrl: string
|
|
18
|
-
onPhase?: (phase: LoginPhase) => void
|
|
19
|
-
timeoutMs?: number
|
|
20
|
-
}): Promise<BrowserLoginResult> {
|
|
21
|
-
const { apiUrl, onPhase, timeoutMs = 120_000 } = options
|
|
22
|
-
const state = randomBytes(16).toString('hex')
|
|
23
|
-
|
|
24
|
-
onPhase?.({ kind: 'starting' })
|
|
25
|
-
|
|
26
|
-
return new Promise<BrowserLoginResult>((resolve, reject) => {
|
|
27
|
-
let timer: ReturnType<typeof setTimeout>
|
|
28
|
-
|
|
29
|
-
const server = createServer((req, res) => {
|
|
30
|
-
const reqUrl = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
31
|
-
if (reqUrl.pathname !== '/callback') {
|
|
32
|
-
res.statusCode = 404
|
|
33
|
-
res.end('Not found')
|
|
34
|
-
return
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const token = reqUrl.searchParams.get('token')
|
|
38
|
-
const returnedState = reqUrl.searchParams.get('state')
|
|
39
|
-
|
|
40
|
-
if (!token || returnedState !== state) {
|
|
41
|
-
res.statusCode = 400
|
|
42
|
-
res.setHeader('content-type', 'text/html')
|
|
43
|
-
res.end(page('Sign-in failed', 'You can close this tab and try again.'))
|
|
44
|
-
finish()
|
|
45
|
-
reject(
|
|
46
|
-
new Error(
|
|
47
|
-
'Sign-in failed: invalid or missing token from the browser.',
|
|
48
|
-
),
|
|
49
|
-
)
|
|
50
|
-
return
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
res.statusCode = 200
|
|
54
|
-
res.setHeader('content-type', 'text/html')
|
|
55
|
-
res.end(
|
|
56
|
-
page(
|
|
57
|
-
'Signed in to the Layerbase CLI',
|
|
58
|
-
'You can close this tab and return to your terminal.',
|
|
59
|
-
),
|
|
60
|
-
)
|
|
61
|
-
finish()
|
|
62
|
-
resolve({ token })
|
|
63
|
-
})
|
|
64
|
-
|
|
65
|
-
function finish() {
|
|
66
|
-
clearTimeout(timer)
|
|
67
|
-
server.close()
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
server.on('error', (error) => {
|
|
71
|
-
clearTimeout(timer)
|
|
72
|
-
reject(error)
|
|
73
|
-
})
|
|
74
|
-
|
|
75
|
-
// Bind to 127.0.0.1 only so no other machine on the network can reach it.
|
|
76
|
-
server.listen(0, '127.0.0.1', () => {
|
|
77
|
-
const { port } = server.address() as AddressInfo
|
|
78
|
-
const redirect = `http://127.0.0.1:${port}/callback`
|
|
79
|
-
const base = apiUrl.replace(/\/$/, '')
|
|
80
|
-
const authUrl =
|
|
81
|
-
`${base}/auth/cli?state=${encodeURIComponent(state)}` +
|
|
82
|
-
`&redirect=${encodeURIComponent(redirect)}`
|
|
83
|
-
|
|
84
|
-
onPhase?.({ kind: 'waiting', authUrl })
|
|
85
|
-
openBrowser(authUrl).catch(() => {
|
|
86
|
-
// Headless or no opener: the URL is shown in the CLI for manual use.
|
|
87
|
-
})
|
|
88
|
-
|
|
89
|
-
timer = setTimeout(() => {
|
|
90
|
-
server.close()
|
|
91
|
-
reject(
|
|
92
|
-
new Error(
|
|
93
|
-
'Sign-in timed out after 2 minutes. Run `layerbase login` again.',
|
|
94
|
-
),
|
|
95
|
-
)
|
|
96
|
-
}, timeoutMs)
|
|
97
|
-
})
|
|
98
|
-
})
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
function page(title: string, body: string): string {
|
|
102
|
-
return `<!doctype html>
|
|
103
|
-
<html lang="en">
|
|
104
|
-
<head><meta charset="utf-8"><title>${title}</title>
|
|
105
|
-
<style>
|
|
106
|
-
body { font-family: -apple-system, system-ui, sans-serif; background:#0b0b0f; color:#e5e5e5;
|
|
107
|
-
display:flex; min-height:100vh; align-items:center; justify-content:center; margin:0; }
|
|
108
|
-
.card { text-align:center; padding:2.5rem 3rem; border:1px solid #ffffff1a; border-radius:14px;
|
|
109
|
-
background:#ffffff08; }
|
|
110
|
-
h1 { font-size:1.25rem; margin:0 0 .5rem; }
|
|
111
|
-
p { color:#a3a3a3; margin:0; }
|
|
112
|
-
</style></head>
|
|
113
|
-
<body><div class="card"><h1>${title}</h1><p>${body}</p></div></body>
|
|
114
|
-
</html>`
|
|
115
|
-
}
|
package/src/lib/cloud-api.ts
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import { loadCredentials } from './config'
|
|
2
|
-
|
|
3
|
-
// These /api/cli/* endpoints and the /auth/cli login pages are implemented in
|
|
4
|
-
// the layerbase web app (app/(frontend)/api/cli/* and app/(frontend)/auth/cli/*).
|
|
5
|
-
// They must be deployed for `login` and the cloud calls below to work; the CLI
|
|
6
|
-
// authenticates with the 30-day JWT and the web app proxies to the cloud API,
|
|
7
|
-
// exactly like layerbase-desktop.
|
|
8
|
-
export const DEFAULT_API_URL =
|
|
9
|
-
process.env.LAYERBASE_API_URL ?? 'https://layerbase.com'
|
|
10
|
-
|
|
11
|
-
export type CloudDatabase = {
|
|
12
|
-
id: string
|
|
13
|
-
name: string
|
|
14
|
-
engine: string
|
|
15
|
-
status: string
|
|
16
|
-
region?: string
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export type ConnectionInfo = {
|
|
20
|
-
engine: string
|
|
21
|
-
host: string
|
|
22
|
-
port: number
|
|
23
|
-
database: string
|
|
24
|
-
username: string
|
|
25
|
-
password: string
|
|
26
|
-
// Some engines hand back a ready-made URI instead of discrete parts.
|
|
27
|
-
uri?: string
|
|
28
|
-
tls?: boolean
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export type WhoamiResponse = {
|
|
32
|
-
user: {
|
|
33
|
-
id: string
|
|
34
|
-
email: string
|
|
35
|
-
name: string | null
|
|
36
|
-
avatarUrl: string | null
|
|
37
|
-
role: 'admin' | 'user' | null
|
|
38
|
-
}
|
|
39
|
-
hasActivePlan: boolean
|
|
40
|
-
cloudApiKey: string | null
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
async function authedFetch(
|
|
44
|
-
path: string,
|
|
45
|
-
init?: RequestInit,
|
|
46
|
-
): Promise<Response> {
|
|
47
|
-
const credentials = await loadCredentials()
|
|
48
|
-
if (!credentials) {
|
|
49
|
-
throw new Error('Not logged in. Run `layerbase login` first.')
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const response = await fetch(new URL(path, credentials.apiUrl), {
|
|
53
|
-
...init,
|
|
54
|
-
headers: {
|
|
55
|
-
authorization: `Bearer ${credentials.token}`,
|
|
56
|
-
'content-type': 'application/json',
|
|
57
|
-
...init?.headers,
|
|
58
|
-
},
|
|
59
|
-
})
|
|
60
|
-
|
|
61
|
-
if (response.status === 401) {
|
|
62
|
-
throw new Error(
|
|
63
|
-
'Your session has expired. Run `layerbase login` to sign in again.',
|
|
64
|
-
)
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
if (!response.ok) {
|
|
68
|
-
const body = await response.text().catch(() => '')
|
|
69
|
-
throw new Error(
|
|
70
|
-
`Cloud API ${response.status}: ${body || response.statusText}. ` +
|
|
71
|
-
'Check the database id or name (`layerbase ls`).',
|
|
72
|
-
)
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
return response
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export async function whoami(): Promise<WhoamiResponse> {
|
|
79
|
-
const response = await authedFetch('/api/cli/whoami')
|
|
80
|
-
return (await response.json()) as WhoamiResponse
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export async function listDatabases(): Promise<CloudDatabase[]> {
|
|
84
|
-
const response = await authedFetch('/api/cli/databases')
|
|
85
|
-
const data = (await response.json()) as { databases: CloudDatabase[] }
|
|
86
|
-
return data.databases
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export async function getConnectionInfo(
|
|
90
|
-
dbRef: string,
|
|
91
|
-
): Promise<ConnectionInfo> {
|
|
92
|
-
const response = await authedFetch(
|
|
93
|
-
`/api/cli/databases/${encodeURIComponent(dbRef)}/connection-info`,
|
|
94
|
-
)
|
|
95
|
-
return (await response.json()) as ConnectionInfo
|
|
96
|
-
}
|
package/src/lib/config.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { homedir } from 'node:os'
|
|
2
|
-
import { join } from 'node:path'
|
|
3
|
-
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
|
4
|
-
|
|
5
|
-
// Mirrors layerbase-desktop's ~/.layerbase-desktop convention. The desktop app
|
|
6
|
-
// relies on Electron safeStorage (OS-encrypted); a plain CLI has no equivalent,
|
|
7
|
-
// so we lock the file down to 0600 ourselves.
|
|
8
|
-
const CONFIG_DIR = join(homedir(), '.layerbase-cli')
|
|
9
|
-
const CREDENTIALS_FILE = join(CONFIG_DIR, 'credentials.json')
|
|
10
|
-
|
|
11
|
-
export type StoredCredentials = {
|
|
12
|
-
apiUrl: string
|
|
13
|
-
// The 30-day Layerbase CLI token (JWT), sent as `Authorization: Bearer`.
|
|
14
|
-
token: string
|
|
15
|
-
// Cached cloud API key from /api/cli/whoami, like the desktop app stores.
|
|
16
|
-
cloudApiKey?: string | null
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export async function saveCredentials(
|
|
20
|
-
credentials: StoredCredentials,
|
|
21
|
-
): Promise<void> {
|
|
22
|
-
await mkdir(CONFIG_DIR, { recursive: true, mode: 0o700 })
|
|
23
|
-
await writeFile(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2), {
|
|
24
|
-
mode: 0o600,
|
|
25
|
-
})
|
|
26
|
-
// writeFile honours umask on an existing file, so force the mode explicitly.
|
|
27
|
-
await chmod(CREDENTIALS_FILE, 0o600)
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export async function loadCredentials(): Promise<StoredCredentials | null> {
|
|
31
|
-
try {
|
|
32
|
-
const raw = await readFile(CREDENTIALS_FILE, 'utf8')
|
|
33
|
-
return JSON.parse(raw) as StoredCredentials
|
|
34
|
-
} catch {
|
|
35
|
-
return null
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export async function clearCredentials(): Promise<void> {
|
|
40
|
-
await rm(CREDENTIALS_FILE, { force: true })
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function credentialsPath(): string {
|
|
44
|
-
return CREDENTIALS_FILE
|
|
45
|
-
}
|
package/src/lib/engines.ts
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
import type { ConnectionInfo } from './cloud-api'
|
|
2
|
-
|
|
3
|
-
// Engine values mirror the canonical `Engine` map shared across the Layerbase
|
|
4
|
-
// ecosystem (web `lib/databases.ts`, cloud `src/config/engines.ts`). Kept as a
|
|
5
|
-
// local literal here so the CLI stays a standalone package with no cross-repo
|
|
6
|
-
// import.
|
|
7
|
-
const PG_FAMILY = new Set(['postgresql', 'cockroachdb'])
|
|
8
|
-
const MYSQL_FAMILY = new Set(['mysql', 'mariadb'])
|
|
9
|
-
const REDIS_FAMILY = new Set(['redis', 'valkey'])
|
|
10
|
-
|
|
11
|
-
// How the child process learns a path-based secret without it touching argv as
|
|
12
|
-
// a value: either via an env var pointing at a 0600 file, or via an argv option
|
|
13
|
-
// whose value is the (non-secret) path to a 0600 file.
|
|
14
|
-
export type TempFile = {
|
|
15
|
-
contents: string
|
|
16
|
-
mode: number
|
|
17
|
-
via:
|
|
18
|
-
| { type: 'env'; envVar: string }
|
|
19
|
-
| { type: 'argv'; render: (path: string) => string[] }
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export type LaunchPlan = {
|
|
23
|
-
bin: string
|
|
24
|
-
// argv never contains the password. Host/port/db/user are not secret.
|
|
25
|
-
argv: string[]
|
|
26
|
-
env?: Record<string, string>
|
|
27
|
-
// Secret env vars are merged just for the child, never logged.
|
|
28
|
-
secretEnv?: Record<string, string>
|
|
29
|
-
tempFile?: TempFile
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function commandMatchesEngine(command: string, engine: string): void {
|
|
33
|
-
const aliasFamily: Record<string, Set<string>> = {
|
|
34
|
-
psql: PG_FAMILY,
|
|
35
|
-
'redis-cli': REDIS_FAMILY,
|
|
36
|
-
mysql: MYSQL_FAMILY,
|
|
37
|
-
}
|
|
38
|
-
const expected = aliasFamily[command]
|
|
39
|
-
if (expected && !expected.has(engine)) {
|
|
40
|
-
throw new Error(
|
|
41
|
-
`\`layerbase ${command}\` does not match engine "${engine}". ` +
|
|
42
|
-
'Use `layerbase connect <db>` to auto-pick the right client.',
|
|
43
|
-
)
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function buildLaunchPlan(options: {
|
|
48
|
-
info: ConnectionInfo
|
|
49
|
-
command: string
|
|
50
|
-
}): LaunchPlan {
|
|
51
|
-
const { info, command } = options
|
|
52
|
-
const engine = info.engine.toLowerCase()
|
|
53
|
-
commandMatchesEngine(command, engine)
|
|
54
|
-
|
|
55
|
-
if (PG_FAMILY.has(engine)) {
|
|
56
|
-
return {
|
|
57
|
-
bin: 'psql',
|
|
58
|
-
argv: [
|
|
59
|
-
'-h',
|
|
60
|
-
info.host,
|
|
61
|
-
'-p',
|
|
62
|
-
String(info.port),
|
|
63
|
-
'-U',
|
|
64
|
-
info.username,
|
|
65
|
-
'-d',
|
|
66
|
-
info.database,
|
|
67
|
-
],
|
|
68
|
-
env: { PGSSLMODE: info.tls === false ? 'prefer' : 'require' },
|
|
69
|
-
tempFile: {
|
|
70
|
-
// ~/.pgpass line format: host:port:database:user:password
|
|
71
|
-
contents: `${info.host}:${info.port}:${info.database}:${info.username}:${info.password}\n`,
|
|
72
|
-
mode: 0o600,
|
|
73
|
-
via: { type: 'env', envVar: 'PGPASSFILE' },
|
|
74
|
-
},
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
if (MYSQL_FAMILY.has(engine)) {
|
|
79
|
-
return {
|
|
80
|
-
bin: 'mysql',
|
|
81
|
-
argv: [
|
|
82
|
-
'-h',
|
|
83
|
-
info.host,
|
|
84
|
-
'-P',
|
|
85
|
-
String(info.port),
|
|
86
|
-
'-u',
|
|
87
|
-
info.username,
|
|
88
|
-
info.database,
|
|
89
|
-
],
|
|
90
|
-
tempFile: {
|
|
91
|
-
// --defaults-extra-file must precede other client options, so it is
|
|
92
|
-
// prepended to argv. The file (0600) holds the password, not argv.
|
|
93
|
-
contents: `[client]\npassword="${info.password}"\n`,
|
|
94
|
-
mode: 0o600,
|
|
95
|
-
via: {
|
|
96
|
-
type: 'argv',
|
|
97
|
-
render: (path) => [`--defaults-extra-file=${path}`],
|
|
98
|
-
},
|
|
99
|
-
},
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
if (REDIS_FAMILY.has(engine)) {
|
|
104
|
-
const argv = ['-h', info.host, '-p', String(info.port)]
|
|
105
|
-
if (info.tls !== false) {
|
|
106
|
-
argv.push('--tls', '--sni', info.host)
|
|
107
|
-
}
|
|
108
|
-
if (info.username && info.username !== 'default') {
|
|
109
|
-
argv.push('--user', info.username)
|
|
110
|
-
}
|
|
111
|
-
return {
|
|
112
|
-
bin: 'redis-cli',
|
|
113
|
-
argv,
|
|
114
|
-
// redis-cli reads the password from REDISCLI_AUTH instead of -a, which
|
|
115
|
-
// would otherwise show in `ps` and trigger its own warning.
|
|
116
|
-
secretEnv: { REDISCLI_AUTH: info.password },
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
throw new Error(
|
|
121
|
-
`No secure interactive client is wired for engine "${engine}" yet. ` +
|
|
122
|
-
`Use \`layerbase connection-string <db>\` or the dashboard query console.`,
|
|
123
|
-
)
|
|
124
|
-
}
|
package/src/lib/format.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import type { ConnectionInfo } from './cloud-api'
|
|
2
|
-
|
|
3
|
-
const SCHEME_BY_ENGINE: Record<string, string> = {
|
|
4
|
-
postgresql: 'postgresql',
|
|
5
|
-
cockroachdb: 'postgresql',
|
|
6
|
-
mysql: 'mysql',
|
|
7
|
-
mariadb: 'mysql',
|
|
8
|
-
redis: 'redis',
|
|
9
|
-
valkey: 'redis',
|
|
10
|
-
mongodb: 'mongodb',
|
|
11
|
-
ferretdb: 'mongodb',
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function buildConnectionString(info: ConnectionInfo): string {
|
|
15
|
-
if (info.uri) {
|
|
16
|
-
return info.uri
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
const scheme = SCHEME_BY_ENGINE[info.engine.toLowerCase()]
|
|
20
|
-
if (!scheme) {
|
|
21
|
-
throw new Error(
|
|
22
|
-
`Cannot build a connection string for engine "${info.engine}". ` +
|
|
23
|
-
'The cloud API did not return a ready-made uri for it.',
|
|
24
|
-
)
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const auth = `${encodeURIComponent(info.username)}:${encodeURIComponent(
|
|
28
|
-
info.password,
|
|
29
|
-
)}`
|
|
30
|
-
const path = info.database ? `/${info.database}` : ''
|
|
31
|
-
return `${scheme}://${auth}@${info.host}:${info.port}${path}`
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// Prints connection details for `--print`. The password is masked; use
|
|
35
|
-
// `layerbase connection-string <db>` to deliberately reveal it.
|
|
36
|
-
export function printConnectionInfo(info: ConnectionInfo): void {
|
|
37
|
-
const lines = [
|
|
38
|
-
`engine ${info.engine}`,
|
|
39
|
-
`host ${info.host}`,
|
|
40
|
-
`port ${info.port}`,
|
|
41
|
-
`database ${info.database}`,
|
|
42
|
-
`username ${info.username}`,
|
|
43
|
-
`password ${'*'.repeat(8)} (hidden)`,
|
|
44
|
-
`tls ${info.tls === false ? 'off' : 'on'}`,
|
|
45
|
-
]
|
|
46
|
-
process.stdout.write(`${lines.join('\n')}\n`)
|
|
47
|
-
}
|
package/src/lib/launch.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process'
|
|
2
|
-
import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
|
3
|
-
import { tmpdir } from 'node:os'
|
|
4
|
-
import { join } from 'node:path'
|
|
5
|
-
import type { LaunchPlan } from './engines'
|
|
6
|
-
|
|
7
|
-
// Spawns the engine's native client with credentials passed via env or a
|
|
8
|
-
// transient 0600 file, never on argv, then cleans the credential up on exit.
|
|
9
|
-
export async function runClient(plan: LaunchPlan): Promise<number> {
|
|
10
|
-
const scratch = await mkdtemp(join(tmpdir(), 'layerbase-'))
|
|
11
|
-
const env: NodeJS.ProcessEnv = {
|
|
12
|
-
...process.env,
|
|
13
|
-
...plan.env,
|
|
14
|
-
...plan.secretEnv,
|
|
15
|
-
}
|
|
16
|
-
let argv = plan.argv
|
|
17
|
-
|
|
18
|
-
try {
|
|
19
|
-
if (plan.tempFile) {
|
|
20
|
-
const file = join(scratch, 'credential')
|
|
21
|
-
await writeFile(file, plan.tempFile.contents, {
|
|
22
|
-
mode: plan.tempFile.mode,
|
|
23
|
-
})
|
|
24
|
-
await chmod(file, plan.tempFile.mode)
|
|
25
|
-
|
|
26
|
-
if (plan.tempFile.via.type === 'env') {
|
|
27
|
-
env[plan.tempFile.via.envVar] = file
|
|
28
|
-
} else {
|
|
29
|
-
argv = [...plan.tempFile.via.render(file), ...argv]
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
return await new Promise<number>((resolve) => {
|
|
34
|
-
const child = spawn(plan.bin, argv, { stdio: 'inherit', env })
|
|
35
|
-
child.on('error', (error) => {
|
|
36
|
-
process.stderr.write(
|
|
37
|
-
`Failed to launch \`${plan.bin}\`: ${error.message}\n` +
|
|
38
|
-
`Make sure \`${plan.bin}\` is installed and on your PATH.\n`,
|
|
39
|
-
)
|
|
40
|
-
resolve(127)
|
|
41
|
-
})
|
|
42
|
-
child.on('exit', (exitCode) => resolve(exitCode ?? 0))
|
|
43
|
-
})
|
|
44
|
-
} finally {
|
|
45
|
-
await rm(scratch, { recursive: true, force: true })
|
|
46
|
-
}
|
|
47
|
-
}
|
package/src/lib/open-browser.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process'
|
|
2
|
-
|
|
3
|
-
// Opens a URL in the user's default browser. No dependency: just the per-OS
|
|
4
|
-
// opener. Rejects if the opener binary can't be spawned (e.g. headless box),
|
|
5
|
-
// so the caller can fall back to printing the URL.
|
|
6
|
-
export async function openBrowser(url: string): Promise<void> {
|
|
7
|
-
const platform = process.platform
|
|
8
|
-
const command =
|
|
9
|
-
platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'
|
|
10
|
-
const args = platform === 'win32' ? ['/c', 'start', '', url] : [url]
|
|
11
|
-
|
|
12
|
-
await new Promise<void>((resolve, reject) => {
|
|
13
|
-
const child = spawn(command, args, { stdio: 'ignore', detached: true })
|
|
14
|
-
child.on('error', reject)
|
|
15
|
-
child.on('spawn', () => {
|
|
16
|
-
child.unref()
|
|
17
|
-
resolve()
|
|
18
|
-
})
|
|
19
|
-
})
|
|
20
|
-
}
|