From 9e294b878de947571b99322fec6ec3ddbcb060fb Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 21 Oct 2026 00:22:56 +0200 Subject: [PATCH 01/52] fix: findings in auth-sessions (cycle 1) --- app/src/lib/passkey.ts | 6 + app/src/lib/password-change.test.ts | 49 ++++++- app/src/lib/password-change.ts | 49 +++++++ app/src/lib/safe-uri.ts | 14 ++ app/src/lib/step-up.ts | 4 +- .../pages/api/passkey/auth-options.test.ts | 38 ++++++ app/src/pages/api/passkey/auth-options.ts | 11 +- app/src/pages/api/passkey/auth-verify.ts | 7 +- app/src/pages/api/passkey/register-options.ts | 6 +- app/src/pages/api/passkey/register-verify.ts | 19 ++- app/src/pages/api/settings/password.ts | 17 ++- app/src/pages/login.astro | 127 +++++++++++++----- app/src/pages/management/settings.astro | 13 +- 13 files changed, 304 insertions(+), 56 deletions(-) diff --git a/app/src/lib/passkey.ts b/app/src/lib/passkey.ts index cfcf024..98e47f1 100644 --- a/app/src/lib/passkey.ts +++ b/app/src/lib/passkey.ts @@ -13,6 +13,7 @@ */ import crypto from 'node:crypto'; +import type { AuthenticatorTransport } from '@simplewebauthn/server'; import { getPref, setPref } from '@/lib/prefs-db'; // ── Types ────────────────────────────────────────────────────────────────────── @@ -23,6 +24,11 @@ export interface StoredCredential { counter: number; // signature counter (anti-replay) name: string; // user-supplied label createdAt: number; // Unix ms + // Transports the authenticator reported at registration (usb, nfc, ble, + // internal, hybrid, cable). Old records may be undefined; callers must + // omit the hint then so browsers probe every transport instead of + // filtering out plugged-in hardware keys. + transports?: AuthenticatorTransport[]; } // ── Credential storage ───────────────────────────────────────────────────────── 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..7c8938c 100644 --- a/app/src/lib/password-change.ts +++ b/app/src/lib/password-change.ts @@ -17,14 +17,61 @@ 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(); +} + +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 +79,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/safe-uri.ts b/app/src/lib/safe-uri.ts index b39be3a..271cc2c 100644 --- a/app/src/lib/safe-uri.ts +++ b/app/src/lib/safe-uri.ts @@ -8,6 +8,20 @@ * 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 { + 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..a444d33 100644 --- a/app/src/lib/step-up.ts +++ b/app/src/lib/step-up.ts @@ -66,8 +66,8 @@ 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, 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..8532aaf 100644 --- a/app/src/pages/api/passkey/auth-options.ts +++ b/app/src/pages/api/passkey/auth-options.ts @@ -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..7ed1a20 100644 --- a/app/src/pages/api/passkey/auth-verify.ts +++ b/app/src/pages/api/passkey/auth-verify.ts @@ -42,6 +42,11 @@ export const POST: APIRoute = async ({ request, clientAddress }) => { } catch { return json({ error: 'Invalid request body.' }, 400); } + // 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); + } const creds = getCredentials(); const storedCred = creds.find((c) => c.id === body.id); @@ -63,7 +68,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..21535a5 100644 --- a/app/src/pages/api/passkey/register-options.ts +++ b/app/src/pages/api/passkey/register-options.ts @@ -45,11 +45,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..a4e7c01 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, @@ -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/settings/password.ts b/app/src/pages/api/settings/password.ts index afb55e8..79e62d5 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 { getClientAddress } from '@/lib/auth'; -export const POST: APIRoute = async ({ request }) => { +export const POST: APIRoute = async ({ request, clientAddress }) => { const form = await readFormData(request); 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/login.astro b/app/src/pages/login.astro index 5ec74dc..ed7241e 100644 --- a/app/src/pages/login.astro +++ b/app/src/pages/login.astro @@ -1,5 +1,6 @@ --- import '@/styles/global.css'; +import { randomUUID } from 'node:crypto'; import { verifyPassword, passwordNeedsRehash, @@ -11,6 +12,8 @@ import { recordLoginFailure, SESSION_COOKIE_NAME, verifySessionToken, getClientAddress, generateTotpSecret } from '@/lib/auth'; +import { verifyAndBurnTotpCode } from '@/lib/step-up'; +import { safeRelativePath } from '@/lib/safe-uri'; import { getStringPref, getPref, setPref, deletePref } from '@/lib/prefs-db'; import TotpQrCode from '@/components/TotpQrCode'; import { getCredentials, isValidRpId, getRpId } from '@/lib/passkey'; @@ -36,25 +39,42 @@ const unconfigured = !passwordHash || !totpSecret; // no web credential source (init.sh only ships secrets for deployments), so // the login page bootstraps them in two steps: (1) choose a password, // (2) scan the staged TOTP secret and confirm a first code. Pending state -// lives in prefs so reloads and restarts keep it. Public only until both -// factors exist (see middleware.ts). +// lives in prefs so reloads and restarts keep it, but it is bound to the +// browser session that staged it (auth_boot cookie) and expires after 15 +// minutes - a third party on the network can neither complete someone +// else's half-finished setup nor stage credentials for the owner to +// confirm. Public only until both factors exist (see middleware.ts). +const BOOTSTRAP_TTL_MS = 15 * 60 * 1000; +const BOOTSTRAP_COOKIE = 'auth_boot'; +const stagedAt = getPref('auth.bootstrap_staged_at') ?? 0; +if (Date.now() - stagedAt > BOOTSTRAP_TTL_MS) { + // Stale half-finished setup: drop it so the page falls back to step 1. + deletePref('auth.password_pending'); + deletePref('auth.totp_secret_pending'); + deletePref('auth.bootstrap_token'); + deletePref('auth.bootstrap_staged_at'); +} const restartRequested = new URL(Astro.request.url).searchParams.has('restart'); if (restartRequested && unconfigured) { deletePref('auth.password_pending'); deletePref('auth.totp_secret_pending'); + deletePref('auth.bootstrap_token'); + deletePref('auth.bootstrap_staged_at'); } const pendingHash = getStringPref('auth.password_pending'); const pendingSecret = getStringPref('auth.totp_secret_pending'); +const stagedToken = getStringPref('auth.bootstrap_token'); const bootstrapping = unconfigured && Boolean(pendingHash) && Boolean(pendingSecret); - // Passkeys: only show if at least one is enrolled AND the RP ID is valid const passkeys = getCredentials(); const rpId = getRpId(Astro.request.url); const hasPasskeys = passkeys.length > 0 && isValidRpId(rpId); -const nextParam = new URL(Astro.request.url).searchParams.get('next') ?? '/'; +// Same-origin relative redirect target only (safeRelativePath rejects +// protocol-relative '//host' and WHATWG backslash forms like '/\\evil.com'). +const nextParam = safeRelativePath(new URL(Astro.request.url).searchParams.get('next') ?? '/'); let errorMessage: string | null = null; @@ -66,37 +86,64 @@ if (Astro.request.method === 'POST' && unconfigured) { const form = await Astro.request.formData(); const stagedHash = getStringPref('auth.password_pending'); if (!stagedHash) { - // Step 1: stage the chosen password and a fresh TOTP secret. - const password = (form.get('password') as string | null) ?? ''; - const confirm = (form.get('password_confirm') as string | null) ?? ''; + // Step 1: stage the chosen password and a fresh TOTP secret, bound to + // this browser via a short-lived cookie so nobody else can finish (or + // overwrite) the setup from another session. + const rawPassword = form.get('password'); + const rawConfirm = form.get('password_confirm'); + const password = typeof rawPassword === 'string' ? rawPassword : ''; + const confirm = typeof rawConfirm === 'string' ? rawConfirm : ''; if (password.length < 8) { errorMessage = 'Password must be at least 8 characters.'; } else if (password !== confirm) { errorMessage = 'Passwords do not match.'; } else { + const bootstrapToken = randomUUID(); setPref('auth.password_pending', await hashPassword(password)); setPref('auth.totp_secret_pending', generateTotpSecret()); - return Astro.redirect(`/login?next=${encodeURIComponent(nextParam)}`, 302); + setPref('auth.bootstrap_token', bootstrapToken); + setPref('auth.bootstrap_staged_at', Date.now()); + return new Response(null, { + status: 302, + headers: { + Location: `/login?next=${encodeURIComponent(nextParam)}`, + 'Set-Cookie': `${BOOTSTRAP_COOKIE}=${bootstrapToken}; Path=/; HttpOnly; SameSite=Strict; Secure; Max-Age=${Math.floor(BOOTSTRAP_TTL_MS / 1000)}`, + }, + }); } } else { - // Step 2: enroll the authenticator by confirming a first code. - const totpCode = ((form.get('totp_code') as string | null) ?? '').trim(); - if (/^\d{6}$/.test(totpCode) && verifyTOTP(totpCode, getStringPref('auth.totp_secret_pending'))) { + // Step 2: enroll the authenticator by confirming a first code. Only + // the browser that staged the credentials holds the matching cookie, + // so a code from another session is rejected before it is checked. + const bootCookie = Astro.cookies.get(BOOTSTRAP_COOKIE)?.value ?? ''; + const totpRaw = form.get('totp_code'); + const totpCode = typeof totpRaw === 'string' ? totpRaw.trim() : ''; + if (!stagedToken || bootCookie !== stagedToken) { + errorMessage = 'Setup session expired. Use "Start over" to begin again.'; + } else if ( + /^\d{6}$/.test(totpCode) && + verifyTOTP(totpCode, getStringPref('auth.totp_secret_pending')) + ) { setPref('auth.password_hash', stagedHash); setPref('auth.totp_secret', getStringPref('auth.totp_secret_pending')); deletePref('auth.password_pending'); deletePref('auth.totp_secret_pending'); + deletePref('auth.bootstrap_token'); + deletePref('auth.bootstrap_staged_at'); const token = generateSessionToken(sessionVersion); - const safeDest = nextParam.startsWith('/') && !nextParam.startsWith('//') ? nextParam : '/'; - return new Response(null, { - status: 302, - headers: { Location: safeDest, 'Set-Cookie': makeSessionCookieHeader(token) }, - }); + const headers = new Headers({ Location: nextParam }); + headers.append('Set-Cookie', makeSessionCookieHeader(token)); + headers.append( + 'Set-Cookie', + `${BOOTSTRAP_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Secure; Max-Age=0`, + ); + return new Response(null, { status: 302, headers }); + } else { + recordLoginFailure(ip); + // Artificial delay to slow brute-force before lockout kicks in + await new Promise((r) => setTimeout(r, 500)); + errorMessage = 'Invalid authenticator code.'; } - recordLoginFailure(ip); - // Artificial delay to slow brute-force before lockout kicks in - await new Promise((r) => setTimeout(r, 500)); - errorMessage = 'Invalid authenticator code.'; } } } @@ -109,31 +156,33 @@ if (Astro.request.method === 'POST' && !unconfigured) { errorMessage = 'Too many login attempts. Try again in 15 minutes.'; } else { const form = await Astro.request.formData(); - const password = (form.get('password') as string | null) ?? ''; - const totpCode = (form.get('totp_code') as string | null) ?? ''; - - // Always evaluate both factors to avoid timing side-channels. - // Deliberately raw verifyTOTP, NOT verifyAndBurnTotpCode: login is already - // IP-throttled by the login limiter, and burning here would consume the - // code the user needs seconds later for a step-up (or vice versa - a send - // would lock them out of logging in for ~60s). - const [passwordOk, totpOk] = await Promise.all([ + const rawPassword = form.get('password'); + const rawTotpCode = form.get('totp_code'); + const password = typeof rawPassword === 'string' ? rawPassword : ''; + const totpCode = typeof rawTotpCode === 'string' ? rawTotpCode.trim() : ''; + + // Always evaluate both factors to avoid timing side-channels. The TOTP + // goes through the shared verify-and-burn path so the single-use + // guarantee holds across channels: a code relayed in real time from a + // login cannot be replayed at a step-up endpoint, and vice versa. The + // cost is that signing in consumes the currently displayed code - a + // step-up seconds later needs the next one. + const [passwordOk, totpCheck] = await Promise.all([ verifyPassword(password, passwordHash), - Promise.resolve(verifyTOTP(totpCode, totpSecret)), + Promise.resolve(verifyAndBurnTotpCode(totpCode, totpSecret, ip)), ]); - if (passwordOk && totpOk) { + if (passwordOk && totpCheck.ok) { // Transparently upgrade hashes created with the old 100k iteration // count now that we have the plaintext in hand. if (passwordNeedsRehash(passwordHash)) { setPref('auth.password_hash', await hashPassword(password)); } const token = generateSessionToken(sessionVersion); - const safeDest = nextParam.startsWith('/') && !nextParam.startsWith('//') ? nextParam : '/'; return new Response(null, { status: 302, headers: { - Location: safeDest, + Location: nextParam, 'Set-Cookie': makeSessionCookieHeader(token), }, }); @@ -141,7 +190,12 @@ if (Astro.request.method === 'POST' && !unconfigured) { recordLoginFailure(ip); // Artificial delay to slow brute-force before lockout kicks in await new Promise((r) => setTimeout(r, 500)); - errorMessage = 'Invalid credentials.'; + if (!passwordOk || !totpCheck.ok || totpCheck.reason === 'invalid') { + errorMessage = 'Invalid credentials.'; + } else { + // Burned or throttled code: say so, the remedy differs from a typo. + errorMessage = totpCheck.error; + } } } } @@ -373,7 +427,10 @@ if (Astro.request.method === 'POST' && !unconfigured) { } const nextParam = btn.dataset.next ?? '/'; - const safeDest = nextParam.startsWith('/') && !nextParam.startsWith('//') ? nextParam : '/'; + const safeDest = + nextParam.startsWith('/') && !nextParam.startsWith('//') && !nextParam.startsWith('/\\') + ? nextParam + : '/'; window.location.href = safeDest; } catch (err: unknown) { const e = err as { name?: string; message?: string }; diff --git a/app/src/pages/management/settings.astro b/app/src/pages/management/settings.astro index 296616a..c826e68 100644 --- a/app/src/pages/management/settings.astro +++ b/app/src/pages/management/settings.astro @@ -41,11 +41,14 @@ if (Astro.request.method === 'POST') { } else if (section === 'password') { // Shared logic with /api/settings/password (single source of truth). 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')), + }, + getClientAddress(Astro.request, Astro.clientAddress as string | undefined), + ); if (!decision.ok) { result = { action: 'error', section, message: decision.error + '.' }; From 17a9cc3a917090c467126fa2965e4b6f195ad7bc Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 21 Oct 2026 00:30:56 +0200 Subject: [PATCH 02/52] fix: findings in tokens-trading (cycle 1) Order confirm totals are now computed with exact decimal math (new lib/decimal.ts) so the confirmed number is the number the chain receives, price inputs no longer carry thousands separators, and issuance metadata is matched by token id instead of list position. Also hardens the explorer token route body read, the search/import races in TokenSearch and the NFT listing error paths. --- app/src/components/IssuedTokensPanel.tsx | 36 ++++++++-- app/src/components/NFTMarketplace.tsx | 19 ++++-- app/src/components/OrderBook.tsx | 28 ++++---- app/src/components/TokenSearch.tsx | 39 +++++++++-- app/src/lib/decimal.test.ts | 75 ++++++++++++++++++++ app/src/lib/decimal.ts | 76 +++++++++++++++++++++ app/src/pages/api/explorer-tokens.ts | 28 ++++++-- app/src/pages/api/settings/password.test.ts | 1 + 8 files changed, 265 insertions(+), 37 deletions(-) create mode 100644 app/src/lib/decimal.test.ts create mode 100644 app/src/lib/decimal.ts diff --git a/app/src/components/IssuedTokensPanel.tsx b/app/src/components/IssuedTokensPanel.tsx index beda8ac..b49e437 100644 --- a/app/src/components/IssuedTokensPanel.tsx +++ b/app/src/components/IssuedTokensPanel.tsx @@ -4,6 +4,7 @@ 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'; // ── Types ────────────────────────────────────────────────────────────────────── @@ -43,7 +44,10 @@ 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. + const parsed: unknown = JSON.parse(localStorage.getItem(LS_KEY) ?? '[]'); + return Array.isArray(parsed) ? (parsed as StoredToken[]) : []; } catch { return []; } @@ -88,14 +92,26 @@ export default function IssuedTokensPanel({ network }: Props) { 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 }); @@ -172,9 +188,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)); diff --git a/app/src/components/NFTMarketplace.tsx b/app/src/components/NFTMarketplace.tsx index cfd565c..112cd6c 100644 --- a/app/src/components/NFTMarketplace.tsx +++ b/app/src/components/NFTMarketplace.tsx @@ -410,6 +410,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. @@ -566,7 +567,9 @@ export default function NFTMarketplace({ }) .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, @@ -580,8 +583,10 @@ export default function NFTMarketplace({ }); 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 +735,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..c56f5ae 100644 --- a/app/src/components/OrderBook.tsx +++ b/app/src/components/OrderBook.tsx @@ -10,6 +10,7 @@ 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'; // Raw shape returned by order_list_all_active (flat, no existing_order_data wrapper) interface ActiveOrderRaw { @@ -124,13 +125,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 ────────────────────────────────────────────────────────── @@ -193,16 +191,17 @@ 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; const canSubmit = !loading && !!effectiveTokenId && totp.length === 6 && ( @@ -227,7 +226,10 @@ 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"); // conclude_address is required - fetch a fresh receive address const addrRes = await rpc<{ address: string }>("address_new", { account: 0 }); const r = await stakeTrade({ diff --git a/app/src/components/TokenSearch.tsx b/app/src/components/TokenSearch.tsx index c7bef34..6f05c8a 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,8 @@ export default function TokenSearch({ network }: Props) { const [searched, setSearched] = useState(false); const [indexerAvailable, setIndexerAvailable] = useState(true); const [favourites, setFavourites] = useState([]); + // Monotonic sequence for search responses (stale-response guard). + const searchSeqRef = useRef(0); const [favInfos, setFavInfos] = useState>(new Map()); const [favLoading, setFavLoading] = useState(false); @@ -193,6 +195,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); @@ -255,6 +269,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 +290,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 +307,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 +343,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', { 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/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/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', () => ({ From ed30df8482f451d0667c71824eae6ebda0308999 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 21 Oct 2026 00:36:59 +0200 Subject: [PATCH 03/52] fix: findings in wallet-rpc (cycle 1) stake-trade and the rpc proxy now complete daemon param shapes (options/output_address) before the TOTP gate so conclude and decommission stop failing after burning a code, zero-amount order legs are rejected up front, transport errors are redacted from send and the proxy, an empty timeout env no longer disables rpc timeouts, the block stream releases its upstream socket on non-abort cancels, a broken scan reports failure instead of an empty wallet, lookahead size is clamped and unknown networks stop borrowing the mainnet chain tip. --- app/src/lib/wallet-rpc.ts | 7 ++++- app/src/pages/api/block-stream.ts | 27 ++++++++++++++---- app/src/pages/api/chain-tip.ts | 14 ++++++++- app/src/pages/api/rpc.test.ts | 18 +++++++++++- app/src/pages/api/rpc.ts | 29 +++++++++++++------ app/src/pages/api/scan-issued-tokens.test.ts | 6 ++-- app/src/pages/api/scan-issued-tokens.ts | 9 ++++-- app/src/pages/api/send.ts | 13 ++++++++- app/src/pages/api/stake-trade.ts | 30 ++++++++++++++++---- 9 files changed, 124 insertions(+), 29 deletions(-) diff --git a/app/src/lib/wallet-rpc.ts b/app/src/lib/wallet-rpc.ts index 20eb353..634b31c 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; } diff --git a/app/src/pages/api/block-stream.ts b/app/src/pages/api/block-stream.ts index c0b191f..96214c7 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,7 +106,7 @@ 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); @@ -107,11 +122,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/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/rpc.test.ts b/app/src/pages/api/rpc.test.ts index e4b2fbe..e53bd32 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', () => { diff --git a/app/src/pages/api/rpc.ts b/app/src/pages/api/rpc.ts index 4f77275..4b302a3 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,15 @@ 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.'; + // Only forward JSON-RPC-class daemon errors. -32000/-32001 are the + // transport band (daemon URL in the message); anything outside the + // -32700..-32002 JSON-RPC error space (HTTP 401/404 on bad daemon + // credentials, 5xx) carries internal details and is redacted. + const forwardable = + err instanceof WalletRpcError && + code !== -32000 && code !== -32001 && + 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..f077fa5 100644 --- a/app/src/pages/api/scan-issued-tokens.ts +++ b/app/src/pages/api/scan-issued-tokens.ts @@ -151,8 +151,11 @@ export const GET: APIRoute = async () => { } 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.ts b/app/src/pages/api/send.ts index 1659d59..fb9c015 100644 --- a/app/src/pages/api/send.ts +++ b/app/src/pages/api/send.ts @@ -82,7 +82,18 @@ 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. + const transport = err.code === -32000 || err.code === -32001 || err.code >= 500; + 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/stake-trade.ts b/app/src/pages/api/stake-trade.ts index dfb396c..436fa93 100644 --- a/app/src/pages/api/stake-trade.ts +++ b/app/src/pages/api/stake-trade.ts @@ -64,7 +64,10 @@ function isCoinAmount(v: unknown): 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); + // 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) @@ -122,14 +125,14 @@ function validateParams(action: string, p: Params): string | null { 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': { @@ -143,7 +146,7 @@ function validateParams(action: string, p: Params): string | null { if (p.account !== 0) return 'account must be 0'; if (!isStr(p.order_id, ID_RE)) return 'order_id is required'; 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': { @@ -196,6 +199,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); From 2a14ae6ae12d10c59066ce4d484694421705b324 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 21 Oct 2026 00:42:14 +0200 Subject: [PATCH 04/52] fix: findings in bitcoin (cycle 1) - auto-sync the wallet after creation, boot and link so balances are never stale at zero until a manual sync - expose syncing state and the last sync error on /status, with visible chips in the UI (pruned-refused scans surface loudly) - actually send the displayed fee estimate with each transaction instead of falling back to the 1 sat/vB default - mark spent outputs right after broadcast so a second send cannot reuse them; kick a follow-up sync from the UI - remove the wallet files when a fresh wallet fails to open so a generated mnemonic is not lost behind a permanent 409 - ignore estimatesmartfee -1 answers (fresh node has no data) - validate the configured network name and fix the restore-dialog wording --- app/src/components/BitcoinWallet.tsx | 28 ++++- app/src/lib/bitcoin-wallet.ts | 4 + bdk-wallet/src/main.rs | 165 +++++++++++++++++++++------ 3 files changed, 156 insertions(+), 41 deletions(-) diff --git a/app/src/components/BitcoinWallet.tsx b/app/src/components/BitcoinWallet.tsx index f65ee2f..95cdc5b 100644 --- a/app/src/components/BitcoinWallet.tsx +++ b/app/src/components/BitcoinWallet.tsx @@ -76,7 +76,7 @@ export default function BitcoinWallet({ explorerUrl, advancedUi = false }: { exp 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); @@ -289,6 +289,9 @@ 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). + ...(typeof feeSatVb === 'number' ? { fee_rate_sat_vb: feeSatVb } : {}), }), }); setSentTxid(res.txid); @@ -296,6 +299,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 +366,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 && (
{feeSatVb !== null && ( -

Suggested fee: ~{feeSatVb} sat/vB

+

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

)}
diff --git a/app/src/lib/bitcoin-wallet.ts b/app/src/lib/bitcoin-wallet.ts index 15d6b9e..77beb12 100644 --- a/app/src/lib/bitcoin-wallet.ts +++ b/app/src/lib/bitcoin-wallet.ts @@ -77,6 +77,10 @@ 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; } export interface BitcoinTransaction { diff --git a/bdk-wallet/src/main.rs b/bdk-wallet/src/main.rs index d89dee9..c3736ce 100644 --- a/bdk-wallet/src/main.rs +++ b/bdk-wallet/src/main.rs @@ -43,11 +43,20 @@ struct Config { impl Config { fn from_env() -> Result { + // Whitelist exactly the four Bitcoin networks: a typo ("Testnet", + // "test-net") must not silently become a MAINNET wallet that derives + // mainnet keys and can spend real coins. let network = match std::env::var("BITCOIN_NETWORK").unwrap_or_default().as_str() { + "" | "mainnet" => Network::Bitcoin, "testnet" => Network::Testnet, "regtest" => Network::Regtest, "signet" => Network::Signet, - _ => Network::Bitcoin, + other => { + eprintln!( + "BITCOIN_NETWORK='{other}' is not one of mainnet|testnet|regtest|signet - falling back to MAINNET" + ); + Network::Bitcoin + } }; Ok(Self { network, @@ -109,6 +118,10 @@ struct AppState { /// Wallet creation unix time - sync horizon for freshly created wallets. sync_start_time: Mutex, syncing: AtomicBool, + /// Human-readable failure from the most recent sync attempt (cleared on + /// success). Surfaced via /status so a silently-refused or failing scan + /// is visible to the client instead of a permanent 0.00 balance. + last_sync_error: Mutex>, node: reqwest::Client, } @@ -482,6 +495,10 @@ async fn create_wallet( match open_wallet(&state, &mnemonic, created_at).await { Ok(()) => { + // Scan immediately: a restore that reads 0.00 until the user + // finds the sync button looks exactly like "your coins are + // gone". Fire-and-forget - the /status endpoint reports progress. + spawn_sync(&state); // Echo the mnemonic ONLY when we generated it. For restores the // user already knows their seed - never serve it back. let mut body = json!({ @@ -494,50 +511,92 @@ async fn create_wallet( } Json(body).into_response() } - Err(e) => internal_error(e.context("opening wallet after creation")), + Err(e) => { + // The seed file now exists but the wallet is unusable (sqlite + // open/write error, disk full): every later POST /wallet would + // 409 "already exists" and a generated mnemonic is lost. Remove + // the failed wallet files so the user can simply retry. + let seed_path = state.seed_path(); + if let Err(cleanup) = fs::remove_file(&seed_path) { + error!( + "wallet open failed ({e:#}) and removing the failed seed file {} failed: {cleanup:#}", + seed_path.display() + ); + } + let _ = fs::remove_file(state.config.data_dir.join("wallet.sqlite")); + internal_error(anyhow!( + "wallet file could not be opened after creation ({e:#}); the failed wallet files were removed so you can retry" + )) + } } } -/// POST /sync - sync the wallet against bitcoind (no-op while one runs). -async fn sync(State(state): State>) -> Response { +/// Kick off a background sync unless one is already running. Returns false +/// when a sync is in flight. Shared by POST /sync, wallet creation and boot +/// so no entry point leaves the wallet stale at 0.00. +fn spawn_sync(state: &Arc) -> bool { if state.syncing.swap(true, Ordering::SeqCst) { - return Json(json!({ "ok": true, "syncStarted": false })).into_response(); + return false; } - let st = Arc::clone(&state); + let st = Arc::clone(state); tokio::spawn(async move { - // A full-history restore (sync horizon 0) on a pruned node would - // silently miss coins. Better no balance than a wrong one: refuse - // the scan until the node can actually serve the whole history. let horizon = *st.sync_start_time.lock().unwrap_or_else(|p| p.into_inner()); - if horizon == 0 { - if let Ok(info) = node_rpc(&st, "getblockchaininfo", json!([])).await { - if info.get("pruned").and_then(|b| b.as_bool()).unwrap_or(false) { - error!( - "wallet restore needs the full chain but the node is pruned - sync refused; switch to a full node (BITCOIN_PRUNE=0, BITCOIN_TXINDEX=1) and resync" - ); - st.syncing.store(false, Ordering::SeqCst); - return; - } + // A scan horizon older than the node's prune window would silently + // miss coins: refuse instead (covers full-history restores AND + // narrowed horizons that still fall inside the pruned range). + let mut refused = false; + if let Ok(info) = node_rpc(&st, "getblockchaininfo", json!([])).await { + let pruned = info.get("pruned").and_then(|b| b.as_bool()).unwrap_or(false); + let prune_height = info.get("pruneheight").and_then(|b| b.as_u64()).unwrap_or(0); + if pruned && (horizon == 0 || horizon < prune_height) { + error!( + "wallet sync horizon {horizon} is older than the prune window (pruneheight {prune_height}) - sync refused; switch to a full node (BITCOIN_PRUNE=0, BITCOIN_TXINDEX=1) and resync" + ); + *st.last_sync_error.lock().unwrap_or_else(|p| p.into_inner()) = + Some(format!( + "sync refused: the node is pruned to block {prune_height}, newer than this wallet's sync horizon" + )); + refused = true; } } - let res = spawn_blocking(move || -> Result<()> { - let start_time = *st.sync_start_time.lock().unwrap_or_else(|p| p.into_inner()); - let chain = RpcBlockchain::from_config(&st.config.rpc_config(start_time))?; - let mut guard = st.wallet.blocking_lock(); - if let Some(w) = guard.as_mut() { - w.sync(&chain, SyncOptions::default())?; + if !refused { + let sb = Arc::clone(&st); + let res = spawn_blocking(move || -> Result<()> { + let start_time = *sb.sync_start_time.lock().unwrap_or_else(|p| p.into_inner()); + let chain = RpcBlockchain::from_config(&sb.config.rpc_config(start_time))?; + let mut guard = sb.wallet.blocking_lock(); + if let Some(w) = guard.as_mut() { + w.sync(&chain, SyncOptions::default())?; + } + Ok(()) + }) + .await; + match res { + Ok(Ok(())) => { + info!("wallet sync complete"); + *st.last_sync_error.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + Ok(Err(e)) => { + warn!("wallet sync failed: {e:#}"); + *st.last_sync_error.lock().unwrap_or_else(|p| p.into_inner()) = + Some(format!("last sync failed: {e}")); + } + Err(e) => { + warn!("sync task join error: {e}"); + *st.last_sync_error.lock().unwrap_or_else(|p| p.into_inner()) = + Some(format!("last sync failed: {e}")); + } } - Ok(()) - }) - .await; - match res { - Ok(Ok(())) => info!("wallet sync complete"), - Ok(Err(e)) => warn!("wallet sync failed: {e:#}"), - Err(e) => warn!("sync task join error: {e}"), } - state.syncing.store(false, Ordering::SeqCst); + st.syncing.store(false, Ordering::SeqCst); }); - Json(json!({ "ok": true, "syncStarted": true })).into_response() + true +} + +/// POST /sync - sync the wallet against bitcoind (no-op while one runs). +async fn sync(State(state): State>) -> Response { + let started = spawn_sync(&state); + Json(json!({ "ok": true, "syncStarted": started })).into_response() } /// GET /status - node + wallet overview for the Settings page. @@ -546,6 +605,12 @@ async fn status(State(state): State>) -> Response { let node_json = chain_node_json(chain.as_ref().ok()); let wallet_exists = state.seed_path().exists(); + let syncing = state.syncing.load(Ordering::SeqCst); + let last_sync_error = state + .last_sync_error + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone(); let wallet = state.wallet.lock().await; let (wallet_loaded, balance) = match wallet.as_ref() { Some(w) => match w.get_balance() { @@ -565,6 +630,8 @@ async fn status(State(state): State>) -> Response { "walletLoaded": wallet_loaded, "node": node_json, "balance": balance, + "syncing": syncing, + "lastSyncError": last_sync_error, })) .into_response() } @@ -748,6 +815,16 @@ async fn send(State(state): State>, Json(req): Json) -> R let tx = psbt.extract_tx(); let txid = tx.txid().to_string(); chain.broadcast(&tx)?; + // Mark the spent outputs locally right away: without a post-broadcast + // sync the wallet db still lists them as available, so a second send + // re-selects the same UTXOs and builds a conflicting transaction the + // node rejects. Best-effort - a failure only leaves the balance + // stale until the next sync. + if let Some(w) = guard.as_mut() { + if let Err(e) = w.sync(&chain, SyncOptions::default()) { + warn!("post-broadcast sync failed: {e:#}"); + } + } Ok(txid) }) .await; @@ -767,10 +844,16 @@ async fn fee_estimate(State(state): State>) -> Response { Ok(v) => { // btc/kB -> sat/vB = btc * 1e8 / 1000 if let Some(btc_per_kb) = v.get("feerate").and_then(|f| f.as_f64()) { - estimates.insert( - target.to_string(), - json!((btc_per_kb * 100_000_000f64 / 1000f64).ceil() as u64), - ); + // estimatesmartfee answers -1 when it lacks data (fresh + // or restarting node): the ceil conversion saturates to + // 0 sat/vB, which the UI would present as a real + // estimate. Skip instead. + if btc_per_kb > 0.0 { + estimates.insert( + target.to_string(), + json!((btc_per_kb * 100_000_000f64 / 1000f64).ceil() as u64), + ); + } } } Err(e) => warn!("estimatesmartfee({target}) failed: {e:#}"), @@ -807,6 +890,7 @@ async fn main() -> Result<()> { wallet: AsyncMutex::new(None), sync_start_time: Mutex::new(now_unix()), syncing: AtomicBool::new(false), + last_sync_error: Mutex::new(None), // Bounded timeouts on the bitcoind client: without them a hung/rpc- // wedged node pins sync/send handlers until the HTTP client gives up // (which, with no timeout, is never). @@ -821,7 +905,12 @@ async fn main() -> Result<()> { match fs::read_to_string(state.seed_path()) { Ok(raw) => match serde_json::from_str::(&raw) { Ok(file) => match open_wallet(&state, &file.mnemonic, file.created_at).await { - Ok(()) => info!("wallet loaded from persisted seed"), + Ok(()) => { + info!("wallet loaded from persisted seed"); + // Boot-time scan so balances and history are current + // without manual action after a restart. + spawn_sync(&state); + } Err(e) => error!("failed to load persisted wallet: {e:#}"), }, Err(e) => error!("seed file unreadable: {e}"), From 6291ccc84c8721f1f7124cd478129775fa3825d0 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 21 Oct 2026 00:46:29 +0200 Subject: [PATCH 05/52] fix: findings in bridge (cycle 1) - read token decimals from the chain for balances (USDC/USDT were shown 10^12x too small and Max built a reverting amount) - a stale tracked-bridge poll can no longer flip the phase while a new submission is talking to the wallet - validate the e2m receiver payload before the on-chain deposit - give up on a dead tracked request after repeated poll failures - label the Mintlayer explorer link by direction (deposit vs payout) - reset the picker icon fallback when the token changes - release unread ipfs gateway bodies and time out pinning uploads --- app/src/components/BridgeHistorySection.tsx | 5 +- app/src/components/BridgePanel.tsx | 53 +++++++++++++++++++-- app/src/components/BridgeTokenPicker.tsx | 5 ++ app/src/lib/evm.ts | 6 ++- app/src/pages/api/ipfs-upload.ts | 13 +++++ app/src/pages/ipfs/[...path].ts | 6 +++ 6 files changed, 80 insertions(+), 8 deletions(-) diff --git a/app/src/components/BridgeHistorySection.tsx b/app/src/components/BridgeHistorySection.tsx index f270492..a165c1c 100644 --- a/app/src/components/BridgeHistorySection.tsx +++ b/app/src/components/BridgeHistorySection.tsx @@ -120,7 +120,10 @@ function Row({ rel="noopener noreferrer" className="text-mint-300 underline hover:opacity-80" > - Payout on the Mintlayer explorer ↗ + {entry.direction === 'm2e' + ? 'Deposit on the Mintlayer explorer' + : 'Payout on the Mintlayer explorer'}{' '} + ↗ )}

diff --git a/app/src/components/BridgePanel.tsx b/app/src/components/BridgePanel.tsx index 90496ed..a17b746 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, @@ -43,9 +44,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 +171,8 @@ 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); + const pollFailuresRef = useRef(0); + const [pollUnavailable, setPollUnavailable] = useState(false); const metamaskInstalled = hasEthereumProvider(); @@ -446,6 +455,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 +465,14 @@ 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). + if (!submittingRef.current && !SUBMIT_PHASES.has(phase)) { + setPhase( + next.kind === 'completed' ? 'done' : next.kind === 'manual' ? 'manual' : 'failed', + ); + } } const advanced = next.step > latest.lastStep; // First sight of the deposit hash (ML→ETH submits without one) - @@ -470,7 +487,14 @@ 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); + } } }, []); @@ -483,15 +507,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 { @@ -525,6 +551,8 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled setTracked(null); setTrackedProgress(null); setTrackedRequest(null); + setPollUnavailable(false); + pollFailuresRef.current = 0; setPhase('idle'); } @@ -595,6 +623,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; + } } } @@ -1151,7 +1191,10 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled rel="noopener noreferrer" className="text-mint-300 underline hover:opacity-80" > - Payout on the Mintlayer explorer ↗ + {direction === 'm2e' + ? 'Deposit on the Mintlayer explorer' + : 'Payout on the Mintlayer explorer'}{' '} + ↗ )}

diff --git a/app/src/components/BridgeTokenPicker.tsx b/app/src/components/BridgeTokenPicker.tsx index 027de4d..f11c6e3 100644 --- a/app/src/components/BridgeTokenPicker.tsx +++ b/app/src/components/BridgeTokenPicker.tsx @@ -73,6 +73,11 @@ const input = function TokenIcon({ metadata, ticker }: { metadata: TokenMetadata | null; ticker: string }) { const [broken, setBroken] = useState(false); const src = metadata?.icon ? safeImageUri(metadata.icon) : null; + // Reset when this instance starts rendering a different token, so a + // 404 on one icon does not poison the next one. + useEffect(() => { + setBroken(false); + }, [src]); if (!src || broken) { return ( diff --git a/app/src/lib/evm.ts b/app/src/lib/evm.ts index 8bac7b5..1995d62 100644 --- a/app/src/lib/evm.ts +++ b/app/src/lib/evm.ts @@ -142,12 +142,14 @@ export async function switchChain( export async function getTokenBalance( tokenAddress: string, userAddress: string, - decimals = 18, ): Promise { const p = provider(); const token = new Contract(tokenAddress, ERC20_ABI, p); + // 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 = await token.decimals(); const balance = await token.balanceOf(userAddress); - return formatUnits(balance, decimals); + return formatUnits(balance, Number(decimals)); } /** 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/ipfs/[...path].ts b/app/src/pages/ipfs/[...path].ts index 18bb50b..336ad80 100644 --- a/app/src/pages/ipfs/[...path].ts +++ b/app/src/pages/ipfs/[...path].ts @@ -186,6 +186,9 @@ export async function GET(ctx: { } } else { clearTimeout(timer); + // Release the unread body so the keep-alive socket goes back to + // the pool instead of waiting for garbage collection. + void upstreamRes.body?.cancel().catch(() => {}); lastStatus = 502; break; // foreign redirect - this gateway misbehaves, next one } @@ -193,6 +196,7 @@ export async function GET(ctx: { if (upstreamRes.status !== 200) { clearTimeout(timer); + void upstreamRes.body?.cancel().catch(() => {}); lastStatus = upstreamRes.status === 404 ? 404 : 502; break; // an HTTP answer - next gateway, not a retry } @@ -201,6 +205,7 @@ export async function GET(ctx: { const declaredLength = Number(upstreamRes.headers.get('content-length') ?? ''); if (Number.isFinite(declaredLength) && declaredLength > MAX_BYTES) { clearTimeout(timer); + void upstreamRes.body?.cancel().catch(() => {}); return errorResponse('Too large', 413); } @@ -209,6 +214,7 @@ export async function GET(ctx: { .trim(); if (!ALLOWED_TYPES.test(contentType)) { clearTimeout(timer); + void upstreamRes.body?.cancel().catch(() => {}); // Fail fast: content-type is a property of the CID content, not // of the gateway - another gateway would serve the same bytes. return errorResponse('Unsupported media type', 415); From 0b23a76d46916cd2512dfbc21fc45b4b8e13c430 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 21 Oct 2026 00:52:25 +0200 Subject: [PATCH 06/52] fix: findings in settings-management (cycle 1) - failed upgrades and rollbacks now render their error instead of reloading over it, and the last failure is shown server-side - validate the large-send threshold before storing it - require a fresh 2FA code to remove a passkey, same as enrolling - stop rendering ipfs provider secrets into the page; keys are write-only with a last-four hint, and the page is no-store - probe the key-lock state without revealing seed material and only for an open wallet - validate the lookahead size and refuse locking while staking - report a failed request write as a 503 instead of a bare 500 --- app/src/pages/api/features/disable.ts | 8 ++- app/src/pages/api/features/enable.ts | 28 ++++---- app/src/pages/api/features/rollback.ts | 8 ++- app/src/pages/api/features/upgrade.ts | 22 ++++--- app/src/pages/management/settings.astro | 87 ++++++++++++++++++------- app/src/pages/management/wallet.astro | 38 +++++++---- 6 files changed, 134 insertions(+), 57 deletions(-) diff --git a/app/src/pages/api/features/disable.ts b/app/src/pages/api/features/disable.ts index d030789..31dea15 100644 --- a/app/src/pages/api/features/disable.ts +++ b/app/src/pages/api/features/disable.ts @@ -58,8 +58,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..9857271 100644 --- a/app/src/pages/api/features/enable.ts +++ b/app/src/pages/api/features/enable.ts @@ -63,18 +63,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/management/settings.astro b/app/src/pages/management/settings.astro index c826e68..b376f82 100644 --- a/app/src/pages/management/settings.astro +++ b/app/src/pages/management/settings.astro @@ -81,17 +81,28 @@ 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.' }; + } } } @@ -111,12 +122,16 @@ 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') ?? ''; 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.' }; } } @@ -126,8 +141,15 @@ 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. + const rawThreshold = (form.get('large_send_threshold') as string | null) ?? ''; + const thresholdNum = Number(rawThreshold); + const threshold = + rawThreshold.trim() !== '' && Number.isFinite(thresholdNum) && thresholdNum >= 0 + ? 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.' }; @@ -292,6 +314,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'); --- @@ -478,9 +502,14 @@ if (localCaPem) { {new Date(pk.createdAt).toLocaleDateString()}
-
+ +