layerbase 0.0.3 → 0.1.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,103 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { Box, Text, useApp } from 'ink'
3
+ import Spinner from 'ink-spinner'
4
+ import { runBrowserLogin } from '../lib/browser-login'
5
+ import { DEFAULT_API_URL, whoami } from '../lib/cloud-api'
6
+ import { saveCredentials, credentialsPath } from '../lib/config'
7
+ import type { CommandFlags } from '../ui/app'
8
+
9
+ type Phase =
10
+ | { kind: 'starting' }
11
+ | { kind: 'waiting'; authUrl: string }
12
+ | { kind: 'finishing' }
13
+ | { kind: 'done'; email: string }
14
+ | { kind: 'error'; message: string }
15
+
16
+ export function Login({ flags }: { flags: CommandFlags }) {
17
+ const { exit } = useApp()
18
+ const apiUrl = flags.apiUrl ?? DEFAULT_API_URL
19
+ const [phase, setPhase] = useState<Phase>({ kind: 'starting' })
20
+
21
+ useEffect(() => {
22
+ async function runLogin() {
23
+ try {
24
+ const { token } = await runBrowserLogin({
25
+ apiUrl,
26
+ onPhase: setPhase,
27
+ })
28
+ setPhase({ kind: 'finishing' })
29
+ // Save the token first so whoami() can read it, then enrich with the
30
+ // cloud API key (best-effort, mirrors how desktop backfills it).
31
+ await saveCredentials({ apiUrl, token })
32
+ let email = ''
33
+ try {
34
+ const me = await whoami()
35
+ email = me.user.email
36
+ await saveCredentials({ apiUrl, token, cloudApiKey: me.cloudApiKey })
37
+ } catch {
38
+ // Token is already saved; enrichment is non-fatal.
39
+ }
40
+ setPhase({ kind: 'done', email })
41
+ } catch (error) {
42
+ process.exitCode = 1
43
+ setPhase({ kind: 'error', message: (error as Error).message })
44
+ }
45
+ }
46
+ runLogin()
47
+ }, [apiUrl])
48
+
49
+ // Exit only after the terminal frame has committed.
50
+ useEffect(() => {
51
+ if (phase.kind === 'done' || phase.kind === 'error') {
52
+ exit()
53
+ }
54
+ }, [phase, exit])
55
+
56
+ if (phase.kind === 'starting') {
57
+ return (
58
+ <Box>
59
+ <Text color="cyan">
60
+ <Spinner type="dots" />
61
+ </Text>
62
+ <Text> Starting sign-in...</Text>
63
+ </Box>
64
+ )
65
+ }
66
+
67
+ if (phase.kind === 'waiting') {
68
+ return (
69
+ <Box flexDirection="column">
70
+ <Box>
71
+ <Text color="cyan">
72
+ <Spinner type="dots" />
73
+ </Text>
74
+ <Text> Waiting for you to finish signing in in your browser...</Text>
75
+ </Box>
76
+ <Text dimColor>If your browser did not open, visit:</Text>
77
+ <Text color="blue">{phase.authUrl}</Text>
78
+ </Box>
79
+ )
80
+ }
81
+
82
+ if (phase.kind === 'finishing') {
83
+ return (
84
+ <Box>
85
+ <Text color="cyan">
86
+ <Spinner type="dots" />
87
+ </Text>
88
+ <Text> Saving credentials...</Text>
89
+ </Box>
90
+ )
91
+ }
92
+
93
+ if (phase.kind === 'done') {
94
+ return (
95
+ <Text color="green">
96
+ Logged in{phase.email ? ` as ${phase.email}` : ''}. Saved to{' '}
97
+ {credentialsPath()}.
98
+ </Text>
99
+ )
100
+ }
101
+
102
+ return <Text color="red">{phase.message}</Text>
103
+ }
@@ -0,0 +1,27 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { Text, useApp } from 'ink'
3
+ import { clearCredentials } from '../lib/config'
4
+
5
+ export function Logout() {
6
+ const { exit } = useApp()
7
+ const [done, setDone] = useState(false)
8
+
9
+ useEffect(() => {
10
+ async function fetchAndClearCredentials() {
11
+ await clearCredentials()
12
+ setDone(true)
13
+ }
14
+ fetchAndClearCredentials()
15
+ }, [])
16
+
17
+ useEffect(() => {
18
+ if (done) {
19
+ exit()
20
+ }
21
+ }, [done, exit])
22
+
23
+ if (!done) {
24
+ return null
25
+ }
26
+ return <Text color="green">Logged out. Stored API key removed.</Text>
27
+ }
@@ -0,0 +1,99 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { Box, Text, useApp } from 'ink'
3
+ import Spinner from 'ink-spinner'
4
+ import { listDatabases } from '../lib/cloud-api'
5
+ import type { CloudDatabase } from '../lib/cloud-api'
6
+
7
+ type State =
8
+ | { kind: 'loading' }
9
+ | { kind: 'ready'; databases: CloudDatabase[] }
10
+ | { kind: 'error'; message: string }
11
+
12
+ const STATUS_COLOR: Record<string, string> = {
13
+ running: 'green',
14
+ hibernated: 'yellow',
15
+ stopped: 'gray',
16
+ archived: 'gray',
17
+ provisioning: 'cyan',
18
+ error: 'red',
19
+ }
20
+
21
+ function pad(value: string, width: number): string {
22
+ return value.length >= width
23
+ ? value
24
+ : value + ' '.repeat(width - value.length)
25
+ }
26
+
27
+ export function List({ json }: { json: boolean }) {
28
+ const { exit } = useApp()
29
+ const [state, setState] = useState<State>({ kind: 'loading' })
30
+
31
+ useEffect(() => {
32
+ async function fetchAndSetDatabases() {
33
+ try {
34
+ const databases = await listDatabases()
35
+ if (json) {
36
+ process.stdout.write(`${JSON.stringify(databases, null, 2)}\n`)
37
+ }
38
+ setState({ kind: 'ready', databases })
39
+ } catch (error) {
40
+ setState({ kind: 'error', message: (error as Error).message })
41
+ process.exitCode = 1
42
+ }
43
+ }
44
+ fetchAndSetDatabases()
45
+ }, [json])
46
+
47
+ // Exit only after the terminal frame has committed, so the table or error is
48
+ // actually rendered before Ink unmounts.
49
+ useEffect(() => {
50
+ if (state.kind !== 'loading') {
51
+ exit()
52
+ }
53
+ }, [state, exit])
54
+
55
+ if (state.kind === 'loading') {
56
+ return (
57
+ <Box>
58
+ <Text color="cyan">
59
+ <Spinner type="dots" />
60
+ </Text>
61
+ <Text> Loading your databases...</Text>
62
+ </Box>
63
+ )
64
+ }
65
+
66
+ if (state.kind === 'error') {
67
+ return <Text color="red">{state.message}</Text>
68
+ }
69
+
70
+ // JSON already written to stdout; render nothing further.
71
+ if (json) {
72
+ return null
73
+ }
74
+
75
+ if (state.databases.length === 0) {
76
+ return <Text>No databases yet. Create one at https://layerbase.com.</Text>
77
+ }
78
+
79
+ return (
80
+ <Box flexDirection="column">
81
+ <Text bold>
82
+ {pad('NAME', 24)}
83
+ {pad('ENGINE', 14)}
84
+ {pad('STATUS', 14)}
85
+ ID
86
+ </Text>
87
+ {state.databases.map((db) => (
88
+ <Text key={db.id}>
89
+ {pad(db.name, 24)}
90
+ {pad(db.engine, 14)}
91
+ <Text color={STATUS_COLOR[db.status] ?? 'white'}>
92
+ {pad(db.status, 14)}
93
+ </Text>
94
+ {db.id}
95
+ </Text>
96
+ ))}
97
+ </Box>
98
+ )
99
+ }
@@ -0,0 +1,64 @@
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
+ }
@@ -0,0 +1,84 @@
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
+ }
@@ -0,0 +1,115 @@
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
+ }
@@ -0,0 +1,96 @@
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
+ }
@@ -0,0 +1,45 @@
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
+ }