Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ minara --help

## Testing

Test suite built with [Vitest](https://vitest.dev/) — 425 tests covering unit, API, command integration, and formatter layers.
Test suite built with [Vitest](https://vitest.dev/) — 438 tests covering unit, API, command integration, and formatter layers.

```bash
npm test # Run all tests
Expand All @@ -413,8 +413,9 @@ npm run test:coverage # With v8 coverage report
- **Token Verification** — Token ticker, name, and full contract address are always displayed before any transaction to prevent wrong-token mistakes. `$TICKER` lookups require an exact symbol match. When you have already chosen a chain (or passed `--chain`), only tokens on that chain are offered. If several tokens share a symbol, the picker shows each one's full contract address and market cap, lists the highest market cap first, and warns about same-chain lookalikes. Third-party token names are length-capped and stripped of control characters
- **Trusted API host only** — requests (including the session token and email login codes) are only sent to `https://*.minara.ai` (localhost only when `MINARA_DEV=1` is set); any other configured base URL is refused
- **Safe terminal output** — every API response (including Hyperliquid market data) is stripped of terminal control sequences, C1 controls, bidi override characters and invisible characters (zero-width, soft hyphen, BOM, Unicode tags…) as it arrives. Chat output is cleaned the same way as it streams. Third-party metadata cannot rewrite or spoof confirmation screens
- **Native tokens per chain** — the native-token placeholder `0x0…0` / `0xE…E` always means the native coin of the selected chain. Lookup only offers it under that coin's symbol (for example `$ETH` on Base, never `$POL` on Base), and never on Solana
- **Recipient checks** — withdraw / send addresses are validated for the chain. A Solana address must decode to a 32-byte key, and one that is not a wallet public key (off the ed25519 curve) gets a warning, because Solana addresses have no checksum
- **Re-login safety** — after an expired session, the original request is only retried if you sign back in to the same account
- **Re-login safety** — after an expired session the CLI offers to sign in again. Only read-only requests are then retried automatically, and only when the new session provably belongs to the same account. A trade, transfer, order or account change is never re-sent: run the command again to review and confirm it with current prices
- Credentials are stored in `~/.minara/credentials.json` with `0600` file permissions (re-applied on every write)
- The `~/.minara/` directory is kept at `0700` permissions
- Tokens are never logged or printed to the console
Expand Down
38 changes: 34 additions & 4 deletions src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@ interface RequestOptions {
headers?: Record<string, string>;
/** Return a plain 401 instead of prompting to log in again (e.g. logout). */
noReauth?: boolean;
/**
* Safe to send again automatically after a re-login: the request has no
* side effects. Defaults to true for GET and false for everything else.
*/
replayable?: boolean;
}

/**
* Tokens superseded by a re-login in this process, for the same account.
* Commands read the token once at start; later requests of the same command
* use the renewed token instead of hitting 401 and prompting again. These
* requests are sent for the first time after the re-login (and after any
* confirmation that follows it), so this is not a replay.
*/
const renewedTokens = new Map<string, string>();

function currentToken(token: string | undefined): string | undefined {
let t = token;
for (let i = 0; t && renewedTokens.has(t) && i < 5; i++) t = renewedTokens.get(t);
return t;
}

// ── Base URL trust check ──────────────────────────────────────────────────
Expand Down Expand Up @@ -92,7 +112,8 @@ async function requestImpl<T>(
opts: RequestOptions,
isRetry: boolean,
): Promise<ApiResponse<T>> {
const { method = 'GET', body, query, token, headers: extraHeaders } = opts;
const { method = 'GET', body, query, headers: extraHeaders } = opts;
const token = currentToken(opts.token);

let url: string;
try {
Expand Down Expand Up @@ -195,11 +216,20 @@ async function handleAuthExpired<T>(
try {
// Dynamic import — only loaded when needed, avoids circular deps
const { attemptReAuth } = await import('../auth-refresh.js');
const newToken = await attemptReAuth();
// Only reads are replayed. The rejected request was not executed, and a
// write (trade, transfer, order, account change) must go back through the
// command's confirmation with current quotes instead of being re-sent.
const outcome = await attemptReAuth({ replayable: opts.replayable ?? (opts.method ?? 'GET') === 'GET' });

if (newToken) {
if (outcome.kind !== 'failed' && outcome.token && opts.token) {
renewedTokens.set(opts.token, outcome.token); // same account confirmed
}
if (outcome.kind === 'retry') {
// Retry the original request with the new token (isRetry = true)
return requestImpl<T>(path, { ...opts, token: newToken }, true);
return requestImpl<T>(path, { ...opts, token: outcome.token }, true);
}
if (outcome.kind === 'renewed') {
return { success: false, error: { code: 401, message: outcome.message } };
}
} catch (err) {
// Module load failure or unexpected error — log for debugging, fall through
Expand Down
5 changes: 3 additions & 2 deletions src/api/crosschain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export function swaps(token: string, swapList: CrossChainSwapDto[]) {
/** Simulate swaps (dry-run) */
export function swapsSimulate(token: string, swapList: CrossChainSwapDto[]) {
return post<CrossChainSwapsSimulateItem[]>('/v1/tx/cross-chain/swaps-simulate', {
replayable: true, // quote only, no side effects
token,
body: { swaps: swapList },
});
Expand All @@ -47,7 +48,7 @@ export function transfer(token: string, dto: CrossChainTransferDto) {

/** Get activities */
export function getActivities(token: string, dto: CrossChainActivitiesDto) {
return post<Record<string, unknown>[]>('/v1/tx/cross-chain/activities', { token, body: dto });
return post<Record<string, unknown>[]>('/v1/tx/cross-chain/activities', { token, body: dto, replayable: true });
}

/** Get PnL history */
Expand All @@ -57,5 +58,5 @@ export function getPnlHistory(token: string, type: string) {

/** Check transaction statuses */
export function getStatuses(token: string, transactionIds: string[]) {
return post<TransactionResult[]>('/v1/tx/cross-chain/statuses', { token, body: { transactionIds } });
return post<TransactionResult[]>('/v1/tx/cross-chain/statuses', { token, body: { transactionIds }, replayable: true });
}
2 changes: 1 addition & 1 deletion src/api/perps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ export function sweepFunds(token: string, dto: SweepFundsDto) {
// ── Price Analysis (Ask Long/Short) ──────────────────────────────────────

export function priceAnalysis(token: string, dto: { symbol: string; startTime?: number; endTime?: number; interval?: string; positionUSD?: number; leverage?: number }) {
return post<Record<string, unknown>>('/tokens/price-analysis', { token, body: dto });
return post<Record<string, unknown>>('/tokens/price-analysis', { token, body: dto, replayable: true });
}

/** Get perps wallet address from user profile */
Expand Down
97 changes: 72 additions & 25 deletions src/auth-refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,52 @@ import chalk from 'chalk';
import { loadCredentials, saveCredentials } from './config.js';
import { sendEmailCode, verifyEmailCode } from './api/auth.js';

/** What happened after a 401, and whether the original request may be sent again. */
export type ReAuthOutcome =
/** Same account confirmed and the request is a read: replay it with this token. */
| { kind: 'retry'; token: string }
/**
* Signed in again (credentials saved) but the request must NOT be replayed.
* `token` is set only when the new session is the same account.
*/
| { kind: 'renewed'; message: string; token?: string }
/** Declined, cancelled or failed: nothing changed. */
| { kind: 'failed' };

/**
* Attempt to re-authenticate interactively.
*
* The caller replays the original request with the returned token, so the new
* session must belong to the same account as the expired one. If the user
* signs in as a different account the new credentials are saved but `null`
* is returned, and the pending request is not replayed.
* Whether the new session provably belongs to the account of the expired one.
* Fails closed: compares user IDs when both are known, otherwise the emails
* the server returned; with nothing to compare, the answer is "no" (M-366).
*/
function provablySameAccount(
old: { userId?: string; email?: string } | null | undefined,
next: { id?: string; email?: string },
): boolean {
if (old?.userId && next.id) return String(old.userId) === String(next.id);
if (old?.email && next.email) return old.email.toLowerCase() === next.email.toLowerCase();
return false;
}

/** The identities are known on both sides and differ. */
function provablyDifferentAccount(
old: { userId?: string; email?: string } | null | undefined,
next: { id?: string; email?: string },
): boolean {
if (old?.userId && next.id && String(old.userId) !== String(next.id)) return true;
return !!old?.email && !!next.email && old.email.toLowerCase() !== next.email.toLowerCase();
}

/**
* Attempt to re-authenticate interactively after a 401.
*
* @returns The new access token on success, or `null` on failure / user decline /
* account change.
* The original request was rejected by the server, so nothing was executed.
* It is only sent again automatically when it is a read (`replayable`) and the
* new session provably belongs to the same account. A write — a swap,
* transfer, order, cancellation, account change — is never replayed: the
* user re-runs the command and goes through its confirmation again with
* current quotes and prices (M-366).
*/
export async function attemptReAuth(): Promise<string | null> {
export async function attemptReAuth(opts: { replayable?: boolean } = {}): Promise<ReAuthOutcome> {
try {
console.log('');
console.log(
Expand All @@ -40,7 +74,7 @@ export async function attemptReAuth(): Promise<string | null> {

if (!wantReLogin) {
console.log(chalk.dim('Run `minara login` to manually refresh your session.'));
return null;
return { kind: 'failed' };
}
// ── Determine email ─────────────────────────────────────────────────
const creds = loadCredentials();
Expand All @@ -63,7 +97,7 @@ export async function attemptReAuth(): Promise<string | null> {
chalk.red('✖'),
`Failed to send code: ${codeRes.error?.message ?? 'Unknown error'}`,
);
return null;
return { kind: 'failed' };
}

console.log(chalk.green('✔'), `Verification code sent to ${chalk.cyan(email)}`);
Expand All @@ -87,15 +121,15 @@ export async function attemptReAuth(): Promise<string | null> {
chalk.red('✖'),
`Verification failed: ${verifyRes.error?.message ?? 'Invalid code'}`,
);
return null;
return { kind: 'failed' };
}

const user = verifyRes.data;
const newToken = user.access_token;

if (!newToken) {
console.error(chalk.red('✖'), 'No access token in response.');
return null;
return { kind: 'failed' };
}

const newEmail = user.email ?? email;
Expand All @@ -108,23 +142,36 @@ export async function attemptReAuth(): Promise<string | null> {
displayName: user.displayName,
});

// ── Only replay the original request for the same account ───────────
const userChanged = creds?.userId !== undefined && user.id !== undefined && creds.userId !== user.id;
const emailChanged = !!creds?.email && !!newEmail && creds.email.toLowerCase() !== newEmail.toLowerCase();
if (userChanged || emailChanged) {
console.log(
chalk.yellow('⚠'),
chalk.yellow(`Signed in as a different account (${newEmail}). The pending request was NOT retried.`),
);
console.log(chalk.dim('Run the command again if you want to perform it with this account.'));
// ── Decide whether the original request may be sent again ───────────
// Only the server's answer counts as the new identity, not the email
// typed or remembered locally.
const next = { id: user.id, email: user.email };
if (provablyDifferentAccount(creds, next)) {
const message = `Signed in as a different account (${newEmail}). The pending request was NOT retried. `
+ 'Run the command again if you want to perform it with this account.';
console.log(chalk.yellow('⚠'), chalk.yellow(message));
console.log('');
return { kind: 'renewed', message };
}
if (!provablySameAccount(creds, next)) {
const message = 'Signed in again, but the new session could not be matched to the expired one, '
+ 'so the pending request was NOT retried. Run the command again.';
console.log(chalk.yellow('⚠'), chalk.yellow(message));
console.log('');
return { kind: 'renewed', message };
}
if (!opts.replayable) {
const message = 'Signed in again. The pending request changes your account (e.g. a trade, transfer or order), '
+ 'so it was NOT sent automatically. Run the command again to review and confirm it with current prices.';
console.log(chalk.green('✔'), message);
console.log('');
return null;
return { kind: 'renewed', message, token: newToken };
}

console.log(chalk.green('✔'), 'Re-login successful! Retrying your request…');
console.log('');

return newToken;
return { kind: 'retry', token: newToken };
} catch (err) {
// Handle Ctrl+C or closed prompt
if (err instanceof Error && (err.message.includes('closed') || err.message.includes('aborted'))) {
Expand All @@ -135,6 +182,6 @@ export async function attemptReAuth(): Promise<string | null> {
`Re-login error: ${err instanceof Error ? err.message : String(err)}`,
);
}
return null;
return { kind: 'failed' };
}
}
Loading