@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.
@@ -0,0 +1,217 @@
1
+ import chalk from 'chalk';
2
+ import axios from 'axios';
3
+ import inquirer from 'inquirer';
4
+ import { trustBadge, browseResults } from './pluginTrigger.mjs';
5
+ import { withSpinner } from './util.mjs';
6
+
7
+ // ── Connectors - reusable OAuth apps / credential-form namespaces plugins can reference ────────
8
+
9
+ export function connectorAuthHeaders() {
10
+ const apiKey = process.env.API_KEY;
11
+ if (!apiKey) {
12
+ console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
13
+ }
14
+ return { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
15
+ }
16
+
17
+ export function connectorBaseUrl() {
18
+ return process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
19
+ }
20
+
21
+ export function formatConnectorListLine(connector, isSelected) {
22
+ const marker = isSelected ? chalk.cyan('❯ ') : ' ';
23
+ const label = connector.name || connector.id;
24
+ const name = isSelected ? chalk.bold.cyan(label) : label;
25
+ const badge = connector.is_official ? chalk.green(' ✓') : '';
26
+ const deprecated = connector.deprecated ? chalk.red(' [deprecated]') : '';
27
+ return `${marker}${name}${badge}${deprecated}${chalk.gray(` (${connector.id}, ${connector.type})`)}`;
28
+ }
29
+
30
+ export function formatConnectorDetail(connector) {
31
+ const lines = [];
32
+ lines.push(chalk.bold.cyan(connector.name || connector.id) + ' ' + trustBadge(connector));
33
+ lines.push(chalk.gray(connector.id));
34
+ lines.push(`${chalk.gray('type')} ${connector.type}`);
35
+ lines.push(`${chalk.gray('visibility')} ${connector.visibility}${connector.store_status ? ` (${connector.store_status})` : ''}`);
36
+ if (connector.description) lines.push(`\n${connector.description}`);
37
+ if (connector.type === 'oauth' && connector.oauth) {
38
+ lines.push(`\n${chalk.gray('authorize_url')} ${connector.oauth.authorize_url}`);
39
+ lines.push(`${chalk.gray('access_url')} ${connector.oauth.access_url}`);
40
+ if (connector.oauth.scopes?.length) lines.push(`${chalk.gray('scopes')} ${connector.oauth.scopes.join(', ')}`);
41
+ } else if (connector.type === 'credential_form' && connector.fields?.length) {
42
+ lines.push(`\n${chalk.gray('fields')}\n${connector.fields.map(f => ` - ${f.name}${f.required ? ' (required)' : ''}${f.label ? `: ${f.label}` : ''}`).join('\n')}`);
43
+ }
44
+ lines.push(chalk.gray(`\nReference it from a plugin manifest's connection_id: "${connector.id}"`));
45
+ return lines.join('\n');
46
+ }
47
+
48
+ export async function searchConnectors(query, options) {
49
+ const params = { query };
50
+ if (options.limit) params.limit = options.limit;
51
+
52
+ let response;
53
+ try {
54
+ response = await axios.get(`${connectorBaseUrl()}/connectors/search`, { ...connectorAuthHeaders(), params });
55
+ } catch (error) {
56
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
57
+ throw new Error(`Search failed: ${message}`, { cause: error });
58
+ }
59
+
60
+ const results = response.data || [];
61
+ if (results.length === 0) {
62
+ console.log(chalk.yellow(`No connectors found matching "${query}".`));
63
+ return;
64
+ }
65
+
66
+ if (process.stdout.isTTY && process.stdin.isTTY && !options.plain) {
67
+ await browseResults(results, `Found ${results.length} connector(s) matching "${query}":\n`, formatConnectorListLine, formatConnectorDetail);
68
+ return;
69
+ }
70
+
71
+ console.log(chalk.blue(`Found ${results.length} connector(s) matching "${query}":\n`));
72
+ for (const c of results) {
73
+ console.log(chalk.bold(c.name || c.id) + chalk.gray(` (${c.id}, ${c.type})`));
74
+ if (c.description) console.log(` ${c.description}`);
75
+ console.log();
76
+ }
77
+ }
78
+
79
+ export async function listConnectors(options) {
80
+ const params = {};
81
+ if (options.page) params.page = options.page;
82
+ if (options.limit) params.limit = options.limit;
83
+ if (options.includeDeprecated) params.include_deprecated = 'true';
84
+
85
+ let response;
86
+ try {
87
+ response = await axios.get(`${connectorBaseUrl()}/connectors/list`, { ...connectorAuthHeaders(), params });
88
+ } catch (error) {
89
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
90
+ throw new Error(`List failed: ${message}`, { cause: error });
91
+ }
92
+
93
+ const { items = [], total = 0 } = response.data || {};
94
+ if (items.length === 0) {
95
+ console.log(chalk.yellow('No connectors found.'));
96
+ return;
97
+ }
98
+
99
+ if (process.stdout.isTTY && process.stdin.isTTY && !options.plain) {
100
+ await browseResults(items, `${total} connector(s):\n`, formatConnectorListLine, formatConnectorDetail);
101
+ return;
102
+ }
103
+
104
+ console.log(chalk.blue(`${total} connector(s):\n`));
105
+ for (const c of items) {
106
+ console.log(chalk.bold(c.name || c.id) + chalk.gray(` (${c.id}, ${c.type})`));
107
+ if (c.description) console.log(` ${c.description}`);
108
+ console.log();
109
+ }
110
+ }
111
+
112
+ export async function registerConnector() {
113
+ console.log(chalk.blue('🔌 Register a new connector\n'));
114
+
115
+ const base = await inquirer.prompt([
116
+ { type: 'input', name: 'id', message: 'Connector id (e.g. mailgun):' },
117
+ { type: 'input', name: 'name', message: 'Display name:' },
118
+ { type: 'input', name: 'description', message: 'Description (optional):' },
119
+ { type: 'input', name: 'image', message: 'Logo/icon URL (optional):' },
120
+ {
121
+ type: 'select',
122
+ name: 'type',
123
+ message: 'Connector type:',
124
+ choices: [
125
+ { name: 'oauth - login flow (client_id/secret, authorize/token URLs)', value: 'oauth' },
126
+ { name: 'credential_form - plain fields the user fills in (host, api_key, ...)', value: 'credential_form' },
127
+ ],
128
+ },
129
+ {
130
+ type: 'select',
131
+ name: 'visibility',
132
+ message: 'Visibility:',
133
+ choices: [
134
+ { name: 'private - only your org can reuse it', value: 'private' },
135
+ { name: 'public - any org can find/reuse it (needs admin review first)', value: 'public' },
136
+ ],
137
+ },
138
+ ]);
139
+
140
+ const dto = { id: base.id, name: base.name, description: base.description || undefined, image: base.image || undefined, type: base.type, visibility: base.visibility };
141
+
142
+ if (base.type === 'oauth') {
143
+ const oauth = await inquirer.prompt([
144
+ { type: 'input', name: 'authorize_url', message: 'Authorize URL:' },
145
+ { type: 'input', name: 'access_url', message: 'Token/access URL:' },
146
+ { type: 'input', name: 'profile_url', message: 'Profile URL (optional):' },
147
+ { type: 'input', name: 'client_id', message: 'Client id:' },
148
+ { type: 'password', name: 'client_secret', message: 'Client secret:' },
149
+ { type: 'input', name: 'scopes', message: 'Scopes (comma-separated, optional):' },
150
+ ]);
151
+ dto.oauth = {
152
+ authorize_url: oauth.authorize_url,
153
+ access_url: oauth.access_url,
154
+ profile_url: oauth.profile_url || undefined,
155
+ client_id: oauth.client_id,
156
+ client_secret: oauth.client_secret,
157
+ scopes: oauth.scopes ? oauth.scopes.split(',').map((s) => s.trim()).filter(Boolean) : [],
158
+ };
159
+ } else {
160
+ const fields = [];
161
+ console.log(chalk.gray('Add the fields a user must fill in (leave name blank to stop):'));
162
+ for (;;) {
163
+ const f = await inquirer.prompt([
164
+ { type: 'input', name: 'name', message: `Field ${fields.length + 1} name:` },
165
+ ]);
166
+ if (!f.name) break;
167
+ const rest = await inquirer.prompt([
168
+ { type: 'input', name: 'label', message: 'Label (optional):' },
169
+ { type: 'select', name: 'type', message: 'Type:', choices: ['string', 'number', 'boolean', 'secret'], default: 'string' },
170
+ { type: 'confirm', name: 'required', message: 'Required?', default: true },
171
+ ]);
172
+ fields.push({ name: f.name, label: rest.label || undefined, type: rest.type, required: rest.required });
173
+ }
174
+ if (fields.length === 0) throw new Error('credential_form connectors need at least one field');
175
+ dto.fields = fields;
176
+ }
177
+
178
+ // Warn about likely-duplicate connectors before submitting - registering "Gmail" when
179
+ // official.google already covers the same thing just fragments the catalog.
180
+ try {
181
+ const dupRes = await withSpinner('🔎 Checking for similar connectors', () =>
182
+ axios.get(`${connectorBaseUrl()}/connectors/check-duplicate`, {
183
+ ...connectorAuthHeaders(),
184
+ params: { name: dto.name },
185
+ }),
186
+ );
187
+ const duplicates = dupRes.data?.duplicates || [];
188
+ if (duplicates.length > 0) {
189
+ console.log(chalk.yellow(`\n⚠ Similar connector(s) already exist - here's what they already provide, in case you can just reuse one instead:\n`));
190
+ for (const d of duplicates) {
191
+ console.log(formatConnectorDetail(d));
192
+ console.log(chalk.gray('─'.repeat(40)));
193
+ }
194
+ const { proceed } = await inquirer.prompt([
195
+ { type: 'confirm', name: 'proceed', message: 'Register this one anyway?', default: false },
196
+ ]);
197
+ if (!proceed) {
198
+ console.log(chalk.gray('Cancelled.'));
199
+ return;
200
+ }
201
+ dto.confirm_duplicate = true;
202
+ }
203
+ } catch (error) {
204
+ console.log(chalk.gray(`(couldn't check for duplicates: ${error.message || 'unknown error'} - continuing)`));
205
+ }
206
+
207
+ try {
208
+ const res = await withSpinner('🔌 Registering connector', () =>
209
+ axios.post(`${connectorBaseUrl()}/connectors/register`, dto, connectorAuthHeaders()),
210
+ );
211
+ console.log(chalk.green(`\n✅ Registered connector "${res.data.connector.id}"`));
212
+ console.log(chalk.gray(` Reference it from a plugin manifest's connection_id: "${res.data.connector.id}"`));
213
+ } catch (error) {
214
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
215
+ throw new Error(`Register failed: ${message}`, { cause: error });
216
+ }
217
+ }
@@ -0,0 +1,149 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import axios from 'axios';
5
+ import { execFileSync } from 'child_process';
6
+
7
+ // `~/.aivin/credentials` - written once by `aivin login [baseUrl]`, read by every plugin project
8
+ // on this machine. One ACTIVE context at a time (base_url + api_key together, like `kubectl config
9
+ // use-context`) - not a per-project setting, and not a multi-server map either. Logging into a
10
+ // different server (`aivin login beta-api.aivin.vn`) simply replaces the active context outright;
11
+ // every project on the machine picks up wherever you last logged in, with zero `.env` needed for
12
+ // the common case. A project's own `.env` can still set AIVIN_BASE_URL/API_KEY directly to pin
13
+ // itself to something other than the machine's current context (e.g. CI using a fixed scoped key)
14
+ // - dotenv.config() never overrides a variable that's already set, so that always wins.
15
+ //
16
+ // Old files from before this existed were flat `API_KEY=...` (implicitly production) - still loads
17
+ // fine, just with no recorded base_url (falls back to the production default below).
18
+ export const GLOBAL_CREDENTIALS_PATH = path.join(os.homedir(), '.aivin', 'credentials');
19
+
20
+ export const DEFAULT_AIVIN_BASE_URL = 'https://api.aivin.cloud';
21
+
22
+ /**
23
+ * The REST API and the gRPC SDK channel are two different hostnames behind the same login (e.g.
24
+ * `api.aivin.cloud` / `sdk.aivin.cloud` in production, `beta-api.aivin.vn` / `beta-sdk.aivin.vn` in
25
+ * staging - proven consistent across both real environments this SDK talks to). Derived once at
26
+ * login time by swapping the leading `api.` label for `sdk.`, so `SDK_ENDPOINT` never needs its own
27
+ * separate manual config for the common case - same context, same command.
28
+ */
29
+ export function deriveSdkEndpoint(baseUrl) {
30
+ try {
31
+ const host = new URL(baseUrl).hostname;
32
+ // Match "api." as its own label, whether at the very start ("api.aivin.cloud") or after a
33
+ // prefix like "beta-" ("beta-api.aivin.vn" -> "beta-sdk.aivin.vn") - a plain `^api\.` anchor
34
+ // only caught the production case and silently produced no SDK_ENDPOINT for staging.
35
+ if (!/(^|-)api\./.test(host)) return null;
36
+ return host.replace(/(^|-)api\./, '$1sdk.');
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * No guessing/hardcoded map - the backend already knows its own web app URL (`config/app.json`'s
44
+ * `app_url`, admin-tunable via ConfigIO, same value every branded page/asset link on that instance
45
+ * already uses) and serves it through `GET /setting/lang/default`, a public route (no auth) meant
46
+ * for exactly this: reading branding/config before a session exists. Each real backend (production,
47
+ * staging, self-hosted) already has this correct for itself - a hardcoded CLI-side map would just
48
+ * be a second, driftable copy of the same fact.
49
+ */
50
+ export async function fetchWebUrl(baseUrl) {
51
+ try {
52
+ const res = await axios.get(`${baseUrl}/setting/lang/default`, { timeout: 5000 });
53
+ const appUrl = res.data?.app_url;
54
+ return typeof appUrl === 'string' && appUrl ? appUrl : null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * JSON-only, no legacy flat `API_KEY=...` dotenv-format fallback - a hard cutover, by request.
62
+ * Anyone with an old-format credentials file just needs to `aivin login` again; this stays simple
63
+ * instead of carrying a permanent "read either shape" branch for a one-time migration.
64
+ */
65
+ export function loadActiveContext() {
66
+ if (!fs.existsSync(GLOBAL_CREDENTIALS_PATH)) return null;
67
+ try {
68
+ const parsed = JSON.parse(fs.readFileSync(GLOBAL_CREDENTIALS_PATH, 'utf8'));
69
+ if (!parsed?.api_key) return null;
70
+ const base_url = parsed.base_url || DEFAULT_AIVIN_BASE_URL;
71
+ return {
72
+ base_url,
73
+ api_key: parsed.api_key,
74
+ sdk_endpoint: parsed.sdk_endpoint || deriveSdkEndpoint(base_url),
75
+ // Absent on credentials files written before these fields existed - `aivin whoami` just
76
+ // falls back to a live `/apikey/whoami` lookup in that case rather than showing stale/blank
77
+ // identity.
78
+ logged_in_at: parsed.logged_in_at || null,
79
+ email: parsed.email || null,
80
+ name: parsed.name || null,
81
+ client: parsed.client || null,
82
+ org_name: parsed.org_name || null,
83
+ org_domain: parsed.org_domain || null,
84
+ };
85
+ } catch {
86
+ return null;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * `{ mode: 0o600 }` on writeFileSync is a POSIX permission bit - Node has no Windows-ACL
92
+ * equivalent for it, so on Windows the file otherwise just inherits whatever access the parent
93
+ * directory/profile already grants (every other local account with access to that tree, not just
94
+ * the owner). Best-effort hardening: explicitly strip inherited permissions and grant only the
95
+ * current user. Never blocks login over this failing (e.g. no `icacls` on a stripped-down PATH).
96
+ */
97
+ function restrictToOwner(filePath) {
98
+ if (process.platform !== 'win32') return;
99
+ try {
100
+ execFileSync('icacls', [filePath, '/inheritance:r', '/grant:r', `${os.userInfo().username}:F`], {
101
+ stdio: 'ignore',
102
+ });
103
+ } catch {
104
+ // best-effort only
105
+ }
106
+ }
107
+
108
+ /**
109
+ * `aivin logout` - removes `~/.aivin/credentials` entirely. A project's own `.env` (AIVIN_BASE_URL/
110
+ * API_KEY, see the dotenv precedence note at the top of cli.mjs) is untouched, so a directory that
111
+ * pins its own key stays "logged in" for itself even after this.
112
+ */
113
+ export function clearActiveContext() {
114
+ if (!fs.existsSync(GLOBAL_CREDENTIALS_PATH)) return false;
115
+ fs.unlinkSync(GLOBAL_CREDENTIALS_PATH);
116
+ return true;
117
+ }
118
+
119
+ /**
120
+ * `identity` ({ email, name, client, org: { name, domain } }) is best-effort and optional -
121
+ * callers that can't reach `/apikey/whoami` at login time (e.g. `-k` direct key set, offline)
122
+ * still get a working login, just with `aivin whoami` showing less than the full picture since
123
+ * nothing here is ever fetched again after login - see GLOBAL_CREDENTIALS_PATH's comment above.
124
+ */
125
+ export function saveActiveContext(baseUrl, apiKey, identity = {}) {
126
+ fs.mkdirSync(path.dirname(GLOBAL_CREDENTIALS_PATH), { recursive: true });
127
+ const sdkEndpoint = deriveSdkEndpoint(baseUrl);
128
+ fs.writeFileSync(
129
+ GLOBAL_CREDENTIALS_PATH,
130
+ JSON.stringify(
131
+ {
132
+ base_url: baseUrl,
133
+ api_key: apiKey,
134
+ sdk_endpoint: sdkEndpoint,
135
+ logged_in_at: new Date().toISOString(),
136
+ email: identity.email || null,
137
+ name: identity.name || null,
138
+ client: identity.client || null,
139
+ org_name: identity.org?.name || null,
140
+ org_domain: identity.org?.domain || null,
141
+ },
142
+ null,
143
+ 2,
144
+ ) + '\n',
145
+ { mode: 0o600 },
146
+ );
147
+ restrictToOwner(GLOBAL_CREDENTIALS_PATH);
148
+ return sdkEndpoint;
149
+ }