minara 0.4.7 → 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.
@@ -5,6 +5,7 @@
5
5
  // ═══════════════════════════════════════════════════════════════════════════
6
6
  import chalk from 'chalk';
7
7
  import Table from 'cli-table3';
8
+ import { sanitizeTerminal, sanitizeDeep } from './utils.js';
8
9
  // ─── Wei / BigInt formatting ──────────────────────────────────────────────
9
10
  /** Convert wei (10^18) string to USD decimal string */
10
11
  export function formatWeiToUsd(weiStr) {
@@ -59,6 +60,9 @@ export function formatLabel(key) {
59
60
  }
60
61
  /** Smart-format a single value for terminal display. */
61
62
  export function formatValue(value, key) {
63
+ // API / on-chain strings are untrusted: strip terminal control sequences
64
+ if (typeof value === 'string')
65
+ value = sanitizeTerminal(value);
62
66
  if (value === null || value === undefined || value === '')
63
67
  return chalk.dim('—');
64
68
  if (typeof value === 'boolean')
@@ -116,7 +120,7 @@ export function formatValue(value, key) {
116
120
  if (value.length === 0)
117
121
  return chalk.dim('—');
118
122
  if (value.every((v) => typeof v === 'string' || typeof v === 'number')) {
119
- return value.join(', ');
123
+ return sanitizeTerminal(value.join(', '));
120
124
  }
121
125
  return chalk.dim(`[${value.length} items]`);
122
126
  }
@@ -124,11 +128,11 @@ export function formatValue(value, key) {
124
128
  // Shallow nested — show as inline key=value
125
129
  const entries = Object.entries(value).filter(([, v]) => v !== null && v !== undefined);
126
130
  if (entries.length <= 3) {
127
- return entries.map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`).join(' ');
131
+ return sanitizeTerminal(entries.map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`).join(' '));
128
132
  }
129
- return chalk.dim(JSON.stringify(value));
133
+ return chalk.dim(sanitizeTerminal(JSON.stringify(value)));
130
134
  }
131
- return String(value);
135
+ return sanitizeTerminal(value);
132
136
  }
133
137
  // ─── printKV ─────────────────────────────────────────────────────────────
134
138
  /**
@@ -144,6 +148,7 @@ export function printKV(data, indent = 2) {
144
148
  console.log(JSON.stringify(data, null, 2));
145
149
  return;
146
150
  }
151
+ data = sanitizeDeep(data);
147
152
  const entries = Object.entries(data).filter(([k, v]) => v !== undefined && v !== null && v !== '' && !HIDDEN_KEYS.test(k));
148
153
  if (entries.length === 0) {
149
154
  console.log(chalk.dim(`${' '.repeat(indent)}No data.`));
@@ -204,6 +209,7 @@ export function printTable(data, columns) {
204
209
  console.log(JSON.stringify(data, null, 2));
205
210
  return;
206
211
  }
212
+ data = sanitizeDeep(data);
207
213
  if (!data || (Array.isArray(data) && data.length === 0)) {
208
214
  console.log(chalk.dim(' No data.'));
209
215
  return;
@@ -254,7 +260,7 @@ export function printTxResult(data) {
254
260
  return;
255
261
  }
256
262
  if (typeof data !== 'object') {
257
- console.log(chalk.dim(` ${data}`));
263
+ console.log(chalk.dim(` ${sanitizeTerminal(data)}`));
258
264
  return;
259
265
  }
260
266
  const obj = data;
@@ -427,6 +433,7 @@ export function printFearGreed(data) {
427
433
  console.log(JSON.stringify(data, null, 2));
428
434
  return;
429
435
  }
436
+ data = sanitizeDeep(data);
430
437
  const entries = Object.entries(data).filter(([k, v]) => v !== undefined && v !== null && v !== '' && !HIDDEN_KEYS.test(k) && !FEAR_GREED_HIDDEN.has(k));
431
438
  if (entries.length === 0) {
432
439
  console.log(chalk.dim(' No data.'));
@@ -448,6 +455,7 @@ export function printCryptoMetrics(data) {
448
455
  console.log(JSON.stringify(data, null, 2));
449
456
  return;
450
457
  }
458
+ data = sanitizeDeep(data);
451
459
  const quote = data.currentQuote;
452
460
  const change24h = data.priceChange24h;
453
461
  // Build a flat display object from the quote
@@ -496,6 +504,8 @@ export function printSwapSimulation(result) {
496
504
  console.log(JSON.stringify(result, null, 2));
497
505
  return;
498
506
  }
507
+ // Token symbol / name come from third-party metadata
508
+ result = sanitizeDeep(result);
499
509
  // Handle error case
500
510
  if (isSimulateError(result)) {
501
511
  console.log(chalk.red.bold(` Error: ${result.error}`));
package/dist/touchid.d.ts CHANGED
@@ -13,6 +13,7 @@ export declare function verifyTouchId(reason?: string): void;
13
13
  * verification. Exits the process on failure.
14
14
  *
15
15
  * Call this before any sensitive financial operation.
16
- * On non-macOS platforms a warning is shown and execution continues.
16
+ * Fails closed: if Touch ID is enabled but cannot run on this platform, the
17
+ * operation is cancelled rather than silently skipping the check.
17
18
  */
18
19
  export declare function requireTouchId(): Promise<void>;
package/dist/touchid.js CHANGED
@@ -143,15 +143,17 @@ export function verifyTouchId(reason) {
143
143
  * verification. Exits the process on failure.
144
144
  *
145
145
  * Call this before any sensitive financial operation.
146
- * On non-macOS platforms a warning is shown and execution continues.
146
+ * Fails closed: if Touch ID is enabled but cannot run on this platform, the
147
+ * operation is cancelled rather than silently skipping the check.
147
148
  */
148
149
  export async function requireTouchId() {
149
150
  const config = loadConfig();
150
151
  if (!config.touchId)
151
152
  return; // Touch ID not enabled — no-op
152
153
  if (platform() !== 'darwin') {
153
- console.log(chalk.yellow('⚠'), 'Touch ID is only available on macOS. Skipping biometric check.');
154
- return;
154
+ console.error(chalk.red('✖'), 'Touch ID is enabled in your config but is only available on macOS. Operation cancelled.');
155
+ console.error(chalk.dim(' Run `minara config` to disable Touch ID protection on this machine.'));
156
+ process.exit(1);
155
157
  }
156
158
  console.log('');
157
159
  console.log(chalk.blue('🔐'), chalk.bold('Touch ID verification required'));
@@ -43,7 +43,8 @@ export async function checkForUpdate(currentVersion) {
43
43
  try {
44
44
  // Use cache to avoid hitting npm on every invocation
45
45
  const cached = readCache();
46
- if (cached && Date.now() - cached.checkedAt < CHECK_INTERVAL_MS) {
46
+ if (cached && typeof cached.latest === 'string' && /^\d+\.\d+\.\d+/.test(cached.latest)
47
+ && Date.now() - cached.checkedAt < CHECK_INTERVAL_MS) {
47
48
  return isNewer(cached.latest, currentVersion)
48
49
  ? formatNotice(currentVersion, cached.latest)
49
50
  : null;
@@ -58,7 +59,8 @@ export async function checkForUpdate(currentVersion) {
58
59
  if (!res.ok)
59
60
  return null;
60
61
  const { version: latest } = (await res.json());
61
- if (!latest)
62
+ // Only accept a plain semver string (it is printed to the terminal)
63
+ if (typeof latest !== 'string' || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(latest))
62
64
  return null;
63
65
  writeCache({ latest, checkedAt: Date.now() });
64
66
  return isNewer(latest, currentVersion)
package/dist/utils.d.ts CHANGED
@@ -9,6 +9,23 @@ export declare function formatAmount(amount: string, currency: string): string;
9
9
  export declare function formatOrderSide(side: string): string;
10
10
  export declare function formatOrderStatus(status: string): string;
11
11
  export declare function truncate(str: string, len: number): string;
12
+ /**
13
+ * Strip terminal control sequences from untrusted text (token metadata, API
14
+ * messages, chat output) so it cannot recolor, move the cursor, rewrite
15
+ * earlier lines, set the clipboard (OSC 52) or visually reorder characters.
16
+ *
17
+ * - Single-line mode (default): tabs and line breaks become a space so a value
18
+ * cannot fake extra rows in a confirmation prompt.
19
+ * - Multiline mode: `\n` is kept (CRLF / lone CR are normalised to `\n`).
20
+ */
21
+ export declare function sanitizeTerminal(value: unknown, opts?: {
22
+ multiline?: boolean;
23
+ }): string;
24
+ /**
25
+ * Recursively apply {@link sanitizeTerminal} to every string (values and keys)
26
+ * inside an API payload before it is rendered as a table or key-value list.
27
+ */
28
+ export declare function sanitizeDeep<T>(value: T): T;
12
29
  /**
13
30
  * Check an API response and exit with a formatted error if it failed.
14
31
  * Returns the response data on success (narrowed to non-undefined).
@@ -41,6 +58,17 @@ export interface TokenDisplayInfo {
41
58
  * `Chain` value used by the swap / transfer APIs.
42
59
  */
43
60
  export declare function normalizeChain(raw?: string): Chain | undefined;
61
+ /**
62
+ * Resolve a user-supplied `--chain` value (name, alias or numeric ID) to a
63
+ * supported chain. Throws on anything unknown instead of passing it through.
64
+ */
65
+ export declare function parseChainOption(raw: string): Chain;
66
+ /**
67
+ * Throw if the token's own chain is known and differs from the chain the
68
+ * request will be sent on (e.g. `--chain ethereum` with a Base-only token).
69
+ * EVM native-token placeholders (0x0…0 / 0xE…E) are chain-agnostic and skipped.
70
+ */
71
+ export declare function assertTokenOnChain(token: TokenDisplayInfo, chain: Chain): void;
44
72
  /**
45
73
  * Look up token metadata by address, ticker, or name.
46
74
  *
@@ -58,27 +86,44 @@ export declare function lookupToken(tokenInput: string): Promise<TokenDisplayInf
58
86
  * symbol/name are unavailable.
59
87
  */
60
88
  export declare function formatTokenLabel(token: TokenDisplayInfo): string;
89
+ export interface TransactionDetails {
90
+ chain?: string;
91
+ side?: string;
92
+ amount?: string;
93
+ destination?: string;
94
+ /** Extra labelled rows (e.g. wallet, leverage, margin mode). */
95
+ extra?: [label: string, value: string][];
96
+ }
61
97
  /**
62
- * Prompt the user for a mandatory second confirmation before executing a
63
- * fund-related operation. Controlled by `confirmBeforeTransaction` in config
64
- * (default: enabled). This confirmation is independent of the `-y` flag and
65
- * Touch ID — it serves as an extra safety net.
98
+ * Prompt the user for a second confirmation before executing a fund-related
99
+ * operation. Controlled by `confirmBeforeTransaction` in config (default:
100
+ * enabled). Callers decide whether `-y` skips this prompt; Touch ID (when
101
+ * enabled) is enforced separately via `requireTouchId()`.
102
+ *
103
+ * All values are passed through {@link sanitizeTerminal} before printing.
66
104
  *
67
105
  * @param description Short one-line summary of the operation.
68
106
  * @param token Optional token metadata to highlight in the prompt.
69
107
  *
70
108
  * Exits the process if the user declines.
71
109
  */
72
- export declare function requireTransactionConfirmation(description: string, token?: TokenDisplayInfo, details?: {
73
- chain?: string;
74
- side?: string;
75
- amount?: string;
76
- destination?: string;
77
- }): Promise<void>;
110
+ export declare function requireTransactionConfirmation(description: string, token?: TokenDisplayInfo, details?: TransactionDetails): Promise<void>;
78
111
  /**
79
112
  * Validate a blockchain address based on the target chain.
80
113
  * Returns `true` on success or an error message string on failure.
81
114
  */
82
115
  export declare function validateAddress(address: string, chain?: string): true | string;
83
- /** Open a URL in the user's default browser (cross-platform). */
116
+ /**
117
+ * Return the normalised URL if it is safe to hand to the OS browser opener
118
+ * (https, or http on a loopback host), otherwise `null`.
119
+ */
120
+ export declare function safeBrowserUrl(url: string): string | null;
121
+ /**
122
+ * Open a URL in the user's default browser (cross-platform).
123
+ *
124
+ * Only https URLs (or http on loopback) are opened. On Windows the URL is
125
+ * passed to `rundll32 url.dll,FileProtocolHandler` instead of `cmd /c start`,
126
+ * because cmd.exe would interpret `&`, `|`, `^` etc. inside a server-supplied
127
+ * URL as shell syntax.
128
+ */
84
129
  export declare function openBrowser(url: string): void;
package/dist/utils.js CHANGED
@@ -48,6 +48,46 @@ export function formatOrderStatus(status) {
48
48
  export function truncate(str, len) {
49
49
  return str.length > len ? str.slice(0, len - 1) + '…' : str;
50
50
  }
51
+ // ─── Terminal sanitization ───────────────────────────────────────────────────
52
+ // CSI (ESC [ … final byte), OSC (ESC ] … BEL | ESC \), and two-byte ESC sequences
53
+ // eslint-disable-next-line no-control-regex
54
+ const ANSI_SEQUENCE_RE = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b[@-Z\\-_]/g;
55
+ // C0 controls (except \t and \n), DEL, C1 controls, and bidi override / isolate characters
56
+ // eslint-disable-next-line no-control-regex
57
+ const CONTROL_CHAR_RE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
58
+ /**
59
+ * Strip terminal control sequences from untrusted text (token metadata, API
60
+ * messages, chat output) so it cannot recolor, move the cursor, rewrite
61
+ * earlier lines, set the clipboard (OSC 52) or visually reorder characters.
62
+ *
63
+ * - Single-line mode (default): tabs and line breaks become a space so a value
64
+ * cannot fake extra rows in a confirmation prompt.
65
+ * - Multiline mode: `\n` is kept (CRLF / lone CR are normalised to `\n`).
66
+ */
67
+ export function sanitizeTerminal(value, opts = {}) {
68
+ let s = String(value ?? '');
69
+ s = s.replace(ANSI_SEQUENCE_RE, '');
70
+ s = opts.multiline ? s.replace(/\r\n?/g, '\n') : s.replace(/[\t\n\r]+/g, ' ');
71
+ return s.replace(CONTROL_CHAR_RE, '');
72
+ }
73
+ /**
74
+ * Recursively apply {@link sanitizeTerminal} to every string (values and keys)
75
+ * inside an API payload before it is rendered as a table or key-value list.
76
+ */
77
+ export function sanitizeDeep(value) {
78
+ if (typeof value === 'string')
79
+ return sanitizeTerminal(value);
80
+ if (Array.isArray(value))
81
+ return value.map((v) => sanitizeDeep(v));
82
+ if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
83
+ const out = {};
84
+ for (const [k, v] of Object.entries(value)) {
85
+ out[sanitizeTerminal(k)] = sanitizeDeep(v);
86
+ }
87
+ return out;
88
+ }
89
+ return value;
90
+ }
51
91
  // ─── API error handling ───────────────────────────────────────────────────────
52
92
  /**
53
93
  * Check an API response and exit with a formatted error if it failed.
@@ -55,7 +95,7 @@ export function truncate(str, len) {
55
95
  */
56
96
  export function unwrapApi(res, fallbackMsg) {
57
97
  if (!res.success || res.data === undefined || res.data === null) {
58
- error(res.error?.message ?? fallbackMsg);
98
+ error(sanitizeTerminal(res.error?.message ?? fallbackMsg));
59
99
  process.exit(1);
60
100
  }
61
101
  return res.data;
@@ -66,7 +106,7 @@ export function unwrapApi(res, fallbackMsg) {
66
106
  */
67
107
  export function assertApiOk(res, fallbackMsg) {
68
108
  if (!res.success) {
69
- error(res.error?.message ?? fallbackMsg);
109
+ error(sanitizeTerminal(res.error?.message ?? fallbackMsg));
70
110
  process.exit(1);
71
111
  }
72
112
  }
@@ -164,6 +204,34 @@ export function normalizeChain(raw) {
164
204
  return lower;
165
205
  return CHAIN_ALIAS[lower];
166
206
  }
207
+ /**
208
+ * Resolve a user-supplied `--chain` value (name, alias or numeric ID) to a
209
+ * supported chain. Throws on anything unknown instead of passing it through.
210
+ */
211
+ export function parseChainOption(raw) {
212
+ const chain = normalizeChain(raw.trim());
213
+ if (!chain) {
214
+ throw new Error(`Unsupported chain: ${sanitizeTerminal(raw)}. Supported: ${SUPPORTED_CHAINS.join(', ')}`);
215
+ }
216
+ return chain;
217
+ }
218
+ // Chain-agnostic placeholders used for EVM native tokens
219
+ const EVM_NATIVE_PLACEHOLDER_RE = /^0x(0{40}|e{40})$/i;
220
+ /**
221
+ * Throw if the token's own chain is known and differs from the chain the
222
+ * request will be sent on (e.g. `--chain ethereum` with a Base-only token).
223
+ * EVM native-token placeholders (0x0…0 / 0xE…E) are chain-agnostic and skipped.
224
+ */
225
+ export function assertTokenOnChain(token, chain) {
226
+ if (EVM_NATIVE_PLACEHOLDER_RE.test(token.address))
227
+ return;
228
+ const tokenChain = normalizeChain(token.chain);
229
+ if (tokenChain && tokenChain !== chain) {
230
+ const label = token.symbol ? `$${sanitizeTerminal(token.symbol)}` : sanitizeTerminal(token.address);
231
+ throw new Error(`${label} (${sanitizeTerminal(token.address)}) is on ${displayChain(tokenChain)}, not ${displayChain(chain)}. ` +
232
+ 'Pick the token on the intended chain or change --chain.');
233
+ }
234
+ }
167
235
  /** Capitalize chain name for display (e.g. "solana" → "Solana", "bsc" → "BSC"). */
168
236
  function displayChain(raw) {
169
237
  const name = normalizeChain(raw) ?? raw ?? 'unknown';
@@ -217,7 +285,13 @@ export async function lookupToken(tokenInput) {
217
285
  if (!res.data || res.data.length === 0) {
218
286
  throw new Error(`Unknown token: ${tokenInput}`);
219
287
  }
220
- let tokens = res.data;
288
+ // Token symbol / name are third-party metadata — strip control sequences
289
+ // before they reach any prompt or confirmation screen.
290
+ let tokens = res.data.map((t) => ({
291
+ ...t,
292
+ symbol: t.symbol === undefined || t.symbol === null ? t.symbol : sanitizeTerminal(t.symbol),
293
+ name: t.name === undefined || t.name === null ? t.name : sanitizeTerminal(t.name),
294
+ }));
221
295
  if (isTicker) {
222
296
  const filtered = tokens.filter((t) => t.symbol?.toLowerCase() === keyword.toLowerCase());
223
297
  if (filtered.length > 0)
@@ -287,16 +361,17 @@ export async function lookupToken(tokenInput) {
287
361
  */
288
362
  export function formatTokenLabel(token) {
289
363
  if (!token.symbol)
290
- return chalk.yellow(token.address);
291
- const ticker = chalk.bold('$' + token.symbol);
292
- return token.name ? `${ticker} ${chalk.dim('—')} ${token.name}` : ticker;
364
+ return chalk.yellow(sanitizeTerminal(token.address));
365
+ const ticker = chalk.bold('$' + sanitizeTerminal(token.symbol));
366
+ return token.name ? `${ticker} ${chalk.dim('—')} ${sanitizeTerminal(token.name)}` : ticker;
293
367
  }
294
- // ─── Transaction confirmation ─────────────────────────────────────────────────
295
368
  /**
296
- * Prompt the user for a mandatory second confirmation before executing a
297
- * fund-related operation. Controlled by `confirmBeforeTransaction` in config
298
- * (default: enabled). This confirmation is independent of the `-y` flag and
299
- * Touch ID — it serves as an extra safety net.
369
+ * Prompt the user for a second confirmation before executing a fund-related
370
+ * operation. Controlled by `confirmBeforeTransaction` in config (default:
371
+ * enabled). Callers decide whether `-y` skips this prompt; Touch ID (when
372
+ * enabled) is enforced separately via `requireTouchId()`.
373
+ *
374
+ * All values are passed through {@link sanitizeTerminal} before printing.
300
375
  *
301
376
  * @param description Short one-line summary of the operation.
302
377
  * @param token Optional token metadata to highlight in the prompt.
@@ -305,31 +380,38 @@ export function formatTokenLabel(token) {
305
380
  */
306
381
  export async function requireTransactionConfirmation(description, token, details) {
307
382
  const config = loadConfig();
308
- if (config.confirmBeforeTransaction === false)
383
+ if (config.confirmBeforeTransaction === false) {
384
+ warn('Transaction confirmation is disabled in config (`minara config` to re-enable).');
309
385
  return;
386
+ }
387
+ const clean = (v) => sanitizeTerminal(v);
310
388
  console.log('');
311
389
  console.log(chalk.yellow('⚠'), chalk.bold('Transaction confirmation'));
312
390
  if (details?.chain) {
313
- console.log(chalk.dim(' Chain : ') + chalk.cyan(details.chain));
391
+ console.log(chalk.dim(' Chain : ') + chalk.cyan(clean(details.chain)));
314
392
  }
315
393
  if (token) {
316
- const ticker = token.symbol ? '$' + token.symbol : undefined;
317
- const label = [ticker, token.name].filter(Boolean).join(' — ');
394
+ const ticker = token.symbol ? '$' + clean(token.symbol) : undefined;
395
+ const label = [ticker, token.name ? clean(token.name) : undefined].filter(Boolean).join(' — ');
318
396
  console.log(chalk.dim(' Token : ') + (label ? chalk.bold(label) : chalk.dim('Unknown token')));
319
- console.log(chalk.dim(' Address : ') + chalk.yellow(token.address));
397
+ console.log(chalk.dim(' Address : ') + chalk.yellow(clean(token.address)));
320
398
  }
321
399
  if (details?.side) {
322
- const s = details.side.toLowerCase();
323
- const colored = s === 'buy' ? chalk.green.bold(details.side.toUpperCase()) : chalk.red.bold(details.side.toUpperCase());
400
+ const side = clean(details.side);
401
+ const s = side.toLowerCase();
402
+ const colored = s === 'buy' ? chalk.green.bold(side.toUpperCase()) : chalk.red.bold(side.toUpperCase());
324
403
  console.log(chalk.dim(' Side : ') + colored);
325
404
  }
326
405
  if (details?.amount) {
327
- console.log(chalk.dim(' Amount : ') + chalk.bold(details.amount));
406
+ console.log(chalk.dim(' Amount : ') + chalk.bold(clean(details.amount)));
328
407
  }
329
408
  if (details?.destination) {
330
- console.log(chalk.dim(' To : ') + chalk.yellow(details.destination));
409
+ console.log(chalk.dim(' To : ') + chalk.yellow(clean(details.destination)));
331
410
  }
332
- console.log(chalk.dim(` Action : ${description}`));
411
+ for (const [label, value] of details?.extra ?? []) {
412
+ console.log(chalk.dim(` ${clean(label).padEnd(9)}: `) + chalk.bold(clean(value)));
413
+ }
414
+ console.log(chalk.dim(` Action : ${clean(description)}`));
333
415
  console.log('');
334
416
  const ok = await confirm({
335
417
  message: 'Are you sure you want to proceed?',
@@ -369,8 +451,39 @@ export function validateAddress(address, chain) {
369
451
  return true;
370
452
  }
371
453
  // ─── Browser ──────────────────────────────────────────────────────────────────
372
- /** Open a URL in the user's default browser (cross-platform). */
454
+ /**
455
+ * Return the normalised URL if it is safe to hand to the OS browser opener
456
+ * (https, or http on a loopback host), otherwise `null`.
457
+ */
458
+ export function safeBrowserUrl(url) {
459
+ let parsed;
460
+ try {
461
+ parsed = new URL(url);
462
+ }
463
+ catch {
464
+ return null;
465
+ }
466
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname);
467
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback))
468
+ return null;
469
+ return parsed.toString();
470
+ }
471
+ /**
472
+ * Open a URL in the user's default browser (cross-platform).
473
+ *
474
+ * Only https URLs (or http on loopback) are opened. On Windows the URL is
475
+ * passed to `rundll32 url.dll,FileProtocolHandler` instead of `cmd /c start`,
476
+ * because cmd.exe would interpret `&`, `|`, `^` etc. inside a server-supplied
477
+ * URL as shell syntax.
478
+ */
373
479
  export function openBrowser(url) {
480
+ const safeUrl = safeBrowserUrl(url);
481
+ if (!safeUrl) {
482
+ console.log(chalk.yellow('⚠'), 'Refusing to open a non-HTTPS link automatically:');
483
+ console.log(chalk.dim(` ${sanitizeTerminal(url)}`));
484
+ return;
485
+ }
486
+ url = safeUrl;
374
487
  const plat = platform();
375
488
  let cmd;
376
489
  let args;
@@ -379,8 +492,8 @@ export function openBrowser(url) {
379
492
  args = [url];
380
493
  }
381
494
  else if (plat === 'win32') {
382
- cmd = 'cmd';
383
- args = ['/c', 'start', '', url];
495
+ cmd = 'rundll32';
496
+ args = ['url.dll,FileProtocolHandler', url];
384
497
  }
385
498
  else {
386
499
  cmd = 'xdg-open';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minara",
3
- "version": "0.4.7",
3
+ "version": "0.5.1",
4
4
  "description": "CLI client for Minara.ai — login, trade, deposit/withdraw, chat and more from your terminal.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -37,6 +37,14 @@
37
37
  "finance"
38
38
  ],
39
39
  "license": "MIT",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/Minara-AI/minara-cli.git"
43
+ },
44
+ "homepage": "https://github.com/Minara-AI/minara-cli#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/Minara-AI/minara-cli/issues"
47
+ },
40
48
  "dependencies": {
41
49
  "@inquirer/prompts": "^7.0.0",
42
50
  "chalk": "^5.3.0",
@@ -46,8 +54,8 @@
46
54
  },
47
55
  "devDependencies": {
48
56
  "@types/node": "^22.0.0",
49
- "@vitest/coverage-v8": "^4.1.0",
57
+ "@vitest/coverage-v8": "^4.1.12",
50
58
  "typescript": "^5.6.0",
51
- "vitest": "^4.0.18"
59
+ "vitest": "^4.1.12"
52
60
  }
53
61
  }
@@ -1,38 +0,0 @@
1
- /**
2
- * Temporary local HTTP server for OAuth callback.
3
- *
4
- * Flow:
5
- * 1. CLI starts a local server on a random port
6
- * 2. CLI opens the browser to the OAuth URL (redirect_uri → localhost)
7
- * 3. User authenticates in the browser
8
- * 4. OAuth provider → Minara backend → redirects to our local server
9
- * 5. Local server captures token from query params
10
- * 6. Returns result and shuts down
11
- */
12
- export interface OAuthCallbackResult {
13
- /** The access token (if login succeeded) */
14
- accessToken?: string;
15
- userId?: string;
16
- email?: string;
17
- displayName?: string;
18
- /** Error message (if login failed) */
19
- error?: string;
20
- /** Raw query parameters from the callback URL */
21
- rawParams: Record<string, string>;
22
- }
23
- export interface OAuthServer {
24
- /** Port the server is listening on */
25
- port: number;
26
- /** The callback URL to use as redirect_uri */
27
- callbackUrl: string;
28
- /** Resolves when the OAuth callback is received (or timeout) */
29
- waitForCallback: () => Promise<OAuthCallbackResult>;
30
- /** Shut down the server early */
31
- close: () => void;
32
- }
33
- /**
34
- * Start a temporary local HTTP server that listens for the OAuth callback.
35
- *
36
- * @param timeoutMs How long to wait before giving up (default: 5 minutes).
37
- */
38
- export declare function startOAuthServer(timeoutMs?: number): Promise<OAuthServer>;