diff --git a/.env.example b/.env.example index 180e67e..6c7c039 100644 --- a/.env.example +++ b/.env.example @@ -14,7 +14,7 @@ ML_GROUP_ID=1000 # WEB_GUI_IMAGE=ghcr.io/mintlayer/web-gui/web-gui:latest # BDK_WALLET_IMAGE=ghcr.io/mintlayer/web-gui/bdk-wallet:latest # BTC_EXPLORER_IMAGE=ghcr.io/mintlayer/web-gui/btc-explorer:latest -# Mintlayer daemons are also rebuilt from v1.4.0 source for arm64: +# Mintlayer daemons are also rebuilt from v1.4.1 source for arm64: # ML_NODE_DAEMON_IMAGE=ghcr.io/mintlayer/web-gui/node-daemon:latest # ML_WALLET_RPC_DAEMON_IMAGE=ghcr.io/mintlayer/web-gui/wallet-rpc-daemon:latest # ML_API_SCANNER_IMAGE=ghcr.io/mintlayer/web-gui/api-blockchain-scanner-daemon:latest @@ -90,6 +90,13 @@ PASSKEY_ORIGIN=http://localhost:4321 # and managed via the web UI Settings page. SESSION_SECRET=<64-hex-chars-random> +# ── Optional-services sidecar ───────────────────── +# The feature-enabler container (settings-page toggles/upgrades) applies +# compose against the REAL host path of this checkout - a container path +# breaks bind mounts and the compose project name. init.sh writes this; +# manual installs must set it to the absolute checkout directory. +PROJECT_DIR_HOST=/absolute/path/to/web-gui + # ── Indexer (optional, profile: indexer) ───────────── # Only needed when running: docker compose --profile indexer up POSTGRES_USER=mintlayer @@ -127,7 +134,8 @@ PINATA_GATEWAY_URL= BITCOIN_ENABLED=false # Bitcoin network. Empty = follow NETWORK above (mainnet/testnet). -# Valid values: mainnet, testnet, regtest, signet. +# Supported end to end: mainnet, testnet, regtest. (signet is not wired +# through the enabler allowlist or Core's -chain fallback - do not use.) BITCOIN_NETWORK= # Credentials for the bitcoind RPC (used by the bdk-wallet sidecar). @@ -139,12 +147,17 @@ BITCOIN_WALLET_HTTP_USERNAME=btcwallet_user BITCOIN_WALLET_HTTP_PASSWORD=btcwallet_password_change_me # Advanced: transaction index and pruning for bitcoind. -# txindex=1 (default) is required for full wallet history. -# prune>0 saves disk but is incompatible with the wallet history sync -# (mainnet chain data is ~700 GB with txindex=1). +# txindex=1 (default) keeps full wallet history available to rescans. +# prune>0 saves disk (pruned keeps only recent blocks) but the wallet +# sidecar refuses restoring an OLD seed against a pruned node. BITCOIN_TXINDEX=1 BITCOIN_PRUNE=0 +# Bitcoin Core's -chain value. init.sh derives this (mainnet -> "main", +# others pass through). Manual installs: leave as "main" for mainnet, +# or set test / regtest / signet to match BITCOIN_NETWORK. +#BITCOIN_CORE_CHAIN=main + # Block explorer used for tx/address links in the Bitcoin page. # Empty default: public networks link to mempool.space; regtest links to # the self-hosted btc-rpc-explorer sidecar (http://localhost:3002). diff --git a/Makefile b/Makefile index 005c4fb..b08f778 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,12 @@ .PHONY: up down restart nuke restart-gui build logs dev dev-build dev-local dev-env wallet-cli bitcoin bitcoin-cli nft-images-public pending-transactions list-utxos ACCOUNT ?= 0 +# Compose derives the network name from the project directory +# (checkout folder), not from a fixed string - derive it the same way. +COMPOSE_NETWORK ?= $(notdir $(CURDIR))_default +# Helper tools read RPC credentials from the env file; dev stacks +# only have .env.dev. +ENV_FILE := $(if $(wildcard .env),.env,.env.dev) ## Start all services up: @@ -9,28 +15,28 @@ up: ## Stop and remove all containers (including optional profiles and orphaned run containers) down: - docker compose --profile indexer --profile wallet_cli --profile bitcoin down --remove-orphans + docker compose --profile indexer --profile wallet_cli --profile bitcoin --profile web --profile watchtower down --remove-orphans ## Full clean restart: tear down everything, fix stuck networks, then bring up fresh ## Fixes "Network still in use" / "network not found" errors from dangling containers. restart: down @# Disconnect any containers still clinging to the project network - @NETWORK=mintlayer-web-gui_default; \ + @NETWORK=$(COMPOSE_NETWORK); \ CONTAINERS=$$(docker network inspect $$NETWORK --format '{{range .Containers}}{{.Name}} {{end}}' 2>/dev/null || true); \ if [ -n "$$CONTAINERS" ]; then \ echo "Disconnecting dangling containers from $$NETWORK: $$CONTAINERS"; \ for c in $$CONTAINERS; do docker network disconnect -f $$NETWORK $$c 2>/dev/null || true; done; \ fi @# Remove the network if it still exists so Docker recreates it cleanly - @docker network rm mintlayer-web-gui_default 2>/dev/null || true + @docker network rm $(COMPOSE_NETWORK) 2>/dev/null || true docker compose up -d -## Nuclear option: remove ALL stopped containers and unused networks project-wide, -## then restart. Use when restart still fails. +## Nuclear option: remove this project's containers/volumes/networks, then +## restart. Use when restart still fails. Deliberately project-scoped - +## host-wide `docker prune` would eat stopped containers from unrelated +## projects on shared machines. nuke: - docker compose --profile indexer --profile wallet_cli --profile bitcoin down --remove-orphans --volumes 2>/dev/null || true - docker container prune -f - docker network prune -f + docker compose --profile indexer --profile wallet_cli --profile bitcoin --profile web --profile watchtower down --remove-orphans --volumes 2>/dev/null || true docker compose up -d ## Rebuild and restart only the web-gui container @@ -88,15 +94,15 @@ bitcoin: ## bitcoin-cli shell inside the Bitcoin node container ## Usage: make bitcoin-cli CMD='getblockchaininfo' bitcoin-cli: - docker compose --profile bitcoin exec bitcoind bitcoin-cli -rpcport=8332 -rpcuser=$$(grep '^BITCOIN_RPC_USERNAME=' .env | cut -d= -f2) -rpcpassword=$$(grep '^BITCOIN_RPC_PASSWORD=' .env | cut -d= -f2) $(CMD) + docker compose --profile bitcoin exec bitcoind bitcoin-cli -rpcport=8332 -rpcuser=$$(grep '^BITCOIN_RPC_USERNAME=' .env | cut -d= -f2-) -rpcpassword=$$(grep '^BITCOIN_RPC_PASSWORD=' .env | cut -d= -f2-) $(CMD) ## List pending transactions for account ACCOUNT (default 0) via wallet RPC. ## Usage: make pending-transactions or make pending-transactions ACCOUNT=1 pending-transactions: docker run --rm \ - --network web-gui_default \ + --network $(COMPOSE_NETWORK) \ -v "$(CURDIR)/tools:/tools:ro" \ - -v "$(CURDIR)/.env:/.env:ro" \ + -v "$(CURDIR)/$(ENV_FILE):/.env:ro" \ -e WALLET_RPC_HOST=wallet-rpc-daemon \ alpine sh -c 'apk add -q bash curl jq >/dev/null && bash /tools/list-pending-transactions.sh $(ACCOUNT)' @@ -104,9 +110,9 @@ pending-transactions: ## Usage: make list-utxos or make list-utxos ACCOUNT=1 list-utxos: docker run --rm \ - --network web-gui_default \ + --network $(COMPOSE_NETWORK) \ -v "$(CURDIR)/tools:/tools:ro" \ - -v "$(CURDIR)/.env:/.env:ro" \ + -v "$(CURDIR)/$(ENV_FILE):/.env:ro" \ -e WALLET_RPC_HOST=wallet-rpc-daemon \ alpine sh -c 'apk add -q bash curl jq >/dev/null && bash /tools/list-utxos.sh $(ACCOUNT)' @@ -114,9 +120,9 @@ list-utxos: ## Runs inside Docker so it can reach wallet-rpc-daemon on the internal network. nft-images-public: docker run --rm \ - --network mintlayer-web-gui_default \ + --network $(COMPOSE_NETWORK) \ -v "$(CURDIR)/tools:/tools:ro" \ - -v "$(CURDIR)/.env:/.env:ro" \ + -v "$(CURDIR)/$(ENV_FILE):/.env:ro" \ -e WALLET_RPC_URL=http://wallet-rpc-daemon:3034 \ node:lts-alpine \ node /tools/make-nft-images-public.mjs diff --git a/app/src/components/BitcoinWallet.tsx b/app/src/components/BitcoinWallet.tsx index f65ee2f..353c1b6 100644 --- a/app/src/components/BitcoinWallet.tsx +++ b/app/src/components/BitcoinWallet.tsx @@ -28,15 +28,23 @@ async function api(path: string, init?: RequestInit): Promise { ...init, headers: init?.body ? { 'Content-Type': 'application/json' } : undefined, }); - // Auth expiry and proxy errors return the login HTML or a plain-text 403, - // never JSON - parsing those surfaces a raw SyntaxError instead of the cause. + // Auth expiry returns the login HTML (or a plain-text 403), never JSON. + // Only a REAL auth signal bounces to /login: a 5xx rendered as an Astro + // error page is a server outage, and telling the user their session + // expired masks it. const contentType = res.headers.get('content-type') ?? ''; - if (res.redirected || res.status === 401 || !contentType.includes('application/json')) { + if (res.redirected || res.status === 401 || res.status === 403 || (!res.ok && !contentType.includes('application/json'))) { window.location.assign('/login'); throw new Error('Your session expired - redirecting to login…'); } const data = (await res.json()) as T & { ok?: boolean; error?: string }; - if (!res.ok || data.ok === false) throw new Error(data.error ?? `Request failed (${res.status})`); + if (!res.ok || data.ok === false) { + // Carry the HTTP status: callers distinguish 409 "already exists" + // (recovery: refresh + show the wallet) from real failures. + const err = new Error(data.error ?? `Request failed (${res.status})`) as Error & { status?: number }; + err.status = res.status; + throw err; + } return data; } @@ -70,13 +78,14 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp const [noticeIsError, setNoticeIsError] = useState(false); const [newMnemonic, setNewMnemonic] = useState(null); + const [seedVerified, setSeedVerified] = useState(false); // Create / restore (2FA-gated) const [setupTotp, setSetupTotp] = useState(''); const [restoreOpen, setRestoreOpen] = useState(false); const [restoreSeed, setRestoreSeed] = useState(''); // Destructive-action gate: the submit stays disabled until the user types - // the confirmation phrase - restoring replaces the current BTC wallet. + // the confirmation phrase - the wallet is then created from the typed seed. const [restoreConfirm, setRestoreConfirm] = useState(''); const [setupError, setSetupError] = useState(null); @@ -92,6 +101,7 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp const [sendError, setSendError] = useState(null); const [sentTxid, setSentTxid] = useState(null); const [feeSatVb, setFeeSatVb] = useState(null); + const [feeUnavailable, setFeeUnavailable] = useState(false); const [addrSuggestion, setAddrSuggestion] = useState<{ corrected: string; fixedChars: number } | null>(null); const timers = useRef[]>([]); @@ -113,16 +123,37 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp useEffect(() => { refresh(); }, [refresh]); - // Best-effort fee hint for the send form. + // While a scan runs, the read endpoints fail fast (503) and the overview + // route serves nulls: poll through the scan so balance, history and the + // receive address fill in as progress lands instead of sitting empty + // until the user hits refresh manually. useEffect(() => { - api<{ satPerVb: Record }>('/api/bitcoin/fee-estimate') - .then((r) => { - const fast = r.satPerVb?.['1'] ?? r.satPerVb?.['3'] ?? r.satPerVb?.['6']; - if (typeof fast === 'number') setFeeSatVb(fast); - }) - .catch(() => { /* fee hint is optional */ }); + if (!overview?.status?.syncing) return; + const t = setInterval(() => { void refresh(); }, 8000); + return () => clearInterval(t); + }, [overview?.status?.syncing, refresh]); + + // Best-effort fee hint for the send form. Re-checked on mount and again + // right before a send when it is still missing: the node may simply not + // have been ready yet. When it never arrives, the send proceeds on the + // BDK default of 1 sat/vB and the form says so instead of doing it + // silently. + const fetchFeeEstimate = useCallback(async (): Promise => { + try { + const r = await api<{ satPerVb: Record }>('/api/bitcoin/fee-estimate'); + const fast = r.satPerVb?.['1'] ?? r.satPerVb?.['3'] ?? r.satPerVb?.['6']; + if (typeof fast === 'number' && fast > 0) { + setFeeSatVb(fast); + setFeeUnavailable(false); + return fast; + } + } catch { /* fee hint is optional */ } + setFeeUnavailable(true); + return null; }, []); + useEffect(() => { void fetchFeeEstimate(); }, [fetchFeeEstimate]); + const walletExists = overview?.status?.walletExists ?? false; function showNotice(message: string, isError = false) { @@ -146,12 +177,22 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp setRestoreConfirm(''); // Restores return no mnemonic - only a fresh generate shows the backup step. setNewMnemonic(res.mnemonic ?? null); + setSeedVerified(false); await refresh(); } catch (err) { // The code may already be burned by this attempt - never leave stale // six digits in the field for the user to blindly resubmit. setSetupTotp(''); - setSetupError((err as Error).message); + const status = (err as { status?: number }).status; + // Only an "already exists" 409 proves the create landed (a dropped + // response after success). The pruned-node restore refusal ALSO + // 409s - treating that as success would hide a real refusal. + if (status === 409 && /already exists/i.test((err as Error).message)) { + setSetupError(null); + await refresh(); + } else { + setSetupError((err as Error).message); + } } finally { setBusy(false); } @@ -174,7 +215,16 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp await refresh(); } catch (err) { setLinkTotp(''); - setLinkError((err as Error).message); + const status = (err as { status?: number }).status; + // Same as the create path: only "already exists" proves the link + // landed; the pruned-node refusal is a different 409 and must show. + if (status === 409 && /already exists/i.test((err as Error).message)) { + setLinkError(null); + showNotice('BTC wallet already linked - loading it.'); + await refresh(); + } else { + setLinkError((err as Error).message); + } } finally { setBusy(false); } @@ -186,8 +236,10 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp if (restoreConfirm !== 'I UNDERSTAND') return; const seed = cleanSeed(restoreSeed); const words = seed.split(/\s+/).filter(Boolean); - if (words.length !== 12 && words.length !== 24) { - setSetupError(`A seed phrase has 12 or 24 words - this one has ${words.length}.`); + // BIP39 defines 12/15/18/21/24-word mnemonics; the checksum verdict + // belongs to the sidecar (Mnemonic::parse_in). + if (![12, 15, 18, 21, 24].includes(words.length)) { + setSetupError(`A seed phrase has 12, 15, 18, 21 or 24 words - this one has ${words.length}.`); return; } createWallet(seed); @@ -260,6 +312,10 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp setSendError('Enter your 6-digit 2FA code to confirm the send.'); return; } + // One fresh estimate right before signing - the mount-time fetch may + // predate a node that only became reachable. + let rate = feeSatVb; + if (typeof rate !== 'number') rate = await fetchFeeEstimate(); // Typo recovery: checksum failure with a within-2-chars fix offers a // suggestion instead of sending. Never auto-replaces the input. @@ -289,6 +345,10 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp address: sendTo.trim(), amount_btc: sendAmount.trim(), totp_code: sendTotp.trim(), + // The fetched estimate is the real fee rate (fallback: the BDK + // default of 1 sat/vB, which can sit unconfirmed for days - the + // form shows a warning whenever this path is taken). + ...(typeof rate === 'number' ? { fee_rate_sat_vb: rate } : {}), }), }); setSentTxid(res.txid); @@ -296,6 +356,9 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp setSendAmount(''); setSendTotp(''); setAddrSuggestion(null); + // The sidecar marks spent outputs right after broadcast; this + // catches the balance/history up fully. + api('/api/bitcoin/sync', { method: 'POST' }).catch(() => {}); later(refresh, 4000); } catch (err) { setSendError((err as Error).message); @@ -360,6 +423,22 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp {overview.status && ( {overview.status.network} )} + {overview.status?.syncing && ( + + scanning + + )} + {overview.status?.lastSyncError && ( + + sync problem: {overview.status.lastSyncError} + + )} {node?.reachable && node.pruned && (

Or restore from a different seed

- Use a different 12 or 24-word seed phrase for the BTC wallet. + Use a different seed phrase for the BTC wallet (12, 15, 18, 21 or 24 words). The words are then stored by the BTC sidecar on this machine.

)} @@ -514,7 +599,7 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp

Restore from seed phrase

- Enter your 12 or 24-word seed phrase. It is stored by the BTC sidecar on this machine. + Enter your seed phrase (12, 15, 18, 21 or 24 words). It is stored by the BTC sidecar on this machine.

@@ -531,7 +616,7 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp className={`${input} resize-none`} />

- {restoreSeed.trim() ? restoreSeed.trim().split(/\s+/).length : 0} of 12 or 24 words + {restoreSeed.trim() ? restoreSeed.trim().split(/\s+/).length : 0} words

@@ -548,7 +633,7 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp
Wallet is loading…

) : ( -
- Wallet file exists but could not be loaded. Try Sync, and if it persists restart - the bitcoin wallet service (docker compose --profile bitcoin up -d). +
+

+ {overview.status?.loadError ?? + 'Wallet file exists but could not be loaded.'} +

+ {!overview.status?.loadError && ( +

+ Try Sync, and if it persists restart the bitcoin wallet service (docker + compose --profile bitcoin up -d). +

+ )}
)}
@@ -691,7 +784,12 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp required /> {feeSatVb !== null && ( -

Suggested fee: ~{feeSatVb} sat/vB

+

Fee rate: ~{feeSatVb} sat/vB (used for this send)

+ )} + {feeUnavailable && ( +

+ Fee estimate unavailable - the wallet default of 1 sat/vB will be used, which can confirm slowly. +

)}
@@ -707,8 +805,19 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp required />
-
@@ -718,7 +827,11 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp

Transactions

{!overview.transactions || overview.transactions.length === 0 ? ( -

No transactions yet.

+ overview.status?.syncing ? ( +

Wallet is scanning - history appears as the scan progresses.

+ ) : ( +

No transactions yet.

+ ) ) : (
{overview.transactions.map(tx => { diff --git a/app/src/components/BridgeHistorySection.tsx b/app/src/components/BridgeHistorySection.tsx index f270492..bc30afe 100644 --- a/app/src/components/BridgeHistorySection.tsx +++ b/app/src/components/BridgeHistorySection.tsx @@ -45,7 +45,18 @@ function Row({ const [open, setOpen] = useState(false); const [failed, setFailed] = useState(false); + // Orphan rows (uuid prefixed orphan- = deposit broadcast but the bridge + // request never submitted) have no backend record: skip the poll entirely + // instead of surfacing a generic error on a guaranteed 404, and render + // the stored status text as final. + const orphan = entry.uuid.startsWith('orphan-'); + // unknown- rows: the m2e broadcast call failed AFTER signing - the bridge + // may or may not hold the request, and no id exists to poll. Render the + // stored status as final and point the user at an explorer. + const unknownOutcome = entry.uuid.startsWith('unknown-'); + const load = useCallback(async () => { + if (orphan || unknownOutcome) return; try { const d = await sdk.getBridgeRequest(entry.uuid); const p = deriveProgress(d); @@ -56,7 +67,7 @@ function Row({ } catch { setFailed(true); } - }, [entry.uuid]); + }, [entry.uuid, orphan, unknownOutcome]); useEffect(() => { if (open && !detail && !failed) void load(); @@ -93,7 +104,13 @@ function Row({ {open && (

receiver {entry.receiver}

-

request {entry.uuid}

+

+ {orphan + ? `deposit tx ${entry.uuid.slice('orphan-'.length)} (the bridge request never submitted)` + : unknownOutcome + ? 'outcome unknown - the bridge did not answer after signing; check an explorer before retrying' + : `request ${entry.uuid}`} +

{failed && (

Couldn't load the current status.{' '} @@ -115,12 +132,31 @@ function Row({ )} {payoutHash && isTxHashLike(payoutHash) && ( + {/* Payout hash: Ethereum-side when the destination is ETH, + Mintlayer-side when it is ML - route by hash shape. */} + {isEthTxHash(payoutHash) + ? 'Payout on Etherscan' + : 'Payout on the Mintlayer explorer'}{' '} + ↗ + + )} + {depositHash && !isEthTxHash(depositHash) && isTxHashLike(depositHash) && ( + - Payout on the Mintlayer explorer ↗ + Deposit on the Mintlayer explorer ↗ )}

diff --git a/app/src/components/BridgePanel.tsx b/app/src/components/BridgePanel.tsx index 90496ed..c1ebf51 100644 --- a/app/src/components/BridgePanel.tsx +++ b/app/src/components/BridgePanel.tsx @@ -13,6 +13,7 @@ import { getSubscribeUrl, isEthTxHash, isTxHashLike, + validateMintlayerAddress, type BridgeConfig, type BridgeFees, type BridgeRequestDetail, @@ -22,10 +23,12 @@ import { import { connectMetaMask, depositToBridge, + formatUnits, getConnectedAccount, - getTokenBalance, + getTokenBalanceBase, hasEthereumProvider, normalizeEvmRejection, + parseUnits, switchChain, } from '@/lib/evm'; import { suggestAddressCorrection, hrpForNetwork } from '@/lib/bech32-correct'; @@ -43,9 +46,15 @@ import BridgeHistorySection from '@/components/BridgeHistorySection'; import { appendHistory, updateHistoryStatus } from '@/lib/bridge-sdk/bridge-history'; import { ethExplorerBase, mlExplorerBase } from '@/lib/bridge-sdk/explorers'; import AddressSuggestion from '@/components/AddressSuggestion'; - const sdk = createBridgeSdk(); +/** Phases owned by an in-flight submission - a stale tracked-bridge poll + * must never overwrite them (see pollTracked). */ +const SUBMIT_PHASES: ReadonlySet = new Set(['approve', 'deposit', 'signing', 'submitting']); + +/** Consecutive poll failures before the status card gives up. */ +const POLL_FAILURE_LIMIT = 5; + type Direction = 'e2m' | 'm2e'; type Phase = | 'idle' @@ -164,6 +173,14 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled // setPhase the async submits leave `busy` false, so the button alone can't // stop a double click from creating two deposits. const submittingRef = useRef(false); + // Mirror of `phase` for stable-identity callbacks (pollTracked): lets + // them read the current submit phase without re-subscribing effects. + const submitPhaseRef = useRef('idle'); + const pollFailuresRef = useRef(0); + const [pollUnavailable, setPollUnavailable] = useState(false); + useEffect(() => { + submitPhaseRef.current = phase; + }, [phase]); const metamaskInstalled = hasEthereumProvider(); @@ -293,6 +310,12 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled const [ethBalances, setEthBalances] = useState>( () => Object.create(null), ); + // Exact base units + decimals per asset, parallel to ethBalances: the + // fraction buttons must truncate in integer land (float math at 18 dp + // can round ABOVE the balance and guarantee a deposit revert). + const [ethBalanceBase, setEthBalanceBase] = useState< + Record + >(() => Object.create(null)); useEffect(() => { let cancelled = false; @@ -339,20 +362,28 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled useEffect(() => { if (!ethAccount) { setEthBalances(Object.create(null)); + setEthBalanceBase(Object.create(null)); return; } let cancelled = false; void Promise.all( assets.map(async (a) => { - if (!a.ethAddress) return [a.ticker, null] as const; - const b = await getTokenBalance(a.ethAddress, ethAccount).catch(() => null); - return [a.ticker, b] as const; + if (!a.ethAddress) return [a.ticker, null, null] as const; + const base = await getTokenBalanceBase(a.ethAddress, ethAccount).catch(() => null); + const formatted = base ? formatUnits(base.raw, base.decimals) : null; + return [a.ticker, formatted, base] as const; }), ).then((entries) => { if (cancelled) return; const next: Record = Object.create(null); - for (const [ticker, balance] of entries) next[ticker] = balance; + const nextBase: Record = + Object.create(null); + for (const [ticker, balance, base] of entries) { + next[ticker] = balance; + nextBase[ticker] = base; + } setEthBalances(next); + setEthBalanceBase(nextBase); }); return () => { cancelled = true; @@ -398,19 +429,31 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled // 25% / 50% / Max of the wallet balance, capped by the per-request max. const applyFraction = useCallback( (fraction: number) => { - const balance = parseFloat(ethBalance ?? ''); - if (!Number.isFinite(balance) || balance <= 0) return; - let target = balance * fraction; + const base = ethBalanceBase[assetTicker]; + if (!base || base.raw <= 0n) return; + // Integer math on base units throughout: floats lose integer precision + // past 2^53 (at 18 decimals that is ~0.009 tokens), so the old + // truncation could land ABOVE the true balance and make the deposit + // revert in transferFrom. 25%/50%/Max map to exact bigint factors. + const pct = BigInt(Math.round(fraction * 100)); + let target = (base.raw * pct) / 100n; const max = asset?.maxAmountPerRequest; if (max !== undefined && /^\d+(\.\d+)?$/.test(max)) { - target = Math.min(target, parseFloat(max)); + try { + const maxBase = parseUnits(max, base.decimals); + if (target > maxBase) target = maxBase; + } catch { + /* malformed cap value - leave the uncapped target */ + } } - // Truncate toward zero at 8 dp - rounding could exceed the real - // balance by dust and guarantee a MetaMask revert on Max. - const scaled = Math.floor(target * 1e8) / 1e8; - setAmount(scaled.toFixed(8).replace(/\.?0+$/, '')); + // Trim formatUnits' cosmetic padding ("100.0" -> "100") but ONLY + // when a decimal point exists: for 0-decimals tokens formatUnits + // emits no fraction at all (1000n -> "1000") and a bare trailing-zero + // strip would corrupt the amount 10^n-fold ("1000" -> "1"). + const s = formatUnits(target, base.decimals); + setAmount(s.includes('.') ? s.replace(/0+$/, '').replace(/\.$/, '') : s); }, - [ethBalance, asset?.maxAmountPerRequest], + [ethBalanceBase, assetTicker, asset?.maxAmountPerRequest], ); /** Persist a freshly broadcast bridge so the card survives refreshes. */ @@ -434,6 +477,14 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled startedAt: new Date().toISOString(), }); setHistoryToken((t) => t + 1); + // Reset the previous bridge's tracking state: a terminal progress card + // and a tripped poll backoff would both early-return the poll and WS + // effects, so the new bridge would render the old bridge's completed + // steps and never get refreshed. + setTrackedProgress(null); + setTrackedRequest(null); + setPollUnavailable(false); + pollFailuresRef.current = 0; setPhase('polling'); } @@ -446,6 +497,7 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled if (!current) return; try { const detail: BridgeRequestDetail = await sdk.getBridgeRequest(current.uuid); + pollFailuresRef.current = 0; const next = deriveProgress(detail); // Fresh re-read doubles as both the takeover guard (a newer bridge's // progress must not be published under the old request) and the save @@ -455,7 +507,22 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled setTrackedRequest(detail); setTrackedProgress(next); if (next.kind !== 'in-progress') { - setPhase(next.kind === 'completed' ? 'done' : next.kind === 'manual' ? 'manual' : 'failed'); + // Never let a stale request's terminal state stomp an active + // submission of a NEW bridge: while the wallet prompt is up the + // phase belongs to the new flow (and `busy` must not drop). + // submitPhaseRef mirrors the `phase` state: this callback's deps + // are empty by design (stable identity for the poll interval), + // so a plain `phase` read would always see the initial value and + // the guard would be dead code. + if (!submittingRef.current && !SUBMIT_PHASES.has(submitPhaseRef.current)) { + setPhase( + next.kind === 'completed' ? 'done' : next.kind === 'manual' ? 'manual' : 'failed', + ); + } + // Flip the collapsed history row's chip too: the section only + // re-reads on a token bump, and the card saying 'Completed' above + // a row still reading 'In progress' reads as a contradiction. + setHistoryToken((t) => t + 1); } const advanced = next.step > latest.lastStep; // First sight of the deposit hash (ML→ETH submits without one) - @@ -470,7 +537,22 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled } updateHistoryStatus(current.uuid, next.rawStatus); } catch { - /* transient - the next poll retries; unknown state keeps polling */ + // A request the server no longer knows (pruned, or the network is + // gone) must not be polled forever: after several consecutive + // failures stop the interval/WS and say so on the card. The history + // section can still retry from scratch. + pollFailuresRef.current += 1; + if (pollFailuresRef.current >= POLL_FAILURE_LIMIT) { + setPollUnavailable(true); + // Release the form: with the phase stuck at 'polling' the submit + // button stayed disabled forever, and when no poll ever succeeded + // the notice lives on the progress card, which never renders + // (trackedProgress stays null). Same guard as the terminal branch: + // never stomp a new submission's phase. + if (!submittingRef.current && !SUBMIT_PHASES.has(submitPhaseRef.current)) { + setPhase('idle'); + } + } } }, []); @@ -483,15 +565,17 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled useEffect(() => { if (!tracked) return; if (trackedProgress && trackedProgress.kind !== 'in-progress') return; + if (pollUnavailable) return; void pollTracked(); const id = setInterval(() => void pollTracked(), PROGRESS_POLL_MS); return () => clearInterval(id); - }, [tracked, trackedProgress?.kind, pollTracked]); + }, [tracked, trackedProgress?.kind, pollUnavailable, pollTracked]); useEffect(() => { const uuid = tracked?.uuid; if (!uuid) return; if (trackedProgress && trackedProgress.kind !== 'in-progress') return; + if (pollUnavailable) return; let socket: WebSocket | null = null; let closed = false; try { @@ -518,13 +602,15 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled closed = true; socket?.close(); }; - }, [tracked?.uuid, trackedProgress?.kind, pollTracked]); + }, [tracked?.uuid, trackedProgress?.kind, pollUnavailable, pollTracked]); function dismissTracked() { clearInFlight(); setTracked(null); setTrackedProgress(null); setTrackedRequest(null); + setPollUnavailable(false); + pollFailuresRef.current = 0; setPhase('idle'); } @@ -595,6 +681,18 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled setError('Invalid Mintlayer address.'); return; } + // The deposit broadcasts on-chain before the bridge backend ever + // sees the receiver, so the payload itself must be valid too (a + // checksum-valid short-payload address would strand the funds). + if ( + !validateMintlayerAddress( + receiver.trim(), + networkType === 'mainnet' ? 'mainnet' : 'testnet', + ).valid + ) { + setError('Invalid Mintlayer address.'); + return; + } } } @@ -648,17 +746,42 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled 18, receiver.trim(), setPhase, + // switchChainIfNeeded already verified this resolves before we + // got here; default to mainnet for the type-level null only. + Number.parseInt(chainForFlavor(flavor)?.id ?? '0x1', 16), ); setPhase('submitting'); - const res = await sdk.broadcastBridgeRequest({ - source_chain: sourceChain, - destination_chain: destinationChain, - asset: asset.ticker, - amount: amount.trim(), - receiver_address: receiver.trim(), - deposit_transactions: [{ transaction_hash: txHash }], - }); - trackRequest(res.bridge_request_uuid, txHash); + try { + const res = await sdk.broadcastBridgeRequest({ + source_chain: sourceChain, + destination_chain: destinationChain, + asset: asset.ticker, + amount: amount.trim(), + receiver_address: receiver.trim(), + deposit_transactions: [{ transaction_hash: txHash }], + }); + trackRequest(res.bridge_request_uuid, txHash); + } catch (broadcastErr) { + // The deposit is already on Ethereum at this point - swallowing + // the failure would orphan real funds. Record a provisional + // history entry so the deposit stays visible, then surface the + // broadcast error with the tx hash for support/contact. + appendHistory({ + // The bridge backend never saw this deposit, so no request with + // this id can ever resolve: prefix the id so the history rows + // render without polling a guaranteed 404 and never offer the + // dead Retry button. + uuid: `orphan-${txHash}`, + direction, + asset: assetTicker, + amount: amount.trim(), + receiver: receiver.trim(), + startedAt: new Date().toISOString(), + status: 'Deposit broadcast; bridge request failed to submit', + }); + setHistoryToken((t) => t + 1); + throw broadcastErr; + } } else { // ── Mintlayer → Ethereum ── if (!ethAccount) throw new Error('Connect MetaMask first (it is the receiver).'); @@ -701,17 +824,40 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled throw new Error((signed.error ?? 'Failed to create the bridge transaction.') + consumedHint); } setPhase('submitting'); - const res = await sdk.broadcastBridgeRequest({ - source_chain: sourceChain, - destination_chain: destinationChain, - asset: asset.ticker, - amount: amount.trim(), - receiver_address: receiver.trim(), - deposit_transactions: [ - { raw_transaction: signed.raw_transaction, intent: signed.intent }, - ], - }); - trackRequest(res.bridge_request_uuid, ''); + try { + const res = await sdk.broadcastBridgeRequest({ + source_chain: sourceChain, + destination_chain: destinationChain, + asset: asset.ticker, + amount: amount.trim(), + receiver_address: receiver.trim(), + deposit_transactions: [ + { raw_transaction: signed.raw_transaction, intent: signed.intent }, + ], + }); + trackRequest(res.bridge_request_uuid, ''); + } catch (broadcastErr) { + // The signed transaction was handed to the bridge backend, which + // broadcasts it itself: a dropped response here can mean the + // deposit ALREADY went through (the e2m analogue records its + // orphan from the on-chain hash; nothing observable is left + // client-side here). Record a provisional row so a retrying user + // sees that attempt one may have landed, then say so in the error. + appendHistory({ + uuid: `unknown-${Date.now()}`, + direction, + asset: assetTicker, + amount: amount.trim(), + receiver: receiver.trim(), + startedAt: new Date().toISOString(), + status: 'Submitted; result unknown - check before retrying', + }); + setHistoryToken((t) => t + 1); + const detail = broadcastErr instanceof Error ? broadcastErr.message : String(broadcastErr); + throw new Error( + `${detail} - after signing, the bridge did not answer: the deposit MAY have gone through. Check the history list below before retrying.`, + ); + } } } catch (err) { // Wallet rejections are user choices, not failures - an EvmError with @@ -721,6 +867,9 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled setInfo(e.message); setPhase('idle'); } else { + // Note: an e2m failure AFTER the deposit broadcast also leaves a + // provisional history entry (see the e2m branch) - the money is + // not lost, it is sitting in the deposit waiting for a retry. setError(e.message); setPhase('idle'); } @@ -855,6 +1004,7 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled setDirection(next); setError(null); setInfo(null); + setReceiverSuggestion(null); } }} > @@ -870,7 +1020,7 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled role="radio" aria-checked={direction === key} tabIndex={direction === key ? 0 : -1} - onClick={() => { setDirection(key); setError(null); setInfo(null); }} + onClick={() => { setDirection(key); setError(null); setInfo(null); setReceiverSuggestion(null); }} className={`rounded-xl border px-4 py-3 text-left transition-colors ${ direction === key ? 'border-mint-600 bg-mint-900/20' @@ -1146,19 +1296,47 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled )} {trackedProgress.mlTxHash && isTxHashLike(trackedProgress.mlTxHash) && ( - Payout on the Mintlayer explorer ↗ + {/* mlTxHash is the payout leg: Ethereum-side when the + destination is ETH, Mintlayer-side when it is ML - + route by hash shape, not the live form toggle. */} + {isEthTxHash(trackedProgress.mlTxHash) + ? 'Payout on Etherscan' + : 'Payout on the Mintlayer explorer'}{' '} + ↗ )} + {tracked.depositTxHash && + !isEthTxHash(tracked.depositTxHash) && + isTxHashLike(tracked.depositTxHash) && ( + + Deposit on the Mintlayer explorer ↗ + + )}

)}

request {tracked.uuid}

+ {pollUnavailable && ( +

+ Live status unavailable - the bridge service did not answer recent checks. The + bridge request itself keeps running; retry from the history list below. +

+ )} {trackedProgress.kind !== 'in-progress' ? (
+
+ )} + {(phase === 'approve' || phase === 'deposit' || phase === 'signing' || phase === 'submitting') && phaseLabel && (
{ + setBroken(false); + }, [src]); if (!src || broken) { return ( diff --git a/app/src/components/DelegationPanel.tsx b/app/src/components/DelegationPanel.tsx index bc86463..a6096eb 100644 --- a/app/src/components/DelegationPanel.tsx +++ b/app/src/components/DelegationPanel.tsx @@ -6,6 +6,7 @@ import { submitWithToast } from "@/lib/toastStore"; import { CopyButton } from "@/components/CopyButton"; import { rpc } from '@/lib/client-rpc'; import { stakeTrade, type StakeTradeFailure } from '@/lib/stake-trade-client'; +import { explorerBase } from '@/lib/explorer-base'; import { TotpField } from '@/components/ui/TotpField'; interface Delegation { @@ -66,18 +67,25 @@ function DelegationRow({ setMsg(""); try { await submitWithToast(fn, watchTx); - setState("success"); - setMsg(""); - // Refresh delegation balance - const list = await rpc("delegation_list_ids", { account: 0 }); - const updated = list.find(d => d.delegation_id === delegation.delegation_id) ?? null; - onUpdated(updated); - setAddAmount(""); - setWithdrawAmount(""); } catch (err) { setMsg((err as Error).message); setState("error"); + return; + } + // The on-chain action is done - a failed post-submit list refresh must + // not flip success to "error" (that invited a resubmit: a second burned + // code and a double stake). + setState("success"); + setMsg(""); + try { + const list = await rpc("delegation_list_ids", { account: 0 }); + const updated = list.find(d => d.delegation_id === delegation.delegation_id) ?? null; + onUpdated(updated); + } catch { + // Stale balance display is cosmetic; the toast tracks the tx itself. } + setAddAmount(""); + setWithdrawAmount(""); }; const handleAdd = () => @@ -140,14 +148,19 @@ function DelegationRow({
- - {delegation.delegation_id} - + {/* regtest/signet have no public explorer - degrade to text. */} + {explorerBase() ? ( + + {delegation.delegation_id} + + ) : ( + {delegation.delegation_id} + )}

@@ -263,13 +276,18 @@ export default function DelegationPanel({ poolId, initialDelegations, network }: setNewState("success"); setNewMsg("Delegation created. It appears below once confirmed; use a fresh 2FA code to add funds to it."); setNewTotp(""); - - // Refresh list - the new delegation row appears with its own Add input. - const list = await rpc("delegation_list_ids", { account: 0 }); - setDelegations(list.filter(d => d.pool_id === poolId)); } catch (err) { setNewMsg((err as Error).message); setNewState("error"); + return; + } + // Success must survive a failed post-submit refresh - the create itself + // went through, and showing "error" invited duplicate creates. + try { + const list = await rpc("delegation_list_ids", { account: 0 }); + setDelegations(list.filter(d => d.pool_id === poolId)); + } catch { + // Row appears on the next page load. } }; diff --git a/app/src/components/IssueNFTModal.tsx b/app/src/components/IssueNFTModal.tsx index 1a27558..9a10b6d 100644 --- a/app/src/components/IssueNFTModal.tsx +++ b/app/src/components/IssueNFTModal.tsx @@ -92,8 +92,10 @@ export default function IssueNFTModal({ ipfsEnabled, onClose, onIssued }: Props) if (ipfsEnabled && !url) { throw new Error('IPFS upload succeeded but returned no URL - cannot proceed without media URI'); } - // Chain max is 32 bytes; SHA-256 hex is 64 chars → truncate to 32 - setMediaHash(hash.slice(0, 32)); + // SHA-256 hex is 64 chars = the full 32-byte digest, and the API cap + // is 64 chars. Slicing the HEX to 32 kept only half the digest - no + // off-chain verifier comparing sha256(media) could ever match it. + setMediaHash(hash); if (url) setMediaUri(url); } catch (err) { setError(`Media upload failed: ${(err as Error).message}`); @@ -251,13 +253,14 @@ export default function IssueNFTModal({ ipfsEnabled, onClose, onIssued }: Props) setTicker(e.target.value.toUpperCase())} + onChange={e => setTicker(e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, ''))} maxLength={5} + pattern="[A-Z0-9]{1,5}" placeholder="MYNFT" required className={inp} /> -

Short identifier, up to 5 characters

+

Short identifier, up to 5 letters/digits

{/* Media file - always shown, but label differs by mode */} diff --git a/app/src/components/IssueTokenModal.tsx b/app/src/components/IssueTokenModal.tsx index e57b8d0..ccb4cb6 100644 --- a/app/src/components/IssueTokenModal.tsx +++ b/app/src/components/IssueTokenModal.tsx @@ -7,6 +7,7 @@ import { tokenManage } from '@/lib/token-manage-client'; import { toHexField } from '@/lib/token-utils'; import { TotpField } from '@/components/ui/TotpField'; import { ModalOverlay } from '@/components/ui/ModalOverlay'; +import { isValidAmount } from '@/lib/validation'; type SupplyType = 'Fixed' | 'Lockable' | 'Unlimited'; type Mode = 'easy' | 'expert'; @@ -105,6 +106,14 @@ export default function IssueTokenModal({ ipfsEnabled, onClose, onIssued }: Prop let newTokenId = ''; const newTxId = await submitWithToast(async () => { + // A fixed supply is denominated in the token's own decimals: 0.555 + // with Decimals = 2 is rejected by the daemon pre-sign - knowable + // here, so fail before the TOTP code is consumed. + if (supplyType === 'Fixed' && !isValidAmount(fixedAmount, decimals)) { + throw new Error( + `Fixed supply "${fixedAmount}" has more decimal places than the token's ${decimals} decimal places`, + ); + } const r = await tokenManage('token_issue_new', { account: 0, destination_address: destAddress, diff --git a/app/src/components/IssuedTokensPanel.tsx b/app/src/components/IssuedTokensPanel.tsx index beda8ac..7b7fa22 100644 --- a/app/src/components/IssuedTokensPanel.tsx +++ b/app/src/components/IssuedTokensPanel.tsx @@ -4,6 +4,8 @@ import { CopyButton } from '@/components/CopyButton'; import TokenManagePanel from '@/components/TokenManagePanel'; import { TokenIdTooltip } from '@/components/TokenIdTooltip'; import { rpc } from '@/lib/client-rpc'; +import { getTokensInfoByIds } from '@/lib/token-info-client'; +import { explorerBase as explorerBaseFn } from '@/lib/explorer-base'; // ── Types ────────────────────────────────────────────────────────────────────── @@ -43,7 +45,24 @@ const LS_KEY = 'ml_issued_tokens'; function loadStored(): StoredToken[] { try { - return JSON.parse(localStorage.getItem(LS_KEY) ?? '[]') as StoredToken[]; + // Array.isArray guards against legacy shapes: JSON.parse('null') and + // JSON.parse('5') do not throw but are not token lists either. The + // element filter keeps junk entries from crashing the render below + // (each card dereferences tokenId) - drop, don't trust. + const parsed: unknown = JSON.parse(localStorage.getItem(LS_KEY) ?? '[]'); + if (!Array.isArray(parsed)) return []; + // Token ids are bech32 token addresses from the wallet daemon (mmltk1…, + // the RPC post-process dehexifies them), not 64-hex - the old hex-only + // guard dropped every legitimate entry on load. Accept the bech32 shape + // too; the charset/length cap is junk protection, not validation (the + // augment rescan re-resolves real ids against the chain). + return parsed.filter( + (t): t is StoredToken => + typeof t === 'object' && t !== null && + typeof (t as StoredToken).tokenId === 'string' && + (/^[0-9a-f]{64}$/i.test((t as StoredToken).tokenId) || + /^[a-z0-9]{20,120}$/i.test((t as StoredToken).tokenId)), + ); } catch { return []; } @@ -77,25 +96,36 @@ function supplyBadge(info: FungibleContent) { export default function IssuedTokensPanel({ network }: Props) { const [stored, setStored] = useState([]); + const [scanError, setScanError] = useState(null); const [liveInfos, setLiveInfos] = useState>(new Map()); const [loading, setLoading] = useState(true); const [manageTokenId, setManageTokenId] = useState(null); const [failedTokenIds, setFailedTokenIds] = useState>(new Set()); - const explorerBase = network === 'testnet' - ? 'https://lovelace.explorer.mintlayer.org' - : 'https://explorer.mintlayer.org'; + const explorerBase = explorerBaseFn(); async function fetchLiveInfos(ids: string[]): Promise> { if (ids.length === 0) return new Map(); - const results = await rpc('node_get_tokens_info', { token_ids: ids }); + // getTokensInfoByIds chunks the RPC and aligns answers by their own + // content.token_id - node_get_tokens_info does NOT preserve input + // order, so zipping by index attributed metadata to the wrong tokens. + const infoMap = await getTokensInfoByIds(ids); const map = new Map(); - ids.forEach((id, i) => map.set(id, results[i] ?? null)); + infoMap.forEach((info, id) => { + map.set(id, info !== null && info.type === 'FungibleToken' ? info : null); + }); return map; } async function checkFailedTxs(tokens: StoredToken[], map: Map) { - const pendingWithTx = tokens.filter(t => map.get(t.tokenId) === null && t.txId); + // Grace window: a tx that confirmed between the info fetch and the + // pending-list check is absent from both (confirmation removes it from + // pending before the token index catches up), which used to flash a + // false "tx failed" badge. Fresh issuances are never marked failed. + const FAILURE_GRACE_MS = 10 * 60 * 1000; + const pendingWithTx = tokens.filter( + t => map.get(t.tokenId) === null && t.txId && Date.now() - t.issuedAt > FAILURE_GRACE_MS, + ); if (pendingWithTx.length === 0) return; try { const pendingTxIds = await rpc('transaction_list_pending', { account: 0 }); @@ -116,6 +146,17 @@ export default function IssuedTokensPanel({ network }: Props) { try { const map = await fetchLiveInfos(tokens.map(t => t.tokenId)); setLiveInfos(map); + // A token that now resolves live was a false "tx failed" marking + // (node/index lag): clear the badge instead of showing a red failure + // on a row with live supply and a Manage button forever. + setFailedTokenIds(prev => { + const next = new Set(prev); + let changed = false; + for (const [id, info] of map) { + if (info !== null && next.delete(id)) changed = true; + } + return changed ? next : prev; + }); // NOTE: deliberately no auto-sweep of "unknown" tokens here. A null // lookup means the node hasn't indexed the issuance yet (or is lagging), // not that the token is gone - deleting the row destroyed the user's @@ -172,9 +213,15 @@ export default function IssuedTokensPanel({ network }: Props) { return { tokenId: id, ticker, decimals, issuedAt: Date.now() }; }); - const merged = [...current, ...newEntries]; - saveStored(merged); - setStored(merged); + // Merge functionally off the latest state (mirrors augmentFromWallet): + // a wallet scan that resolved while the indexer fetch was in flight + // must not be dropped by a stale-snapshot overwrite. + setStored(prev => { + const prevIds = new Set(prev.map(t => t.tokenId)); + const merged = [...prev, ...newEntries.filter(e => !prevIds.has(e.tokenId))]; + saveStored(merged); + return merged; + }); setLiveInfos(prev => { const next = new Map(prev); infoMap.forEach((v, k) => next.set(k, v)); @@ -194,9 +241,17 @@ export default function IssuedTokensPanel({ network }: Props) { const res = await fetch('/api/scan-issued-tokens'); const data = await res.json() as { ok: boolean; + error?: string; fungible?: Array<{ tokenId: string; ticker: string; decimals: number }>; }; - if (!data.ok || !data.fungible || data.fungible.length === 0) return; + if (!data.ok) { + // The scan failing is not the same as having no tokens - without + // this state a broken wallet renders as an empty ("clean") list. + setScanError(data.error ?? 'The wallet scan failed.'); + return; + } + setScanError(null); + if (!data.fungible || data.fungible.length === 0) return; // Use current to filter what's already known at call time const knownIds = new Set(current.map(t => t.tokenId)); @@ -266,6 +321,17 @@ export default function IssuedTokensPanel({ network }: Props) { } if (stored.length === 0) { + if (scanError) { + return ( +
+

Could not scan the wallet for your tokens: {scanError}

+ +
+ ); + } return (

No authoritable tokens found. Use Mint Token above to create one. @@ -327,10 +393,14 @@ export default function IssuedTokensPanel({ network }: Props) { - - {token.tokenId.slice(0, 16)}… - + {explorerBase ? ( + + {token.tokenId.slice(0, 16)}… + + ) : ( + {token.tokenId.slice(0, 16)}… + )} diff --git a/app/src/components/NFTMarketplace.tsx b/app/src/components/NFTMarketplace.tsx index cfd565c..27aaed3 100644 --- a/app/src/components/NFTMarketplace.tsx +++ b/app/src/components/NFTMarketplace.tsx @@ -8,6 +8,7 @@ import { safeImageUri } from "@/lib/safe-uri"; import type { TokenCurrency, OrderInfo } from "@/lib/wallet-rpc"; import { rpc } from '@/lib/client-rpc'; import { stakeTrade } from '@/lib/stake-trade-client'; +import { mulDecimal } from '@/lib/decimal'; import { TotpField } from '@/components/ui/TotpField'; // ── Types ───────────────────────────────────────────────────────────────────── @@ -27,6 +28,14 @@ interface ActiveOrderRaw { ask_balance: { atoms: string; decimal: string }; give_balance: { atoms: string; decimal: string }; is_own: boolean; + is_marked_as_concluded_in_wallet: boolean; + is_marked_as_frozen_in_wallet: boolean; + existing_order_data: { + ask_balance: { atoms: string; decimal: string }; + give_balance: { atoms: string; decimal: string }; + creation_timestamp: { timestamp: number }; + is_frozen: boolean; + } | null; } interface NFTListing { @@ -37,6 +46,7 @@ interface NFTListing { iconUri: string | null; // already resolved to HTTP URL priceML: string; // decimal string isOwn: boolean; + frozen: boolean; // frozen orders cannot be cancelled daemon-side } // ── Helpers ─────────────────────────────────────────────────────────────────── @@ -93,7 +103,10 @@ function SellNFTModal({ const resolvedIcon = resolveUri(nft.iconUri); const [iconErrored, setIconErrored] = useState(false); - const canSubmit = !loading && !!listPrice && parseFloat(listPrice) > 0 && totp.length === 6; + // Exact-decimal validity, not parseFloat: a scientific-notation input + // ('1e5') would sail past this check and hit the daemon raw. + const listPriceValid = mulDecimal(listPrice, '1') !== null && Number(listPrice) > 0; + const canSubmit = !loading && listPriceValid && totp.length === 6; async function handleList(e: React.FormEvent) { e.preventDefault(); @@ -382,8 +395,13 @@ function NFTCard({

{listing.nftId.slice(0, 16)}…

{listing.priceML} ML
+ {listing.frozen && ( + + Frozen - cancel unavailable + + )} {showBuy && } - {showCancel && } + {showCancel && !listing.frozen && }
); } @@ -410,6 +428,7 @@ export default function NFTMarketplace({ // My listings state const [myListings, setMyListings] = useState([]); const [myListingsLoading, setMyListingsLoading] = useState(false); + const [myListingsError, setMyListingsError] = useState(null); // Shared 2FA code for buying (browse tab) and cancelling (sell tab) - both // move funds and burn a code server-side via /api/stake-trade. @@ -466,8 +485,13 @@ export default function NFTMarketplace({ ), ]; - // Resolve metadata one-at-a-time to avoid ordering issues + // Resolve metadata one-at-a-time to avoid ordering issues. Ids that + // positively resolve as FUNGIBLE are dropped below: the atoms==1 + // heuristic alone also catches whole units of 0-decimal tokens, and + // rendering those as NFT cards misrepresents the order. Only ids with + // NO info at all keep the unknown-collection fallback. const metaMap = new Map(); + const fungibleIds = new Set(); await Promise.all( uniqueIds.map(async id => { try { @@ -475,6 +499,10 @@ export default function NFTMarketplace({ "node_get_tokens_info", { token_ids: [id] }, ); + if (info?.type === "FungibleToken") { + fungibleIds.add(id); + return; + } if (info?.type === "NonFungibleToken") { const meta = info.content.metadata!; metaMap.set(id, { @@ -492,11 +520,14 @@ export default function NFTMarketplace({ const enriched: NFTListing[] = nftCandidates .filter(o => { const id = (o.initially_given as { type: "Token"; content: { id: string } }).content.id; - return metaMap.has(id); + return !fungibleIds.has(id); }) .map(o => { const id = (o.initially_given as { type: "Token"; content: { id: string } }).content.id; - const meta = metaMap.get(id)!; + // Listings with unresolvable metadata stay visible to buyers + // (same fallback as the own-listings side) - filtering them out + // hid live offers behind an RPC glitch. + const meta = metaMap.get(id) ?? { name: "unknown collection", ticker: "", iconUri: null }; return { orderId: o.order_id, nftId: id, @@ -505,6 +536,7 @@ export default function NFTMarketplace({ iconUri: meta.iconUri, priceML: o.ask_balance.decimal, isOwn: o.is_own, + frozen: !!(o.existing_order_data?.is_frozen || o.is_marked_as_frozen_in_wallet), }; }); @@ -560,13 +592,11 @@ export default function NFTMarketplace({ ); const enriched: NFTListing[] = nftSells - .filter(o => { - const id = (o.initially_given as { type: "Token"; content: { id: string } }).content.id; - return metaMap.has(id); - }) .map(o => { const id = (o.initially_given as { type: "Token"; content: { id: string } }).content.id; - const meta = metaMap.get(id)!; + // Own listings must survive unresolvable metadata (RPC glitch, unknown + // collection) - dropping them hides the only Cancel affordance. + const meta = metaMap.get(id) ?? { name: id.slice(0, 8) + "…", ticker: "", iconUri: null }; const data = o.existing_order_data!; return { orderId: o.order_id, @@ -576,12 +606,15 @@ export default function NFTMarketplace({ iconUri: meta.iconUri, priceML: data.ask_balance.decimal, isOwn: true, + frozen: !!(data.is_frozen || o.is_marked_as_frozen_in_wallet), }; }); setMyListings(enriched); - } catch { - // non-critical, silently ignore + } catch (err) { + // The cancel affordance lives here - a silent empty list would hide + // the user's own open orders behind an unrelated RPC hiccup. + setMyListingsError(friendlyError(err)); } finally { setMyListingsLoading(false); } @@ -730,7 +763,13 @@ export default function NFTMarketplace({
Loading…
)} - {!myListingsLoading && myListings.length === 0 && ( + {myListingsError && ( +
+ Could not load your listings: {myListingsError} +
+ )} + + {!myListingsLoading && !myListingsError && myListings.length === 0 && (
No active NFT listings.
diff --git a/app/src/components/OrderBook.tsx b/app/src/components/OrderBook.tsx index 2905a9f..2612d76 100644 --- a/app/src/components/OrderBook.tsx +++ b/app/src/components/OrderBook.tsx @@ -10,6 +10,8 @@ import { getTokensInfoByIds } from '@/lib/token-info-client'; import { stakeTrade } from '@/lib/stake-trade-client'; import { TotpField } from '@/components/ui/TotpField'; import { aggregateLevels, fmtQty } from '@/components/orderBookDepth'; +import { mulDecimal, divDecimal } from '@/lib/decimal'; +import { isValidAmount } from '@/lib/validation'; // Raw shape returned by order_list_all_active (flat, no existing_order_data wrapper) interface ActiveOrderRaw { @@ -75,6 +77,7 @@ function friendlyError(err: unknown): string { const gotMatch = raw.match(/got:\s*Amount\s*\{\s*atoms:\s*(\d+)\s*\}/i); const gotAtoms = gotMatch ? BigInt(gotMatch[1]) : null; const gotML = gotAtoms !== null + // ML carries 11 decimals (1 ML = 10^11 atoms, consensus conventions). ? (Number(gotAtoms) / 1e11).toLocaleString(undefined, { maximumFractionDigits: 8 }) + ' ML' : null; return gotML @@ -124,13 +127,10 @@ function formatTimestamp(ts: number): string { /** Price in ML per token unit */ function calcPrice(mlDecimal: string, tokenDecimal: string): string { - const ml = parseFloat(mlDecimal); - const tok = parseFloat(tokenDecimal); - if (!tok || !ml) return "-"; - // Plain decimal formatting: toPrecision(6) switches to exponent notation - // for large prices ("1.50000e+6") and the trailing-zero strip turns - // 100000 into "1" - both mangled what the user can click "Fill" on. - return (ml / tok).toLocaleString("en-US", { maximumFractionDigits: 8 }); + // Exact BigInt division (no float rounding, no exponent notation, and no + // thousands separators: a comma-grouped string pasted into the number + // input below would parseFloat-truncate at the comma - "1,234.5" -> 1). + return divDecimal(mlDecimal, tokenDecimal, 8) ?? "-"; } // ── Buy / Sell panel ────────────────────────────────────────────────────────── @@ -142,6 +142,7 @@ function BuySellPanel({ pairBids, mlBalance, tokenBalance, + pairDecimals, onCreated, onPairRefresh, prefill, @@ -152,6 +153,8 @@ function BuySellPanel({ pairBids: OrderInfo[]; mlBalance: string | null; tokenBalance: string | null; + /** Pair token's number_of_decimals (SSR-resolved) for pre-burn validation. */ + pairDecimals: number; onCreated: () => void; onPairRefresh: () => void; /** Order-book rows never execute here - a click prefills this form. */ @@ -193,24 +196,39 @@ function BuySellPanel({ ? calcPrice(bestBid.existing_order_data.give_balance.decimal, bestBid.existing_order_data.ask_balance.decimal) : null; - const totalML = amount && price - ? (parseFloat(amount) * parseFloat(price)).toPrecision(8).replace(/\.?0+$/, "") - : ""; + // Exact decimal product: what this shows is what the order submits, so a + // user buying 1,000,000 tokens at price 10 sees 10000000 - not the "1" + // the old float-toPrecision+strip produced. + const totalML = amount && price ? mulDecimal(amount, price) : null; const estTokens = mlAmount && bestAskPrice && bestAskPrice !== "-" - ? (parseFloat(mlAmount) / parseFloat(bestAskPrice)).toPrecision(6).replace(/\.?0+$/, "") + ? divDecimal(mlAmount, bestAskPrice, 6) : null; const estML = amount && bestBidPrice && bestBidPrice !== "-" - ? (parseFloat(amount) * parseFloat(bestBidPrice)).toPrecision(6).replace(/\.?0+$/, "") + ? mulDecimal(amount, bestBidPrice) : null; + // Same exact-decimal rule the submit path enforces: a lenient + // parseFloat() here lets '1e5' reach the button and burn a TOTP code on + // a request the daemon is guaranteed to reject. const canSubmit = !loading && !!effectiveTokenId && totp.length === 6 && ( type === "limit" - ? (!!amount && !!price && parseFloat(amount) > 0 && parseFloat(price) > 0) + ? (mulDecimal(amount, "1") !== null && Number(amount) > 0 && + mulDecimal(price, "1") !== null && Number(price) > 0 && + // Token legs (give on sell, ask on buy) honor the pair token's + // own precision - 18dp-generic gates let knowable rejections + // through to burn the code. + isValidAmount(amount, pairDecimals) && + // The limit order's Coin leg is the ML total: the coin's own + // precision cap (11 dp) applies to the PRODUCT, not just the + // inputs - a 26-dp total would 400 after the code check. + isValidAmount(mulDecimal(amount, price) ?? "", 11)) : side === "buy" - ? (!!mlAmount && parseFloat(mlAmount) > 0 && !!bestAsk) - : (!!amount && parseFloat(amount) > 0 && !!bestBid) + ? (mulDecimal(mlAmount, "1") !== null && Number(mlAmount) > 0 && + isValidAmount(mlAmount, 11) && !!bestAsk) + : (mulDecimal(amount, "1") !== null && Number(amount) > 0 && + isValidAmount(amount, pairDecimals) && !!bestBid) ); const failTotp = () => { @@ -227,7 +245,22 @@ function BuySellPanel({ try { await submitWithToast(async () => { if (type === "limit") { - const total = (parseFloat(amount) * parseFloat(price)).toString(); + // Exact product, no float artifacts: 0.1 * 0.3 is "0.03", not the + // "0.30000000000000004" the daemon rejects after a wasted TOTP code. + const total = mulDecimal(amount, price); + if (total === null) throw new Error("Invalid amount or price"); + // Token legs honor the pair token's precision: a 3-dp amount on a + // 2-decimal token is a guaranteed daemon rejection after the + // code check (the API gate is 18dp-generic). + if (!isValidAmount(amount, pairDecimals)) { + throw new Error(`Amount supports up to ${pairDecimals} decimal places for ${ticker}`); + } + // Re-checked at submit: fields can change between the last + // render and this handler, and a >11-dp ML total is a + // guaranteed daemon rejection after the code check. + if (!isValidAmount(total, 11)) { + throw new Error("The ML total supports up to 11 decimal places - adjust the amount or price"); + } // conclude_address is required - fetch a fresh receive address const addrRes = await rpc<{ address: string }>("address_new", { account: 0 }); const r = await stakeTrade({ @@ -256,6 +289,27 @@ function BuySellPanel({ // buy market → fill ask → provide ML (what the ask order asks for) // sell market → fill bid → provide Token (what the bid order asks for) const fillAmt = side === "buy" ? mlAmount : amount; + // Guard BEFORE the TOTP burn: a malformed amount ('1e5') must + // fail client-side, not server-side after the code is spent. + if (mulDecimal(fillAmt, "1") === null || !(Number(fillAmt) > 0)) { + throw new Error("Enter a plain decimal amount (e.g. 12.5)"); + } + // Market sells exchange tokens - honor the pair token's decimals. + if (side === "sell" && !isValidAmount(fillAmt, pairDecimals)) { + throw new Error(`Amount supports up to ${pairDecimals} decimal places for ${ticker}`); + } + // Cap at the target order's remaining ask (both sides): the ask + // order's ask_balance is what it still wants (ML for a buy, tokens + // for a sell). Overfilling is a guaranteed chainstate rejection + // (OrderOverbid) after the code is spent. + const remaining = targetOrder.existing_order_data?.ask_balance.decimal; + if ( + remaining !== undefined && + mulDecimal(remaining, "1") !== null && + Number(fillAmt) > Number(remaining) + ) { + throw new Error(`Order only has ${remaining} ${side === "buy" ? "ML" : ticker} remaining - reduce the amount`); + } const r = await stakeTrade({ action: "order_fill", params: { @@ -443,20 +497,25 @@ function MyOrderRow({ order, onAction, tickerMap, totp, onTotpChange, onTotpCons const [error, setError] = useState(null); const needsTotp = totp.length !== 6; - // Freeze is a wallet-local flag (no transaction, no funds move) - stays on - // the plain RPC allowlist. + // Freeze is an on-chain transaction (fee-burning, funds-affecting), so it + // goes through the TOTP-gated /api/stake-trade like every other tx + // action - the plain-RPC allowlist is for read-only calls only. const freeze = async () => { setLoading(true); setError(null); try { await submitWithToast( async () => { - const res = await rpc<{ tx_id?: string }>("order_freeze", { - account: 0, - order_id: order.order_id, - options: {}, - }); - return res.tx_id ?? "frozen"; + const r = await stakeTrade( + { action: "order_freeze", params: { account: 0, order_id: order.order_id } }, + totp, + ); + if (!r.ok) { + if (r.code_consumed) onTotpConsumed(); + throw new Error(r.error); + } + onTotpConsumed(); // burned - clear the field + return r.results[0]?.tx_id as string ?? "frozen"; }, watchTx, ); @@ -513,7 +572,8 @@ function MyOrderRow({ order, onAction, tickerMap, totp, onTotpChange, onTotpCons
{!isConcluded && !isFrozen && ( -
{/* Dismiss */} diff --git a/app/src/components/TokenManagePanel.tsx b/app/src/components/TokenManagePanel.tsx index c92d7dc..648c525 100644 --- a/app/src/components/TokenManagePanel.tsx +++ b/app/src/components/TokenManagePanel.tsx @@ -6,6 +6,7 @@ import { TokenIdTooltip } from '@/components/TokenIdTooltip'; import SafeExternalLink from '@/components/SafeExternalLink'; import { rpc } from '@/lib/client-rpc'; import { tokenManage, type TokenManageFailure } from '@/lib/token-manage-client'; +import { isValidAmount } from '@/lib/validation'; import { toHexField } from '@/lib/token-utils'; import { TotpField } from '@/components/ui/TotpField'; import { ModalOverlay } from '@/components/ui/ModalOverlay'; @@ -114,7 +115,7 @@ function useTotpAction() { // ── Mint section ─────────────────────────────────────────────────────────────── -function MintSection({ tokenId, onRefresh }: { tokenId: string; onRefresh: () => void }) { +function MintSection({ tokenId, decimals, onRefresh }: { tokenId: string; decimals: number; onRefresh: () => void }) { const [amount, setAmount] = useState(''); const [address, setAddress] = useState(''); const { state, msg, run } = useAction(); @@ -157,6 +158,12 @@ function MintSection({ tokenId, onRefresh }: { tokenId: string; onRefresh: () =>
)} - {canMint && } - {canUnmint && } + {canMint && } + {canUnmint && } {canLock && } {isUnfreezable && } diff --git a/app/src/components/TokenSearch.tsx b/app/src/components/TokenSearch.tsx index c7bef34..9d9bbca 100644 --- a/app/src/components/TokenSearch.tsx +++ b/app/src/components/TokenSearch.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import type { TokenInfo } from '@/lib/wallet-rpc'; import { hexToText } from '@/lib/token-utils'; import { safeImageUri } from '@/lib/safe-uri'; @@ -158,6 +158,11 @@ export default function TokenSearch({ network }: Props) { const [searched, setSearched] = useState(false); const [indexerAvailable, setIndexerAvailable] = useState(true); const [favourites, setFavourites] = useState([]); + // Ref mirror of `favourites` for toggle arithmetic: rapid toggles must + // build on the last computed list, not on a render-time snapshot. + const favouritesRef = useRef([]); + // Monotonic sequence for search responses (stale-response guard). + const searchSeqRef = useRef(0); const [favInfos, setFavInfos] = useState>(new Map()); const [favLoading, setFavLoading] = useState(false); @@ -185,6 +190,7 @@ export default function TokenSearch({ network }: Props) { .then(r => r.json()) .then((data: { ok: boolean; value?: FavouriteEntry[] }) => { const stored = data.ok ? (data.value ?? []) : []; + favouritesRef.current = stored; setFavourites(stored); if (stored.length > 0) { fetchFavInfos(stored.map(f => f.tokenId)); @@ -193,6 +199,18 @@ export default function TokenSearch({ network }: Props) { .catch(() => {}); }, []); + /** Latest favourites straight from the server (avoids lost updates). */ + async function fetchCurrentFavourites(): Promise { + try { + const res = await fetch('/api/prefs'); + const data = await res.json() as { ok: boolean; value?: FavouriteEntry[] }; + if (data.ok && Array.isArray(data.value)) return data.value; + } catch { + // Fall back to the render snapshot below. + } + return favourites; + } + async function fetchFavInfos(ids: string[]) { if (ids.length === 0) return; setFavLoading(true); @@ -207,19 +225,26 @@ export default function TokenSearch({ network }: Props) { } async function toggleFavourite(tokenId: string, ticker: string) { - const alreadyPinned = favourites.some(f => f.tokenId === tokenId); + // Build on a ref mirror, not the render's snapshot: two rapid toggles + // (e.g. double-click on different rows) previously read the same + // stale array and the second POST silently dropped the first change. + const current = favouritesRef.current; + const alreadyPinned = current.some(f => f.tokenId === tokenId); let next: FavouriteEntry[]; if (alreadyPinned) { - next = favourites.filter(f => f.tokenId !== tokenId); + next = current.filter(f => f.tokenId !== tokenId); } else { - if (favourites.length >= FAVOURITES_CAP) { + if (current.length >= FAVOURITES_CAP) { setSaveError(`Your list is at its cap (${FAVOURITES_CAP}) - unpin something first.`); return; } - next = [...favourites, { tokenId, ticker: ticker === '???' ? `${tokenId.slice(0, 8)}…` : ticker }]; + next = [...current, { tokenId, ticker: ticker === '???' ? `${tokenId.slice(0, 8)}…` : ticker }]; } - // Persist first, then commit - the UI never claims a state the store - // doesn't hold, and a later import can't overwrite a failed toggle. + // Optimistic commit: a later toggle must build on this result even if + // the POST is still in flight. + favouritesRef.current = next; + setFavourites(next); + // Persist - the UI never claims a state the store doesn't hold. try { const res = await fetch('/api/prefs', { method: 'POST', @@ -229,11 +254,14 @@ export default function TokenSearch({ network }: Props) { const data = await res.json() as { ok: boolean; error?: string }; if (!data.ok) throw new Error(data.error ?? 'Saving failed'); } catch (err) { + // Roll the mirror back so the next toggle doesn't build on a list + // the store rejected. + favouritesRef.current = current; + setFavourites(current); setSaveError(`Could not save your list: ${(err as Error).message}`); return; } setSaveError(null); - setFavourites(next); if (!alreadyPinned) { // Fetch fresh info for newly pinned token if not already cached setFavInfos(current => { @@ -255,6 +283,9 @@ export default function TokenSearch({ network }: Props) { const q = query.trim(); if (!q) return; + // Sequence guard: a slow earlier search must never overwrite a newer + // one's results (stale-response race). + const seq = ++searchSeqRef.current; setLoading(true); setError(null); setResults([]); @@ -273,6 +304,7 @@ export default function TokenSearch({ network }: Props) { } const res = await fetch(`/api/token-search?ticker=${encodeURIComponent(q)}`); const data = await res.json() as { ok: boolean; result?: string[]; error?: string }; + if (seq !== searchSeqRef.current) return; if (!data.ok) throw new Error(data.error ?? 'Search failed'); tokenIds = data.result ?? []; } @@ -289,11 +321,12 @@ export default function TokenSearch({ network }: Props) { // Batched calls, aligned by each result's own token_id. const infoMap = await getTokensInfoByIds(tokenIds); + if (seq !== searchSeqRef.current) return; setResults(tokenIds.map(id => ({ tokenId: id, info: infoMap.get(id) ?? null }))); } catch (err) { - setError((err as Error).message); + if (seq === searchSeqRef.current) setError((err as Error).message); } finally { - setLoading(false); + if (seq === searchSeqRef.current) setLoading(false); } } @@ -324,16 +357,22 @@ export default function TokenSearch({ network }: Props) { setVtImporting(true); setVtNote(null); try { - const existing = new Set(favourites.map(f => f.tokenId)); + // Re-read the server state before merging: a toggleFavourite POST that + // landed while the verified-token dialog was open would otherwise be + // clobbered by this full-array write (lost-update race). + const base = await fetchCurrentFavourites(); + const existing = new Set(base.map(f => f.tokenId)); const additions = picked.filter(r => !existing.has(r.tokenId)); - const room = Math.max(0, FAVOURITES_CAP - favourites.length); + const room = Math.max(0, FAVOURITES_CAP - base.length); const accepted = additions.slice(0, room); if (accepted.length === 0) { - setVtNote('Nothing to import - these tokens are already in your list.'); + setVtNote(room === 0 + ? 'The favourites cap was reached - remove a token from your list first.' + : 'Nothing to import - these tokens are already in your list.'); return; } const next: FavouriteEntry[] = [ - ...favourites, + ...base, ...accepted.map(r => ({ tokenId: r.tokenId, ticker: r.ticker })), ]; const res = await fetch('/api/prefs', { @@ -343,6 +382,7 @@ export default function TokenSearch({ network }: Props) { }); const data = await res.json() as { ok: boolean; error?: string }; if (!data.ok) throw new Error(data.error ?? 'Saving failed'); + favouritesRef.current = next; setFavourites(next); fetchFavInfos(next.map(f => f.tokenId)); setVtNote(additions.length > accepted.length diff --git a/app/src/layouts/Layout.astro b/app/src/layouts/Layout.astro index b6e7f6d..05fe0aa 100644 --- a/app/src/layouts/Layout.astro +++ b/app/src/layouts/Layout.astro @@ -15,6 +15,16 @@ export interface Props { const { title = 'Home', activeNav } = Astro.props; const network = (process.env.NETWORK ?? 'mainnet').toLowerCase(); +// Single source for explorer links (read by lib/explorer-base.ts): the +// ML_EXPLORER_URL override wins, else the network's public explorer - '' +// when none exists (regtest/signet), so callers degrade to plain text. +const explorerBase = (process.env.ML_EXPLORER_URL ?? ( + network === 'testnet' + ? 'https://lovelace.explorer.mintlayer.org' + : network === 'mainnet' + ? 'https://explorer.mintlayer.org' + : '' +)).replace(/\/+$/, ''); const indexerEnabled = process.env.INDEXER_ENABLED === 'true'; const bitcoinEnabled = isBitcoinEnabled() && getBitcoinShowUi(); // The bridge agents run on Mintlayer mainnet only - hide the section elsewhere. @@ -81,7 +91,7 @@ const PLUGIN_ICON_DEFAULT = 'M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.8 - + diff --git a/app/src/lib/api-utils.test.ts b/app/src/lib/api-utils.test.ts index 4574014..b3a5df5 100644 --- a/app/src/lib/api-utils.test.ts +++ b/app/src/lib/api-utils.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { json } from './api-utils'; +import { json, readFormWithinLimit, readJsonWithinLimit } from './api-utils'; describe('json()', () => { it('serializes the body with the JSON content type', async () => { @@ -25,3 +25,70 @@ describe('json()', () => { expect(res.headers.get('Cache-Control')).toBe('no-store'); }); }); + +describe('body size limits (public POST endpoints)', () => { + + it('returns null for content-length over the cap (413 path)', async () => { + const req = new Request('http://x.test/login', { + method: 'POST', + headers: new Headers({ 'content-type': 'application/x-www-form-urlencoded', 'content-length': String(2 << 20) }), + body: 'a=1', + }); + expect(await readFormWithinLimit(req, 1 << 20)).toBeNull(); + }); + + it('parses a normal form body within the cap', async () => { + const req = new Request('http://x.test/login', { + method: 'POST', + headers: new Headers({ 'content-type': 'application/x-www-form-urlencoded' }), + body: 'password=hunter2&totp_code=123456', + }); + const form = await readFormWithinLimit(req, 1 << 20); + expect(form?.get('password')).toBe('hunter2'); + }); + + it('caps chunked bodies without content-length', async () => { + const big = 'x'.repeat(2 << 20); + const stream = new ReadableStream({ + start(c) { c.enqueue(new TextEncoder().encode(big)); c.close(); }, + }); + const req = new Request('http://x.test/login', { + method: 'POST', + headers: new Headers({ 'content-type': 'application/x-www-form-urlencoded', 'transfer-encoding': 'chunked' }), + body: stream, + // @ts-expect-error duplex is valid at runtime for stream bodies + duplex: 'half', + }); + expect(await readFormWithinLimit(req, 1 << 20)).toBeNull(); + }); + + it('parses a chunked body within the cap after re-buffering', async () => { + const stream = new ReadableStream({ + start(c) { c.enqueue(new TextEncoder().encode('password=ok')); c.close(); }, + }); + const req = new Request('http://x.test/login', { + method: 'POST', + headers: new Headers({ 'content-type': 'application/x-www-form-urlencoded', 'transfer-encoding': 'chunked' }), + body: stream, + // @ts-expect-error duplex is valid at runtime for stream bodies + duplex: 'half', + }); + const form = await readFormWithinLimit(req, 1 << 20); + expect(form?.get('password')).toBe('ok'); + }); + + it('returns null for oversized JSON and for malformed JSON', async () => { + const big = new Request('http://x.test/api', { + method: 'POST', + headers: new Headers({ 'content-type': 'application/json', 'content-length': String(128 << 10) }), + body: '{"a":1}', + }); + expect(await readJsonWithinLimit(big, 64 << 10)).toBeNull(); + const bad = new Request('http://x.test/api', { + method: 'POST', + headers: new Headers({ 'content-type': 'application/json' }), + body: 'not json', + }); + expect(await readJsonWithinLimit(bad, 64 << 10)).toBeNull(); + }); +}); diff --git a/app/src/lib/api-utils.ts b/app/src/lib/api-utils.ts index e45baa9..9a3ab71 100644 --- a/app/src/lib/api-utils.ts +++ b/app/src/lib/api-utils.ts @@ -24,3 +24,57 @@ export async function readFormData(request: Request): Promise { return null; } } + +/** Pre-parse body caps for the public POST endpoints: request.formData() + * / request.json() buffer the entire body before any validation, so a + * multi-GB POST to an unauthenticated route can exhaust container memory. + */ +export const LOGIN_BODY_LIMIT = 1 << 20; // 1 MiB: password + TOTP + passkey blobs +export const UPLOAD_BODY_LIMIT = 55 << 20; // covers the 50 MB wallet-file cap +export const PASSKEY_BODY_LIMIT = 64 << 10; // 64 KiB: WebAuthn client data + +async function bufferedWithin(request: Request, maxBytes: number): Promise { + const len = Number(request.headers.get('content-length') ?? ''); + if (Number.isFinite(len) && len > 0) return len > maxBytes ? null : request; + // No content-length (chunked): read with a hard cap and re-parse the + // buffer so the raw stream can never outgrow the limit. + const reader = request.body?.getReader(); + if (!reader) return request; + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > maxBytes) { + try { await reader.cancel(); } catch { /* already gone */ } + return null; + } + chunks.push(value); + } + const merged = new Uint8Array(total); + let off = 0; + for (const c of chunks) { merged.set(c, off); off += c.byteLength; } + const headers = new Headers(request.headers); + headers.delete('content-length'); + headers.delete('transfer-encoding'); + return new Request(request.url, { method: request.method, headers, body: merged }); +} + +/** Parsed form body, or null when malformed OR over the byte cap. */ +export async function readFormWithinLimit(request: Request, maxBytes: number): Promise { + const bounded = await bufferedWithin(request, maxBytes); + if (!bounded) return null; + return readFormData(bounded); +} + +/** Parsed JSON body, or null when malformed OR over the byte cap. */ +export async function readJsonWithinLimit(request: Request, maxBytes: number): Promise { + const bounded = await bufferedWithin(request, maxBytes); + if (!bounded) return null; + try { + return (await bounded.json()) as T; + } catch { + return null; + } +} diff --git a/app/src/lib/auth.ts b/app/src/lib/auth.ts index 49639be..57e9858 100644 --- a/app/src/lib/auth.ts +++ b/app/src/lib/auth.ts @@ -265,6 +265,38 @@ export function recordLoginFailure(ip: string): void { } } +// ── Bootstrap KDF throttling ───────────────────────────────────────────────── +// The pre-bootstrap endpoints (login step 1 and first-time /setup) run +// expensive key derivation for unauthenticated visitors, and step 1 never +// produces a password *failure* by design (any ≥8-char password is accepted), +// so the login limiter above cannot see it. A plain per-IP fixed-window +// counter keeps a fresh install from being turned into a free KDF farm while +// the owner has not yet completed setup. + +const BOOTSTRAP_MAX_ATTEMPTS = 10; +const BOOTSTRAP_WINDOW_MS = 10 * 60 * 1000; + +const bootstrapAttempts = new Map(); + +export function checkBootstrapRateLimit(ip: string): boolean { + const now = Date.now(); + pruneExpired(bootstrapAttempts, now); + const entry = bootstrapAttempts.get(ip); + if (!entry || now >= entry.resetAt) return true; + return entry.count < BOOTSTRAP_MAX_ATTEMPTS; +} + +export function recordBootstrapAttempt(ip: string): void { + const now = Date.now(); + pruneExpired(bootstrapAttempts, now); + const entry = bootstrapAttempts.get(ip); + if (!entry || now >= entry.resetAt) { + bootstrapAttempts.set(ip, { count: 1, resetAt: now + BOOTSTRAP_WINDOW_MS }); + } else { + entry.count += 1; + } +} + // ── RPC rate limiting ────────────────────────────────────────────────────────── // Max 120 requests per 60 seconds per IP diff --git a/app/src/lib/bech32-correct.test.ts b/app/src/lib/bech32-correct.test.ts index 61db076..938977e 100644 --- a/app/src/lib/bech32-correct.test.ts +++ b/app/src/lib/bech32-correct.test.ts @@ -41,6 +41,43 @@ function toBech32mV1(hrp: string): string { } const BTC_V1 = toBech32mV1("bcrt"); +// bech32 v0 address with an explicit final 5-bit group (BIP-173 P2WSH +// padding probe): 32-byte program -> 51 full groups + 1 leftover bit, so +// the crafted final group's low 4 bits are pure padding and must be zero. +function toBech32V0WithFinalGroup(hrp: string, finalGroup: number): string { + const CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; + const GEN = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; + const polymod = (values: number[]) => { + let chk = 1; + for (const v of values) { + const top = chk >> 25; + chk = ((chk & 0x1ffffff) << 5) ^ v; + for (let i = 0; i < 5; i++) if ((top >> i) & 1) chk ^= GEN[i]; + } + return chk; + }; + const hrpExpand = (hrp: string) => { + const r: number[] = []; + for (const c of hrp) r.push(c.charCodeAt(0) >> 5); + r.push(0); + for (const c of hrp) r.push(c.charCodeAt(0) & 31); + return r; + }; + const program = Uint8Array.from(Buffer.alloc(32, 0xff)); + const data5 = [0]; + let acc = 0, bits = 0; + for (const b of program) { + acc = (acc << 8) | b; bits += 8; + while (bits >= 5) { data5.push((acc >> (bits - 5)) & 31); bits -= 5; } + } + data5.push(finalGroup & 31); + const values = hrpExpand(hrp).concat(data5); + const chk = polymod(values.concat([0, 0, 0, 0, 0, 0])) ^ 1; + const cs: number[] = []; + for (let i = 0; i < 6; i++) cs.push((chk >> (5 * (5 - i))) & 31); + return hrp + "1" + data5.concat(cs).map((d) => CHARSET[d]).join(""); +} + describe("suggestAddressCorrection", () => { it("accepts valid addresses as-is", () => { expect(suggestAddressCorrection(ML, "tmt", "ml")).toEqual({ status: "valid" }); @@ -77,6 +114,19 @@ describe("suggestAddressCorrection", () => { expect(r).toEqual({ status: "corrected", corrected: BTC_V1, fixedChars: 1 }); }); + it("rejects a v0 P2WSH address with nonzero padding bits", () => { + // 0b10001: leftover bit 1 (correct), low 4 bits 1 (must be zero). + const bad = toBech32V0WithFinalGroup("bcrt", 0b10001); + const r = suggestAddressCorrection(bad, "bcrt", "btc"); + expect(r.status).not.toBe("valid"); + }); + + it("accepts a v0 P2WSH address with zero padding bits", () => { + // 0b10000: leftover bit 1, padding zero - what a real encoder emits. + const good = toBech32V0WithFinalGroup("bcrt", 0b10000); + expect(suggestAddressCorrection(good, "bcrt", "btc")).toEqual({ status: "valid" }); + }); + it("cannot correct 3 substitutions", () => { const typo = ML.slice(0, 5) + "abc" + ML.slice(8); const r = suggestAddressCorrection(typo, "tmt", "ml"); @@ -148,7 +198,7 @@ describe("hrpForNetwork", () => { expect(hrpForNetwork("btc", "mainnet")).toBe("bc"); expect(hrpForNetwork("btc", "testnet")).toBe("tb"); expect(hrpForNetwork("btc", "regtest")).toBe("bcrt"); - expect(hrpForNetwork("btc", "signet")).toBe("sb"); + expect(hrpForNetwork("btc", "signet")).toBe("tb"); }); it("maps ML networks", () => { diff --git a/app/src/lib/bech32-correct.ts b/app/src/lib/bech32-correct.ts index 1044536..3826a86 100644 --- a/app/src/lib/bech32-correct.ts +++ b/app/src/lib/bech32-correct.ts @@ -45,21 +45,32 @@ function isValidChainPayload(_hrp: string, data: number[], encoding: Bech32Encod const version = data[0]; if (version === undefined || version > 16) return false; if (chain === "btc") { + // Lengths are counted in 5-bit symbols (the checksum is 6 symbols), + // so a 20-byte P2WPKH program is 32 symbols and a 32-byte P2WSH is + // 52 - comparing against byte counts rejected valid P2WSH addresses. const programLen = data.length - 7; + // BIP-173: the final converted group's padding bits must be zero. + // Only bites the 52-symbol (32-byte) P2WSH case: 52*5 = 260 bits for + // 256 bytes of payload leaves 4 padding bits; the 32-symbol P2WPKH + // case has none. A nonzero-pad string has a valid checksum but Core's + // segwit decoder rejects it, so the validator must too. + const bits = programLen * 5; + const padBits = bits - Math.floor(bits / 8) * 8; + if (padBits > 0 && (data[programLen] & ((1 << padBits) - 1)) !== 0) return false; if (version === 0) { if (encoding !== "bech32") return false; - if (programLen !== 20 && programLen !== 32) return false; + if (programLen !== 32 && programLen !== 52) return false; } else { if (encoding !== "bech32m") return false; // program length in symbols: 2..40 bytes -> ceil(bytes*8/5) symbols if (programLen < Math.ceil((2 * 8) / 5) || programLen > Math.ceil((40 * 8) / 5)) return false; - // BIP-173: the final converted group's padding bits must be zero - const bits = programLen * 5; - const padBits = bits - Math.floor(bits / 8) * 8; - if (padBits > 0 && (data[programLen] & ((1 << padBits) - 1)) !== 0) return false; } } - // ML: final payload validation is the wallet daemon's job on submit. + // ML addresses are bech32m (BIP-350 style): a string that only carries + // the legacy bech32 checksum must not be reported valid, and a typo in a + // real bech32m address must not be excused because it accidentally + // satisfies the legacy constant. + if (chain === "ml" && encoding !== "bech32m") return false; return true; } @@ -86,6 +97,13 @@ export function suggestAddressCorrection( return { status: "invalid", reason: "invalid characters" }; } + // Bech32 addresses are at most 90 chars and decode() rejects anything + // over 1023; without this cap a long paste runs a quadratic syndrome + // build on every keystroke and freezes the tab. + if (lower.length > 1023) { + return { status: "invalid", reason: "too long" }; + } + // separator = the LAST '1'; the hrp region must equal the expected hrp // exactly (hrp symbols are never correction candidates, so a fuzzy scan // could only ever lock onto a "tmt1"-shaped coincidence inside the data diff --git a/app/src/lib/bech32.ts b/app/src/lib/bech32.ts index 1e83162..6c7049c 100644 --- a/app/src/lib/bech32.ts +++ b/app/src/lib/bech32.ts @@ -130,7 +130,7 @@ export function hrpForNetwork(chain: Bech32Chain, network: string): string | nul case 'mainnet': return 'bc'; case 'testnet': return 'tb'; case 'regtest': return 'bcrt'; - case 'signet': return 'sb'; + case 'signet': return 'tb'; // signet shares the testnet HRP (BIP-0326) default: return null; } } diff --git a/app/src/lib/bitcoin-wallet.ts b/app/src/lib/bitcoin-wallet.ts index 15d6b9e..7ec8994 100644 --- a/app/src/lib/bitcoin-wallet.ts +++ b/app/src/lib/bitcoin-wallet.ts @@ -77,6 +77,12 @@ export interface BitcoinStatus { walletLoaded: boolean; node: BitcoinNodeInfo; balance: BitcoinBalance | null; + /** True while a background scan is running (create/boot/manual). */ + syncing?: boolean; + /** Human-readable failure from the most recent sync attempt. */ + lastSyncError?: string | null; + /** Why the persisted wallet is not loaded (network mismatch, corrupt db). */ + loadError?: string | null; } export interface BitcoinTransaction { diff --git a/app/src/lib/bridge-sdk/endpoints.ts b/app/src/lib/bridge-sdk/endpoints.ts index 2a25a43..763499d 100644 --- a/app/src/lib/bridge-sdk/endpoints.ts +++ b/app/src/lib/bridge-sdk/endpoints.ts @@ -73,7 +73,11 @@ export const createBridgeSdk = ( }, broadcastBridgeRequest: (input) => - apiRequest(`${bridgeUrl}bridge-request`, { method: 'POST', body: input }, fetchImpl), + // 60s: the backend broadcasts the signed deposit ON-CHAIN inside this + // call, so it must not be abandoned mid-flight (a client timeout there + // turns a slow success into an invisible success and a retry would + // double-deposit). + apiRequest(`${bridgeUrl}bridge-request`, { method: 'POST', body: input, timeoutMs: 60_000 }, fetchImpl), getBridgeRequest: (id) => apiRequest(`${bridgeUrl}bridge-request/${encodeURIComponent(id)}`, {}, fetchImpl), diff --git a/app/src/lib/bridge-sdk/http.ts b/app/src/lib/bridge-sdk/http.ts index 169e240..81bc5c4 100644 --- a/app/src/lib/bridge-sdk/http.ts +++ b/app/src/lib/bridge-sdk/http.ts @@ -10,6 +10,11 @@ export interface RequestOptions { /** JSON-serializable request body. */ body?: unknown; headers?: Record; + /** Abort budget in ms. Defaults to 10s; endpoints that make the SERVER + * perform an on-chain action (e.g. broadcastBridgeRequest) need more - + * aborting a slow-but-successful broadcast desyncs client belief from + * chain state and invites a double deposit on retry. */ + timeoutMs?: number; } /** Error thrown by bridge-sdk requests; carries the HTTP status when known. */ @@ -45,7 +50,7 @@ export async function apiRequest( options: RequestOptions = {}, fetchImpl: FetchLike = fetch, ): Promise { - const { method = 'GET', body, headers = {} } = options; + const { method = 'GET', body, headers = {}, timeoutMs = 10_000 } = options; const init: RequestInit = { method, @@ -53,6 +58,10 @@ export async function apiRequest( ? { 'Content-Type': 'application/json', ...headers } : headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + // Bounded so a hung bridge host cannot pin a poll forever: uncounted + // pending fetches never trip the panel's failure backoff and pile up + // until the browser's per-host connection pool starves. + signal: AbortSignal.timeout(timeoutMs), }; let response: Response; diff --git a/app/src/lib/bridge-sdk/token-metadata.test.ts b/app/src/lib/bridge-sdk/token-metadata.test.ts index 38c21da..139b5bc 100644 --- a/app/src/lib/bridge-sdk/token-metadata.test.ts +++ b/app/src/lib/bridge-sdk/token-metadata.test.ts @@ -116,12 +116,12 @@ describe('resolveTokenMetadata', () => { expect(fetchImpl).toHaveBeenNthCalledWith( 1, expect.stringContaining('/token/tid1'), - { method: 'GET', headers: {} }, + { method: 'GET', headers: {}, signal: expect.any(AbortSignal) }, ); expect(fetchImpl).toHaveBeenNthCalledWith( 2, '/ipfs/QmMeta', - { method: 'GET', headers: {} }, + { method: 'GET', headers: {}, signal: expect.any(AbortSignal) }, ); expect(meta?.name).toBe('Bridged Token'); }); diff --git a/app/src/lib/client-rpc.test.ts b/app/src/lib/client-rpc.test.ts index af8e420..03503a9 100644 --- a/app/src/lib/client-rpc.test.ts +++ b/app/src/lib/client-rpc.test.ts @@ -32,6 +32,7 @@ describe('rpc', () => { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ method: 'get_blockchain_info', params: { verbose: true } }), + signal: expect.any(AbortSignal), }); }); @@ -45,6 +46,7 @@ describe('rpc', () => { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ method: 'get_height', params: {} }), + signal: expect.any(AbortSignal), }); }); diff --git a/app/src/lib/client-rpc.ts b/app/src/lib/client-rpc.ts index fc3baab..4aec037 100644 --- a/app/src/lib/client-rpc.ts +++ b/app/src/lib/client-rpc.ts @@ -3,12 +3,31 @@ * Throws with the RPC error message when the call fails. */ export async function rpc(method: string, params: Record = {}): Promise { - const res = await fetch('/api/rpc', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ method, params }), - }); - const data = await res.json() as { ok: boolean; result?: T; error?: { message: string } }; + let res: Response; + try { + res = await fetch('/api/rpc', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ method, params }), + signal: AbortSignal.timeout(15_000), + }); + } catch (err) { + if (err instanceof Error && err.name === 'TimeoutError') { + throw new Error('The wallet service took too long to answer.'); + } + throw new Error('Could not reach the wallet service.'); + } + // A proxy or error page can answer with HTML - report the status + // instead of a JSON parse error. + let data: { ok: boolean; result?: T; error?: { message: string } }; + try { + data = await res.json(); + } catch { + throw new Error(`Wallet service error (HTTP ${res.status}).`); + } + if (!res.ok) { + throw new Error(data.error?.message ?? `Wallet service error (HTTP ${res.status}).`); + } if (!data.ok) throw new Error(data.error?.message ?? 'RPC error'); return data.result as T; } diff --git a/app/src/lib/csp.ts b/app/src/lib/csp.ts index c26c008..009c0a0 100644 --- a/app/src/lib/csp.ts +++ b/app/src/lib/csp.ts @@ -14,8 +14,10 @@ * are dropped, so a stray value cannot widen the policy into * `connect-src *`. * - * Rollout stays report-only by default (see middleware.ts); enforcement - * still requires the inline-script nonce work. + * Rollout stays report-only - middleware.ts never flips this into an + * enforcing header. Enforcement still requires the inline-script nonce + * work: script-src currently carries 'unsafe-inline', so enforcing as-is + * would not contain injected scripts while breaking nothing else. */ import { getBridgeApiUrl, getMintlayerApiUrl } from '@/lib/bridge-sdk/config'; diff --git a/app/src/lib/decimal.test.ts b/app/src/lib/decimal.test.ts new file mode 100644 index 0000000..59a710f --- /dev/null +++ b/app/src/lib/decimal.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect } from 'vitest'; +import { mulDecimal, divDecimal, trimTrailingZeros } from './decimal'; + +describe('mulDecimal', () => { + it('multiplies exactly without float artifacts', () => { + expect(mulDecimal('0.1', '0.3')).toBe('0.03'); + expect(mulDecimal('0.7', '0.1')).toBe('0.07'); + expect(mulDecimal('1.1', '1.1')).toBe('1.21'); + }); + + it('keeps significant trailing zeros in integer products', () => { + // The old (parseFloat).toString + /\.?0+$/ strip turned these into "1". + expect(mulDecimal('1000000', '10')).toBe('10000000'); + expect(mulDecimal('12000000', '1')).toBe('12000000'); + expect(mulDecimal('9000000', '1')).toBe('9000000'); + }); + + it('trims only insignificant fraction zeros', () => { + expect(mulDecimal('1.50', '2')).toBe('3'); + expect(mulDecimal('0.100', '0.100')).toBe('0.01'); + expect(mulDecimal('10', '10')).toBe('100'); + }); + + it('handles signs and zero', () => { + expect(mulDecimal('-2', '3')).toBe('-6'); + expect(mulDecimal('-2', '-3')).toBe('6'); + expect(mulDecimal('0', '5')).toBe('0'); + expect(mulDecimal('0.000', '5')).toBe('0'); + }); + + it('supports very large values exactly', () => { + // 99999999999.99999999 * 99999999999, exact (BigInt math, no rounding). + expect(mulDecimal('99999999999.99999999', '99999999999')).toBe( + '9999999999899999999000.00000001', + ); + }); + + it('rejects non-plain-decimal input', () => { + expect(mulDecimal('1e5', '2')).toBeNull(); + expect(mulDecimal('1,234.5', '2')).toBeNull(); + expect(mulDecimal('', '2')).toBeNull(); + expect(mulDecimal('abc', '2')).toBeNull(); + expect(mulDecimal('1.2.3', '2')).toBeNull(); + }); +}); + +describe('divDecimal', () => { + it('divides and rounds half-up at the requested scale', () => { + expect(divDecimal('6172.5', '1234.5')).toBe('5'); + expect(divDecimal('1', '3', 8)).toBe('0.33333333'); + expect(divDecimal('2', '3', 8)).toBe('0.66666667'); + expect(divDecimal('1', '4')).toBe('0.25'); + }); + + it('keeps large quotients intact', () => { + expect(divDecimal('10000000', '10')).toBe('1000000'); + }); + + it('rejects division by zero and malformed input', () => { + expect(divDecimal('1', '0')).toBeNull(); + expect(divDecimal('1', '0.000')).toBeNull(); + expect(divDecimal('x', '2')).toBeNull(); + expect(divDecimal('1', '1e3')).toBeNull(); + }); +}); + +describe('trimTrailingZeros', () => { + it('only touches the fraction part', () => { + expect(trimTrailingZeros('10000000')).toBe('10000000'); + expect(trimTrailingZeros('12.5000')).toBe('12.5'); + expect(trimTrailingZeros('12.000')).toBe('12'); + expect(trimTrailingZeros('0.00000000')).toBe('0'); + expect(trimTrailingZeros('-0.000')).toBe('0'); + }); +}); diff --git a/app/src/lib/decimal.ts b/app/src/lib/decimal.ts new file mode 100644 index 0000000..835035d --- /dev/null +++ b/app/src/lib/decimal.ts @@ -0,0 +1,76 @@ +/** + * Exact decimal-string arithmetic for order amounts. + * + * Order totals end up in `amount.decimal` fields that the daemon parses as + * exact decimals, and the same numbers are what the user confirms on screen. + * Float math corrupts both ends: 0.1 * 0.3 === 0.30000000000000004 (rejected + * by the daemon), and naive trailing-zero strips eat significant digits + * (10000000 -> "1"). These helpers compute on BigInt unscaled values so + * every result is the mathematically exact decimal, then format minimally. + */ + +interface Decimal { + neg: boolean; + unscaled: bigint; // digits without the decimal point + scale: number; // number of fraction digits +} + +function parseDecimal(raw: string): Decimal | null { + const s = raw.trim(); + if (!/^-?\d+(\.\d+)?$/.test(s)) return null; // rejects '', '1e5', 'NaN', ',' + const neg = s.startsWith('-'); + const body = neg ? s.slice(1) : s; + const dot = body.indexOf('.'); + const unscaled = BigInt(dot === -1 ? body : body.replace('.', '')); + return { neg: neg && unscaled !== 0n, unscaled, scale: dot === -1 ? 0 : body.length - dot - 1 }; +} + +function formatUnscaled(value: Decimal): string { + if (value.unscaled === 0n) return '0'; + let digits = value.unscaled.toString(); + if (value.scale > 0) { + if (digits.length <= value.scale) digits = digits.padStart(value.scale + 1, '0'); + digits = `${digits.slice(0, digits.length - value.scale)}.${digits.slice(digits.length - value.scale)}`; + } + return value.neg ? `-${digits}` : digits; +} + +/** Strip fraction-only trailing zeros: '0.030000' -> '0.03'; integers untouched. */ +export function trimTrailingZeros(s: string): string { + if (!s.includes('.')) return s; + const trimmed = s.replace(/0+$/, '').replace(/\.$/, ''); + return trimmed === '' || trimmed === '-' || trimmed === '-0' ? '0' : trimmed; +} + +/** + * Exact product of two decimal strings, or null when either input is not a + * plain decimal number. '0.1' * '0.3' === '0.03'; '1000000' * '10' stays + * '10000000'. + */ +export function mulDecimal(a: string, b: string): string | null { + const da = parseDecimal(a); + const db = parseDecimal(b); + if (!da || !db) return null; + return trimTrailingZeros( + formatUnscaled({ + neg: da.neg !== db.neg, + unscaled: da.unscaled * db.unscaled, + scale: da.scale + db.scale, + }), + ); +} + +/** + * Quotient a/b rounded half-up to `maxScale` fraction digits (display + * estimates), or null when either input is not a plain decimal or b is 0. + */ +export function divDecimal(a: string, b: string, maxScale = 8): string | null { + const da = parseDecimal(a); + const db = parseDecimal(b); + if (!da || !db || db.unscaled === 0n || maxScale < 0) return null; + const num = da.unscaled * 10n ** BigInt(db.scale + maxScale); + const den = db.unscaled * 10n ** BigInt(da.scale); + let q = num / den; + if ((num % den) * 2n >= den) q += 1n; + return trimTrailingZeros(formatUnscaled({ neg: da.neg !== db.neg, unscaled: q, scale: maxScale })); +} diff --git a/app/src/lib/evm.ts b/app/src/lib/evm.ts index 8bac7b5..d0c7c12 100644 --- a/app/src/lib/evm.ts +++ b/app/src/lib/evm.ts @@ -11,6 +11,9 @@ */ import { BrowserProvider, Contract, formatUnits, parseUnits } from 'ethers'; +// Re-exported for components that must stay in integer base-unit land. +export { formatUnits, parseUnits }; + export const ERC20_ABI = [ 'function balanceOf(address owner) view returns (uint256)', 'function approve(address spender, uint256 amount) returns (bool)', @@ -126,8 +129,11 @@ export async function switchChain( }); } catch (err) { const code = (err as { code?: number }).code; - // 4902 = chain not added to the wallet - if (code === 4902 && chainParams) { + const msg = (err as { message?: string }).message ?? ''; + // 4902 = chain not added to the wallet; some MetaMask versions + // (mobile especially) report -32603 "Unrecognized chain" instead. + const missing = code === 4902 || (code === -32603 && /unrecognized chain/i.test(msg)); + if (missing && chainParams) { await eth().request({ method: 'wallet_addEthereumChain', params: [{ chainId: chainIdHex, ...chainParams }], @@ -142,12 +148,26 @@ export async function switchChain( export async function getTokenBalance( tokenAddress: string, userAddress: string, - decimals = 18, ): Promise { + const b = await getTokenBalanceBase(tokenAddress, userAddress); + return formatUnits(b.raw, b.decimals); +} + +/** Balance as exact base units + the token's own decimals: callers doing + * arithmetic (fraction buttons, caps) must not go through float strings - + * at 18 decimals 2^53 is only ~0.009 tokens and rounding lands above the + * real balance. */ +export async function getTokenBalanceBase( + tokenAddress: string, + userAddress: string, +): Promise<{ raw: bigint; decimals: number }> { const p = provider(); const token = new Contract(tokenAddress, ERC20_ABI, p); - const balance = await token.balanceOf(userAddress); - return formatUnits(balance, decimals); + // Read the decimals from the token itself: assuming 18 shows USDC/USDT + // (6 decimals) balances 10^12x too small and breaks the Max buttons. + const decimals = Number(await token.decimals()); + const raw = (await token.balanceOf(userAddress)) as bigint; + return { raw, decimals }; } /** @@ -162,6 +182,7 @@ export async function depositToBridge( decimals: number, mintlayerAddress: string, onProgress?: (phase: 'approve' | 'deposit') => void, + expectedChainId?: number, ): Promise { if (!bridgeContractAddress) { throw new Error('Bridge contract address is not configured.'); @@ -169,14 +190,29 @@ export async function depositToBridge( const p = provider(); const signer = await p.getSigner(); + // Signing happens against whatever chain the wallet currently has + // active (another tab or a mobile app can switch it): verify right + // before the money moves. A codeless address on the wrong chain would + // otherwise "mine" a deposit that never exists. + if (typeof expectedChainId === 'number') { + const { chainId } = await p.getNetwork(); + if (chainId !== BigInt(expectedChainId)) { + throw new EvmError( + 'Your wallet switched to a different network. Switch back to the bridge network and try again.', + ); + } + } + const token = new Contract(tokenAddress, ERC20_ABI, signer); // The chain is the source of truth for decimals - many bridgeable // tokens (USDC et al.) are not 18, and the config carries no value. + // ethers v6 decodes uint8 returns as bigint: convert before the + // integer check or the guard rejects every honest answer. let resolvedDecimals = decimals; try { - const onChain = await token.decimals(); - if (Number.isInteger(onChain) && onChain >= 0 && onChain <= 36) { - resolvedDecimals = onChain; + const n = Number(await token.decimals()); + if (Number.isInteger(n) && n >= 0 && n <= 36) { + resolvedDecimals = n; } } catch { /* keep the caller-provided fallback */ @@ -198,8 +234,30 @@ export async function depositToBridge( } if (needsApproval) { onProgress?.('approve'); - const approveTx = await token.approve(bridgeContractAddress, amountWei); - await approveTx.wait(); + try { + const approveTx = await token.approve(bridgeContractAddress, amountWei); + await approveTx.wait(); + } catch (err) { + // USDT-class tokens revert on a non-zero -> non-zero approve; the + // fix is a zero-reset first, then the real allowance. + if (normalizeEvmRejection(err).code === 4001) throw err; + const resetTx = await token.approve(bridgeContractAddress, 0); + await resetTx.wait(); + const approveTx = await token.approve(bridgeContractAddress, amountWei); + await approveTx.wait(); + } + } + + // Re-verify the chain right before the deposit: the approve can mine + // for minutes, and a chain switched during that window (other tab, + // mobile push) must not carry the deposit. + if (typeof expectedChainId === 'number') { + const { chainId } = await p.getNetwork(); + if (chainId !== BigInt(expectedChainId)) { + throw new EvmError( + 'Your wallet switched to a different network. Switch back to the bridge network and try again.', + ); + } } const bridge = new Contract(bridgeContractAddress, BRIDGE_DEPOSIT_ABI, signer); diff --git a/app/src/lib/explorer-base.ts b/app/src/lib/explorer-base.ts new file mode 100644 index 0000000..2a09451 --- /dev/null +++ b/app/src/lib/explorer-base.ts @@ -0,0 +1,22 @@ +/** + * Explorer base URL for tx/pool/delegation/token links. + * + * Layout.astro renders the resolved base (ML_EXPLORER_URL override, else the + * network's public explorer) into , so the override + * that management/transactions.astro honors applies to client links too. + * Networks without a public explorer (regtest/signet) resolve to '' - callers + * must degrade to plain text instead of linking at a dead mainnet URL. + */ +export function explorerBase(): string { + if (typeof document !== 'undefined') { + const rendered = document.body?.dataset['explorerBase']; + if (rendered !== undefined) return rendered; + } + // Fallback when the attribute is absent (tests, non-Layout hosts). + const network = typeof document !== 'undefined' + ? (document.body?.dataset['network'] ?? 'mainnet') + : 'mainnet'; + if (network === 'testnet') return 'https://lovelace.explorer.mintlayer.org'; + if (network === 'mainnet') return 'https://explorer.mintlayer.org'; + return ''; +} diff --git a/app/src/lib/feature-requests.ts b/app/src/lib/feature-requests.ts index 4ed6e0e..9e70381 100644 --- a/app/src/lib/feature-requests.ts +++ b/app/src/lib/feature-requests.ts @@ -84,9 +84,18 @@ function requestPath(service: FeatureService): string { /** A request is pending while the sidecar has not picked it up yet. */ export async function isRequestPending(service: FeatureService): Promise { + // Two states count: the queue file (not yet claimed) and the claim file + // (renamed to .req.lock while the sidecar applies it - a deploy + // can take minutes). Checking only the queue file made auto-install + // re-queue the same upgrade mid-deploy, and 409 copies lie during that + // window. try { await stat(requestPath(service)); return true; + } catch { /* fall through to the claim check */ } + try { + await stat(`${requestPath(service)}.lock`); + return true; } catch { return false; } diff --git a/app/src/lib/indexer-capabilities.ts b/app/src/lib/indexer-capabilities.ts index bcfc1cc..ae69f85 100644 --- a/app/src/lib/indexer-capabilities.ts +++ b/app/src/lib/indexer-capabilities.ts @@ -13,7 +13,11 @@ * checked independently so partial deployments are handled honestly). */ -const INDEXER_URL = process.env.INDEXER_URL ?? 'http://api-web-server:3000'; +// Trailing slash stripped: an operator-supplied base like +// 'http://api-web-server:3000/' would otherwise produce '//api/v2/...' +// paths that the api server 404s, and every indexer feature would look +// dead while the container is perfectly healthy. +const INDEXER_URL = (process.env.INDEXER_URL ?? 'http://api-web-server:3000').replace(/\/+$/, ''); const CAPABILITIES_TTL_MS = 60_000; @@ -31,10 +35,10 @@ let cache: { capabilities: IndexerCapabilities; expiresAt: number } | null = nul * aborted as soon as the response headers arrive only costs one HTTP round * trip and no event delivery. */ -async function probeEndpoint(path: string): Promise { +async function probeEndpoint(path: string, accept: string): Promise { try { const res = await fetch(`${INDEXER_URL}/api/v2${path}`, { - headers: { accept: 'text/event-stream' }, + headers: { accept }, signal: AbortSignal.timeout(5_000), }); // Release the connection immediately - we only care about the status. @@ -54,8 +58,10 @@ export async function getIndexerCapabilities(force = false): Promise 0; } -export function getRpId(requestUrl: string): string { +export function getRpId(request: Request | string): string { if (process.env.PASSKEY_RP_ID) return process.env.PASSKEY_RP_ID; - return new URL(requestUrl).hostname; + return proxyAwareUrl(request).hostname; } -export function getOrigin(requestUrl: string): string { +export function getOrigin(request: Request | string): string { if (process.env.PASSKEY_ORIGIN) return process.env.PASSKEY_ORIGIN; - return new URL(requestUrl).origin; + return proxyAwareUrl(request).origin; +} + +/** + * WebAuthn compares the SERVER-declared rpId/origin against the BROWSER's + * origin, which is always the TLS URL a user visits. Behind the shipped + * caddy gateway the raw socket URL is http:// (the node adapter does + * not apply X-Forwarded-Proto - the same reason lib/csrf.ts exists), so the + * bare fallback breaks registration AND login on every HTTPS deployment. + * Mirror csrf.ts: honor X-Forwarded-* only under TRUST_PROXY, else the + * request's own URL. + */ +function proxyAwareUrl(request: Request | string): URL { + if (typeof request === 'string') return new URL(request); + const url = new URL(request.url); + if (process.env.TRUST_PROXY !== 'true') return url; + const firstForwarded = (v: string | null) => v?.split(',')[0]?.trim() || undefined; + const proto = (firstForwarded(request.headers.get('x-forwarded-proto')) ?? url.protocol.replace(/:$/, '')).toLowerCase(); + const host = firstForwarded(request.headers.get('x-forwarded-host')) ?? request.headers.get('host') ?? url.host; + return new URL(`${proto}://${host}`); } // ── Challenge cookie header helpers ─────────────────────────────────────────── diff --git a/app/src/lib/password-change.test.ts b/app/src/lib/password-change.test.ts index 3b71ea4..5f2e9b1 100644 --- a/app/src/lib/password-change.test.ts +++ b/app/src/lib/password-change.test.ts @@ -10,7 +10,12 @@ vi.mock('@/lib/prefs-db', () => ({ setPref: vi.fn(), })); -import { resolvePasswordChange, applyPasswordChange } from '@/lib/password-change'; +import { + resolvePasswordChange, + applyPasswordChange, + isPasswordChangeThrottled, + resetPasswordChangeThrottle, +} from '@/lib/password-change'; import { verifyPassword, hashPassword } from '@/lib/auth'; import { getStringPref, getPref, setPref } from '@/lib/prefs-db'; @@ -24,6 +29,7 @@ beforeEach(() => { mockHash.mockReset(); mockGetStringPref.mockReset(); mockGetPref.mockReset(); + resetPasswordChangeThrottle(); }); describe('resolvePasswordChange', () => { @@ -64,6 +70,47 @@ describe('resolvePasswordChange', () => { const d = await resolvePasswordChange({ ...valid, confirmPassword: 'different' }); expect(d).toMatchObject({ ok: false, error: 'New passwords do not match', httpStatus: 400 }); }); + + it('locks out after 5 wrong current passwords for the same key', async () => { + mockGetStringPref.mockReturnValue('stored-hash'); + mockVerify.mockResolvedValue(false); + for (let i = 0; i < 5; i++) { + await resolvePasswordChange(valid, '1.2.3.4'); + } + const d = await resolvePasswordChange(valid, '1.2.3.4'); + expect(d).toMatchObject({ ok: false, httpStatus: 429 }); + expect(isPasswordChangeThrottled('1.2.3.4')).toBe(true); + // A correct password no longer bypasses the lockout. + mockVerify.mockResolvedValue(true); + const ok = await resolvePasswordChange(valid, '1.2.3.4'); + expect(ok).toMatchObject({ ok: false, httpStatus: 429 }); + }); + + it('does not count failures for other keys', async () => { + mockGetStringPref.mockReturnValue('stored-hash'); + mockVerify.mockResolvedValue(false); + await resolvePasswordChange(valid, '1.1.1.1'); + expect(isPasswordChangeThrottled('2.2.2.2')).toBe(false); + }); + + it('clears the failure count after a successful change', async () => { + mockGetStringPref.mockReturnValue('stored-hash'); + mockVerify.mockResolvedValue(false); + await resolvePasswordChange(valid, '1.2.3.4'); + mockVerify.mockResolvedValue(true); + mockHash.mockResolvedValue('new-hash'); + await resolvePasswordChange(valid, '1.2.3.4'); + expect(isPasswordChangeThrottled('1.2.3.4')).toBe(false); + }); + + it('skips throttling when no key is supplied', async () => { + mockGetStringPref.mockReturnValue('stored-hash'); + mockVerify.mockResolvedValue(false); + for (let i = 0; i < 10; i++) { + const d = await resolvePasswordChange(valid); + expect(d).toMatchObject({ httpStatus: 401 }); + } + }); }); describe('applyPasswordChange', () => { diff --git a/app/src/lib/password-change.ts b/app/src/lib/password-change.ts index 606453c..abeca6b 100644 --- a/app/src/lib/password-change.ts +++ b/app/src/lib/password-change.ts @@ -17,14 +17,71 @@ export type PasswordChangeDecision = | { ok: true; newHash: string } | { ok: false; error: string; httpStatus: number }; +// ── Failed current-password throttle ──────────────────────────────────────── +// Login throttles wrong passwords per IP, so password change must too: a +// hijacked session would otherwise brute-force the current password online +// at PBKDF2 speed and lock the owner out permanently. Mirrors the TOTP +// throttle in step-up.ts: 5 failures per key per 15 minutes. + +const MAX_PASSWORD_FAILURES = 5; +const PASSWORD_FAILURE_WINDOW_MS = 15 * 60 * 1000; +const passwordFailures = new Map(); + +export function isPasswordChangeThrottled(key: string, now: number = Date.now()): boolean { + const entry = passwordFailures.get(key); + return ( + !!entry && + entry.count >= MAX_PASSWORD_FAILURES && + now < entry.firstAt + PASSWORD_FAILURE_WINDOW_MS + ); +} + +/** Test hook: clear all throttles (module state survives across tests). */ +export function resetPasswordChangeThrottle(): void { + passwordFailures.clear(); +} + +/** + * Record a failed credential attempt against a throttle key. The wallet + * unlock form shares this map (under its own key namespace) - the unlock + * password is the same class of guessable secret as the current-password + * check, and RPC speed alone is no rate limit. + */ +export function recordThrottledFailure(key: string, now: number = Date.now()): void { + recordPasswordFailure(key, now); +} + +function recordPasswordFailure(key: string, now: number): void { + const entry = passwordFailures.get(key); + if (!entry || now >= entry.firstAt + PASSWORD_FAILURE_WINDOW_MS) { + passwordFailures.set(key, { count: 1, firstAt: now }); + } else { + entry.count += 1; + } +} + /** * Validate a password change against the stored hash. Does not persist * anything - call applyPasswordChange() with the returned hash afterwards * so callers keep control over response handling. + * + * @param throttleKey rate-limit key (usually the client IP). Wrong + * current-password attempts count toward a 5-per-15-minutes lockout; + * omitting the key skips throttling (discouraged outside tests). */ export async function resolvePasswordChange( input: PasswordChangeInput, + throttleKey?: string, ): Promise { + const now = Date.now(); + if (throttleKey && isPasswordChangeThrottled(throttleKey, now)) { + return { + ok: false, + error: 'Too many failed attempts. Try again in 15 minutes.', + httpStatus: 429, + }; + } + const storedHash = getStringPref('auth.password_hash'); if (!storedHash) { return { ok: false, error: 'Password not configured', httpStatus: 400 }; @@ -32,8 +89,10 @@ export async function resolvePasswordChange( const currentOk = await verifyPassword(input.currentPassword, storedHash); if (!currentOk) { + if (throttleKey) recordPasswordFailure(throttleKey, now); return { ok: false, error: 'Current password is incorrect', httpStatus: 401 }; } + if (throttleKey) passwordFailures.delete(throttleKey); if (input.newPassword.length < 8) { return { ok: false, error: 'New password must be at least 8 characters', httpStatus: 400 }; diff --git a/app/src/lib/plugins.test.ts b/app/src/lib/plugins.test.ts index 8021376..09e05bc 100644 --- a/app/src/lib/plugins.test.ts +++ b/app/src/lib/plugins.test.ts @@ -6,15 +6,23 @@ vi.mock('@/lib/prefs-db', () => ({ deletePref: vi.fn(), })); -vi.mock('node:fs', () => ({ - existsSync: vi.fn(), - mkdirSync: vi.fn(), - readFileSync: vi.fn(), - readdirSync: vi.fn(), - realpathSync: vi.fn(), - rmSync: vi.fn(), - statSync: vi.fn(), - writeFileSync: vi.fn(), +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + return { + existsSync: vi.fn(), + mkdirSync: vi.fn(), + mkdtempSync: vi.fn(() => actual.mkdtempSync('/tmp/plugin-test-')), + readFileSync: vi.fn(), + readdirSync: vi.fn(), + realpathSync: vi.fn(), + rmSync: vi.fn(), + statSync: vi.fn(), + writeFileSync: vi.fn(), + }; +}); + +vi.mock('node:url', () => ({ + pathToFileURL: (p: string) => ({ href: `file://${p}` }), })); vi.mock('node:child_process', () => ({ @@ -130,24 +138,24 @@ describe('togglePlugin', () => { // ── uninstallPlugin ─────────────────────────────────────────────────────────── describe('uninstallPlugin', () => { - it('throws when plugin is not installed', () => { + it('throws when plugin is not installed', async () => { mockGetPref.mockReturnValue([]); - expect(() => uninstallPlugin('unknown')).toThrow('not installed'); + await expect(uninstallPlugin('unknown')).rejects.toThrow('not installed'); }); - it('removes plugin from registry', () => { + it('removes plugin from registry', async () => { const other = { ...MANIFEST, id: 'other-plugin' }; mockGetPref.mockReturnValue([MANIFEST, other]); - uninstallPlugin('my-plugin'); + await uninstallPlugin('my-plugin'); expect(mockSetPref).toHaveBeenCalledWith('plugins.registry', [other]); expect(mockDeletePref).toHaveBeenCalledWith('plugins.my-plugin.enabled'); }); - it('tolerates rmSync failure gracefully', () => { + it('tolerates rmSync failure gracefully', async () => { mockGetPref.mockReturnValue([MANIFEST]); vi.mocked(rmSync).mockImplementationOnce(() => { throw new Error('ENOENT'); }); // should not throw - expect(() => uninstallPlugin('my-plugin')).not.toThrow(); + await expect(uninstallPlugin('my-plugin')).resolves.toBeUndefined(); expect(mockSetPref).toHaveBeenCalledWith('plugins.registry', []); }); }); diff --git a/app/src/lib/plugins.ts b/app/src/lib/plugins.ts index 1d10b25..fdf0c1c 100644 --- a/app/src/lib/plugins.ts +++ b/app/src/lib/plugins.ts @@ -10,6 +10,7 @@ import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, + mkdtempSync, readFileSync, readdirSync, realpathSync, @@ -18,9 +19,12 @@ import { writeFileSync, } from 'node:fs'; import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { pathToFileURL } from 'node:url'; import { getPref, setPref, deletePref } from './prefs-db'; import { rpcCall } from './wallet-rpc'; import { ALLOWED_RPC_METHODS } from './rpc-allowlist'; +import { indexerBaseUrl } from './indexer'; // ── Config ──────────────────────────────────────────────────────────────────── @@ -107,8 +111,32 @@ export function togglePlugin(id: string, enabled: boolean): void { // ── Install / Uninstall ─────────────────────────────────────────────────────── export async function installPlugin(buffer: Buffer): Promise { - const tmpTgz = `/tmp/plugin-upload-${Date.now()}.tgz`; - const tmpDir = `/tmp/plugin-extract-${Date.now()}`; + // Serialize installs: the read-modify-write on the registry pref and the + // duplicate-id check must not interleave with another install's, or a + // concurrent install silently vanishes from the registry (files stay on + // disk, admin has to re-upload + burn another TOTP code). + const done = installQueue.then(() => installPluginInner(buffer)); + // Swallow here so the queue never rejects; the caller still sees the error. + installQueue = done.catch(() => {}); + return done; +} + +let installQueue: Promise = Promise.resolve(); + +async function installPluginInner(buffer: Buffer): Promise { + // mkdtemp gives a unique directory per install - two same-millisecond + // uploads must not share an extraction target. + const tmpDir = mkdtempSync(join(tmpdir(), 'plugin-install-')); + // The escape check canonicalizes every extracted entry; the base must be + // canonical too or a symlinked TMPDIR (e.g. macOS /tmp -> /private/tmp) + // rejects every path and fails 100% of installs. + const realTmp = realpathSync(tmpDir); + // The archive itself lives OUTSIDE the extraction dir: a plugin.tgz next + // to the extracted entries would break the single-directory (npm pack) + // layout detection below and, for flat layouts, leak the 50 MB raw + // archive into the served plugin directory. + const dlDir = mkdtempSync(join(tmpdir(), 'plugin-dl-')); + const tmpTgz = join(dlDir, 'plugin.tgz'); try { writeFileSync(tmpTgz, buffer); @@ -137,7 +165,7 @@ export async function installPlugin(buffer: Buffer): Promise { } catch { throw new Error(`Archive contains path escaping extraction directory: ${p}`); } - if (!real.startsWith(tmpDir + '/') && real !== tmpDir) { + if (!real.startsWith(realTmp + '/') && real !== realTmp) { throw new Error(`Archive contains path escaping extraction directory: ${p}`); } } @@ -177,6 +205,10 @@ export async function installPlugin(buffer: Buffer): Promise { const destDir = join(PLUGINS_DIR, manifest.id); mkdirSync(PLUGINS_DIR, { recursive: true }); + // A crashed prior install can leave the directory without a registry + // entry; POSIX cp -r into an existing dir would nest the tree one + // level down and the plugin could never load. Clear first. + rmSync(destDir, { recursive: true, force: true }); execFileSync('cp', ['-r', pluginRoot, destDir], { timeout: 10_000 }); existing.push(manifest); @@ -188,10 +220,21 @@ export async function installPlugin(buffer: Buffer): Promise { } finally { try { rmSync(tmpTgz); } catch { /* ignore */ } try { rmSync(tmpDir, { recursive: true }); } catch { /* ignore */ } + try { rmSync(dlDir, { recursive: true }); } catch { /* ignore */ } } } -export function uninstallPlugin(id: string): void { +export async function uninstallPlugin(id: string): Promise { + // Serialize against installs too: an uninstall interleaving with a queued + // install's registry write could drop the fresh install from the registry + // (files on disk, id gone) or resurrect the uninstalled id (files gone, + // id still listed). Same queue, same reasoning as installPlugin. + const done = installQueue.then(() => uninstallInner(id)); + installQueue = done.catch(() => {}); + return done; +} + +async function uninstallInner(id: string): Promise { const plugins = getInstalledPlugins(); const idx = plugins.findIndex((p) => p.id === id); if (idx === -1) throw new Error(`Plugin "${id}" is not installed`); @@ -228,8 +271,9 @@ export async function loadPluginHandler(id: string): Promise { } const entryPath = join(PLUGINS_DIR, id, manifest.entry); - // Query parameter busts Node's ESM cache after reinstall - const url = `file://${entryPath}?gen=${gen}`; + // pathToFileURL percent-encodes reserved characters ('#', '?') so the + // cache-busting query can't swallow part of the path. + const url = `${pathToFileURL(entryPath).href}?gen=${gen}`; const module = await import(/* @vite-ignore */ url) as PluginModule; if (typeof module.handler !== 'function') { @@ -254,7 +298,8 @@ export function makePluginContext(pluginId: string, request: Request): PluginCon setPref: (key, value) => setPref(`plugins.${pluginId}.data.${key}`, value), indexerBaseUrl: process.env.INDEXER_ENABLED === 'true' - ? (process.env.INDEXER_URL ?? null) + ? // Same normalization as the built-in clients (trailing-slash 404s). + indexerBaseUrl() : null, request, }; diff --git a/app/src/lib/rpc-allowlist.ts b/app/src/lib/rpc-allowlist.ts index 5f6d8fe..f6611b0 100644 --- a/app/src/lib/rpc-allowlist.ts +++ b/app/src/lib/rpc-allowlist.ts @@ -39,11 +39,11 @@ export const ALLOWED_RPC_METHODS = new Set([ // Orders / Trading 'order_list_own', 'order_list_all_active', - // order_create / order_fill / order_conclude sign fund-moving transactions - // (placing an order locks coins/tokens; filling pays the ask). Only - // reachable through POST /api/stake-trade (TOTP step-up) - shared by the - // order book and the NFT marketplace. - 'order_freeze', + // order_create / order_fill / order_conclude / order_freeze are all on-chain + // transactions (freeze pays a fee and broadcasts; placing locks + // coins/tokens; filling pays the ask). Only reachable through POST + // /api/stake-trade (TOTP step-up) - shared by the order book and the NFT + // marketplace. // Wallet settings - non-sensitive only // NOTE: wallet_show_seed_phrase and wallet_unlock_private_keys are intentionally // absent - they are handled server-side in management/wallet.astro directly. @@ -52,7 +52,10 @@ export const ALLOWED_RPC_METHODS = new Set([ // Transactions 'transaction_list_by_address', 'transaction_list_pending', - 'transaction_abandon', + // transaction_abandon removed: un-reserving a pending tx's inputs is + // fund-affecting (a hijacked session could clobber a payment the user + // just approved) - same policy as address_send/token_send. If the UI + // needs it, expose it behind requireStepUp. // UTXOs 'account_utxos', // address_sweep_spendable removed: with `all: true` (or empty from_addresses) diff --git a/app/src/lib/safe-uri.test.ts b/app/src/lib/safe-uri.test.ts index 2c1a01a..25cd128 100644 --- a/app/src/lib/safe-uri.test.ts +++ b/app/src/lib/safe-uri.test.ts @@ -1,5 +1,35 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { safeExternalUri, safeImageUri, getIpfsGateway } from '@/lib/safe-uri'; +import { safeExternalUri, safeImageUri, getIpfsGateway, safeRelativePath } from '@/lib/safe-uri'; + +describe('safeRelativePath (login next= redirect)', () => { + it('keeps same-origin relative paths', () => { + expect(safeRelativePath('/balances')).toBe('/balances'); + expect(safeRelativePath('/management/transactions?tab=history')).toBe('/management/transactions?tab=history'); + }); + + it('rejects protocol-relative and backslash forms', () => { + expect(safeRelativePath('//evil.com')).toBe('/'); + expect(safeRelativePath('/\\evil.com')).toBe('/'); + expect(safeRelativePath('https://evil.com')).toBe('/'); + }); + + it('rejects control characters that undici refuses in header values', () => { + // A crafted ?next= with CR/LF used to reach the Location header and + // crash the login POST with an unhandled 500 after session minting. + expect(safeRelativePath('/foo\r\nbar')).toBe('/'); + expect(safeRelativePath('/foo\nbar')).toBe('/'); + expect(safeRelativePath('/foo\x00bar')).toBe('/'); + expect(safeRelativePath('/foo\x7fbar')).toBe('/'); + }); + + it('rejects non-ASCII code points that undici refuses in header values', () => { + // undici rejects any ByteString above U+00FF, so U+2028 (survives URL + // encoding as %E2%80%A8) crashed the redirect after irreversible side + // effects - guard is printable-ASCII only, which subsumes the controls. + expect(safeRelativePath('/foo\u2028bar')).toBe('/'); + expect(safeRelativePath('/foo\u00e9bar')).toBe('/'); + }); +}); describe('safeExternalUri (javascript: URI sink)', () => { it('allows https: URLs through unchanged', () => { diff --git a/app/src/lib/safe-uri.ts b/app/src/lib/safe-uri.ts index b39be3a..8710dbe 100644 --- a/app/src/lib/safe-uri.ts +++ b/app/src/lib/safe-uri.ts @@ -8,6 +8,26 @@ * else degrades to plain text. */ +/** + * Sanitize a user-supplied relative redirect target (the login `next=` + * parameter). Returns the path only when it is a same-origin relative URL; + * anything else degrades to '/'. + * + * Protocol-relative '//host' is rejected, and so is any backslash form: + * WHATWG URL parsing treats '\' as '/' for special schemes, so '/\\evil.com' + * and '/\\/evil.com' resolve cross-origin even though they start with '/' + * (new URL('/\\evil.com', 'http://x.test').href === 'http://evil.com/'). + */ +export function safeRelativePath(raw: string): string { + // Anything outside printable ASCII (control chars AND higher code points + // like U+2028) crashes the login redirect: undici rejects it as a header + // value, and the throw happens after the session was minted (or after + // setup credentials were promoted) - an avoidable 500 on a crafted + // ?next=. Degrade like every other unsafe value. + if (/[^\x21-\x7e]/.test(raw)) return '/'; + return raw.startsWith('/') && !raw.startsWith('//') && !raw.startsWith('/\\') ? raw : '/'; +} + export const DEFAULT_IPFS_GATEWAY = 'https://ipfs.io/ipfs/'; export function getIpfsGateway(): string { diff --git a/app/src/lib/step-up.ts b/app/src/lib/step-up.ts index 922572d..75b43a1 100644 --- a/app/src/lib/step-up.ts +++ b/app/src/lib/step-up.ts @@ -66,14 +66,18 @@ export function isTotpThrottled(key: string, now: number = Date.now()): boolean /** * Verify a TOTP code against `secret` and burn it (single use per window). * verifyTOTP accepts T-1..T+1, so the code is burned for the candidate - * periods (~90s). Shared by the web step-up gate and the Telegram bot so a - * code leaked via either channel cannot be replayed at the other. + * periods (~90s). Shared by web login, the step-up gate and the Telegram + * bot so a code observed at one channel cannot be replayed at another. */ export function verifyAndBurnTotpCode( - code: string, + rawCode: string, secret: string, throttleKey?: string, ): TotpCheck { + // Trim here so EVERY caller treats ' 123456 ' uniformly - a paste with + // whitespace used to fail one caller while passing another, and failed + // checks burn throttle slots. + const code = rawCode.trim(); const now = Date.now(); pruneUsedCodes(now); pruneTotpFailures(now); diff --git a/app/src/lib/toastStore.ts b/app/src/lib/toastStore.ts index 03421b1..fee78a1 100644 --- a/app/src/lib/toastStore.ts +++ b/app/src/lib/toastStore.ts @@ -3,6 +3,8 @@ * Uses useSyncExternalStore-compatible subscribe/getSnapshot pattern. */ +import { explorerBase } from '@/lib/explorer-base'; + export type ToastStatus = 'pending' | 'confirmed' | 'failed' | 'untracked'; export interface TxToast { @@ -48,15 +50,6 @@ export const toastStore = { }, }; -function explorerBase(): string { - const network = typeof document !== 'undefined' - ? (document.body.dataset['network'] ?? 'mainnet') - : 'mainnet'; - return network === 'testnet' - ? 'https://lovelace.explorer.mintlayer.org' - : 'https://explorer.mintlayer.org'; -} - export function explorerTxUrl(txId: string): string { return `${explorerBase()}/tx/${txId}`; } @@ -106,7 +99,6 @@ export async function submitWithToast( const url = explorerTxUrl(txId); toastStore.add({ id: txId, txId, explorerUrl: url, status: 'pending', pendingSince: Date.now() }); - // A pending toast must never spin forever without a reality check: if the // watcher hasn't resolved after 3 minutes, ask the indexer whether the tx // is actually still pending (1.4.1 mempool visibility) instead of guessing. diff --git a/app/src/lib/tx-decoder.ts b/app/src/lib/tx-decoder.ts index 1ee4a92..84c8b65 100644 --- a/app/src/lib/tx-decoder.ts +++ b/app/src/lib/tx-decoder.ts @@ -44,11 +44,25 @@ export interface DecodedTransaction { // ── Network detection ────────────────────────────────────────────────────────── +let loggedNetworkFallback = false; function detectNetwork(): number { + // Explicit env first - the repo-wide convention (NETWORK=mainnet|testnet| + // regtest) also covers daemons configured via config file, which the old + // CLI-substring probe silently mislabeled as mainnet. + const env = (process.env.NETWORK ?? '').toLowerCase(); + if (env === 'mainnet') return Network.Mainnet; + if (env === 'testnet') return Network.Testnet; + if (env === 'regtest') return Network.Regtest; + if (env === 'signet') return Network.Signet; + const cmd = process.env.WALLET_RPC_CMD ?? ''; if (cmd.includes('testnet')) return Network.Testnet; if (cmd.includes('regtest')) return Network.Regtest; if (cmd.includes('signet')) return Network.Signet; + if (!loggedNetworkFallback) { + loggedNetworkFallback = true; + console.error('[tx-decoder] NETWORK is not set and WALLET_RPC_CMD declares no network - decoding as mainnet'); + } return Network.Mainnet; } @@ -94,11 +108,25 @@ export function isTransferOutput(output: DecodedOutput): boolean { return TRANSFER_VARIANTS.has(outputVariant(output)); } +/** The TokenV1 id(s) an output moves, for batched decimals resolution. */ +export function tokenIdsOfOutput(output: DecodedOutput): string[] { + const variant = outputVariant(output); + if (!TRANSFER_VARIANTS.has(variant)) return []; + const args = output[variant] as unknown[]; + if (!Array.isArray(args) || args.length === 0) return []; + const value = args[0] as { Coin?: unknown; TokenV1?: [string, unknown] }; + return value?.TokenV1 ? [value.TokenV1[0]] : []; +} + /** * Extract the value from a Transfer or LockThenTransfer output. * Returns a human-readable string like "1.5 ML" or "100.0 (token ttkn1…)". + * Token amounts use the token's on-chain `number_of_decimals` when the + * caller supplies one (batched via getTokensInfo); without it the raw + * value is rendered with an explicit `atoms` hint - silently dividing by + * a guessed precision would show a wrong amount. */ -export function outputValueLabel(output: DecodedOutput): string | null { +export function outputValueLabel(output: DecodedOutput, tokenDecimals?: Map): string | null { const variant = outputVariant(output); if (!TRANSFER_VARIANTS.has(variant)) return null; @@ -110,7 +138,12 @@ export function outputValueLabel(output: DecodedOutput): string | null { if (value?.Coin) return `${atomsToDecimal(value.Coin.atoms, 11)} ML`; if (value?.TokenV1) { const [tokenId, amount] = value.TokenV1; - return `${atomsToDecimal(amount.atoms, 0)} (token ${tokenId.slice(0, 12)}…)`; + const decimals = tokenDecimals?.get(tokenId); + const pretty = + typeof decimals === 'number' && Number.isInteger(decimals) && decimals >= 0 + ? atomsToDecimal(amount.atoms, decimals) + : `${amount.atoms} atoms`; + return `${pretty} (token ${tokenId.slice(0, 12)}…)`; } return null; } diff --git a/app/src/lib/txWatcher.ts b/app/src/lib/txWatcher.ts index ad8d6f0..dbafac9 100644 --- a/app/src/lib/txWatcher.ts +++ b/app/src/lib/txWatcher.ts @@ -12,7 +12,10 @@ type TxState = type Callback = (state: TxState) => void; -const watchers = new Map(); +// A Set per tx id: two islands (or a retried submit) may watch the SAME tx. +// A single-callback map would let the first promise's timeout delete the +// second (live) watcher, so both callers miss the confirmation. +const watchers = new Map>(); let es: EventSource | null = null; function ensureStream() { @@ -29,19 +32,28 @@ function ensureStream() { | { type: 'error' }; if (msg.type === 'TxUpdated') { - watchers.get(msg.tx_id)?.(msg.state); + watchers.get(msg.tx_id)?.forEach((cb) => cb(msg.state)); } else if (msg.type === 'TxDropped') { - watchers.get(msg.tx_id)?.({ type: 'Inactive' }); + // A drop is definitive - the tx left the mempool. Map to Conflicted + // (which watchTx rejects immediately) instead of Inactive, whose + // keep-waiting semantics would burn the full timeout and then + // surface a neutral 'not tracked' hint for a tx that can never + // confirm. + watchers.get(msg.tx_id)?.forEach((cb) => cb({ type: 'Conflicted', content: { with_block: '' } })); } } catch { /* ignore malformed */ } }; const source = es; source.onerror = () => { - // Close the errored EventSource before dropping the reference - without - // this a second watchTx could open a duplicate stream (Minor hardening). - source.close(); - es = null; + // EventSource reconnects transient drops on its own (readyState + // CONNECTING) - closing here would kill auto-recovery and leave every + // in-flight watchTx to burn the full 5-minute timeout on a tx that may + // have confirmed during the blip. Close ONLY when the browser gave up + // (CLOSED); the next watchTx then opens a fresh stream. + if (source.readyState === EventSource.CLOSED) { + es = null; + } }; } @@ -55,22 +67,30 @@ export function watchTx(txId: string): Promise<{ block_height: number }> { return new Promise((resolve, reject) => { const TIMEOUT = 5 * 60 * 1000; - const timer = setTimeout(() => { - watchers.delete(txId); - reject(new Error('Transaction confirmation timed out')); - }, TIMEOUT); + const settle = (fail: Error | null) => { + clearTimeout(timer); + const set = watchers.get(txId); + set?.delete(callback); + // Only drop the map entry while this watcher's own callback is still + // registered - a stale promise must never remove a NEWER watcher. + if (set && set.size === 0) watchers.delete(txId); + if (fail) reject(fail); + else resolve(resolved); + }; + const resolved = { block_height: 0 }; + const timer = setTimeout(() => settle(new Error('Transaction confirmation timed out')), TIMEOUT); - watchers.set(txId, (state) => { + const callback = (state: TxState) => { if (state.type === 'Confirmed') { - clearTimeout(timer); - watchers.delete(txId); - resolve({ block_height: state.content.block_height }); + resolved.block_height = state.content.block_height; + settle(null); } else if (state.type === 'Conflicted' || state.type === 'Abandoned') { - clearTimeout(timer); - watchers.delete(txId); - reject(new Error(`Transaction ${state.type.toLowerCase()}`)); + settle(new Error(`Transaction ${state.type.toLowerCase()}`)); } // InMempool / Inactive - keep waiting - }); + }; + const set = watchers.get(txId) ?? new Set(); + set.add(callback); + watchers.set(txId, set); }); } diff --git a/app/src/lib/update-check.ts b/app/src/lib/update-check.ts index ac51655..a0bd8b5 100644 --- a/app/src/lib/update-check.ts +++ b/app/src/lib/update-check.ts @@ -150,12 +150,7 @@ async function fetchReleases(): Promise { if (!type.includes('application/json')) throw new Error('release check failed: unexpected content type'); const body: unknown = await res.json(); if (!Array.isArray(body)) throw new Error('release check failed: unexpected body'); - return body - .map(asRelease) - .filter((r): r is ReleaseInfo => r !== null) - // Cap AFTER filtering: a burst of published pre-releases must not hide a - // newer final release that sits beyond the window. - .slice(0, MAX_RELEASES); + return body.map(asRelease).filter((r): r is ReleaseInfo => r !== null); } /** @@ -169,7 +164,11 @@ export async function checkForUpdate(includePrereleases: boolean): Promise includePrereleases || !r.prerelease); + // The prerelease filter must run BEFORE the window cap: GitHub returns + // releases newest-first, so slicing a raw feed that opens with a long rc + // train would slice the newest final out of the window entirely and the + // UI would report up-to-date until the feed shifts. + const applicable = cache.releases.filter((r) => includePrereleases || !r.prerelease).slice(0, MAX_RELEASES); const newest = applicable.reduce((best, r) => { if (best === null || compareVersions(r.version, best.version) > 0) return r; return best; diff --git a/app/src/lib/validation.test.ts b/app/src/lib/validation.test.ts index 8022dc0..ee159f7 100644 --- a/app/src/lib/validation.test.ts +++ b/app/src/lib/validation.test.ts @@ -43,6 +43,12 @@ describe('isValidAmount', () => { expect(isValidAmount('1.234', 2)).toBe(false); }); + it('accepts integer amounts for zero-decimal tokens (no quantifier SyntaxError)', () => { + expect(isValidAmount('100', 0)).toBe(true); + expect(isValidAmount('1.0', 0)).toBe(false); + expect(isValidAmount('0.5', 0)).toBe(false); + }); + it('rejects malformed decimal shapes', () => { for (const bad of ['', '.', '1.', '.5', '1..2', '1.2.3']) { expect(isValidAmount(bad, 8)).toBe(false); diff --git a/app/src/lib/validation.ts b/app/src/lib/validation.ts index 6ef2c80..ca8d752 100644 --- a/app/src/lib/validation.ts +++ b/app/src/lib/validation.ts @@ -15,7 +15,10 @@ export function isPositiveDecimal(value: string): boolean { */ export function isValidAmount(value: string, maxDecimals: number): boolean { const t = value.trim(); - return new RegExp(`^\\d{1,38}(\\.\\d{1,${maxDecimals}})?$`).test(t) && parseFloat(t) > 0; + // maxDecimals 0 is legal (indivisible tokens): {1,0} would throw + // "numbers out of order in {} quantifier", so the fraction group is omitted. + const frac = maxDecimals > 0 ? `(\\.\\d{1,${maxDecimals}})?` : ''; + return new RegExp(`^\\d{1,38}${frac}$`).test(t) && parseFloat(t) > 0; } /** EVM address: 0x + 40 hex chars (checksum handled by ethers at the edges). */ diff --git a/app/src/lib/wallet-recovery.test.ts b/app/src/lib/wallet-recovery.test.ts index 1ac26a8..fa2a148 100644 --- a/app/src/lib/wallet-recovery.test.ts +++ b/app/src/lib/wallet-recovery.test.ts @@ -31,7 +31,10 @@ describe('recoverThenSwapWallet (never destroy the wallet before recovery succee `unlink:${OPTS.localPath}.recover`, `recover:${OPTS.rpcPath}.recover`, 'close', - `unlink:${OPTS.localPath}`, + // No unlink of localPath: rename alone replaces the destination + // atomically, so a crash mid-swap never leaves the canonical path + // empty (an unlink->rename window reported not_found and invited + // creating a different wallet). `rename:${OPTS.localPath}.recover->${OPTS.localPath}`, `open:${OPTS.rpcPath}`, ]); diff --git a/app/src/lib/wallet-recovery.ts b/app/src/lib/wallet-recovery.ts index 4d1a70c..25da036 100644 --- a/app/src/lib/wallet-recovery.ts +++ b/app/src/lib/wallet-recovery.ts @@ -48,8 +48,10 @@ export async function recoverThenSwapWallet( // 4. The daemon leaves the recovered temp wallet open - close before swap try { await deps.walletClose(); } catch { /* already closed */ } - // 5. Swap: out with the old, in with the recovered temp - await deps.unlink(opts.localPath); + // 5. Swap: rename ALONE replaces the destination atomically. An unlink + // before the rename would leave a crash window where the canonical + // path is empty while the data lives only in the temp file - the UI + // would then report not_found and invite creating a DIFFERENT wallet. await deps.rename(recoverLocalPath, opts.localPath); // 6. Open the recovered wallet at its canonical path diff --git a/app/src/lib/wallet-rpc.ts b/app/src/lib/wallet-rpc.ts index 20eb353..413dd90 100644 --- a/app/src/lib/wallet-rpc.ts +++ b/app/src/lib/wallet-rpc.ts @@ -20,7 +20,12 @@ export function getWalletRpcWsUrl(): string { * wallet_recover). Override via WALLET_RPC_TIMEOUT_MS. */ export function getWalletRpcTimeoutMs(): number { - const raw = Number(process.env.WALLET_RPC_TIMEOUT_MS); + // Empty/whitespace values (a common .env/compose accident) must fall back + // to the default rather than parse as 0 = "timeout disabled" for every + // call. An explicit "0" stays the intentional disable. + const text = (process.env.WALLET_RPC_TIMEOUT_MS ?? '').trim(); + if (text === '') return 30_000; + const raw = Number(text); return Number.isFinite(raw) && raw >= 0 ? raw : 30_000; } @@ -165,7 +170,9 @@ export type WalletOpenResult = | { status: 'ok' } | { status: 'needs_password' } | { status: 'not_found' } - | { status: 'error'; message: string }; + // `error` preserves the thrown value (usually a WalletRpcError) so API + // routes can apply code-based redaction instead of guessing from text. + | { status: 'error'; message: string; error?: unknown }; /** * Returns true if the error indicates no wallet is currently open. @@ -217,7 +224,7 @@ export async function ensureWalletOpen(walletPath = '/home/mintlayer/mintlayer.w return { status: 'not_found' }; } console.error(`[wallet] auto-open failed for ${walletPath}: ${msg}`); - return { status: 'error', message: msg }; + return { status: 'error', message: msg, error: err }; } } diff --git a/app/src/middleware.ts b/app/src/middleware.ts index 0264e3e..5e6c81a 100644 --- a/app/src/middleware.ts +++ b/app/src/middleware.ts @@ -46,8 +46,6 @@ const SECURITY_HEADERS: Record = { */ const CSP_POLICY = buildCsp(); -const CSP_ENABLED = process.env.CSP_ENABLED === 'true'; - export const onRequest = defineMiddleware(async (context, next) => { const { pathname } = new URL(context.request.url); @@ -91,10 +89,16 @@ export const onRequest = defineMiddleware(async (context, next) => { const sessionVersion = getPref('auth.session_version') ?? 0; if (!verifySessionToken(token, sessionVersion)) { - const nextParam = - pathname !== '/' && !pathname.startsWith('/api/') - ? `?next=${encodeURIComponent(pathname)}` - : ''; + if (pathname.startsWith('/api/')) { + // fetch() follows 302s silently, so API consumers would read login + // HTML as a 200 and report "Wallet service error (HTTP 200)" instead + // of an expired session. Browsers navigating pages keep the redirect. + return new Response(JSON.stringify({ error: 'session_expired' }), { + status: 401, + headers: { 'Content-Type': 'application/json' }, + }); + } + const nextParam = pathname !== '/' ? `?next=${encodeURIComponent(pathname)}` : ''; return new Response(null, { status: 302, headers: { Location: `/login${nextParam}` }, @@ -137,12 +141,11 @@ function applySecurityHeaders(response: Response): void { response.headers.set(key, value); } } - // CSP: report-only by default; opt into enforcement with CSP_ENABLED=true. - if (CSP_ENABLED) { - if (!response.headers.has('Content-Security-Policy')) { - response.headers.set('Content-Security-Policy', CSP_POLICY); - } - } else if (!response.headers.has('Content-Security-Policy-Report-Only')) { + // CSP: report-only by default, and CSP_ENABLED=true keeps it that way + // for scripts: the policy still carries 'unsafe-inline' in script-src + // (no nonce plumbing yet), so enforcing it today would change connect + // behavior without containing any injected script. + if (!response.headers.has('Content-Security-Policy-Report-Only')) { response.headers.set('Content-Security-Policy-Report-Only', CSP_POLICY); } } diff --git a/app/src/pages/api/address-tokens.ts b/app/src/pages/api/address-tokens.ts index 674c6e3..a66b4eb 100644 --- a/app/src/pages/api/address-tokens.ts +++ b/app/src/pages/api/address-tokens.ts @@ -47,8 +47,11 @@ export const GET: APIRoute = async ({ url }) => { } try { - // Fan-out to indexer - one request per address, all in parallel - const perAddress = await Promise.all( + // Fan-out to indexer - one request per address, all in parallel. A single + // aborted request or malformed body (proxy 200 with an HTML error page) + // must not discard every address's data - allSettled keeps the rest, + // mirroring the cycle-2 token-authority fix. + const settled = await Promise.allSettled( addresses.map(async (addr) => { const res = await fetch( `${INDEXER_URL}/api/v2/address/${encodeURIComponent(addr)}`, @@ -59,6 +62,12 @@ export const GET: APIRoute = async ({ url }) => { return { addr, tokens: Array.isArray(data.tokens) ? data.tokens : [] }; }), ); + const perAddress = settled.map((s, i) => + s.status === 'fulfilled' + ? s.value + : // Keep every address key present, ordered as requested. + { addr: addresses[i], tokens: [] as IndexerAddressBalance['tokens'] }, + ); // Collect all unique token IDs across all addresses const allTokenIds = [...new Set(perAddress.flatMap(p => p.tokens.map(t => t.token_id)))]; @@ -70,7 +79,9 @@ export const GET: APIRoute = async ({ url }) => { const ENRICH_BATCH = 20; for (let i = 0; i < allTokenIds.length; i += ENRICH_BATCH) { const batch = allTokenIds.slice(i, i + ENRICH_BATCH); - await Promise.all( + // Same partial-health rule: one flaky lookup degrades that token to + // '???' (the caller's fallback) instead of failing the whole page. + await Promise.allSettled( batch.map(async (id) => { // Try fungible token first const tokenRes = await fetch( diff --git a/app/src/pages/api/bitcoin/link-seed.ts b/app/src/pages/api/bitcoin/link-seed.ts index b8ab251..ea9a93d 100644 --- a/app/src/pages/api/bitcoin/link-seed.ts +++ b/app/src/pages/api/bitcoin/link-seed.ts @@ -111,9 +111,12 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json(result); } catch (err) { const status = (err as { status?: number }).status ?? 500; + // 502/504 pass through (parity with wallet.ts): the link mutates state + // and may have SUCCEEDED after the client gave up - flattening to 400 + // invites a retry that 409s and burns a second TOTP. return json( { ok: false, error: (err as Error).message }, - status === 503 ? 503 : status === 409 ? 409 : 400, + status === 503 ? 503 : status === 504 ? 504 : status === 409 ? 409 : status === 502 ? 502 : 400, ); } }; diff --git a/app/src/pages/api/bitcoin/wallet.ts b/app/src/pages/api/bitcoin/wallet.ts index 76a1cf4..ccbb3a4 100644 --- a/app/src/pages/api/bitcoin/wallet.ts +++ b/app/src/pages/api/bitcoin/wallet.ts @@ -39,6 +39,12 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json(result); } catch (err) { const status = (err as { status?: number }).status ?? 500; - return json({ ok: false, error: (err as Error).message }, status === 503 ? 503 : status === 409 ? 409 : 400); + // 502/504 pass through: the sidecar call mutates state and may have + // SUCCEEDED after the client gave up - flattening to 400 invites a + // retry that 409s ("wallet already exists") and burns a second TOTP. + return json( + { ok: false, error: (err as Error).message }, + status === 503 ? 503 : status === 504 ? 504 : status === 409 ? 409 : status === 502 ? 502 : 400, + ); } }; diff --git a/app/src/pages/api/block-stream.ts b/app/src/pages/api/block-stream.ts index c0b191f..4ed5363 100644 --- a/app/src/pages/api/block-stream.ts +++ b/app/src/pages/api/block-stream.ts @@ -32,6 +32,20 @@ export const GET: APIRoute = async ({ request }) => { const encoder = new TextEncoder(); + let heartbeat: ReturnType | undefined; + let upstream: WebSocket | null = null; + + // Shared teardown: the abort listener covers normal client disconnects; + // cancel() covers runtimes that drop the response body without firing + // request.signal (otherwise the upstream ws + heartbeat leak per viewer). + const teardown = () => { + if (heartbeat !== undefined) { + clearInterval(heartbeat); + heartbeat = undefined; + } + upstream?.close(); + }; + const body = new ReadableStream({ start(controller) { const send = (data: Record) => { @@ -52,6 +66,7 @@ export const GET: APIRoute = async ({ request }) => { controller.close(); return; } + upstream = ws; ws.on('open', () => { ws.send(JSON.stringify({ @@ -91,13 +106,16 @@ export const GET: APIRoute = async ({ request }) => { // Comment-style heartbeat: keeps intermediaries from idling out the // connection; ignored by EventSource (nit - low impact, but free). - const heartbeat = setInterval(() => { + heartbeat = setInterval(() => { try { controller.enqueue(encoder.encode(': ping\n\n')); } catch { /* closed */ } }, 30_000); ws.on('error', (err) => { clearInterval(heartbeat); - send({ type: 'error', message: err.message }); + // Generic message only: raw ws errors embed the daemon host/port, + // which must not reach the browser (same redaction rule as rpc.ts). + console.error('[block-stream] upstream error:', err.message); + send({ type: 'error', message: 'Event stream error. Try reloading the page.' }); try { controller.close(); } catch { /* already closed */ } }); @@ -107,11 +125,11 @@ export const GET: APIRoute = async ({ request }) => { }); // Clean up when the browser disconnects - request.signal.addEventListener('abort', () => { - clearInterval(heartbeat); - ws.close(); - try { controller.close(); } catch { /* already closed */ } - }); + request.signal.addEventListener('abort', teardown); + }, + + cancel() { + teardown(); }, }); diff --git a/app/src/pages/api/bridge/ml-intent-tx.test.ts b/app/src/pages/api/bridge/ml-intent-tx.test.ts index 9525eef..fd054cf 100644 --- a/app/src/pages/api/bridge/ml-intent-tx.test.ts +++ b/app/src/pages/api/bridge/ml-intent-tx.test.ts @@ -139,7 +139,8 @@ describe('POST /api/bridge/ml-intent-tx', () => { const res = await POST(makeCtx({ token_id: 'crv', amount: '1', intent })); expect(res.status).toBe(503); const body = (await res.json()) as Record; - expect(body.error).toBe('bridge M2E deposits are not configured'); + // Fail closed: no cross-flavor fallback, the error names the network gap. + expect(body.error).toBe('bridge M2E deposits are not configured for this network'); }); it('returns 503 when the bridge config is unreachable', async () => { diff --git a/app/src/pages/api/bridge/ml-intent-tx.ts b/app/src/pages/api/bridge/ml-intent-tx.ts index 681a9a9..6e40148 100644 --- a/app/src/pages/api/bridge/ml-intent-tx.ts +++ b/app/src/pages/api/bridge/ml-intent-tx.ts @@ -44,14 +44,16 @@ interface AgentsConfig { function pickFlavorConfig(config: AgentsConfig) { const flavors = config.eth_flavor_specific_config ?? {}; - // Flavor keys are network-specific ('' = mainnet, 'sepolia' = testnet) and - // their order is not - pick the one matching the configured network first. + // Flavor keys are network-specific ('' = mainnet, 'sepolia' = testnet). + // Fail closed on a missing flavor: falling back to another flavor's m2e + // config would sign an intent paying a DIFFERENT network's bridge address, + // which this deployment's bridge keys do not control - an unrecoverable + // transfer. The caller turns null into a 503. const preferred = config.network_type === 'mainnet' ? '' : 'sepolia'; - const key = - flavors[preferred]?.m2e != null - ? preferred - : (Object.keys(flavors).find((k) => flavors[k]?.m2e != null) ?? ''); - return { flavor: key, cfg: flavors[key] }; + if (!Object.prototype.hasOwnProperty.call(flavors, preferred) || flavors[preferred]?.m2e == null) { + return null; + } + return { flavor: preferred, cfg: flavors[preferred] }; } /** @@ -118,8 +120,13 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { // for a request the wallet would reject anyway. return json({ ok: false, error: `token ${tokenId} is not bridged` }, 400); } - const { cfg } = pickFlavorConfig(config); - destination = cfg?.m2e?.deposit_tx_destination ?? ''; + const picked = pickFlavorConfig(config); + if (!picked) { + // No cross-flavor fallback: paying the other flavor's bridge address + // would move funds this deployment does not control. + return json({ ok: false, error: 'bridge M2E deposits are not configured for this network' }, 503); + } + destination = picked.cfg?.m2e?.deposit_tx_destination ?? ''; if (!destination) { return json({ ok: false, error: 'bridge M2E deposits are not configured' }, 503); } diff --git a/app/src/pages/api/chain-tip.ts b/app/src/pages/api/chain-tip.ts index 7d36ffb..457df08 100644 --- a/app/src/pages/api/chain-tip.ts +++ b/app/src/pages/api/chain-tip.ts @@ -15,7 +15,19 @@ const TIP_URLS: Record = { export const GET: APIRoute = async () => { const network = (process.env.NETWORK ?? 'mainnet').toLowerCase(); - const url = TIP_URLS[network] ?? TIP_URLS['mainnet']; + const url = TIP_URLS[network]; + + // regtest/signet have no public indexer: silently substituting the + // mainnet tip made dev deployments show a permanently wrong + // "behind/syncing" verdict. The consumers ignore responses without a + // numeric height, so an explicit no-indexer status is a clean degraded + // state there. + if (!url) { + return new Response(JSON.stringify({ error: `no public indexer for network "${network}"` }), { + status: 404, + headers: { 'Content-Type': 'application/json' }, + }); + } try { const res = await fetch(url, { signal: AbortSignal.timeout(5000) }); diff --git a/app/src/pages/api/explorer-tokens.ts b/app/src/pages/api/explorer-tokens.ts index fd275f4..5508b26 100644 --- a/app/src/pages/api/explorer-tokens.ts +++ b/app/src/pages/api/explorer-tokens.ts @@ -123,17 +123,33 @@ async function fetchList(base: string, filter: string): Promise MAX_RESPONSE_BYTES) return null; + if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) { + clearTimeout(timer); + return null; + } // Streamed read with a hard cap - chunked responses without a - // content-length header can't blow the heap. - const text = await readCapped(res, MAX_RESPONSE_BYTES); + // content-length header can't blow the heap. The abort timer stays armed + // until the body is fully read: a server that sends headers promptly + // then stalls the body must not hold the route open for minutes past + // the deadline (the in-flight guard would block every caller). + let text: string | null; + try { + text = await readCapped(res, MAX_RESPONSE_BYTES); + } finally { + clearTimeout(timer); + } if (text === null) return null; let parsed: unknown; diff --git a/app/src/pages/api/features/disable.ts b/app/src/pages/api/features/disable.ts index d030789..e636987 100644 --- a/app/src/pages/api/features/disable.ts +++ b/app/src/pages/api/features/disable.ts @@ -6,6 +6,7 @@ import { isFeatureService, isRequestPending, queueFeatureRequest, + SERVICE_ACTIONS, } from '@/lib/feature-requests'; import { isBitcoinEnabled } from '@/lib/bitcoin-wallet'; @@ -40,6 +41,12 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { } const service = body.service; + // SERVICE_ACTIONS also covers 'web-gui' (upgrade/rollback) - reject the + // mismatched pair BEFORE step-up so no TOTP is burned on it. + if (!(SERVICE_ACTIONS[service] as readonly string[]).includes('disable')) { + return json({ ok: false, error: 'Unknown service' }, 400); + } + // Current-state checks come before step-up: /api/features/status already // exposes this state to any signed-in session, so burning a fresh TOTP for // a redundant click would only hurt. @@ -58,8 +65,12 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json({ ok: false, error: stepUp.error }, stepUp.status); } - if (!(await queueFeatureRequest({ action: 'disable', service }))) { - return json({ ok: false, error: 'A request for this service is already queued' }, 409); + try { + if (!(await queueFeatureRequest({ action: 'disable', service }))) { + return json({ ok: false, error: 'A request for this service is already queued' }, 409); + } + } catch { + return json({ ok: false, error: 'Could not write the request - check the feature-enabler volume.' }, 503); } return json({ ok: true, queued: true, service }, 202); }; diff --git a/app/src/pages/api/features/enable.ts b/app/src/pages/api/features/enable.ts index ef52719..72a4992 100644 --- a/app/src/pages/api/features/enable.ts +++ b/app/src/pages/api/features/enable.ts @@ -2,6 +2,7 @@ import type { APIRoute } from 'astro'; import { json } from '@/lib/api-utils'; import { requireStepUp, totpFromBody } from '@/lib/step-up'; import { + SERVICE_ACTIONS, isBitcoinNetwork, isFeatureEnablerAvailable, isFeatureService, @@ -45,6 +46,14 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { } const service = body.service; + // SERVICE_ACTIONS also covers 'web-gui' (upgrade/rollback) - that flow is + // managed elsewhere. Rejecting it here (before step-up) keeps a mismatched + // action/service pair from burning a TOTP and then failing in + // queueFeatureRequest as a misleading 503. + if (!(SERVICE_ACTIONS[service] as readonly string[]).includes('enable')) { + return json({ ok: false, error: 'Unknown service' }, 400); + } + // Current-state checks come before step-up: /api/features/status already // exposes this state to any signed-in session, so burning a fresh TOTP for // a redundant click would only hurt. @@ -63,18 +72,24 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json({ ok: false, error: stepUp.error }, stepUp.status); } - if (service === 'bitcoin') { - const network = body.network === undefined ? 'mainnet' : body.network; - if (!isBitcoinNetwork(network)) { - return json({ ok: false, error: 'Network must be mainnet, testnet or regtest' }, 400); - } - if (!(await queueFeatureRequest({ action: 'enable', service, network, pruned: body.pruned !== false }))) { - return json({ ok: false, error: 'A request for this service is already queued' }, 409); - } - } else { - if (!(await queueFeatureRequest({ action: 'enable', service }))) { - return json({ ok: false, error: 'A request for this service is already queued' }, 409); + try { + if (service === 'bitcoin') { + const network = body.network === undefined ? 'mainnet' : body.network; + if (!isBitcoinNetwork(network)) { + return json({ ok: false, error: 'Network must be mainnet, testnet or regtest' }, 400); + } + if (!(await queueFeatureRequest({ action: 'enable', service, network, pruned: body.pruned !== false }))) { + return json({ ok: false, error: 'A request for this service is already queued' }, 409); + } + } else { + if (!(await queueFeatureRequest({ action: 'enable', service }))) { + return json({ ok: false, error: 'A request for this service is already queued' }, 409); + } } + } catch { + // A filesystem failure (volume missing or full) must not read as an + // opaque 500 after the 2FA code was consumed. + return json({ ok: false, error: 'Could not write the request - check the feature-enabler volume.' }, 503); } return json({ ok: true, queued: true, service }, 202); diff --git a/app/src/pages/api/features/rollback.ts b/app/src/pages/api/features/rollback.ts index 54cae04..4285389 100644 --- a/app/src/pages/api/features/rollback.ts +++ b/app/src/pages/api/features/rollback.ts @@ -41,8 +41,12 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json({ ok: false, error: stepUp.error }, stepUp.status); } - if (!(await queueFeatureRequest({ action: 'rollback', service: 'web-gui' }))) { - return json({ ok: false, error: 'A request for this service is already queued' }, 409); + try { + if (!(await queueFeatureRequest({ action: 'rollback', service: 'web-gui' }))) { + return json({ ok: false, error: 'A request for this service is already queued' }, 409); + } + } catch { + return json({ ok: false, error: 'Could not write the request - check the feature-enabler volume.' }, 503); } return json({ ok: true, queued: true, service: 'web-gui' }, 202); diff --git a/app/src/pages/api/features/upgrade.ts b/app/src/pages/api/features/upgrade.ts index 5b1a17a..47567d7 100644 --- a/app/src/pages/api/features/upgrade.ts +++ b/app/src/pages/api/features/upgrade.ts @@ -59,15 +59,19 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json({ ok: false, error: stepUp.error }, stepUp.status); } - if ( - !(await queueFeatureRequest({ - action: 'upgrade', - service: 'web-gui', - tag, - ...(typeof body.bitcoind === 'string' ? { bitcoind: body.bitcoind } : {}), - })) - ) { - return json({ ok: false, error: 'An upgrade request is already queued' }, 409); + try { + if ( + !(await queueFeatureRequest({ + action: 'upgrade', + service: 'web-gui', + tag, + ...(typeof body.bitcoind === 'string' ? { bitcoind: body.bitcoind } : {}), + })) + ) { + return json({ ok: false, error: 'An upgrade request is already queued' }, 409); + } + } catch { + return json({ ok: false, error: 'Could not write the request - check the feature-enabler volume.' }, 503); } return json({ ok: true, queued: true, service: 'web-gui' }, 202); diff --git a/app/src/pages/api/ipfs-upload.ts b/app/src/pages/api/ipfs-upload.ts index 6d4ec5f..5932162 100644 --- a/app/src/pages/api/ipfs-upload.ts +++ b/app/src/pages/api/ipfs-upload.ts @@ -16,6 +16,9 @@ import type { APIRoute } from 'astro'; import { getStringPref } from '@/lib/prefs-db'; import { json } from '@/lib/api-utils'; +/** Hard cap for a single pinning-provider upload. */ +const UPLOAD_TIMEOUT_MS = 120_000; + export const POST: APIRoute = async ({ request }) => { // Read per-request so settings changes take effect without restart const provider = getStringPref('ipfs.provider'); @@ -64,12 +67,18 @@ async function uploadToFilebase(file: File, token: string): Promise { let res: Response; try { + // A stalled upload must not hold the request (and its 50MB body) + // open forever. res = await fetch('https://rpc.filebase.io/api/v0/add', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form, + signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS), }); } catch (err) { + if (err instanceof Error && err.name === 'TimeoutError') { + return json({ ok: false, error: { message: 'Filebase upload timed out.' } }, 504); + } return json({ ok: false, error: { message: `Filebase unreachable: ${String(err)}` } }, 502); } @@ -110,8 +119,12 @@ async function uploadToPinata(file: File, jwt: string): Promise { method: 'POST', headers: { Authorization: `Bearer ${jwt}` }, body: pinataForm, + signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS), }); } catch (err) { + if (err instanceof Error && err.name === 'TimeoutError') { + return json({ ok: false, error: { message: 'Pinata upload timed out.' } }, 504); + } return json({ ok: false, error: { message: `Pinata unreachable: ${String(err)}` } }, 502); } diff --git a/app/src/pages/api/passkey/auth-options.test.ts b/app/src/pages/api/passkey/auth-options.test.ts index 56836f9..cf1980f 100644 --- a/app/src/pages/api/passkey/auth-options.test.ts +++ b/app/src/pages/api/passkey/auth-options.test.ts @@ -64,4 +64,42 @@ describe('GET /api/passkey/auth-options', () => { }), ); }); + + it('omits the transport hint for legacy records without one', async () => { + vi.mocked(getCredentials).mockReturnValue([ + { id: 'old1', publicKey: 'pk', counter: 0, name: 'old', createdAt: 1 }, + ]); + await GET(makeCtx()); + expect(generateAuthenticationOptions).toHaveBeenCalledWith( + expect.objectContaining({ + allowCredentials: [{ id: 'old1' }], + }), + ); + }); + + it('replays stored transports so hardware keys are discoverable', async () => { + vi.mocked(getCredentials).mockReturnValue([ + { + id: 'usb1', + publicKey: 'pk', + counter: 0, + name: 'yubikey', + createdAt: 1, + transports: ['usb'], + }, + ]); + await GET(makeCtx()); + expect(generateAuthenticationOptions).toHaveBeenCalledWith( + expect.objectContaining({ + allowCredentials: [{ id: 'usb1', transports: ['usb'] }], + }), + ); + }); + + it('requires user verification to match the verifier default', async () => { + await GET(makeCtx()); + expect(generateAuthenticationOptions).toHaveBeenCalledWith( + expect.objectContaining({ userVerification: 'required' }), + ); + }); }); diff --git a/app/src/pages/api/passkey/auth-options.ts b/app/src/pages/api/passkey/auth-options.ts index 6bffbf6..0de7dbb 100644 --- a/app/src/pages/api/passkey/auth-options.ts +++ b/app/src/pages/api/passkey/auth-options.ts @@ -16,7 +16,7 @@ export const GET: APIRoute = async ({ request, clientAddress }) => { return json({ error: 'Too many requests. Please slow down.' }, 429); } - const rpId = getRpId(request.url); + const rpId = getRpId(request); if (!isValidRpId(rpId)) { return json({ error: 'Passkeys require a DNS hostname.' }, 400); @@ -28,9 +28,16 @@ export const GET: APIRoute = async ({ request, clientAddress }) => { rpID: rpId, allowCredentials: creds.map((c) => ({ id: c.id, - transports: ['internal', 'hybrid'] as AuthenticatorTransport[], + // Replay the transports the key reported at registration. Omitting + // the hint (legacy records) makes browsers probe every transport, so + // USB/NFC keys enrolled before this field existed keep working. + ...(c.transports && c.transports.length > 0 ? { transports: c.transports } : {}), })), - userVerification: 'preferred', + // Verification is required by verifyAuthenticationResponse's default, + // so the ceremony must ask the authenticator for it up front; asking + // for 'preferred' would let non-UV assertions in that then fail + // verification (dead-end loop that burns a TOTP code per retry). + userVerification: 'required', }); const token = createChallenge(options.challenge, 'authentication'); diff --git a/app/src/pages/api/passkey/auth-verify.ts b/app/src/pages/api/passkey/auth-verify.ts index 0fcc5ec..617cc58 100644 --- a/app/src/pages/api/passkey/auth-verify.ts +++ b/app/src/pages/api/passkey/auth-verify.ts @@ -12,7 +12,7 @@ import { } from '@/lib/passkey'; import { generateSessionToken, makeSessionCookieHeader } from '@/lib/auth'; import { getPref } from '@/lib/prefs-db'; -import { json } from '@/lib/api-utils'; +import { json, readJsonWithinLimit, PASSKEY_BODY_LIMIT } from '@/lib/api-utils'; import { checkRpcRateLimit, getClientAddress } from '@/lib/auth'; export const POST: APIRoute = async ({ request, clientAddress }) => { @@ -21,8 +21,8 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json({ error: 'Too many requests. Please slow down.' }, 429); } - const rpId = getRpId(request.url); - const origin = getOrigin(request.url); + const rpId = getRpId(request); + const origin = getOrigin(request); if (!isValidRpId(rpId)) { return json({ error: 'Passkeys require a DNS hostname.' }, 400); @@ -36,10 +36,16 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { }); } - let body: AuthenticationResponseJSON; - try { - body = await request.json(); - } catch { + // Capped before parse: this endpoint is public and request.json() + // buffers the whole body. + const parsed = await readJsonWithinLimit(request, PASSKEY_BODY_LIMIT); + if (!parsed || typeof parsed !== 'object') { + return json({ error: 'Invalid request body.' }, 400); + } + const body: AuthenticationResponseJSON = parsed; + // request.json() parses successfully for JSON literals like `null`; the + // property reads below need a real object. + if (body == null || typeof body !== 'object') { return json({ error: 'Invalid request body.' }, 400); } @@ -63,7 +69,7 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { id: storedCred.id, publicKey: Buffer.from(storedCred.publicKey, 'base64url'), counter: storedCred.counter, - transports: ['internal', 'hybrid'] as AuthenticatorTransport[], + ...(storedCred.transports ? { transports: storedCred.transports } : {}), }, }); } catch (err) { diff --git a/app/src/pages/api/passkey/register-options.ts b/app/src/pages/api/passkey/register-options.ts index f8ef8d3..67e9270 100644 --- a/app/src/pages/api/passkey/register-options.ts +++ b/app/src/pages/api/passkey/register-options.ts @@ -7,11 +7,11 @@ import { isValidRpId, makeChallengeCookieHeader, } from '@/lib/passkey'; -import { json } from '@/lib/api-utils'; +import { json, readJsonWithinLimit, PASSKEY_BODY_LIMIT } from '@/lib/api-utils'; import { requireStepUp } from '@/lib/step-up'; export const POST: APIRoute = async ({ request, clientAddress }) => { - const rpId = getRpId(request.url); + const rpId = getRpId(request); if (!isValidRpId(rpId)) { return json({ error: 'Passkeys require a DNS hostname, not an IP address.' }, 400); @@ -23,11 +23,10 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { // issued: challenges are single-use and short-lived, so register-verify can // only complete when this check passed moments before. Burning up front also // means a mistyped code never strands the user mid-ceremony. - let totpCode = ''; - try { - const body = (await request.json()) as { totp_code?: unknown }; - totpCode = typeof body.totp_code === 'string' ? body.totp_code : ''; - } catch { + // Capped before parse: public step-up endpoint, buffered body. + const body = await readJsonWithinLimit<{ totp_code?: unknown }>(request, PASSKEY_BODY_LIMIT); + const totpCode = typeof body?.totp_code === 'string' ? body.totp_code : ''; + if (body === null) { return json({ error: 'Invalid request body.' }, 400); } const stepUp = requireStepUp(totpCode, request, clientAddress); @@ -45,11 +44,13 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { attestationType: 'none', excludeCredentials: existingCreds.map((c) => ({ id: c.id, - transports: ['internal', 'hybrid'] as AuthenticatorTransport[], + ...(c.transports && c.transports.length > 0 ? { transports: c.transports } : {}), })), authenticatorSelection: { residentKey: 'preferred', - userVerification: 'preferred', + // verifyRegistrationResponse defaults to requiring user verification; + // request it here too so the authenticator actually performs it. + userVerification: 'required', }, }); diff --git a/app/src/pages/api/passkey/register-verify.ts b/app/src/pages/api/passkey/register-verify.ts index 0a2dc30..cb2400b 100644 --- a/app/src/pages/api/passkey/register-verify.ts +++ b/app/src/pages/api/passkey/register-verify.ts @@ -1,6 +1,6 @@ import type { APIRoute } from 'astro'; import { verifyRegistrationResponse } from '@simplewebauthn/server'; -import type { RegistrationResponseJSON } from '@simplewebauthn/server'; +import type { RegistrationResponseJSON, AuthenticatorTransport } from '@simplewebauthn/server'; import { getCredentials, saveCredentials, @@ -13,8 +13,8 @@ import { import { json } from '@/lib/api-utils'; export const POST: APIRoute = async ({ request }) => { - const rpId = getRpId(request.url); - const origin = getOrigin(request.url); + const rpId = getRpId(request); + const origin = getOrigin(request); if (!isValidRpId(rpId)) { return json({ error: 'Passkeys require a DNS hostname.' }, 400); @@ -42,8 +42,14 @@ export const POST: APIRoute = async ({ request }) => { } catch { return json({ error: 'Invalid request body.' }, 400); } + // request.json() parses JSON literals like `null` fine; the reads below + // need a real object. + if (body == null || typeof body !== 'object') { + return json({ error: 'Invalid request body.' }, 400); + } - const credentialName = (body.name ?? 'Passkey').slice(0, 64).trim() || 'Passkey'; + const credentialName = + (typeof body.name === 'string' ? body.name : 'Passkey').slice(0, 64).trim() || 'Passkey'; let verification; try { @@ -74,6 +80,15 @@ export const POST: APIRoute = async ({ request }) => { counter: credential.counter, name: credentialName, createdAt: Date.now(), + // Remember how this key connects (usb/nfc/ble/internal/hybrid/cable) + // so auth-options can advertise it; hardcoding a subset here used to + // make enrolled USB/NFC keys unlistable at sign-in. Unknown future + // transport names are filtered out so the stored value stays a plain + // AuthenticatorTransport[]. + transports: credential.transports?.filter( + (t): t is AuthenticatorTransport => + ['usb', 'nfc', 'ble', 'internal', 'hybrid'].includes(t), + ), }); saveCredentials(creds); diff --git a/app/src/pages/api/plugins/[id]/uninstall.ts b/app/src/pages/api/plugins/[id]/uninstall.ts index 0ef9335..d9264de 100644 --- a/app/src/pages/api/plugins/[id]/uninstall.ts +++ b/app/src/pages/api/plugins/[id]/uninstall.ts @@ -34,7 +34,7 @@ export const POST: APIRoute = async ({ params, request, clientAddress }) => { } try { - uninstallPlugin(id); + await uninstallPlugin(id); return json({ ok: true }); } catch (err) { return json({ ok: false, error: (err as Error).message }, 422); diff --git a/app/src/pages/api/rpc.test.ts b/app/src/pages/api/rpc.test.ts index e4b2fbe..85d4e8e 100644 --- a/app/src/pages/api/rpc.test.ts +++ b/app/src/pages/api/rpc.test.ts @@ -142,10 +142,26 @@ describe('allowlist enforcement - allowed methods', () => { }); it.each(ALLOWED_METHODS)('allows method "%s"', async (method) => { - const { status, json } = await postRpc({ method, params: {} }); + // wallet_set_lookahead_size is server-clamped to [0, 10000]; empty + // params would be rejected before the proxy call. + const params = method === 'wallet_set_lookahead_size' ? { lookahead_size: 100 } : {}; + const { status, json } = await postRpc({ method, params }); expect(status).toBe(200); expect(json).toMatchObject({ ok: true }); }); + + it('clamps wallet_set_lookahead_size to a sane maximum', async () => { + const tooBig = await postRpc({ method: 'wallet_set_lookahead_size', params: { lookahead_size: 999999 } }); + expect(tooBig.status).toBe(400); + expect(rpcCall).not.toHaveBeenCalled(); + + const nonInt = await postRpc({ method: 'wallet_set_lookahead_size', params: { lookahead_size: 'big' } }); + expect(nonInt.status).toBe(400); + + const ok = await postRpc({ method: 'wallet_set_lookahead_size', params: { lookahead_size: 250 } }); + expect(ok.status).toBe(200); + expect(rpcCall).toHaveBeenCalledWith('wallet_set_lookahead_size', { lookahead_size: 250 }); + }); }); describe('allowlist enforcement - blocked methods', () => { @@ -293,11 +309,30 @@ describe('error paths', () => { expect(errBody.message).toBe('The wallet service is unavailable. Check that all services are running.'); vi.mocked(rpcCall).mockRejectedValueOnce( - new WalletRpcError('Not enough funds to cover transaction', -32005), + // The daemon maps all application errors (wallet closed, not enough + // funds, bad ids) to code -1 - the code real toasts depend on. + new WalletRpcError('Not enough funds to cover transaction', -1), ); const forwarded = await postRpc({ method: 'wallet_info', params: {} }); - const fwdBody = (forwarded.json as { error: { message: string } }).error; + const fwdBody = (forwarded.json as { error: { message: string; code: number } }).error; expect(fwdBody.message).toBe('Not enough funds to cover transaction'); + expect(fwdBody.code).toBe(-1); + }); + + it('redacts the transport band and non-negative codes even when shaped as WalletRpcError', async () => { + vi.mocked(rpcCall).mockRejectedValueOnce( + new WalletRpcError('HTTP 401 Unauthorized from wallet-rpc-daemon', 401), + ); + const auth = await postRpc({ method: 'wallet_info', params: {} }); + expect((auth.json as { error: { message: string } }).error.message) + .toBe('The wallet service is unavailable. Check that all services are running.'); + + vi.mocked(rpcCall).mockRejectedValueOnce( + new WalletRpcError('No wallet opened', -32000), + ); + const transport = await postRpc({ method: 'wallet_info', params: {} }); + expect((transport.json as { error: { message: string } }).error.message) + .toBe('The wallet service is unavailable. Check that all services are running.'); }); it('returns Content-Type: application/json on error responses', async () => { diff --git a/app/src/pages/api/rpc.ts b/app/src/pages/api/rpc.ts index 4f77275..8677ecf 100644 --- a/app/src/pages/api/rpc.ts +++ b/app/src/pages/api/rpc.ts @@ -33,6 +33,18 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { ? (params as Record) : {}; + // A huge lookahead makes the daemon generate massive address batches - + // persistent wallet-file bloat that outlives the session. Clamp it here: + // the daemon treats the field as a plain unbounded number and this + // method is the only allowlisted write with no natural bound. + if (method === 'wallet_set_lookahead_size') { + const size = Number((rpcParams as Record).lookahead_size); + if (!Number.isInteger(size) || size < 0 || size > 10_000) { + return jsonError('lookahead_size must be an integer in [0, 10000]', 400); + } + (rpcParams as Record).lookahead_size = size; + } + try { const result = await rpcCall(method, rpcParams); return new Response(JSON.stringify({ ok: true, result }), { @@ -41,14 +53,17 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { }); } catch (err) { const code = err instanceof WalletRpcError ? err.code : -1; - // Transport-level failures (-32000/-32001) and daemon 5xx carry internal - // details (daemon URL, HTTP status text) in their messages - never forward - // them to the browser. The full error is logged above for server-side - // diagnostics; the client gets an actionable, information-free message. - const message = - err instanceof WalletRpcError && code !== -32000 && code !== -32001 && code < 500 - ? err.message - : 'The wallet service is unavailable. Check that all services are running.'; + // Forward daemon *application* errors: the wallet daemon maps them all + // to code -1 (wallet closed, not enough funds, bad pool/order id, ...). + // Also forward the JSON-RPC protocol band. -32000/-32001 are the + // transport band (daemon URL in the message); positive codes are HTTP + // statuses from the daemon (401/404 on bad credentials, 5xx) and carry + // internal details, so both stay redacted. + const forwardable = + err instanceof WalletRpcError && + code !== -32000 && code !== -32001 && code < 0 && + (code === -1 || (code >= -32700 && code <= -32002)); + const message = forwardable ? err.message : 'The wallet service is unavailable. Check that all services are running.'; console.error('[rpc-proxy]', method, err); return new Response( JSON.stringify({ ok: false, error: { message, code } }), diff --git a/app/src/pages/api/scan-issued-tokens.test.ts b/app/src/pages/api/scan-issued-tokens.test.ts index 2c35955..5886a22 100644 --- a/app/src/pages/api/scan-issued-tokens.test.ts +++ b/app/src/pages/api/scan-issued-tokens.test.ts @@ -55,12 +55,12 @@ describe('GET /api/scan-issued-tokens', () => { expect(body).toEqual({ ok: true, fungible: [], nfts: [] }); }); - it('returns empty arrays when account_utxos throws', async () => { + it('returns ok:false when account_utxos throws (broken backend is not an empty wallet)', async () => { mockRpcCall.mockRejectedValueOnce(new Error('wallet not open')); const res = await GET({} as Parameters[0]); const body = await res.json() as Record; - expect(res.status).toBe(200); - expect(body).toEqual({ ok: true, fungible: [], nfts: [] }); + expect(res.status).toBe(502); + expect(body).toMatchObject({ ok: false, fungible: [], nfts: [] }); }); it('skips unrecognized output types', async () => { diff --git a/app/src/pages/api/scan-issued-tokens.ts b/app/src/pages/api/scan-issued-tokens.ts index 350406c..b8038aa 100644 --- a/app/src/pages/api/scan-issued-tokens.ts +++ b/app/src/pages/api/scan-issued-tokens.ts @@ -27,13 +27,11 @@ const TOKEN_ID_HRP: Record = { mainnet: 'mmltk', testnet: 'tmltk', regtest: 'rmltk', - signet: 'smltk', }; -const hrp = TOKEN_ID_HRP[NETWORK] ?? 'mmltk'; // ── Token ID computation ────────────────────────────────────────────────────── -function computeTokenId(prevTxIdHex: string, prevOutputIndex: number): string | null { +function computeTokenId(hrp: string, prevTxIdHex: string, prevOutputIndex: number): string | null { try { const txIdBytes = Buffer.from(prevTxIdHex, 'hex'); if (txIdBytes.length !== 32) return null; @@ -47,7 +45,6 @@ function computeTokenId(prevTxIdHex: string, prevOutputIndex: number): string | return null; } } - // ── UTXO types ──────────────────────────────────────────────────────────────── interface UtxoEntry { @@ -97,6 +94,13 @@ interface TxGetResult { // ── Endpoint ────────────────────────────────────────────────────────────────── export const GET: APIRoute = async () => { + // Fail fast on an unknown NETWORK instead of silently bech32-encoding + // token ids with the wrong HRP (would produce ids that mismatch every + // real authoritative token - same rule as chain-tip's network guard). + const hrp = TOKEN_ID_HRP[NETWORK]; + if (!hrp) { + return json({ ok: false, error: `Unsupported NETWORK '${NETWORK}'` }, 400); + } try { const utxos = await rpcCall('account_utxos', { account: 0 }); @@ -144,15 +148,18 @@ export const GET: APIRoute = async () => { const prevOutputIndex = firstUtxoInput.Utxo.index; if (!prevTxIdHex || prevOutputIndex === undefined) continue; - const tokenId = computeTokenId(prevTxIdHex, prevOutputIndex); + const tokenId = computeTokenId(hrp, prevTxIdHex, prevOutputIndex); if (!tokenId) continue; fungibleResult.push({ tokenId, ticker, decimals }); } return json({ ok: true, fungible: fungibleResult, nfts: nftResult }, 200); - } catch { - // Best-effort - never crash the page - return json({ ok: true, fungible: [], nfts: [] }, 200); + } catch (err) { + // A broken backend must not masquerade as "no issuances": transport + // failures return ok:false so the UI can show an error state instead + // of an empty wallet. The original is logged for diagnosis. + console.error('[scan-issued-tokens]', err); + return json({ ok: false, error: 'The wallet service is unavailable.', fungible: [], nfts: [] }, 502); } }; diff --git a/app/src/pages/api/send.test.ts b/app/src/pages/api/send.test.ts index c10a921..4b5a692 100644 --- a/app/src/pages/api/send.test.ts +++ b/app/src/pages/api/send.test.ts @@ -44,12 +44,17 @@ function makeContext(request: Request): APIContext { } const validBody = { - address: 'mtc1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjkzs', + // Valid bech32m address (live Mintlayer testnet fixture). The route + // pre-decodes the address against the configured network's HRP before + // burning a TOTP code, so a fake string would 400 before step-up. + address: 'tmt1q9rlgx4dsse920z35xh5d8s5ydlj3xl7gqeze89c', amount: '1.5', asset_type: 'ml', totp_code: '123456', }; +process.env.NETWORK = 'testnet'; + describe('POST /api/send', () => { beforeEach(() => { vi.clearAllMocks(); diff --git a/app/src/pages/api/send.ts b/app/src/pages/api/send.ts index 1659d59..34abb16 100644 --- a/app/src/pages/api/send.ts +++ b/app/src/pages/api/send.ts @@ -3,6 +3,7 @@ import { json } from '@/lib/api-utils'; import { rpcCall, WalletRpcError } from '@/lib/wallet-rpc'; import { requireStepUp, totpFromBody } from '@/lib/step-up'; import { isValidAmount } from '@/lib/validation'; +import { decode as bech32Decode, hrpForNetwork } from '@/lib/bech32'; /** * POST /api/send - send ML coins or tokens (incl. NFTs). @@ -53,6 +54,22 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { if (assetType === 'token' && !tokenId) { return json({ ok: false, error: 'token_id is required for token sends' }, 400); } + // Knowable failures must not consume a code: decode the pasted address + // structurally and check its HRP against this deployment's network BEFORE + // step-up. The daemon stays authoritative for checksum and semantic checks + // (this only rejects strings that could never be valid here). + try { + const expectedHrp = hrpForNetwork('ml', (process.env.NETWORK ?? 'mainnet').toLowerCase()); + const { prefix } = bech32Decode(address, 'bech32m'); + if (expectedHrp && prefix !== expectedHrp) { + return json( + { ok: false, error: `Destination address looks like a "${prefix}" address - this network expects "${expectedHrp}" addresses` }, + 400, + ); + } + } catch { + return json({ ok: false, error: 'Destination address is not a valid Mintlayer address' }, 400); + } const stepUp = requireStepUp(totpFromBody(body), request, clientAddress as string | undefined); if (!stepUp.ok) { @@ -82,7 +99,20 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { // broadcast. Flag it so the UI can tell the user to enter a FRESH code // instead of silently retrying the dead one. if (err instanceof WalletRpcError) { - return json({ ok: false, error: err.message, code_consumed: true }, 502); + // Transport-class failures (-32000/-32001/5xx, and daemon HTTP status + // codes) carry the daemon URL in their message - never forward those + // to the browser (mirror of the rpc.ts proxy redaction). Daemon + // user-actionable messages (insufficient funds, amount too small) + // still pass through. + // Positive codes are daemon HTTP statuses (401/404 on bad credentials + // carry the daemon URL in the message) - redact them too, not just 5xx. + const transport = err.code === -32000 || err.code === -32001 || err.code >= 400; + if (transport) console.error('[send]', err.message); + return json({ + ok: false, + error: transport ? 'The wallet service is unavailable. Check that all services are running.' : err.message, + code_consumed: true, + }, 502); } console.error('[send]', err); return json({ ok: false, error: 'Send failed', code_consumed: true }, 500); diff --git a/app/src/pages/api/settings/ipfs.test.ts b/app/src/pages/api/settings/ipfs.test.ts index 2ab5848..30bf0e5 100644 --- a/app/src/pages/api/settings/ipfs.test.ts +++ b/app/src/pages/api/settings/ipfs.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; vi.mock('@/lib/prefs-db', () => ({ setPref: vi.fn(), + getStringPref: vi.fn(() => ''), })); vi.mock('@/lib/step-up', () => ({ diff --git a/app/src/pages/api/settings/ipfs.ts b/app/src/pages/api/settings/ipfs.ts index 358f995..add8480 100644 --- a/app/src/pages/api/settings/ipfs.ts +++ b/app/src/pages/api/settings/ipfs.ts @@ -1,12 +1,13 @@ import type { APIRoute } from 'astro'; -import { setPref } from '@/lib/prefs-db'; -import { json, readFormData } from '@/lib/api-utils'; +import { setPref, getStringPref } from '@/lib/prefs-db'; +import { json, LOGIN_BODY_LIMIT, readFormWithinLimit } from '@/lib/api-utils'; import { requireStepUp } from '@/lib/step-up'; const VALID_PROVIDERS = new Set(['filebase', 'pinata', '']); export const POST: APIRoute = async ({ request, clientAddress }) => { - const form = await readFormData(request); + // Body cap: request.formData() buffers the whole body before validation. + const form = await readFormWithinLimit(request, LOGIN_BODY_LIMIT); if (!form) return json({ ok: false, error: 'Invalid request body' }, 400); // Coerce non-strings (e.g. File parts) to '' so they fail validation cleanly. @@ -28,9 +29,23 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json({ ok: false, error: stepUp.error }, stepUp.status); } + // Secrets are write-only (same contract as the settings page): blank input + // keeps the stored key, so a "just change the provider" call cannot wipe it. + const storedFilebase = getStringPref('ipfs.filebase_token') ?? ''; + const storedPinata = getStringPref('ipfs.pinata_jwt') ?? ''; + if (provider === 'filebase' && !filebaseToken && !storedFilebase) { + return json({ ok: false, error: 'Paste your Filebase access key - pinning cannot work without it.' }, 400); + } + if (provider === 'pinata' && !pinataJwt && !storedPinata) { + return json({ ok: false, error: 'Paste your Pinata JWT - pinning cannot work without it.' }, 400); + } + setPref('ipfs.provider', provider); - setPref('ipfs.filebase_token', filebaseToken); - setPref('ipfs.pinata_jwt', pinataJwt); + // Disabling IPFS also clears any stored provider keys - keeping them on + // disk while "Disabled" protects nothing and leaves third-party + // credentials behind. + setPref('ipfs.filebase_token', provider === '' ? '' : (filebaseToken || storedFilebase)); + setPref('ipfs.pinata_jwt', provider === '' ? '' : (pinataJwt || storedPinata)); return json({ ok: true }, 200); }; diff --git a/app/src/pages/api/settings/password.test.ts b/app/src/pages/api/settings/password.test.ts index dec10c0..ecc6452 100644 --- a/app/src/pages/api/settings/password.test.ts +++ b/app/src/pages/api/settings/password.test.ts @@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; vi.mock('@/lib/auth', () => ({ verifyPassword: vi.fn(), hashPassword: vi.fn(), + getClientAddress: vi.fn(() => '127.0.0.1'), })); vi.mock('@/lib/prefs-db', () => ({ diff --git a/app/src/pages/api/settings/password.ts b/app/src/pages/api/settings/password.ts index afb55e8..ce206f0 100644 --- a/app/src/pages/api/settings/password.ts +++ b/app/src/pages/api/settings/password.ts @@ -1,19 +1,24 @@ import type { APIRoute } from 'astro'; import { resolvePasswordChange, applyPasswordChange } from '@/lib/password-change'; -import { json, readFormData } from '@/lib/api-utils'; +import { json, LOGIN_BODY_LIMIT, readFormWithinLimit } from '@/lib/api-utils'; +import { getClientAddress } from '@/lib/auth'; -export const POST: APIRoute = async ({ request }) => { - const form = await readFormData(request); +export const POST: APIRoute = async ({ request, clientAddress }) => { + const form = await readFormWithinLimit(request, LOGIN_BODY_LIMIT); if (!form) return json({ ok: false, error: 'Invalid request body' }, 400); // form.get() returns string | File | null; a File part would bypass the length // check and crash hashPassword. Coerce non-strings to '' so they fail cleanly. const str = (v: FormDataEntryValue | null) => (typeof v === 'string' ? v : ''); - const decision = await resolvePasswordChange({ - currentPassword: str(form.get('current_password')), - newPassword: str(form.get('new_password')), - confirmPassword: str(form.get('confirm_password')), - }); + const decision = await resolvePasswordChange( + { + currentPassword: str(form.get('current_password')), + newPassword: str(form.get('new_password')), + confirmPassword: str(form.get('confirm_password')), + }, + // Throttle wrong current-password guesses like the login limiter does. + getClientAddress(request, clientAddress), + ); if (!decision.ok) { return json({ ok: false, error: decision.error }, decision.httpStatus); diff --git a/app/src/pages/api/settings/reset-2fa.ts b/app/src/pages/api/settings/reset-2fa.ts index 09025da..4175287 100644 --- a/app/src/pages/api/settings/reset-2fa.ts +++ b/app/src/pages/api/settings/reset-2fa.ts @@ -2,10 +2,10 @@ import type { APIRoute } from 'astro'; import { generateTotpSecret, getClientAddress } from '@/lib/auth'; import { verifyAndBurnTotpCode } from '@/lib/step-up'; import { getStringPref, setPref } from '@/lib/prefs-db'; -import { json, readFormData } from '@/lib/api-utils'; +import { json, LOGIN_BODY_LIMIT, readFormWithinLimit } from '@/lib/api-utils'; export const POST: APIRoute = async ({ request, clientAddress }) => { - const form = await readFormData(request); + const form = await readFormWithinLimit(request, LOGIN_BODY_LIMIT); if (!form) return json({ ok: false, error: 'Invalid request body' }, 400); // Coerce non-strings (e.g. File parts) to '' so they fail validation cleanly diff --git a/app/src/pages/api/settings/telegram.test.ts b/app/src/pages/api/settings/telegram.test.ts index 8cb4437..08da960 100644 --- a/app/src/pages/api/settings/telegram.test.ts +++ b/app/src/pages/api/settings/telegram.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; vi.mock('@/lib/prefs-db', () => ({ setPref: vi.fn(), + getStringPref: vi.fn(() => ''), })); vi.mock('@/lib/telegram', () => ({ diff --git a/app/src/pages/api/settings/telegram.ts b/app/src/pages/api/settings/telegram.ts index 7fc9380..1036175 100644 --- a/app/src/pages/api/settings/telegram.ts +++ b/app/src/pages/api/settings/telegram.ts @@ -1,11 +1,12 @@ import type { APIRoute } from 'astro'; -import { setPref } from '@/lib/prefs-db'; +import { setPref, getStringPref } from '@/lib/prefs-db'; import { sendTelegramMessage } from '@/lib/telegram'; -import { json, readFormData } from '@/lib/api-utils'; +import { json, LOGIN_BODY_LIMIT, readFormWithinLimit } from '@/lib/api-utils'; import { requireStepUp } from '@/lib/step-up'; export const POST: APIRoute = async ({ request, clientAddress }) => { - const form = await readFormData(request); + // Body cap: request.formData() buffers the whole body before validation. + const form = await readFormWithinLimit(request, LOGIN_BODY_LIMIT); if (!form) return json({ ok: false, error: 'Invalid request body' }, 400); // Coerce non-strings (e.g. File parts) to '' so they fail validation cleanly. @@ -15,9 +16,20 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { const test = form.get('test') === '1'; const totpCode = str(form.get('totp_code')); - if (!botToken || !chatId) { + // Blank fields keep the stored values (same contract as the settings + // page) - a chat-id-only update must not wipe the stored bot token. + const effToken = botToken || getStringPref('telegram.bot_token') || ''; + const effChatId = chatId || getStringPref('telegram.chat_id') || ''; + + if (!effToken || !effChatId) { return json({ ok: false, error: 'Bot token and chat ID are required' }, 400); } + // Digits only: negative group-chat IDs are refused because every group + // member could run /balance and /address against the bot and read wallet + // data (same rule as the settings page handler). + if (!/^[0-9]{1,20}$/.test(effChatId)) { + return json({ ok: false, error: 'Chat ID must be a numeric user or channel ID (group chats are not supported)' }, 400); + } // Changing the notification channel redirects every wallet alert (balances, // incoming funds, receive addresses) - same sensitivity class as a password @@ -27,12 +39,12 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { return json({ ok: false, error: stepUp.error }, stepUp.status); } - setPref('telegram.bot_token', botToken); - setPref('telegram.chat_id', chatId); + setPref('telegram.bot_token', effToken); + setPref('telegram.chat_id', effChatId); if (test) { try { - await sendTelegramMessage(botToken, chatId, '✅ Test message from Mintlayer Nexus - Telegram notifications are working.'); + await sendTelegramMessage(effToken, effChatId, '✅ Test message from Mintlayer Nexus - Telegram notifications are working.'); } catch (err) { return json({ ok: false, error: `Saved, but test message failed: ${(err as Error).message}` }, 200); } diff --git a/app/src/pages/api/stake-trade.ts b/app/src/pages/api/stake-trade.ts index dfb396c..26bd6b7 100644 --- a/app/src/pages/api/stake-trade.ts +++ b/app/src/pages/api/stake-trade.ts @@ -36,6 +36,7 @@ const ACTIONS = new Set([ 'order_create', 'order_fill', 'order_conclude', + 'order_freeze', ]); const MAX_BATCH = 5; @@ -45,6 +46,11 @@ const MAX_BATCH = 5; // before a code is burned. const ID_RE = /^[a-z0-9]{10,120}$/i; const DECIMAL_RE = /^\d{1,20}(\.\d{1,18})?$/; +// The native coin carries 11 decimals (1 ML = 10^11 atoms, consensus +// conventions). ML-denominated amounts are pre-burn validated against 11 so +// an over-precise value 400s here instead of dying daemon-side after the +// code check. Token legs keep the 0-18 token decimal range. +const COIN_DECIMALS = 11; function isStr(v: unknown, re: RegExp): boolean { return typeof v === 'string' && re.test(v); @@ -59,12 +65,23 @@ function isAmountField(v: unknown): boolean { isValidAmount((v as Params).decimal as string, 18); } +// ML-denominated variant: the coin's own precision cap applies. +function isMlAmount(v: unknown): boolean { + return isObj(v) && typeof (v as Params).decimal === 'string' && + isValidAmount((v as Params).decimal as string, COIN_DECIMALS); +} + // Order legs carry either a decimal or an atom amount (NFTs trade in atoms). -function isCoinAmount(v: unknown): boolean { +// maxDecimals differs per leg type: Coin legs are ML (11), token legs use +// the token's own 0-18 range. +function isCoinAmount(v: unknown, maxDecimals: number): boolean { if (!isObj(v)) return false; const a = v as Params; - if (typeof a.decimal === 'string') return isValidAmount(a.decimal, 18); - return typeof a.atoms === 'string' && /^\d{1,40}$/.test(a.atoms); + if (typeof a.decimal === 'string') return isValidAmount(a.decimal, maxDecimals); + // Atoms path must be a positive integer string: a zero amount is rejected + // daemon-side as a zero-value order, which would burn a TOTP code on a + // knowable 400 (the decimal path already enforces > 0 via isValidAmount). + return typeof a.atoms === 'string' && /^[1-9][0-9]{0,39}$/.test(a.atoms); } // give/ask leg: Coin (ML) or Token (id + amount) @@ -72,12 +89,12 @@ function isOrderLeg(v: unknown): boolean { if (!isObj(v)) return false; const leg = v as Params; if (leg.type === 'Coin') { - return isObj(leg.content) && isCoinAmount((leg.content as Params).amount); + return isObj(leg.content) && isCoinAmount((leg.content as Params).amount, COIN_DECIMALS); } if (leg.type === 'Token') { if (!isObj(leg.content)) return false; const c = leg.content as Params; - return isStr(c.id, ID_RE) && isCoinAmount(c.amount); + return isStr(c.id, ID_RE) && isCoinAmount(c.amount, 18); } return false; } @@ -96,13 +113,13 @@ function validateParams(action: string, p: Params): string | null { case 'delegation_stake': { if (p.account !== 0) return 'account must be 0'; if (!isStr(p.delegation_id, ID_RE)) return 'delegation_id is required'; - if (!isAmountField(p.amount)) return 'amount is invalid'; + if (!isMlAmount(p.amount)) return 'amount is invalid'; return null; } case 'delegation_withdraw': { if (p.account !== 0) return 'account must be 0'; if (!isStr(p.delegation_id, ID_RE)) return 'delegation_id is required'; - if (!isAmountField(p.amount)) return 'amount is invalid'; + if (!isMlAmount(p.amount)) return 'amount is invalid'; if (!isStr(p.address, ID_RE)) return 'address is required'; return null; } @@ -114,22 +131,22 @@ function validateParams(action: string, p: Params): string | null { } case 'staking_create_pool': { if (p.account !== 0) return 'account must be 0'; - if (!isAmountField(p.amount)) return 'amount is invalid'; - if (!isObj(p.cost_per_block) || typeof (p.cost_per_block as Params).decimal !== 'string' || - !DECIMAL_RE.test((p.cost_per_block as Params).decimal as string)) return 'cost_per_block is invalid'; + if (!isMlAmount(p.amount)) return 'amount is invalid'; + // ML per block: the coin precision cap applies here too. + if (!isMlAmount(p.cost_per_block)) return 'cost_per_block is invalid'; if (typeof p.margin_ratio_per_thousand !== 'string' || !DECIMAL_RE.test(p.margin_ratio_per_thousand) || parseFloat(p.margin_ratio_per_thousand) <= 0 || parseFloat(p.margin_ratio_per_thousand) > 1000) return 'margin_ratio_per_thousand must be a ratio in (0, 1000]'; if (!isStr(p.decommission_address, ID_RE)) return 'decommission_address is required'; - if (p.staker_address !== null) return 'staker_address must be null'; - if (p.vrf_public_key !== null) return 'vrf_public_key must be null'; + if (p.staker_address !== undefined && p.staker_address !== null) return 'staker_address must be null'; + if (p.vrf_public_key !== undefined && p.vrf_public_key !== null) return 'vrf_public_key must be null'; return null; } case 'staking_decommission_pool': { if (p.account !== 0) return 'account must be 0'; if (!isStr(p.pool_id, ID_RE)) return 'pool_id is required'; - if (p.output_address !== null) return 'output_address must be null'; + if (p.output_address !== undefined && p.output_address !== null) return 'output_address must be null'; return null; } case 'order_create': { @@ -142,13 +159,23 @@ function validateParams(action: string, p: Params): string | null { case 'order_fill': { if (p.account !== 0) return 'account must be 0'; if (!isStr(p.order_id, ID_RE)) return 'order_id is required'; + // Denominated in the ASK leg's currency, which may be a token with + // up to 18 decimals - the order itself is not loaded here, so the + // generic (looser) bound is the only correct pre-burn check. if (!isAmountField(p.fill_amount_in_ask_currency)) return 'fill amount is invalid'; - if (p.output_address !== null) return 'output_address must be null'; + if (p.output_address !== undefined && p.output_address !== null) return 'output_address must be null'; return null; } case 'order_conclude': { if (p.account !== 0) return 'account must be 0'; if (!isStr(p.order_id, ID_RE)) return 'order_id is required'; + if (p.output_address !== undefined && p.output_address !== null) return 'output_address must be null'; + return null; + } + case 'order_freeze': { + if (p.account !== 0) return 'account must be 0'; + if (!isStr(p.order_id, ID_RE)) return 'order_id is required'; + if (p.output_address !== undefined && p.output_address !== null) return 'output_address must be null'; return null; } default: @@ -196,6 +223,23 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { } } + // The daemon's jsonrpsee layer decodes named params into structs with no + // field defaults: `options` is REQUIRED on every tx method and optional + // address fields must still be PRESENT as null. Older UI call sites omit + // them, which made cancel/conclude/decommission fail with "missing field + // options" AFTER the TOTP code was burned. Inject the safe defaults here + // so a knowable daemon rejection never consumes a code. + for (const item of items) { + if (item.params.options === undefined) item.params.options = {}; + if (item.action === 'staking_create_pool') { + if (item.params.staker_address === undefined) item.params.staker_address = null; + if (item.params.vrf_public_key === undefined) item.params.vrf_public_key = null; + } + if (item.action === 'staking_decommission_pool' || item.action === 'order_fill' || item.action === 'order_conclude') { + if (item.params.output_address === undefined) item.params.output_address = null; + } + } + const stepUp = requireStepUp(totpFromBody(body), request, clientAddress as string | undefined); if (!stepUp.ok) { return json({ ok: false, error: stepUp.error }, stepUp.status); @@ -217,7 +261,9 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { // their message - never forward those to the browser (mirror of the // rpc.ts proxy redaction). Daemon user-actionable messages (insufficient // funds, orphaned transactions) still pass through. - const transport = err.code === -32000 || err.code === -32001 || err.code >= 500; + // Positive codes are daemon HTTP statuses (401/404 on bad credentials + // carry the daemon URL in the message) - redact them too, not just 5xx. + const transport = err.code === -32000 || err.code === -32001 || err.code >= 400; if (transport) console.error('[stake-trade]', items.map(i => i.action).join(','), err.message); return json({ ok: false, diff --git a/app/src/pages/api/token-authority.test.ts b/app/src/pages/api/token-authority.test.ts index b933690..bd2ee71 100644 --- a/app/src/pages/api/token-authority.test.ts +++ b/app/src/pages/api/token-authority.test.ts @@ -95,11 +95,18 @@ describe('POST /api/token-authority', () => { expect(body.result).toEqual([]); }); - it('returns 502 on fetch exception', async () => { - mockFetch.mockRejectedValueOnce(new Error('network error')); + it('keeps other addresses\' results when one fetch rejects', async () => { + // allSettled: a single address failure (network error, malformed body) + // degrades to [] instead of nuking the whole batch. + mockFetch + .mockRejectedValueOnce(new Error('network error')) + .mockResolvedValueOnce(new Response(JSON.stringify(['0xabc']), { status: 200 })); const { POST } = await import('@/pages/api/token-authority'); - const res = await POST(makeCtx(['addr1'])); - expect(res.status).toBe(502); + const res = await POST(makeCtx(['addr1', 'addr2'])); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.ok).toBe(true); + expect(body.result).toEqual(['0xabc']); }); it('trims whitespace from addresses', async () => { diff --git a/app/src/pages/api/token-authority.ts b/app/src/pages/api/token-authority.ts index 2ea54b0..0112141 100644 --- a/app/src/pages/api/token-authority.ts +++ b/app/src/pages/api/token-authority.ts @@ -58,8 +58,10 @@ export const POST: APIRoute = async ({ request }) => { } try { - // Fan-out: one request per address, all in parallel - const perAddress = await Promise.all( + // Fan-out: one request per address, all in parallel. A single malformed + // body (proxy 200 with an HTML error page) must not nuke the whole + // batch - allSettled keeps the other addresses' results. + const settled = await Promise.allSettled( addresses.map(async (addr) => { // The endpoint takes no query params (verified in api-server v2.rs): // it always returns the full authority list for the address. @@ -72,9 +74,10 @@ export const POST: APIRoute = async ({ request }) => { return Array.isArray(data) ? data : []; }), ); + const perAddress = settled.flatMap(s => (s.status === 'fulfilled' ? s.value : [] as string[])); // Deduplicate across all addresses - const tokenIds = [...new Set(perAddress.flat())]; + const tokenIds = [...new Set(perAddress)]; return json({ ok: true, result: tokenIds }, 200); } catch (err) { return json({ ok: false, error: 'Indexer request failed' }, 502); diff --git a/app/src/pages/api/token-manage.ts b/app/src/pages/api/token-manage.ts index 257e974..2325217 100644 --- a/app/src/pages/api/token-manage.ts +++ b/app/src/pages/api/token-manage.ts @@ -95,7 +95,10 @@ function validateParams(action: string, p: Params): string | null { if (typeof m.media_hash !== 'string' || m.media_hash.length > 64) return 'media_hash is invalid'; if (typeof m.name !== 'string' || m.name.length > 200) return 'name is invalid'; if (m.description !== null && typeof m.description !== 'string') return 'description is invalid'; - if (m.ticker !== null && typeof m.ticker !== 'string') return 'ticker is invalid'; + // The daemon's TokenTicker constraint is 1-5 alphanumerics (the + // fungible path enforces the same) - reject here pre-burn instead of + // after a wasted code. + if (m.ticker !== null && !isStr(m.ticker, TICKER_RE)) return 'ticker must be 1-5 letters/digits'; if (m.creator !== null) return 'creator must be null'; if (!isHexField(m.icon_uri) || !isHexField(m.media_uri) || !isHexField(m.additional_metadata_uri)) { return 'metadata URIs are invalid'; @@ -188,7 +191,9 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { // their message - never forward those to the browser (mirror of the // rpc.ts proxy redaction). Daemon user-actionable messages still pass // through. - const transport = err.code === -32000 || err.code === -32001 || err.code >= 500; + // Positive codes are daemon HTTP statuses (401/404 on bad credentials + // carry the daemon URL in the message) - redact them too, not just 5xx. + const transport = err.code === -32000 || err.code === -32001 || err.code >= 400; if (transport) console.error('[token-manage]', action, err.message); return json({ ok: false, diff --git a/app/src/pages/api/transaction-abandon.ts b/app/src/pages/api/transaction-abandon.ts new file mode 100644 index 0000000..5991f1b --- /dev/null +++ b/app/src/pages/api/transaction-abandon.ts @@ -0,0 +1,60 @@ +import type { APIRoute } from 'astro'; +import { json } from '@/lib/api-utils'; +import { rpcCall, WalletRpcError } from '@/lib/wallet-rpc'; +import { requireStepUp, totpFromBody } from '@/lib/step-up'; + +/** + * POST /api/transaction-abandon - TOTP-gated abandon of a pending transaction. + * + * Abandoning un-reserves a pending transaction's inputs for re-spend, so it + * is fund-affecting: it requires a fresh TOTP code (step-up) on top of the + * session cookie, exactly like /api/send and /api/stake-trade. The method is + * intentionally absent from the browser/plugin RPC allowlist - this endpoint + * is the only path. + * + * Body: { totp_code, transaction_id }. The account is fixed server-side. + */ + +export const POST: APIRoute = async ({ request, clientAddress }) => { + let body: Record = {}; + try { + const parsed: unknown = await request.json(); + if (parsed !== null && typeof parsed === 'object') body = parsed as Record; + } catch { + return json({ ok: false, error: 'Invalid request body.' }, 400); + } + + const transactionId = typeof body.transaction_id === 'string' ? body.transaction_id.trim() : ''; + // ML transaction ids are hex; refuse anything else before burning a code. + if (!/^[0-9a-f]{16,80}$/i.test(transactionId)) { + return json({ ok: false, error: 'A valid transaction id is required.' }, 400); + } + + const stepUp = requireStepUp(totpFromBody(body), request, clientAddress as string | undefined); + if (!stepUp.ok) { + return json({ ok: false, error: stepUp.error }, stepUp.status); + } + + try { + await rpcCall('transaction_abandon', { account: 0, transaction_id: transactionId }); + return json({ ok: true }, 200); + } catch (err) { + if (err instanceof WalletRpcError) { + // Transport-class failures (-32000/-32001 and daemon HTTP statuses) + // embed the daemon URL in their message - redact like every other + // money endpoint (send.ts, stake-trade.ts, rpc.ts) does. + const transport = err.code === -32000 || err.code === -32001 || err.code >= 400; + if (transport) console.error('[transaction-abandon]', err.message); + return json( + { ok: false, error: transport + ? 'The wallet service is unavailable. Check that all services are running.' + : err.message }, + 502, + ); + } + return json( + { ok: false, error: 'The wallet service is unavailable. Check that all services are running.' }, + 502, + ); + } +}; diff --git a/app/src/pages/api/wallet-open.test.ts b/app/src/pages/api/wallet-open.test.ts index e916a1e..0ab47b2 100644 --- a/app/src/pages/api/wallet-open.test.ts +++ b/app/src/pages/api/wallet-open.test.ts @@ -4,6 +4,13 @@ vi.mock('@/lib/wallet-rpc', () => ({ walletInfo: vi.fn(), ensureWalletOpen: vi.fn(), isWalletNotOpenError: vi.fn(), + // Real class shape so browserSafeOpenError can read `.code` on thrown values. + WalletRpcError: class WalletRpcError extends Error { + constructor(message: string, public readonly code: number) { + super(message); + this.name = 'WalletRpcError'; + } + }, })); import { POST } from '@/pages/api/wallet-open'; @@ -60,10 +67,19 @@ describe('POST /api/wallet-open', () => { it('returns error when ensureWalletOpen fails unexpectedly', async () => { vi.mocked(walletInfo).mockRejectedValue(new Error('not open')); vi.mocked(isWalletNotOpenError).mockReturnValue(true); - vi.mocked(ensureWalletOpen).mockResolvedValue({ status: 'error', message: 'boom' } as never); + // A transport-band WalletRpcError (-32000) must surface as the generic + // copy - the raw message carries the daemon URL. + const { WalletRpcError } = await import('@/lib/wallet-rpc'); + vi.mocked(ensureWalletOpen).mockResolvedValue({ + status: 'error', + message: 'Cannot reach wallet-rpc-daemon at http://localhost:3034: boom', + error: new WalletRpcError('Cannot reach wallet-rpc-daemon at http://localhost:3034: boom', -32000), + } as never); const res = await POST(makeCtx()); const body = await res.json(); - expect(body).toMatchObject({ ok: false, status: 'error', message: 'boom' }); + expect(body).toMatchObject({ ok: false, status: 'error' }); + expect(body.message).not.toContain('3034'); + expect(body.message).toMatch(/unavailable/); }); it('surfaces error when walletInfo throws a non-wallet error', async () => { @@ -71,7 +87,24 @@ describe('POST /api/wallet-open', () => { vi.mocked(isWalletNotOpenError).mockReturnValue(false); const res = await POST(makeCtx()); const body = await res.json(); - expect(body).toMatchObject({ ok: false, status: 'error', message: 'daemon unreachable' }); + // Redacted: the raw pre-check error must not reach the browser. + expect(body).toMatchObject({ ok: false, status: 'error' }); + expect(body.message).not.toContain('daemon unreachable'); + expect(body.message).toMatch(/unavailable/); expect(ensureWalletOpen).not.toHaveBeenCalled(); }); + + it('forwards application-band rpc errors verbatim', async () => { + vi.mocked(walletInfo).mockRejectedValue(new Error('not open')); + vi.mocked(isWalletNotOpenError).mockReturnValue(true); + const { WalletRpcError } = await import('@/lib/wallet-rpc'); + vi.mocked(ensureWalletOpen).mockResolvedValue({ + status: 'error', + message: 'wallet file is corrupted', + error: new WalletRpcError('wallet file is corrupted', -1), + } as never); + const res = await POST(makeCtx()); + const body = await res.json(); + expect(body).toMatchObject({ ok: false, status: 'error', message: 'wallet file is corrupted' }); + }); }); diff --git a/app/src/pages/api/wallet-open.ts b/app/src/pages/api/wallet-open.ts index e619dd0..e5ae4e0 100644 --- a/app/src/pages/api/wallet-open.ts +++ b/app/src/pages/api/wallet-open.ts @@ -10,9 +10,24 @@ */ import type { APIRoute } from 'astro'; -import { ensureWalletOpen, isWalletNotOpenError, walletInfo } from '@/lib/wallet-rpc'; +import { ensureWalletOpen, isWalletNotOpenError, walletInfo, WalletRpcError } from '@/lib/wallet-rpc'; import { json } from '@/lib/api-utils'; +/** Redaction parity with /api/rpc: transport-band codes (-32000/-32001) and + * HTTP-status errors carry the daemon URL / internal details, so they become + * the generic unavailable copy instead of being forwarded to the browser. */ +function browserSafeOpenError(err: unknown): string { + const code = err instanceof WalletRpcError ? err.code : undefined; + const forwardable = + err instanceof WalletRpcError && + typeof code === 'number' && + code !== -32000 && code !== -32001 && code < 0 && + (code === -1 || (code >= -32700 && code <= -32002)); + return forwardable + ? (err as WalletRpcError).message + : 'The wallet service is unavailable. Check that all services are running.'; +} + export const POST: APIRoute = async () => { // Check if already open - if so, nothing to do try { @@ -21,9 +36,10 @@ export const POST: APIRoute = async () => { return json({ ok: true, status: 'already_open' }); } catch (alreadyErr) { if (!isWalletNotOpenError(alreadyErr)) { - // Daemon unreachable or some other hard error - surface it + // Daemon unreachable or some other hard error - log the detail, give + // the browser the redacted copy (never the raw daemon URL). console.error('[wallet] wallet-open pre-check failed:', (alreadyErr as Error).message); - return json({ ok: false, status: 'error', message: (alreadyErr as Error).message }); + return json({ ok: false, status: 'error', message: browserSafeOpenError(alreadyErr) }); } // "No wallet opened" - proceed to open console.log('[wallet] no wallet open, attempting auto-open...'); @@ -39,5 +55,5 @@ export const POST: APIRoute = async () => { if (result.status === 'not_found') { return json({ ok: false, status: 'not_found' }); } - return json({ ok: false, status: 'error', message: result.message }); + return json({ ok: false, status: 'error', message: browserSafeOpenError(result.error) }); }; diff --git a/app/src/pages/balances.astro b/app/src/pages/balances.astro index 41d8b19..5c65f7c 100644 --- a/app/src/pages/balances.astro +++ b/app/src/pages/balances.astro @@ -155,9 +155,13 @@ function nftIconUrl(info: TokenInfo | undefined): string | null { const ticker = tokenTicker(info); const nft = isNFT(info); const iconUrl = nftIconUrl(info); - const explorerBase = network === 'testnet' - ? 'https://lovelace.explorer.mintlayer.org' - : 'https://explorer.mintlayer.org'; + const explorerBase = (process.env.ML_EXPLORER_URL ?? ( + network === 'testnet' + ? 'https://lovelace.explorer.mintlayer.org' + : network === 'mainnet' + ? 'https://explorer.mintlayer.org' + : '' + )).replace(/\/+$/, ''); return ( @@ -200,10 +204,14 @@ function nftIconUrl(info: TokenInfo | undefined): string | null { - - {tokenId.slice(0, 12)}…{tokenId.slice(-6)} - + {explorerBase ? ( + + {tokenId.slice(0, 12)}…{tokenId.slice(-6)} + + ) : ( + {tokenId.slice(0, 12)}…{tokenId.slice(-6)} + )} - Start over + )} + {bootstrapping && !stagedForViewer && ( +
+

First-time setup is in progress in another browser session.

+

+ For safety the enrollment details are only shown there. It expires + after 15 minutes, or the other session can start over. +

+
+ )} + {!unconfigured && (
(typeof v === 'string' ? v : ''); - const decision = await resolvePasswordChange({ - currentPassword: str(form.get('current_password')), - newPassword: str(form.get('new_password')), - confirmPassword: str(form.get('confirm_password')), - }); + const decision = await resolvePasswordChange( + { + currentPassword: str(form.get('current_password')), + newPassword: str(form.get('new_password')), + confirmPassword: str(form.get('confirm_password')), + }, + getClientAddress(Astro.request, Astro.clientAddress as string | undefined), + ); if (!decision.ok) { result = { action: 'error', section, message: decision.error + '.' }; @@ -78,28 +81,44 @@ if (Astro.request.method === 'POST') { } } } else if (section === 'remove_passkey') { - const credentialId = str(form.get('credential_id')); - if (!credentialId) { - result = { action: 'error', section, message: 'No credential ID provided.' }; + // Destroying a fallback auth factor is as sensitive as enrolling one: + // a hijacked session must not be able to strip the passkeys silently. + const totpCode = str(form.get('totp_code')); + const currentSecret = getStringPref('auth.totp_secret'); + const burn = currentSecret + ? verifyAndBurnTotpCode(totpCode, currentSecret, getClientAddress(Astro.request, Astro.clientAddress)) + : { ok: false as const, error: '2FA is not configured.' }; + if (!burn.ok) { + result = { action: 'error', section, message: burn.error }; } else { - const creds = getCredentials(); - const filtered = creds.filter((c) => c.id !== credentialId); - if (filtered.length === creds.length) { - result = { action: 'error', section, message: 'Passkey not found.' }; + const credentialId = str(form.get('credential_id')); + if (!credentialId) { + result = { action: 'error', section, message: 'No credential ID provided.' }; } else { - saveCredentials(filtered); - result = { action: 'success', section, message: 'Passkey removed.' }; + const creds = getCredentials(); + const filtered = creds.filter((c) => c.id !== credentialId); + if (filtered.length === creds.length) { + result = { action: 'error', section, message: 'Passkey not found.' }; + } else { + saveCredentials(filtered); + result = { action: 'success', section, message: 'Passkey removed.' }; + } } } } else if (section === 'ipfs') { - const provider = (form.get('provider') as string | null) ?? ''; + const provider = str(form.get('provider')); const filebaseToken = str(form.get('filebase_token')); - const pinataJwt = (form.get('pinata_jwt') as string | null) ?? ''; + const pinataJwt = str(form.get('pinata_jwt')); const totpCode = str(form.get('totp_code')); if (!['filebase', 'pinata', ''].includes(provider)) { result = { action: 'error', section, message: `Invalid provider: ${provider}` }; + } else if (!getStringPref('auth.totp_secret')) { + // Verify against a configured secret only: burning against an empty + // one reports 'Invalid authenticator code.' and burns throttle slots + // while the real problem is that setup was never finished. + result = { action: 'error', section, message: '2FA is not configured. Complete first-time setup at /setup to enable it.' }; } else { // Pinata/Filebase keys are third-party account credentials: whoever sets // them can pivot into the owner's pinning account. Same sensitivity class @@ -108,13 +127,23 @@ if (Astro.request.method === 'POST') { if (!burn.ok) { result = { action: 'error', section, message: burn.error }; } else { + // Secrets are write-only (same as the Telegram token): empty input + // keeps the stored key, so the page never has to render them. + const storedFilebase = getStringPref('ipfs.filebase_token') ?? ''; + const storedPinata = getStringPref('ipfs.pinata_jwt') ?? ''; + if (provider === 'filebase' && !filebaseToken && !storedFilebase) { + result = { action: 'error', section, message: 'Paste your Filebase access key - pinning cannot work without it.' }; + } else if (provider === 'pinata' && !pinataJwt && !storedPinata) { + result = { action: 'error', section, message: 'Paste your Pinata JWT - pinning cannot work without it.' }; + } else { setPref('ipfs.provider', provider); // Disabling IPFS also clears any stored provider keys - keeping them // on disk while "Disabled" protects nothing and leaves third-party // credentials behind. - setPref('ipfs.filebase_token', provider === '' ? '' : filebaseToken); - setPref('ipfs.pinata_jwt', provider === '' ? '' : pinataJwt); + setPref('ipfs.filebase_token', provider === '' ? '' : (filebaseToken || storedFilebase)); + setPref('ipfs.pinata_jwt', provider === '' ? '' : (pinataJwt || storedPinata)); result = { action: 'success', section, message: 'IPFS settings saved.' }; + } } } @@ -123,8 +152,19 @@ if (Astro.request.method === 'POST') { for (const key of notifKeys) { setPref(`telegram.notify.${key}`, form.get(`notify_${key}`) === '1'); } - const threshold = (form.get('large_send_threshold') as string | null) ?? '100'; - setPref('telegram.notify.large_send_threshold', threshold || '100'); + // Reject junk before storing: a negative or non-numeric threshold + // would fire a Telegram alert on every send. str() coerces File parts + // (crafted multipart POSTs) to '' so they fail cleanly instead of + // throwing on .trim(). + const rawThreshold = str(form.get('large_send_threshold')); + const thresholdNum = Number(rawThreshold); + // >= 1: 0 would alert on every send (the behavior the comment below + // warns about); the form's min="1" already promises this to UI users. + const threshold = + rawThreshold.trim() !== '' && Number.isFinite(thresholdNum) && thresholdNum >= 1 + ? String(Math.floor(thresholdNum)) + : '100'; + setPref('telegram.notify.large_send_threshold', threshold); setPref('telegram.staking.status', form.get('staking_status') === '1'); setPref('telegram.staking.controls', form.get('staking_controls') === '1'); result = { action: 'success', section, message: 'Notification preferences saved.' }; @@ -289,6 +329,8 @@ if (localCaPem) { const { createHash } = await import('node:crypto'); localCaFingerprint = createHash('sha256').update(localCaPem).digest('hex').toUpperCase().replace(/(.{2})(?=.)/g, '$1:'); } +// Session-bound management data and secrets-adjacent settings - never cache. +Astro.response.headers.set('Cache-Control', 'no-store'); --- @@ -475,9 +517,14 @@ if (localCaPem) { {new Date(pk.createdAt).toLocaleDateString()}
- + +