@aivin-labs/cli 1.0.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 +214 -0
- package/bin/assets/aivin-icon.png +0 -0
- package/bin/cli.mjs +1256 -0
- package/bin/lib/auth.mjs +355 -0
- package/bin/lib/browserAutomation.mjs +575 -0
- package/bin/lib/codegen.mjs +858 -0
- package/bin/lib/connectors.mjs +217 -0
- package/bin/lib/context.mjs +149 -0
- package/bin/lib/deploy.mjs +350 -0
- package/bin/lib/mcpProxy.mjs +380 -0
- package/bin/lib/mission.mjs +68 -0
- package/bin/lib/missionStream.mjs +656 -0
- package/bin/lib/pluginTrigger.mjs +535 -0
- package/bin/lib/scaffold.mjs +653 -0
- package/bin/lib/store.mjs +204 -0
- package/bin/lib/tasks.mjs +345 -0
- package/bin/lib/util.mjs +40 -0
- package/bin/lib/workspace.mjs +280 -0
- package/docs/CHANGELOG.md +8 -0
- package/docs/CLI.md +1079 -0
- package/docs/GETTING_STARTED.md +234 -0
- package/package.json +59 -0
package/bin/lib/auth.mjs
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { exec } from 'child_process';
|
|
3
|
+
import http from 'http';
|
|
4
|
+
import os from 'os';
|
|
5
|
+
import { randomBytes } from 'crypto';
|
|
6
|
+
import inquirer from 'inquirer';
|
|
7
|
+
import axios from 'axios';
|
|
8
|
+
import { DEFAULT_AIVIN_BASE_URL, saveActiveContext } from './context.mjs';
|
|
9
|
+
|
|
10
|
+
// ── Login - get an API key saved once, machine-wide ─────────────────────────
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Writes to `~/.aivin/credentials`, not the current project's `.env` - a login is a per-machine
|
|
14
|
+
* context, not a per-project one, so `aivin login` only needs to happen once regardless of how many
|
|
15
|
+
* plugin projects you work in on this machine, and switching targets is just logging in again with
|
|
16
|
+
* a different `baseUrl`. A project's own `.env` can still set `AIVIN_BASE_URL`/`API_KEY` directly to
|
|
17
|
+
* pin itself to something other than the machine's current context - see the dotenv.config()
|
|
18
|
+
* precedence at the top of this file.
|
|
19
|
+
*/
|
|
20
|
+
export function saveGlobalApiKey(apiKey, baseUrl = process.env.AIVIN_BASE_URL || DEFAULT_AIVIN_BASE_URL, identity) {
|
|
21
|
+
return saveActiveContext(baseUrl, apiKey, identity);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function openBrowser(url) {
|
|
25
|
+
const platform = process.platform;
|
|
26
|
+
const command =
|
|
27
|
+
platform === 'win32' ? `start "" "${url}"` : platform === 'darwin' ? `open "${url}"` : `xdg-open "${url}"`;
|
|
28
|
+
exec(command, (error) => {
|
|
29
|
+
if (error) {
|
|
30
|
+
console.log(chalk.yellow('Could not open a browser automatically - open this URL manually:'));
|
|
31
|
+
console.log(chalk.cyan(` ${url}`));
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Default `aivin login` flow: opens the platform's actual web app (not the API) so the user logs
|
|
38
|
+
* in exactly the way they normally would - custom-domain org, password, Google, OTP, whatever
|
|
39
|
+
* applies to their account - none of that multi-tenant login logic is reimplemented here. A tiny
|
|
40
|
+
* local HTTP server waits for the browser to hand back a freshly-minted API key. The web app side
|
|
41
|
+
* of this handoff lives in ApiKeysTab.jsx (mint + redirect) and ProfileHook.jsx (auto-open the tab) -
|
|
42
|
+
* see docs/CLI.md#aivin-login.
|
|
43
|
+
*/
|
|
44
|
+
export async function browserLogin() {
|
|
45
|
+
// Defaults to the production web app - override with AIVIN_WEB_URL only if you're pointing at a
|
|
46
|
+
// local/dev/staging frontend instead.
|
|
47
|
+
const webBaseUrl = process.env.AIVIN_WEB_URL || 'https://brain.aivin.cloud';
|
|
48
|
+
|
|
49
|
+
const state = randomBytes(16).toString('hex');
|
|
50
|
+
let resolveKey, rejectKey;
|
|
51
|
+
const keyPromise = new Promise((resolve, reject) => {
|
|
52
|
+
resolveKey = resolve;
|
|
53
|
+
rejectKey = reject;
|
|
54
|
+
});
|
|
55
|
+
// If `server.listen()` itself errors below, this promise gets rejected via rejectKey() but the
|
|
56
|
+
// function throws from the port-await first (before `return keyPromise` is ever reached) - leaving
|
|
57
|
+
// it as an unobserved rejection. This passive handler only silences that warning; it doesn't
|
|
58
|
+
// consume keyPromise's rejection for the normal caller, who awaits the promise returned below.
|
|
59
|
+
keyPromise.catch(() => {});
|
|
60
|
+
|
|
61
|
+
let timeout;
|
|
62
|
+
const server = http.createServer((req, res) => {
|
|
63
|
+
let url;
|
|
64
|
+
try {
|
|
65
|
+
url = new URL(req.url, 'http://127.0.0.1');
|
|
66
|
+
} catch {
|
|
67
|
+
res.writeHead(400).end();
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (url.pathname !== '/callback') {
|
|
71
|
+
res.writeHead(404).end();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const key = url.searchParams.get('key');
|
|
76
|
+
const receivedState = url.searchParams.get('state');
|
|
77
|
+
const ok = !!key && receivedState === state;
|
|
78
|
+
|
|
79
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
80
|
+
res.end(
|
|
81
|
+
'<html><body style="font-family:sans-serif;text-align:center;padding-top:4rem">' +
|
|
82
|
+
(ok
|
|
83
|
+
? '<h2>Login successful</h2><p>You can close this window and return to your terminal.</p>'
|
|
84
|
+
: '<h2>Login failed</h2><p>Close this window and retry <code>aivin login</code>.</p>') +
|
|
85
|
+
// Only works on tabs opened via script (window.open), not a typed/clicked URL - harmless
|
|
86
|
+
// no-op otherwise, hence the fallback "you can close this" text above regardless.
|
|
87
|
+
'<script>window.close();</script>' +
|
|
88
|
+
'</body></html>',
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
clearTimeout(timeout);
|
|
92
|
+
server.close();
|
|
93
|
+
if (ok) resolveKey(key);
|
|
94
|
+
else rejectKey(new Error('Login callback was missing a key or had a state mismatch'));
|
|
95
|
+
});
|
|
96
|
+
server.on('error', (err) => rejectKey(err));
|
|
97
|
+
|
|
98
|
+
const port = await new Promise((resolve, reject) => {
|
|
99
|
+
server.once('error', reject);
|
|
100
|
+
server.listen(0, '127.0.0.1', () => resolve(server.address().port));
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const authUrl = new URL('/', webBaseUrl);
|
|
104
|
+
authUrl.searchParams.set('cli_redirect', `http://127.0.0.1:${port}/callback`);
|
|
105
|
+
authUrl.searchParams.set('cli_state', state);
|
|
106
|
+
authUrl.searchParams.set('cli_name', os.hostname());
|
|
107
|
+
|
|
108
|
+
console.log(chalk.blue('🌐 Opening your browser to log in...'));
|
|
109
|
+
console.log(chalk.gray(` ${authUrl.toString()}`));
|
|
110
|
+
console.log(chalk.gray(' Not opened automatically? Paste that URL into your browser.'));
|
|
111
|
+
console.log(chalk.gray(' Waiting for you to confirm in the browser (5 min timeout)...'));
|
|
112
|
+
openBrowser(authUrl.toString());
|
|
113
|
+
|
|
114
|
+
timeout = setTimeout(() => {
|
|
115
|
+
server.close();
|
|
116
|
+
rejectKey(new Error('Timed out waiting for browser login (5 minutes)'));
|
|
117
|
+
}, 5 * 60 * 1000);
|
|
118
|
+
|
|
119
|
+
return keyPromise;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Prompts for email/password directly in the terminal (no browser) and exchanges them for a real
|
|
124
|
+
* session JWT via `POST /user/login`. Only supports the platform's default/shared client
|
|
125
|
+
* (`--client`, falls back to the same 'aivin.cloud' default the web app itself falls back to when
|
|
126
|
+
* no custom-domain org is resolved) - accounts under a custom-domain organization need that domain
|
|
127
|
+
* resolved first, which is exactly what the web login page normally does.
|
|
128
|
+
*
|
|
129
|
+
* This JWT is deliberately never persisted anywhere (unlike the final API key `aivin login` saves
|
|
130
|
+
* to `~/.aivin/credentials`) - every command that needs one (`aivin login --basic`, `aivin key
|
|
131
|
+
* gen`/`revoke`) re-prompts and re-exchanges it fresh. That mirrors the backend on purpose: the
|
|
132
|
+
* `/apikey` routes (list/create/delete) require this session JWT and deliberately do NOT accept an
|
|
133
|
+
* existing API key in its place (see AuthGuard.tryApiKeyAuth's doc comment) - a leaked/scoped key
|
|
134
|
+
* must never be able to mint or revoke other keys on its own.
|
|
135
|
+
*/
|
|
136
|
+
export async function obtainAccessToken(options) {
|
|
137
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
138
|
+
const client = options.client || 'aivin.cloud';
|
|
139
|
+
|
|
140
|
+
const answers = await inquirer.prompt([
|
|
141
|
+
{
|
|
142
|
+
type: 'input',
|
|
143
|
+
name: 'email',
|
|
144
|
+
message: 'Email:',
|
|
145
|
+
validate: (input) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input) || 'Please enter a valid email address',
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
type: 'password',
|
|
149
|
+
name: 'password',
|
|
150
|
+
message: 'Password:',
|
|
151
|
+
mask: '*',
|
|
152
|
+
validate: (input) => input.length > 0 || 'Password is required',
|
|
153
|
+
},
|
|
154
|
+
]);
|
|
155
|
+
|
|
156
|
+
console.log(chalk.yellow('🔄 Logging in...'));
|
|
157
|
+
console.log(
|
|
158
|
+
chalk.gray(
|
|
159
|
+
` Using client "${client}" - if your account belongs to a custom-domain organization, use ` +
|
|
160
|
+
'`aivin login` (browser flow) instead, which resolves that automatically.',
|
|
161
|
+
),
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
const loginRes = await axios.post(`${serverUrl}/user/login`, {
|
|
166
|
+
client,
|
|
167
|
+
email: answers.email,
|
|
168
|
+
nickname: answers.email.toLowerCase(),
|
|
169
|
+
password: answers.password,
|
|
170
|
+
auth_type: 'basic',
|
|
171
|
+
auth_provider: 'tenant',
|
|
172
|
+
});
|
|
173
|
+
const accessToken = loginRes.data?.access_token;
|
|
174
|
+
if (!accessToken) throw new Error('Login response did not include an access token');
|
|
175
|
+
return { serverUrl, accessToken };
|
|
176
|
+
} catch (error) {
|
|
177
|
+
const message = error.response?.data?.message || error.message;
|
|
178
|
+
throw new Error(`Login failed: ${message}`, { cause: error });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* `aivin login --basic`: the login-specific half of the flow above - exchange credentials for a
|
|
184
|
+
* JWT, then mint (replacing any previous same-named key) the one API key that gets saved to
|
|
185
|
+
* `~/.aivin/credentials`.
|
|
186
|
+
*/
|
|
187
|
+
export async function basicLogin(options) {
|
|
188
|
+
const { serverUrl, accessToken } = await obtainAccessToken(options);
|
|
189
|
+
const authHeaders = { headers: { Authorization: `Bearer ${accessToken}` } };
|
|
190
|
+
const deviceName = os.hostname();
|
|
191
|
+
|
|
192
|
+
// Replace (not accumulate) a previous key from this same device - `aivin login` re-run on the
|
|
193
|
+
// same machine used to create yet another "Aivin CLI - <host>" entry every time, cluttering the
|
|
194
|
+
// key list with duplicates. Best-effort: if listing/revoking fails for any reason, still proceed
|
|
195
|
+
// to mint a new key rather than blocking login on it.
|
|
196
|
+
try {
|
|
197
|
+
const listRes = await axios.get(`${serverUrl}/apikey`, authHeaders);
|
|
198
|
+
const existing = (listRes.data?.items || []).find((k) => k.name === deviceName);
|
|
199
|
+
if (existing) {
|
|
200
|
+
await axios.delete(`${serverUrl}/apikey/${existing.id || existing._id}`, authHeaders);
|
|
201
|
+
}
|
|
202
|
+
} catch (error) {
|
|
203
|
+
console.log(chalk.gray(` (couldn't check for an existing key to replace: ${error.message})`));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
try {
|
|
207
|
+
const keyRes = await axios.post(`${serverUrl}/apikey`, { name: deviceName }, authHeaders);
|
|
208
|
+
if (!keyRes.data?.plainKey) throw new Error('Response did not include an API key');
|
|
209
|
+
return keyRes.data.plainKey;
|
|
210
|
+
} catch (error) {
|
|
211
|
+
const message = error.response?.data?.message || error.message;
|
|
212
|
+
throw new Error(`Failed to create API key: ${message}`, { cause: error });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ── API key management - named keys for your account, separate from `aivin login`'s one ───────
|
|
217
|
+
//
|
|
218
|
+
// `aivin login` mints exactly one machine-wide key named after this hostname. These commands
|
|
219
|
+
// manage arbitrary named keys on the same account (e.g. one per CI pipeline, one per teammate's
|
|
220
|
+
// script) via the same `/apikey` endpoints the web app's Settings > API Keys tab and `aivin
|
|
221
|
+
// login`'s device-key replacement already use - authenticated with the API_KEY already saved by
|
|
222
|
+
// `aivin login`, not a fresh email/password prompt (see ApiKeyController's `@AllowApiKey()` +
|
|
223
|
+
// AuthGuard's `request.apiKeyAuth` fallback on the backend).
|
|
224
|
+
//
|
|
225
|
+
// `key gen` still prompts for your account password even though it doesn't ask for email - minting
|
|
226
|
+
// a new key from an existing one is the one action here that could otherwise let an
|
|
227
|
+
// already-compromised key re-provision itself indefinitely after being revoked, so the backend
|
|
228
|
+
// requires this step-up proof before creating one. `key list`/`key revoke` never grant anything
|
|
229
|
+
// (read metadata / remove access only), so they need no such prompt.
|
|
230
|
+
|
|
231
|
+
export function requireSavedApiKey() {
|
|
232
|
+
const apiKey = process.env.API_KEY;
|
|
233
|
+
if (!apiKey) {
|
|
234
|
+
throw new Error('API_KEY not set - run `aivin login` first.');
|
|
235
|
+
}
|
|
236
|
+
return apiKey;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* The client id a key was minted under is baked right into it (`${client}-ak-<...>`, see
|
|
241
|
+
* ApiKeyService.createApiKey/parseApiKeyBearer on the backend) - parse it out locally so `client`
|
|
242
|
+
* is always shown even if the `/apikey/whoami` network call below fails.
|
|
243
|
+
*/
|
|
244
|
+
export function parseApiKeyClient(apiKey) {
|
|
245
|
+
const anchorIndex = apiKey.lastIndexOf('-ak-');
|
|
246
|
+
return anchorIndex === -1 ? undefined : apiKey.substring(0, anchorIndex);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** `{ email, client, name }` for the account the given API key belongs to - see `GET /apikey/whoami`. */
|
|
250
|
+
export async function fetchWhoami(serverUrl, apiKey) {
|
|
251
|
+
const res = await axios.get(`${serverUrl}/apikey/whoami`, { headers: { Authorization: `Bearer ${apiKey}` } });
|
|
252
|
+
return res.data || {};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Best-effort variant for call sites where identity is a nice-to-have saved alongside credentials
|
|
257
|
+
* (so `aivin whoami` can later read it straight from the file) rather than the point of the call -
|
|
258
|
+
* a lookup failure here shouldn't block login/key creation itself.
|
|
259
|
+
*/
|
|
260
|
+
export async function tryFetchWhoami(serverUrl, apiKey) {
|
|
261
|
+
try {
|
|
262
|
+
return await fetchWhoami(serverUrl, apiKey);
|
|
263
|
+
} catch {
|
|
264
|
+
return {};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Prints which account/client the saved API_KEY resolves to, so a gen/revoke/list failure (wrong
|
|
270
|
+
* account, wrong client) is obvious up front instead of a confusing 401/403 further down. Never
|
|
271
|
+
* fatal - a lookup failure here shouldn't block the actual command, just fall back to what's
|
|
272
|
+
* derivable locally from the key string itself.
|
|
273
|
+
*/
|
|
274
|
+
export async function logAccountIdentity(serverUrl, apiKey) {
|
|
275
|
+
const localClient = parseApiKeyClient(apiKey);
|
|
276
|
+
try {
|
|
277
|
+
const { email, client, org } = await fetchWhoami(serverUrl, apiKey);
|
|
278
|
+
const orgLabel = org?.name || client || localClient || 'unknown';
|
|
279
|
+
console.log(chalk.gray(` Account: ${email || 'unknown'} (org: ${orgLabel})`));
|
|
280
|
+
} catch (error) {
|
|
281
|
+
const message = error.response?.data?.message || error.message;
|
|
282
|
+
console.log(chalk.gray(` Client: ${localClient || 'unknown'} (couldn't resolve account email: ${message})`));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export async function listRemoteApiKeys(serverUrl, apiKey) {
|
|
287
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey}` } };
|
|
288
|
+
// 100 is the backend's own max page size (ApiKeyController.listApiKeys clamps `limit` there) -
|
|
289
|
+
// plenty for the "find my one named key" lookups these commands do, and for `key list` itself.
|
|
290
|
+
const res = await axios.get(`${serverUrl}/apikey`, { ...authHeaders, params: { limit: 100 } });
|
|
291
|
+
return res.data?.items || [];
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export async function findApiKeyByName(serverUrl, apiKey, name) {
|
|
295
|
+
const items = await listRemoteApiKeys(serverUrl, apiKey);
|
|
296
|
+
return items.find((k) => k.name === name);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export async function generateApiKey(name) {
|
|
300
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
301
|
+
const apiKey = requireSavedApiKey();
|
|
302
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey}` } };
|
|
303
|
+
await logAccountIdentity(serverUrl, apiKey);
|
|
304
|
+
|
|
305
|
+
const { password } = await inquirer.prompt([
|
|
306
|
+
{
|
|
307
|
+
type: 'password',
|
|
308
|
+
name: 'password',
|
|
309
|
+
message: 'Account password:',
|
|
310
|
+
mask: '*',
|
|
311
|
+
validate: (input) => input.length > 0 || 'Password is required',
|
|
312
|
+
},
|
|
313
|
+
]);
|
|
314
|
+
|
|
315
|
+
try {
|
|
316
|
+
// Replace, not accumulate - same behavior `aivin login` already relies on for its own device
|
|
317
|
+
// key, so re-running `aivin key gen "ci"` doesn't pile up duplicate "ci" entries.
|
|
318
|
+
const existing = await findApiKeyByName(serverUrl, apiKey, name);
|
|
319
|
+
if (existing) {
|
|
320
|
+
await axios.delete(`${serverUrl}/apikey/${existing.id || existing._id}`, authHeaders);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const keyRes = await axios.post(`${serverUrl}/apikey`, { name, password }, authHeaders);
|
|
324
|
+
if (!keyRes.data?.plainKey) throw new Error('Response did not include an API key');
|
|
325
|
+
return keyRes.data.plainKey;
|
|
326
|
+
} catch (error) {
|
|
327
|
+
const message = error.response?.data?.message || error.message;
|
|
328
|
+
throw new Error(`Failed to create API key: ${message}`, { cause: error });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export async function revokeApiKeyByName(name) {
|
|
333
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
334
|
+
const apiKey = requireSavedApiKey();
|
|
335
|
+
await logAccountIdentity(serverUrl, apiKey);
|
|
336
|
+
|
|
337
|
+
let existing;
|
|
338
|
+
try {
|
|
339
|
+
existing = await findApiKeyByName(serverUrl, apiKey, name);
|
|
340
|
+
} catch (error) {
|
|
341
|
+
const message = error.response?.data?.message || error.message;
|
|
342
|
+
throw new Error(`Failed to look up API keys: ${message}`, { cause: error });
|
|
343
|
+
}
|
|
344
|
+
if (!existing) {
|
|
345
|
+
throw new Error(`No API key named "${name}" found on your account.`);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
try {
|
|
349
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey}` } };
|
|
350
|
+
await axios.delete(`${serverUrl}/apikey/${existing.id || existing._id}`, authHeaders);
|
|
351
|
+
} catch (error) {
|
|
352
|
+
const message = error.response?.data?.message || error.message;
|
|
353
|
+
throw new Error(`Failed to revoke API key: ${message}`, { cause: error });
|
|
354
|
+
}
|
|
355
|
+
}
|