minara 0.4.6 → 0.5.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.
- package/README.md +19 -12
- package/dist/api/chat.js +3 -5
- package/dist/api/client.d.ts +15 -0
- package/dist/api/client.js +50 -3
- package/dist/api/crosschain.d.ts +2 -2
- package/dist/auth-refresh.d.ts +7 -1
- package/dist/auth-refresh.js +18 -2
- package/dist/commands/account.js +3 -3
- package/dist/commands/assets.js +3 -3
- package/dist/commands/chat.js +9 -8
- package/dist/commands/config.js +8 -16
- package/dist/commands/discover.js +2 -3
- package/dist/commands/limit-order.js +50 -14
- package/dist/commands/login.js +13 -10
- package/dist/commands/perps.d.ts +20 -0
- package/dist/commands/perps.js +237 -42
- package/dist/commands/premium.js +1 -78
- package/dist/commands/swap.js +53 -14
- package/dist/commands/transfer.js +22 -4
- package/dist/commands/withdraw.js +43 -23
- package/dist/config.d.ts +1 -0
- package/dist/config.js +24 -5
- package/dist/formatters.d.ts +9 -0
- package/dist/formatters.js +127 -5
- package/dist/touchid.d.ts +2 -1
- package/dist/touchid.js +5 -3
- package/dist/types.d.ts +48 -0
- package/dist/update-check.js +4 -2
- package/dist/utils.d.ts +56 -11
- package/dist/utils.js +144 -31
- package/package.json +11 -3
- package/dist/oauth-server.d.ts +0 -38
- package/dist/oauth-server.js +0 -145
package/README.md
CHANGED
|
@@ -164,6 +164,7 @@ minara perps close # Close a position: pick from list → market
|
|
|
164
164
|
minara perps close --all # Close all positions at once
|
|
165
165
|
minara perps cancel # Cancel an order: pick from open orders list
|
|
166
166
|
minara perps leverage # Interactive: shows max leverage per asset
|
|
167
|
+
minara perps leverage -s ETH -l 5 --margin isolated # Non-interactive (asks for confirmation)
|
|
167
168
|
minara perps trades # Recent fills from Hyperliquid (default 7 days)
|
|
168
169
|
minara perps trades -d 30 # Last 30 days of trade history
|
|
169
170
|
minara perps deposit -a 100 # Deposit 100 USDC to perps
|
|
@@ -186,7 +187,7 @@ minara perps ask # AI analysis → optional quick order
|
|
|
186
187
|
>
|
|
187
188
|
> **Autopilot:** When autopilot is ON for a wallet, manual order placement on that wallet is blocked to prevent conflicts with AI-managed trades. Turn off autopilot first via `minara perps autopilot`.
|
|
188
189
|
>
|
|
189
|
-
> **Ask AI → Quick Order:** After the AI analysis, you can instantly place a market order
|
|
190
|
+
> **Ask AI → Quick Order:** After the AI analysis, you can instantly place a market order in the recommended direction. The order is priced from the live market (not the AI's entry), its size is capped at your margin × leverage, it is disabled if the AI entry is more than 2% away from the current price, and it uses the wallet's current leverage setting (shown in the confirmation).
|
|
190
191
|
|
|
191
192
|
### Limit Orders
|
|
192
193
|
|
|
@@ -313,7 +314,7 @@ Available settings:
|
|
|
313
314
|
|
|
314
315
|
| Setting | Default | Description |
|
|
315
316
|
| ------------------------ | ------- | ---------------------------------------------------- |
|
|
316
|
-
| Base URL |
|
|
317
|
+
| Base URL | `https://api.minara.ai` | API endpoint — must be `https://*.minara.ai` (or localhost for development) |
|
|
317
318
|
| Touch ID | Off | Biometric verification for fund operations (macOS) |
|
|
318
319
|
| Transaction Confirmation | **On** | Mandatory second confirmation before fund operations |
|
|
319
320
|
|
|
@@ -322,12 +323,13 @@ Available settings:
|
|
|
322
323
|
All fund-related operations go through a multi-layer safety flow:
|
|
323
324
|
|
|
324
325
|
```
|
|
325
|
-
1.
|
|
326
|
-
2.
|
|
327
|
-
3.
|
|
328
|
-
4. Execute
|
|
326
|
+
1. Transaction confirmation (on by default — configurable in minara config)
|
|
327
|
+
2. Touch ID verification (optional — macOS only)
|
|
328
|
+
3. Execute
|
|
329
329
|
```
|
|
330
330
|
|
|
331
|
+
Covered operations include swaps, transfers / withdrawals, perps deposit / withdraw / order / close / sweep / transfer, leverage changes, and autopilot changes (turning a strategy ON, updating its symbols or config, creating a strategy).
|
|
332
|
+
|
|
331
333
|
The **transaction confirmation** shows chain, token, address, side, amount, and operation details before asking for final approval:
|
|
332
334
|
|
|
333
335
|
```
|
|
@@ -341,7 +343,9 @@ The **transaction confirmation** shows chain, token, address, side, amount, and
|
|
|
341
343
|
? Are you sure you want to proceed? (y/N)
|
|
342
344
|
```
|
|
343
345
|
|
|
344
|
-
|
|
346
|
+
For `swap`, the expected output, fees, slippage and price impact are fetched and shown before this prompt.
|
|
347
|
+
|
|
348
|
+
**About `-y` / `--yes`:** on `swap`, `transfer`, `withdraw`, `deposit` (Spot → Perps), `limit-order create`, `perps order`, `perps close`, `perps sweep`, `perps transfer` and `perps leverage`, `-y` skips the transaction confirmation for scripting. `perps deposit`, `perps withdraw`, the `perps ask` quick order and autopilot changes always show it. Touch ID, when enabled, is never skipped. If you disable transaction confirmation via `minara config`, every skipped prompt prints a warning.
|
|
345
349
|
|
|
346
350
|
### Touch ID (macOS)
|
|
347
351
|
|
|
@@ -351,9 +355,9 @@ Minara CLI supports macOS Touch ID to protect all fund-related operations. When
|
|
|
351
355
|
minara config # Select "Touch ID" to enable / disable
|
|
352
356
|
```
|
|
353
357
|
|
|
354
|
-
**Protected operations:** `withdraw`, `send` / `transfer`, `swap`, `receive` / `deposit` (Spot→Perps transfer), `perps deposit`, `perps withdraw`, `perps order`, `perps close`, `limit-order create`
|
|
358
|
+
**Protected operations:** `withdraw`, `send` / `transfer`, `swap`, `receive` / `deposit` (Spot→Perps transfer), `perps deposit`, `perps withdraw`, `perps order`, `perps close`, `perps sweep`, `perps transfer`, `perps leverage`, `perps autopilot` (enable / update / create), `limit-order create`
|
|
355
359
|
|
|
356
|
-
> **Note:** Touch ID requires macOS with Touch ID hardware. The `--yes` flag
|
|
360
|
+
> **Note:** Touch ID requires macOS with Touch ID hardware. The `--yes` flag does **not** bypass Touch ID. If Touch ID is enabled in your config but the current machine cannot use it (e.g. Linux), fund operations are cancelled instead of silently skipping the check.
|
|
357
361
|
|
|
358
362
|
## Supported Chains
|
|
359
363
|
|
|
@@ -381,7 +385,7 @@ minara --help
|
|
|
381
385
|
|
|
382
386
|
## Testing
|
|
383
387
|
|
|
384
|
-
Test suite built with [Vitest](https://vitest.dev/) —
|
|
388
|
+
Test suite built with [Vitest](https://vitest.dev/) — 343 tests covering unit, API, command integration, and formatter layers.
|
|
385
389
|
|
|
386
390
|
```bash
|
|
387
391
|
npm test # Run all tests
|
|
@@ -394,8 +398,11 @@ npm run test:coverage # With v8 coverage report
|
|
|
394
398
|
- **Transaction Confirmation** — Mandatory second confirmation before all fund operations, showing full token details and contract addresses (default: enabled, configurable)
|
|
395
399
|
- **Touch ID** — Optional biometric protection for all fund operations (macOS only). A native Swift helper binary is compiled on first use and cached in `~/.minara/`
|
|
396
400
|
- **Token Verification** — Token ticker, name, and full contract address are always displayed before any transaction to prevent wrong-token mistakes
|
|
397
|
-
-
|
|
398
|
-
-
|
|
401
|
+
- **Trusted API host only** — requests (including the session token and email login codes) are only sent to `https://*.minara.ai` or localhost; any other configured base URL is refused
|
|
402
|
+
- **Safe terminal output** — token names / symbols, API messages and chat output are stripped of terminal control sequences before display, so third-party metadata cannot rewrite or spoof confirmation screens
|
|
403
|
+
- **Re-login safety** — after an expired session, the original request is only retried if you sign back in to the same account
|
|
404
|
+
- Credentials are stored in `~/.minara/credentials.json` with `0600` file permissions (re-applied on every write)
|
|
405
|
+
- The `~/.minara/` directory is kept at `0700` permissions
|
|
399
406
|
- Tokens are never logged or printed to the console
|
|
400
407
|
- OAuth login uses a temporary local server that shuts down after the callback
|
|
401
408
|
- Non-TTY environments (CI/pipes) skip interactive prompts and return errors directly
|
package/dist/api/chat.js
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import { get, post, put, del } from './client.js';
|
|
2
|
-
import { loadConfig } from '../config.js';
|
|
1
|
+
import { get, post, put, del, getApiBaseUrl } from './client.js';
|
|
3
2
|
/** Send chat message — returns SSE stream (raw Response) */
|
|
4
3
|
export async function sendChatStream(token, dto) {
|
|
5
|
-
|
|
6
|
-
const
|
|
7
|
-
const url = `${base}/v1/chat`;
|
|
4
|
+
// Throws if the configured base URL is not a trusted Minara host
|
|
5
|
+
const url = `${getApiBaseUrl()}/v1/chat`;
|
|
8
6
|
const res = await fetch(url, {
|
|
9
7
|
method: 'POST',
|
|
10
8
|
headers: {
|
package/dist/api/client.d.ts
CHANGED
|
@@ -7,6 +7,21 @@ interface RequestOptions {
|
|
|
7
7
|
token?: string;
|
|
8
8
|
headers?: Record<string, string>;
|
|
9
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* The CLI sends the session token, email login codes and fund-moving requests
|
|
12
|
+
* to `baseUrl`, so it must point at a Minara-operated host.
|
|
13
|
+
*
|
|
14
|
+
* Allowed: `https://minara.ai` and `https://*.minara.ai`, plus http/https on
|
|
15
|
+
* loopback for local development. Anything else is rejected.
|
|
16
|
+
*/
|
|
17
|
+
export declare function isTrustedBaseUrl(raw: unknown): boolean;
|
|
18
|
+
export declare const UNTRUSTED_BASE_URL_MESSAGE: string;
|
|
19
|
+
/**
|
|
20
|
+
* Return the configured API base URL (without trailing slash).
|
|
21
|
+
* Throws if it is not a trusted Minara host, so no request — authenticated or
|
|
22
|
+
* not (e.g. email login codes) — is ever sent elsewhere.
|
|
23
|
+
*/
|
|
24
|
+
export declare function getApiBaseUrl(): string;
|
|
10
25
|
export declare function request<T>(path: string, opts?: RequestOptions): Promise<ApiResponse<T>>;
|
|
11
26
|
export declare function get<T>(path: string, opts?: Omit<RequestOptions, 'method'>): Promise<ApiResponse<T>>;
|
|
12
27
|
export declare function post<T>(path: string, opts?: Omit<RequestOptions, 'method'>): Promise<ApiResponse<T>>;
|
package/dist/api/client.js
CHANGED
|
@@ -1,7 +1,47 @@
|
|
|
1
1
|
import { loadConfig } from '../config.js';
|
|
2
|
-
|
|
2
|
+
// ── Base URL trust check ──────────────────────────────────────────────────
|
|
3
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
4
|
+
/**
|
|
5
|
+
* The CLI sends the session token, email login codes and fund-moving requests
|
|
6
|
+
* to `baseUrl`, so it must point at a Minara-operated host.
|
|
7
|
+
*
|
|
8
|
+
* Allowed: `https://minara.ai` and `https://*.minara.ai`, plus http/https on
|
|
9
|
+
* loopback for local development. Anything else is rejected.
|
|
10
|
+
*/
|
|
11
|
+
export function isTrustedBaseUrl(raw) {
|
|
12
|
+
if (typeof raw !== 'string')
|
|
13
|
+
return false;
|
|
14
|
+
let url;
|
|
15
|
+
try {
|
|
16
|
+
url = new URL(raw);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
if (url.username || url.password)
|
|
22
|
+
return false;
|
|
23
|
+
const host = url.hostname.toLowerCase();
|
|
24
|
+
if (LOOPBACK_HOSTS.has(host))
|
|
25
|
+
return url.protocol === 'https:' || url.protocol === 'http:';
|
|
26
|
+
return url.protocol === 'https:' && (host === 'minara.ai' || host.endsWith('.minara.ai'));
|
|
27
|
+
}
|
|
28
|
+
export const UNTRUSTED_BASE_URL_MESSAGE = 'Refusing to contact the API: the base URL in ~/.minara/config.json is not a Minara host. ' +
|
|
29
|
+
'Only https://*.minara.ai (or localhost for development) is allowed. ' +
|
|
30
|
+
'Run `minara config` → "Set base URL" to reset it.';
|
|
31
|
+
/**
|
|
32
|
+
* Return the configured API base URL (without trailing slash).
|
|
33
|
+
* Throws if it is not a trusted Minara host, so no request — authenticated or
|
|
34
|
+
* not (e.g. email login codes) — is ever sent elsewhere.
|
|
35
|
+
*/
|
|
36
|
+
export function getApiBaseUrl() {
|
|
3
37
|
const config = loadConfig();
|
|
4
|
-
|
|
38
|
+
if (!isTrustedBaseUrl(config.baseUrl)) {
|
|
39
|
+
throw new Error(UNTRUSTED_BASE_URL_MESSAGE);
|
|
40
|
+
}
|
|
41
|
+
return config.baseUrl.replace(/\/$/, '');
|
|
42
|
+
}
|
|
43
|
+
function buildUrl(path, query) {
|
|
44
|
+
const base = getApiBaseUrl();
|
|
5
45
|
const url = new URL(`${base}${path}`);
|
|
6
46
|
if (query) {
|
|
7
47
|
for (const [k, v] of Object.entries(query)) {
|
|
@@ -18,7 +58,14 @@ function buildUrl(path, query) {
|
|
|
18
58
|
*/
|
|
19
59
|
async function requestImpl(path, opts, isRetry) {
|
|
20
60
|
const { method = 'GET', body, query, token, headers: extraHeaders } = opts;
|
|
21
|
-
|
|
61
|
+
let url;
|
|
62
|
+
try {
|
|
63
|
+
url = buildUrl(path, query);
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
67
|
+
return { success: false, error: { code: 0, message } };
|
|
68
|
+
}
|
|
22
69
|
const headers = {
|
|
23
70
|
'Content-Type': 'application/json',
|
|
24
71
|
'Accept': 'application/json',
|
package/dist/api/crosschain.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CrossChainSwapDto, CrossChainTransferDto, CrossChainActivitiesDto, CrossChainAccount, WalletAsset, TransactionResult } from '../types.js';
|
|
1
|
+
import type { CrossChainSwapDto, CrossChainTransferDto, CrossChainActivitiesDto, CrossChainAccount, WalletAsset, TransactionResult, CrossChainSwapsSimulateItem } from '../types.js';
|
|
2
2
|
/** Get cross-chain account info */
|
|
3
3
|
export declare function getAccount(token: string): Promise<import("../types.js").ApiResponse<CrossChainAccount>>;
|
|
4
4
|
/** Get wallet assets */
|
|
@@ -8,7 +8,7 @@ export declare function swap(token: string, dto: CrossChainSwapDto): Promise<imp
|
|
|
8
8
|
/** Execute multiple swaps */
|
|
9
9
|
export declare function swaps(token: string, swapList: CrossChainSwapDto[]): Promise<import("../types.js").ApiResponse<TransactionResult[]>>;
|
|
10
10
|
/** Simulate swaps (dry-run) */
|
|
11
|
-
export declare function swapsSimulate(token: string, swapList: CrossChainSwapDto[]): Promise<import("../types.js").ApiResponse<
|
|
11
|
+
export declare function swapsSimulate(token: string, swapList: CrossChainSwapDto[]): Promise<import("../types.js").ApiResponse<CrossChainSwapsSimulateItem[]>>;
|
|
12
12
|
/** Transfer tokens */
|
|
13
13
|
export declare function transfer(token: string, dto: CrossChainTransferDto): Promise<import("../types.js").ApiResponse<TransactionResult>>;
|
|
14
14
|
/** Get activities */
|
package/dist/auth-refresh.d.ts
CHANGED
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
/**
|
|
11
11
|
* Attempt to re-authenticate interactively.
|
|
12
12
|
*
|
|
13
|
-
*
|
|
13
|
+
* The caller replays the original request with the returned token, so the new
|
|
14
|
+
* session must belong to the same account as the expired one. If the user
|
|
15
|
+
* signs in as a different account the new credentials are saved but `null`
|
|
16
|
+
* is returned, and the pending request is not replayed.
|
|
17
|
+
*
|
|
18
|
+
* @returns The new access token on success, or `null` on failure / user decline /
|
|
19
|
+
* account change.
|
|
14
20
|
*/
|
|
15
21
|
export declare function attemptReAuth(): Promise<string | null>;
|
package/dist/auth-refresh.js
CHANGED
|
@@ -14,7 +14,13 @@ import { sendEmailCode, verifyEmailCode } from './api/auth.js';
|
|
|
14
14
|
/**
|
|
15
15
|
* Attempt to re-authenticate interactively.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
17
|
+
* The caller replays the original request with the returned token, so the new
|
|
18
|
+
* session must belong to the same account as the expired one. If the user
|
|
19
|
+
* signs in as a different account the new credentials are saved but `null`
|
|
20
|
+
* is returned, and the pending request is not replayed.
|
|
21
|
+
*
|
|
22
|
+
* @returns The new access token on success, or `null` on failure / user decline /
|
|
23
|
+
* account change.
|
|
18
24
|
*/
|
|
19
25
|
export async function attemptReAuth() {
|
|
20
26
|
try {
|
|
@@ -70,13 +76,23 @@ export async function attemptReAuth() {
|
|
|
70
76
|
console.error(chalk.red('✖'), 'No access token in response.');
|
|
71
77
|
return null;
|
|
72
78
|
}
|
|
79
|
+
const newEmail = user.email ?? email;
|
|
73
80
|
// ── Save new credentials ────────────────────────────────────────────
|
|
74
81
|
saveCredentials({
|
|
75
82
|
accessToken: newToken,
|
|
76
83
|
userId: user.id,
|
|
77
|
-
email:
|
|
84
|
+
email: newEmail,
|
|
78
85
|
displayName: user.displayName,
|
|
79
86
|
});
|
|
87
|
+
// ── Only replay the original request for the same account ───────────
|
|
88
|
+
const userChanged = creds?.userId !== undefined && user.id !== undefined && creds.userId !== user.id;
|
|
89
|
+
const emailChanged = !!creds?.email && !!newEmail && creds.email.toLowerCase() !== newEmail.toLowerCase();
|
|
90
|
+
if (userChanged || emailChanged) {
|
|
91
|
+
console.log(chalk.yellow('⚠'), chalk.yellow(`Signed in as a different account (${newEmail}). The pending request was NOT retried.`));
|
|
92
|
+
console.log(chalk.dim('Run the command again if you want to perform it with this account.'));
|
|
93
|
+
console.log('');
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
80
96
|
console.log(chalk.green('✔'), 'Re-login successful! Retrying your request…');
|
|
81
97
|
console.log('');
|
|
82
98
|
return newToken;
|
package/dist/commands/account.js
CHANGED
|
@@ -2,7 +2,7 @@ import { Command } from 'commander';
|
|
|
2
2
|
import chalk from 'chalk';
|
|
3
3
|
import { getCurrentUser } from '../api/auth.js';
|
|
4
4
|
import { requireAuth } from '../config.js';
|
|
5
|
-
import { spinner, unwrapApi, wrapAction } from '../utils.js';
|
|
5
|
+
import { spinner, unwrapApi, wrapAction, sanitizeTerminal, sanitizeDeep } from '../utils.js';
|
|
6
6
|
// Wallets to show by default (user-facing addresses)
|
|
7
7
|
const DEFAULT_WALLETS = new Set([
|
|
8
8
|
'abstraction-evm',
|
|
@@ -22,7 +22,7 @@ export const accountCommand = new Command('account')
|
|
|
22
22
|
const spin = spinner('Fetching account info…');
|
|
23
23
|
const res = await getCurrentUser(creds.accessToken);
|
|
24
24
|
spin.stop();
|
|
25
|
-
const u = unwrapApi(res, 'Failed to fetch account info');
|
|
25
|
+
const u = sanitizeDeep(unwrapApi(res, 'Failed to fetch account info'));
|
|
26
26
|
console.log('');
|
|
27
27
|
console.log(chalk.bold('Account Info:'));
|
|
28
28
|
if (u.displayName)
|
|
@@ -54,7 +54,7 @@ export const accountCommand = new Command('account')
|
|
|
54
54
|
if (u.accounts && Object.keys(u.accounts).length > 0) {
|
|
55
55
|
console.log(` Linked:`);
|
|
56
56
|
for (const provider of Object.keys(u.accounts)) {
|
|
57
|
-
console.log(` ${chalk.green('✔')} ${provider}`);
|
|
57
|
+
console.log(` ${chalk.green('✔')} ${sanitizeTerminal(provider)}`);
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
60
|
console.log('');
|
package/dist/commands/assets.js
CHANGED
|
@@ -3,7 +3,7 @@ import chalk from 'chalk';
|
|
|
3
3
|
import * as perpsApi from '../api/perps.js';
|
|
4
4
|
import { get } from '../api/client.js';
|
|
5
5
|
import { requireAuth } from '../config.js';
|
|
6
|
-
import { spinner, wrapAction } from '../utils.js';
|
|
6
|
+
import { spinner, wrapAction, sanitizeTerminal } from '../utils.js';
|
|
7
7
|
import { printTable, SPOT_COLUMNS, POSITION_COLUMNS } from '../formatters.js';
|
|
8
8
|
// ─── spot ────────────────────────────────────────────────────────────────
|
|
9
9
|
const spotCmd = new Command('spot')
|
|
@@ -22,7 +22,7 @@ async function showSpotAssets(token) {
|
|
|
22
22
|
console.log(chalk.bold('Spot Wallet Assets:'));
|
|
23
23
|
console.log(chalk.dim(' Could not fetch spot assets.'));
|
|
24
24
|
if (res.error?.message)
|
|
25
|
-
console.log(chalk.dim(` ${res.error.message}`));
|
|
25
|
+
console.log(chalk.dim(` ${sanitizeTerminal(res.error.message)}`));
|
|
26
26
|
console.log('');
|
|
27
27
|
return;
|
|
28
28
|
}
|
|
@@ -139,7 +139,7 @@ async function showPerpsAssets(token) {
|
|
|
139
139
|
if (!res.success || !res.data) {
|
|
140
140
|
console.log(chalk.dim(' Could not fetch perps account.'));
|
|
141
141
|
if (res.error?.message)
|
|
142
|
-
console.log(chalk.dim(` ${res.error.message}`));
|
|
142
|
+
console.log(chalk.dim(` ${sanitizeTerminal(res.error.message)}`));
|
|
143
143
|
return;
|
|
144
144
|
}
|
|
145
145
|
const d = res.data;
|
package/dist/commands/chat.js
CHANGED
|
@@ -3,7 +3,7 @@ import { select } from '@inquirer/prompts';
|
|
|
3
3
|
import chalk from 'chalk';
|
|
4
4
|
import { sendChatStream, listChats, getMemories } from '../api/chat.js';
|
|
5
5
|
import { requireAuth } from '../config.js';
|
|
6
|
-
import { error, info, spinner, unwrapApi, wrapAction } from '../utils.js';
|
|
6
|
+
import { error, info, spinner, unwrapApi, wrapAction, sanitizeTerminal } from '../utils.js';
|
|
7
7
|
import { createInterface } from 'node:readline';
|
|
8
8
|
import { randomUUID } from 'node:crypto';
|
|
9
9
|
/** Parse SSE stream and yield text chunks */
|
|
@@ -88,7 +88,7 @@ async function chatAction(messageArg, opts) {
|
|
|
88
88
|
return;
|
|
89
89
|
}
|
|
90
90
|
for (const c of chats) {
|
|
91
|
-
console.log(` ${chalk.bold((c.chatId).slice(0, 12))}… ${c.name ?? '(untitled)'} ${chalk.dim(c.updatedAt ?? '')}`);
|
|
91
|
+
console.log(` ${chalk.bold(sanitizeTerminal(c.chatId).slice(0, 12))}… ${sanitizeTerminal(c.name ?? '(untitled)')} ${chalk.dim(sanitizeTerminal(c.updatedAt ?? ''))}`);
|
|
92
92
|
}
|
|
93
93
|
return;
|
|
94
94
|
}
|
|
@@ -101,7 +101,7 @@ async function chatAction(messageArg, opts) {
|
|
|
101
101
|
for (const m of memories) {
|
|
102
102
|
const prefix = m.role === 'user' ? chalk.blue.bold('You ') : chalk.green.bold('Minara');
|
|
103
103
|
const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content);
|
|
104
|
-
console.log(`${prefix}: ${content}`);
|
|
104
|
+
console.log(`${prefix}: ${sanitizeTerminal(content, { multiline: true })}`);
|
|
105
105
|
}
|
|
106
106
|
return;
|
|
107
107
|
}
|
|
@@ -122,7 +122,7 @@ async function chatAction(messageArg, opts) {
|
|
|
122
122
|
if (!response.ok) {
|
|
123
123
|
const body = await response.text();
|
|
124
124
|
console.log('');
|
|
125
|
-
error(`API error ${response.status}: ${body}`);
|
|
125
|
+
error(`API error ${response.status}: ${sanitizeTerminal(body)}`);
|
|
126
126
|
return;
|
|
127
127
|
}
|
|
128
128
|
// Debug: Check if response body exists
|
|
@@ -134,7 +134,8 @@ async function chatAction(messageArg, opts) {
|
|
|
134
134
|
try {
|
|
135
135
|
for await (const chunk of parseSSE(response)) {
|
|
136
136
|
if (chunk) {
|
|
137
|
-
|
|
137
|
+
// Model output is untrusted: keep line breaks, drop control sequences
|
|
138
|
+
process.stdout.write(sanitizeTerminal(chunk, { multiline: true }));
|
|
138
139
|
hasContent = true;
|
|
139
140
|
}
|
|
140
141
|
}
|
|
@@ -235,9 +236,9 @@ async function chatAction(messageArg, opts) {
|
|
|
235
236
|
if (chats && chats.length > 0) {
|
|
236
237
|
console.log('');
|
|
237
238
|
for (const c of chats) {
|
|
238
|
-
const id = chalk.dim(c.chatId.slice(0, 8));
|
|
239
|
-
const name = c.name
|
|
240
|
-
const time = c.updatedAt ? chalk.dim(` ${c.updatedAt}`) : '';
|
|
239
|
+
const id = chalk.dim(sanitizeTerminal(c.chatId).slice(0, 8));
|
|
240
|
+
const name = c.name ? sanitizeTerminal(c.name) : chalk.dim('(untitled)');
|
|
241
|
+
const time = c.updatedAt ? chalk.dim(` ${sanitizeTerminal(c.updatedAt)}`) : '';
|
|
241
242
|
console.log(` ${id} ${name}${time}`);
|
|
242
243
|
}
|
|
243
244
|
console.log('');
|
package/dist/commands/config.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
2
|
import { input, select, confirm } from '@inquirer/prompts';
|
|
3
3
|
import chalk from 'chalk';
|
|
4
|
-
import { loadConfig, saveConfig, getMinaraDir } from '../config.js';
|
|
5
|
-
import { success, info, warn, wrapAction } from '../utils.js';
|
|
4
|
+
import { loadConfig, saveConfig, getMinaraDir, DEFAULT_BASE_URL } from '../config.js';
|
|
5
|
+
import { success, info, warn, wrapAction, sanitizeTerminal } from '../utils.js';
|
|
6
6
|
import { isTouchIdAvailable } from '../touchid.js';
|
|
7
|
+
import { isTrustedBaseUrl } from '../api/client.js';
|
|
7
8
|
export const configCommand = new Command('config')
|
|
8
9
|
.description('View or update CLI configuration')
|
|
9
10
|
.action(wrapAction(async () => {
|
|
@@ -29,7 +30,7 @@ export const configCommand = new Command('config')
|
|
|
29
30
|
case 'show':
|
|
30
31
|
console.log('');
|
|
31
32
|
console.log(chalk.bold('Current Configuration:'));
|
|
32
|
-
console.log(` Base URL : ${chalk.cyan(config.baseUrl)}`);
|
|
33
|
+
console.log(` Base URL : ${chalk.cyan(sanitizeTerminal(config.baseUrl))}${isTrustedBaseUrl(config.baseUrl) ? '' : chalk.red(' (untrusted — requests are blocked)')}`);
|
|
33
34
|
console.log(` Touch ID : ${config.touchId ? chalk.green('Enabled') : chalk.dim('Disabled')}`);
|
|
34
35
|
console.log(` Confirm Tx : ${confirmTx ? chalk.green('Enabled') : chalk.dim('Disabled')}`);
|
|
35
36
|
console.log(` Config Dir : ${chalk.dim(getMinaraDir())}`);
|
|
@@ -38,19 +39,10 @@ export const configCommand = new Command('config')
|
|
|
38
39
|
case 'baseUrl': {
|
|
39
40
|
const url = await input({
|
|
40
41
|
message: 'Base URL:',
|
|
41
|
-
default: config.baseUrl,
|
|
42
|
-
validate: (v) =>
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (u.protocol !== 'https:' && u.hostname !== 'localhost' && u.hostname !== '127.0.0.1') {
|
|
46
|
-
return 'Base URL must use HTTPS (HTTP allowed only for localhost)';
|
|
47
|
-
}
|
|
48
|
-
return true;
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
return 'Please enter a valid URL';
|
|
52
|
-
}
|
|
53
|
-
},
|
|
42
|
+
default: isTrustedBaseUrl(config.baseUrl) ? config.baseUrl : DEFAULT_BASE_URL,
|
|
43
|
+
validate: (v) => isTrustedBaseUrl(v)
|
|
44
|
+
? true
|
|
45
|
+
: 'Base URL must be https://minara.ai or https://*.minara.ai (http/https on localhost allowed for development)',
|
|
54
46
|
});
|
|
55
47
|
saveConfig({ baseUrl: url });
|
|
56
48
|
success(`Base URL set to ${url}`);
|
|
@@ -20,11 +20,10 @@ function flattenStock(item) {
|
|
|
20
20
|
// ─── trending ────────────────────────────────────────────────────────────
|
|
21
21
|
const trendingCmd = new Command('trending')
|
|
22
22
|
.description('View trending tokens or stocks')
|
|
23
|
-
.argument('[category]', 'tokens or stocks (default: interactive)')
|
|
24
23
|
.option('-t, --type <category>', 'Trending type: tokens or stocks (skips interactive prompt)')
|
|
25
|
-
.action(wrapAction(async (
|
|
24
|
+
.action(wrapAction(async (options) => {
|
|
26
25
|
let category;
|
|
27
|
-
const typeOpt = options?.type?.toLowerCase()
|
|
26
|
+
const typeOpt = options?.type?.toLowerCase();
|
|
28
27
|
if (typeOpt === 'tokens' || typeOpt === 'token') {
|
|
29
28
|
category = 'tokens';
|
|
30
29
|
}
|
|
@@ -3,42 +3,81 @@ import { input, select, confirm, number as numberPrompt } from '@inquirer/prompt
|
|
|
3
3
|
import chalk from 'chalk';
|
|
4
4
|
import * as loApi from '../api/limitorder.js';
|
|
5
5
|
import { requireAuth } from '../config.js';
|
|
6
|
-
import { success, info, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, formatTokenLabel } from '../utils.js';
|
|
6
|
+
import { success, info, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, formatTokenLabel, parseChainOption, assertTokenOnChain } from '../utils.js';
|
|
7
7
|
import { requireTouchId } from '../touchid.js';
|
|
8
8
|
import { printTxResult, printTable, LIMIT_ORDER_COLUMNS } from '../formatters.js';
|
|
9
9
|
// ─── create ──────────────────────────────────────────────────────────────
|
|
10
10
|
const createCmd = new Command('create')
|
|
11
11
|
.description('Create a limit order')
|
|
12
|
-
.option('-y, --yes', 'Skip confirmation')
|
|
12
|
+
.option('-y, --yes', 'Skip transaction confirmation (Touch ID still required)')
|
|
13
|
+
.option('--chain <chain>', 'Blockchain (ethereum, base, solana, etc.)')
|
|
14
|
+
.option('--side <side>', 'buy or sell')
|
|
15
|
+
.option('--token <ticker|address>', 'Token symbol or contract address')
|
|
16
|
+
.option('--condition <condition>', 'Price condition (above or below)')
|
|
17
|
+
.option('--price <number>', 'Target price in USD')
|
|
18
|
+
.option('--amount <number>', 'Amount in USD')
|
|
19
|
+
.option('--expiry <hours>', 'Expiry time in hours')
|
|
13
20
|
.action(wrapAction(async (opts) => {
|
|
14
21
|
const creds = requireAuth();
|
|
15
|
-
|
|
16
|
-
|
|
22
|
+
// Validate all flags upfront before any interactive prompts
|
|
23
|
+
if (opts.side && !['buy', 'sell'].includes(opts.side)) {
|
|
24
|
+
throw new Error(`Invalid side: ${opts.side}. Must be "buy" or "sell".`);
|
|
25
|
+
}
|
|
26
|
+
if (opts.condition && !['above', 'below'].includes(opts.condition)) {
|
|
27
|
+
throw new Error(`Invalid condition: ${opts.condition}. Must be "above" or "below".`);
|
|
28
|
+
}
|
|
29
|
+
if (opts.price !== undefined) {
|
|
30
|
+
const price = parseFloat(opts.price);
|
|
31
|
+
if (isNaN(price) || price <= 0) {
|
|
32
|
+
throw new Error('Target price must be a positive number.');
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (opts.amount !== undefined) {
|
|
36
|
+
const amountVal = parseFloat(opts.amount);
|
|
37
|
+
if (isNaN(amountVal) || amountVal <= 0) {
|
|
38
|
+
throw new Error('Amount must be a positive number.');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (opts.expiry !== undefined) {
|
|
42
|
+
const expiryVal = parseFloat(opts.expiry);
|
|
43
|
+
if (isNaN(expiryVal) || expiryVal <= 0) {
|
|
44
|
+
throw new Error('Expiry must be a positive number of hours.');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const chainOpt = opts.chain ? parseChainOption(opts.chain) : undefined;
|
|
48
|
+
const chain = chainOpt ?? await selectChain('Chain:', true);
|
|
49
|
+
const side = opts.side ?? await select({
|
|
17
50
|
message: 'Side:',
|
|
18
51
|
choices: [
|
|
19
52
|
{ name: 'Buy', value: 'buy' },
|
|
20
53
|
{ name: 'Sell', value: 'sell' },
|
|
21
54
|
],
|
|
22
55
|
});
|
|
23
|
-
const tokenInput = await input({
|
|
56
|
+
const tokenInput = opts.token ?? await input({
|
|
24
57
|
message: 'Target token (contract address or ticker):',
|
|
25
58
|
validate: (v) => (v.length > 0 ? true : 'Required'),
|
|
26
59
|
});
|
|
27
60
|
const tokenInfo = await lookupToken(tokenInput);
|
|
28
|
-
|
|
61
|
+
assertTokenOnChain(tokenInfo, chain);
|
|
62
|
+
const priceCondition = opts.condition ?? await select({
|
|
29
63
|
message: 'Trigger when price is:',
|
|
30
64
|
choices: [
|
|
31
65
|
{ name: 'Above target price', value: 'above' },
|
|
32
66
|
{ name: 'Below target price', value: 'below' },
|
|
33
67
|
],
|
|
34
68
|
});
|
|
35
|
-
const targetPrice = await numberPrompt({ message: 'Target price (USD):', required: true });
|
|
36
|
-
const
|
|
69
|
+
const targetPrice = opts.price ? parseFloat(opts.price) : await numberPrompt({ message: 'Target price (USD):', required: true });
|
|
70
|
+
const amountInput = opts.amount ?? await input({
|
|
37
71
|
message: 'Amount (USD):',
|
|
38
72
|
validate: (v) => (parseFloat(v) > 0 ? true : 'Enter positive number'),
|
|
39
73
|
});
|
|
40
|
-
const
|
|
41
|
-
const
|
|
74
|
+
const amount = typeof amountInput === 'string' ? amountInput : String(amountInput);
|
|
75
|
+
const expireHoursRaw = opts.expiry ? parseFloat(opts.expiry) : await numberPrompt({ message: 'Expire after (hours):', default: 24 });
|
|
76
|
+
const expireHours = expireHoursRaw ?? 24;
|
|
77
|
+
if (isNaN(expireHours) || expireHours <= 0) {
|
|
78
|
+
throw new Error('Expiry must be a positive number of hours.');
|
|
79
|
+
}
|
|
80
|
+
const expiredAt = Math.floor(Date.now() / 1000) + expireHours * 3600;
|
|
42
81
|
console.log('');
|
|
43
82
|
console.log(chalk.bold('Limit Order:'));
|
|
44
83
|
console.log(` Chain : ${chalk.cyan(chain)}`);
|
|
@@ -50,11 +89,8 @@ const createCmd = new Command('create')
|
|
|
50
89
|
console.log(` Expires : ${new Date(expiredAt * 1000).toLocaleString()}`);
|
|
51
90
|
console.log('');
|
|
52
91
|
if (!opts.yes) {
|
|
53
|
-
|
|
54
|
-
if (!ok)
|
|
55
|
-
return;
|
|
92
|
+
await requireTransactionConfirmation(`Limit ${side} · $${amount} · price ${priceCondition} $${targetPrice} · ${chain}`, tokenInfo, { chain, side, amount: `$${amount}` });
|
|
56
93
|
}
|
|
57
|
-
await requireTransactionConfirmation(`Limit ${side} · $${amount} · price ${priceCondition} $${targetPrice} · ${chain}`, tokenInfo, { chain, side, amount: `$${amount}` });
|
|
58
94
|
await requireTouchId();
|
|
59
95
|
const spin = spinner('Creating limit order…');
|
|
60
96
|
const res = await loApi.createLimitOrder(creds.accessToken, {
|
package/dist/commands/login.js
CHANGED
|
@@ -3,7 +3,7 @@ import { input, select, confirm } from '@inquirer/prompts';
|
|
|
3
3
|
import chalk from 'chalk';
|
|
4
4
|
import { sendEmailCode, verifyEmailCode, startDeviceAuth, getDeviceAuthStatus, } from '../api/auth.js';
|
|
5
5
|
import { saveCredentials, loadCredentials, loadConfig, saveConfig } from '../config.js';
|
|
6
|
-
import { success, error, info, spinner, openBrowser, unwrapApi, wrapAction } from '../utils.js';
|
|
6
|
+
import { success, error, info, spinner, openBrowser, unwrapApi, wrapAction, sanitizeTerminal } from '../utils.js';
|
|
7
7
|
import { isTouchIdAvailable } from '../touchid.js';
|
|
8
8
|
// ─── Email login flow ─────────────────────────────────────────────────────
|
|
9
9
|
async function loginWithEmail(emailOpt) {
|
|
@@ -38,7 +38,7 @@ async function loginWithEmail(emailOpt) {
|
|
|
38
38
|
email: user.email ?? email,
|
|
39
39
|
displayName: user.displayName,
|
|
40
40
|
});
|
|
41
|
-
success(`Welcome${user.displayName ? `, ${user.displayName}` : ''}! Credentials saved to ~/.minara/`);
|
|
41
|
+
success(`Welcome${user.displayName ? `, ${sanitizeTerminal(user.displayName)}` : ''}! Credentials saved to ~/.minara/`);
|
|
42
42
|
}
|
|
43
43
|
// ─── Device login flow (RFC 8628) ─────────────────────────────────────────
|
|
44
44
|
async function loginWithDevice() {
|
|
@@ -54,18 +54,21 @@ async function loginWithDevice() {
|
|
|
54
54
|
console.log('');
|
|
55
55
|
console.log(chalk.bold('To complete login:'));
|
|
56
56
|
console.log('');
|
|
57
|
-
|
|
58
|
-
|
|
57
|
+
// Server-supplied timings: guard against 0 / missing values (hot polling loop)
|
|
58
|
+
const expiresInSec = Number.isFinite(expires_in) && expires_in > 0 ? Math.min(expires_in, 3600) : 600;
|
|
59
|
+
const intervalSec = Number.isFinite(interval) && interval >= 1 ? Math.min(interval, 60) : 5;
|
|
60
|
+
console.log(` 1. Visit: ${chalk.cyan(sanitizeTerminal(verification_url))}`);
|
|
61
|
+
console.log(` 2. Enter code: ${chalk.bold.yellow(sanitizeTerminal(user_code))}`);
|
|
59
62
|
console.log('');
|
|
60
|
-
info(`Waiting for authentication (expires in ${Math.floor(
|
|
63
|
+
info(`Waiting for authentication (expires in ${Math.floor(expiresInSec / 60)} minutes)...`);
|
|
61
64
|
info(chalk.dim('(Press Ctrl+C to cancel)'));
|
|
62
65
|
console.log('');
|
|
63
66
|
// Try to open browser
|
|
64
|
-
openBrowser(`${verification_url}?user_code=${user_code}`);
|
|
67
|
+
openBrowser(`${verification_url}?user_code=${encodeURIComponent(user_code)}`);
|
|
65
68
|
// Poll for completion
|
|
66
69
|
const startTime = Date.now();
|
|
67
|
-
const expiresAt = startTime +
|
|
68
|
-
|
|
70
|
+
const expiresAt = startTime + expiresInSec * 1000;
|
|
71
|
+
const pollInterval = intervalSec * 1000;
|
|
69
72
|
while (Date.now() < expiresAt) {
|
|
70
73
|
await new Promise((r) => setTimeout(r, pollInterval));
|
|
71
74
|
const statusRes = await getDeviceAuthStatus(device_code);
|
|
@@ -88,9 +91,9 @@ async function loginWithDevice() {
|
|
|
88
91
|
});
|
|
89
92
|
success('Login successful! Credentials saved to ~/.minara/');
|
|
90
93
|
if (user.displayName)
|
|
91
|
-
console.log(chalk.dim(` Welcome, ${user.displayName}`));
|
|
94
|
+
console.log(chalk.dim(` Welcome, ${sanitizeTerminal(user.displayName)}`));
|
|
92
95
|
if (user.email)
|
|
93
|
-
console.log(chalk.dim(` ${user.email}`));
|
|
96
|
+
console.log(chalk.dim(` ${sanitizeTerminal(user.email)}`));
|
|
94
97
|
return;
|
|
95
98
|
}
|
|
96
99
|
// Still pending, show progress
|
package/dist/commands/perps.d.ts
CHANGED
|
@@ -1,2 +1,22 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
+
/**
|
|
3
|
+
* Turn an AI recommendation into a bounded market order plan:
|
|
4
|
+
* - requires a live mark price (the order executes at market),
|
|
5
|
+
* - refuses when the AI entry is more than 2% away from it,
|
|
6
|
+
* - caps size at margin × leverage / mark price (AI size can only go lower),
|
|
7
|
+
* - floors size to the asset's size decimals.
|
|
8
|
+
*/
|
|
9
|
+
export declare function buildQuickOrderPlan(rec: {
|
|
10
|
+
entryPrice: number;
|
|
11
|
+
size: number;
|
|
12
|
+
}, meta: {
|
|
13
|
+
markPx: number;
|
|
14
|
+
szDecimals?: number;
|
|
15
|
+
} | undefined, marginUSD: number, leverage: number): {
|
|
16
|
+
markPx: number;
|
|
17
|
+
size: number;
|
|
18
|
+
capped: boolean;
|
|
19
|
+
} | {
|
|
20
|
+
error: string;
|
|
21
|
+
};
|
|
2
22
|
export declare const perpsCommand: Command;
|