@gheima/cli 0.4.0 → 0.5.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/CHANGELOG.md +24 -0
- package/README.md +29 -1
- package/dist/cli.js +49 -2
- package/dist/device-login.js +102 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# @gheima/cli
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 06d9ffc: Sign in through the browser instead of pasting an API key.
|
|
8
|
+
|
|
9
|
+
`gheima login` now starts a device authorization (RFC 8628): it prints a short code, opens
|
|
10
|
+
the dashboard, and polls until someone approves. The key arrives over the same connection
|
|
11
|
+
and is stored in the profile as before, so nothing downstream changes. Approving creates a
|
|
12
|
+
key named after the machine, revocable in Settings → API keys like any other, and only an
|
|
13
|
+
owner or admin can approve one because approving mints a credential.
|
|
14
|
+
|
|
15
|
+
The old path is still there for the cases the browser cannot serve: `--with-key` pastes a
|
|
16
|
+
key, `--no-browser` prints the URL for a headless or SSH session, and passing `--key`
|
|
17
|
+
skips the browser entirely.
|
|
18
|
+
|
|
19
|
+
The polling loop honours the server's `interval` and backs off further on `slow_down`,
|
|
20
|
+
because a client that ignores those is a self-inflicted denial of service against an
|
|
21
|
+
endpoint that takes no credential.
|
|
22
|
+
|
|
23
|
+
Note the published 0.4.0 has the paste-only flow while this repo's 0.4.0 does not, so the
|
|
24
|
+
README on `main` currently describes a browser login that installed clients do not have.
|
|
25
|
+
This release is what closes that gap.
|
|
26
|
+
|
|
3
27
|
## 0.4.0
|
|
4
28
|
|
|
5
29
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -13,16 +13,44 @@ Requires Node.js 18 or newer.
|
|
|
13
13
|
|
|
14
14
|
## Authentication
|
|
15
15
|
|
|
16
|
+
`gheima login` signs you in through the browser. It prints a short code, opens the
|
|
17
|
+
dashboard, and waits while you approve it — nothing is pasted.
|
|
18
|
+
|
|
16
19
|
```bash
|
|
17
|
-
gheima login #
|
|
20
|
+
gheima login # browser sign-in; the key is stored in ~/.config/gheima/config.json (0600)
|
|
21
|
+
gheima login --no-browser # print the URL instead of opening one (SSH, CI, headless)
|
|
22
|
+
gheima login --with-key # paste an existing API key instead
|
|
18
23
|
gheima login --profile work # named profile
|
|
19
24
|
gheima whoami
|
|
20
25
|
gheima logout
|
|
21
26
|
```
|
|
22
27
|
|
|
28
|
+
Approving creates an API key named after your machine. It appears in **Settings → API
|
|
29
|
+
keys** like any other and can be revoked there at any time. Only an owner or admin can
|
|
30
|
+
approve a device, because approving one mints a key.
|
|
31
|
+
|
|
32
|
+
Approve a login only if you just started it yourself. The approval screen shows the client
|
|
33
|
+
name and the address the request came from — an unfamiliar one means someone else's login,
|
|
34
|
+
and approving it would hand them a key on your account.
|
|
35
|
+
|
|
36
|
+
The login expires after ten minutes and each code can be used once.
|
|
37
|
+
|
|
23
38
|
Resolution order for every command: `--key` → `GHEIMA_API_KEY` → stored profile
|
|
24
39
|
(`--profile` or the current one). Base URL: `--url` → `GHEIMA_URL` → profile.
|
|
25
40
|
|
|
41
|
+
### `command not found: gheima` after a global install
|
|
42
|
+
|
|
43
|
+
Your npm global bin directory is not on `PATH` — the package installed fine. Check where it
|
|
44
|
+
went and add it:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npm prefix -g # e.g. /Users/you/.npm-global
|
|
48
|
+
echo 'export PATH="$(npm prefix -g)/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
This bites anyone who set a custom npm prefix to avoid `sudo` without also extending
|
|
52
|
+
`PATH`. `npx gheima <command>` works regardless.
|
|
53
|
+
|
|
26
54
|
## Commands
|
|
27
55
|
|
|
28
56
|
### Account
|
package/dist/cli.js
CHANGED
|
@@ -13,6 +13,7 @@ import { prompt, promptHidden, confirm } from './prompt.js';
|
|
|
13
13
|
import { table, printJson, spinner, success, info, color } from './ui.js';
|
|
14
14
|
import { completionScript } from './completion.js';
|
|
15
15
|
import { registerGenerated } from './generated.js';
|
|
16
|
+
import { defaultClientName, openBrowser, pollForApproval, startDeviceLogin, } from './device-login.js';
|
|
16
17
|
const require = createRequire(import.meta.url);
|
|
17
18
|
const pkg = require('../package.json');
|
|
18
19
|
const program = new Command();
|
|
@@ -65,10 +66,25 @@ function fail(err) {
|
|
|
65
66
|
// ---------------------------------------------------------------------------
|
|
66
67
|
program
|
|
67
68
|
.command('login')
|
|
68
|
-
.description('
|
|
69
|
-
.
|
|
69
|
+
.description('Sign in through the browser, or with an existing API key')
|
|
70
|
+
.option('--no-browser', 'print the URL instead of opening a browser')
|
|
71
|
+
.option('--with-key', 'paste an existing API key instead of using the browser')
|
|
72
|
+
.action(async (opts, cmd) => {
|
|
70
73
|
const g = globals(cmd);
|
|
71
74
|
const profileName = g.profile || 'default';
|
|
75
|
+
const baseUrl = (g.url || process.env.GHEIMA_URL || 'https://gheima.ma').replace(/\/$/, '');
|
|
76
|
+
// `--key` on the program means the caller already has a credential and is not asking to
|
|
77
|
+
// be sent through a browser at all.
|
|
78
|
+
const pasteInstead = opts.withKey || Boolean(g.key);
|
|
79
|
+
if (!pasteInstead) {
|
|
80
|
+
try {
|
|
81
|
+
await browserLogin(baseUrl, profileName, opts.browser !== false, g.url);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
fail(err);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
72
88
|
let key = g.key;
|
|
73
89
|
if (!key) {
|
|
74
90
|
info('Create an API key in the dashboard → Settings → API keys.');
|
|
@@ -89,6 +105,37 @@ program
|
|
|
89
105
|
fail(err);
|
|
90
106
|
}
|
|
91
107
|
});
|
|
108
|
+
/**
|
|
109
|
+
* Browser half of `gheima login`.
|
|
110
|
+
*
|
|
111
|
+
* The user code is printed BEFORE the browser opens, and printed again if opening fails, so
|
|
112
|
+
* the flow never depends on a browser launching. On a headless box `--no-browser` prints the
|
|
113
|
+
* URL and the code and nothing else is needed.
|
|
114
|
+
*/
|
|
115
|
+
async function browserLogin(baseUrl, profileName, wantBrowser, urlOverride) {
|
|
116
|
+
const started = await startDeviceLogin(baseUrl, defaultClientName());
|
|
117
|
+
info(`Your code is ${color.bold(started.user_code)}`);
|
|
118
|
+
info(`Open ${color.bold(started.verification_uri_complete)} and approve it.`);
|
|
119
|
+
if (wantBrowser && !openBrowser(started.verification_uri_complete)) {
|
|
120
|
+
info('Could not open a browser — open the URL above by hand.');
|
|
121
|
+
}
|
|
122
|
+
const spin = spinner('Waiting for approval…');
|
|
123
|
+
try {
|
|
124
|
+
const result = await pollForApproval(baseUrl, started, {
|
|
125
|
+
onSlowDown: (seconds) => info(`Server asked for a slower poll — now every ${seconds}s.`),
|
|
126
|
+
});
|
|
127
|
+
spin.stop();
|
|
128
|
+
setProfile(profileName, { apiKey: result.apiKey, url: urlOverride });
|
|
129
|
+
const client = new GheimaClient({ apiKey: result.apiKey, baseUrl: urlOverride });
|
|
130
|
+
const account = await client.account.get();
|
|
131
|
+
success(`Logged in as ${color.bold(account.name)} (${account.slug}) → profile "${profileName}"`);
|
|
132
|
+
info(`Key "${result.keyName}" created. Revoke it any time in Settings → API keys.`);
|
|
133
|
+
}
|
|
134
|
+
catch (err) {
|
|
135
|
+
spin.stop();
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
92
139
|
program
|
|
93
140
|
.command('logout')
|
|
94
141
|
.description('Remove a stored profile')
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { hostname, userInfo } from 'node:os';
|
|
3
|
+
/** A name the approver will recognise as their own machine — or not, if it is not theirs. */
|
|
4
|
+
export function defaultClientName() {
|
|
5
|
+
let who = 'cli';
|
|
6
|
+
try {
|
|
7
|
+
who = userInfo().username || 'cli';
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
// Some sandboxes have no passwd entry; the host alone is still useful.
|
|
11
|
+
}
|
|
12
|
+
let host = '';
|
|
13
|
+
try {
|
|
14
|
+
host = hostname();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// Fall through to the bare user name.
|
|
18
|
+
}
|
|
19
|
+
return host ? `CLI on ${host} (${who})` : `CLI (${who})`;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Open a URL in the platform's default browser, best-effort.
|
|
23
|
+
*
|
|
24
|
+
* Returns false rather than throwing when there is no browser to open — headless CI, a
|
|
25
|
+
* bare SSH session — because the flow still works if the person opens the URL themselves.
|
|
26
|
+
* The child is detached and its stdio discarded so a browser that logs to stdout cannot
|
|
27
|
+
* interleave with the CLI's own output or hold the process open.
|
|
28
|
+
*/
|
|
29
|
+
export function openBrowser(url) {
|
|
30
|
+
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
|
|
31
|
+
try {
|
|
32
|
+
const child = spawn(cmd, [url], {
|
|
33
|
+
stdio: 'ignore',
|
|
34
|
+
detached: true,
|
|
35
|
+
shell: process.platform === 'win32',
|
|
36
|
+
});
|
|
37
|
+
child.on('error', () => undefined); // a missing xdg-open must not crash the login
|
|
38
|
+
child.unref();
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
async function postJson(url, body, signal) {
|
|
46
|
+
return fetch(url, {
|
|
47
|
+
method: 'POST',
|
|
48
|
+
headers: { 'content-type': 'application/json', 'user-agent': 'gheima-cli' },
|
|
49
|
+
body: JSON.stringify(body),
|
|
50
|
+
signal,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export async function startDeviceLogin(baseUrl, clientName) {
|
|
54
|
+
const res = await postJson(`${baseUrl}/api/v1/device/start`, { client_name: clientName });
|
|
55
|
+
if (!res.ok) {
|
|
56
|
+
const body = (await res.json().catch(() => ({})));
|
|
57
|
+
throw new Error(body.error?.message ?? `Could not start a login (HTTP ${res.status})`);
|
|
58
|
+
}
|
|
59
|
+
return (await res.json());
|
|
60
|
+
}
|
|
61
|
+
const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
62
|
+
/**
|
|
63
|
+
* Poll until the login is approved, denied or expires.
|
|
64
|
+
*
|
|
65
|
+
* Honours the server's `interval`, and on `slow_down` increases it permanently for the rest
|
|
66
|
+
* of this login — RFC 8628 §3.5 says a client that receives `slow_down` must increase its
|
|
67
|
+
* interval, not retry at the same rate and hope.
|
|
68
|
+
*/
|
|
69
|
+
export async function pollForApproval(baseUrl, start, opts = {}) {
|
|
70
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
71
|
+
const now = opts.now ?? (() => Date.now());
|
|
72
|
+
const deadline = now() + start.expires_in * 1000;
|
|
73
|
+
let intervalMs = Math.max(1, start.interval) * 1000;
|
|
74
|
+
for (;;) {
|
|
75
|
+
if (now() >= deadline) {
|
|
76
|
+
throw new Error('This login expired before it was approved — run `gheima login` again');
|
|
77
|
+
}
|
|
78
|
+
await sleep(intervalMs);
|
|
79
|
+
const res = await postJson(`${baseUrl}/api/v1/device/token`, {
|
|
80
|
+
device_code: start.device_code,
|
|
81
|
+
});
|
|
82
|
+
if (res.ok) {
|
|
83
|
+
const body = (await res.json());
|
|
84
|
+
return { apiKey: body.api_key, accountId: body.account_id, keyName: body.key_name };
|
|
85
|
+
}
|
|
86
|
+
const body = (await res.json().catch(() => ({})));
|
|
87
|
+
switch (body.error?.code) {
|
|
88
|
+
case 'authorization_pending':
|
|
89
|
+
break; // keep waiting
|
|
90
|
+
case 'slow_down':
|
|
91
|
+
intervalMs += 5000;
|
|
92
|
+
opts.onSlowDown?.(Math.round(intervalMs / 1000));
|
|
93
|
+
break;
|
|
94
|
+
case 'access_denied':
|
|
95
|
+
throw new Error('The login was denied in the dashboard');
|
|
96
|
+
case 'expired_token':
|
|
97
|
+
throw new Error('This login expired or was already used — run `gheima login` again');
|
|
98
|
+
default:
|
|
99
|
+
throw new Error(body.error?.message ?? `Login failed (HTTP ${res.status})`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|