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
+ {webGuiServiceResult && !webGuiServiceResult.ok && webGuiServiceResult.error && (
+
+ Last upgrade request failed: {webGuiServiceResult.error}
+
+ )}
@@ -819,7 +851,7 @@ if (localCaPem) {
}
}
- function watchWebGui(startedAt: number, onDone: () => void) {
+ function watchWebGui(startedAt: number, onDone: (ok: boolean) => void) {
let failures = 0;
const timer = window.setInterval(async () => {
if (Date.now() - startedAt > 12 * 60 * 1000) {
@@ -836,11 +868,15 @@ if (localCaPem) {
const fresh = state.lastResult && state.lastResult.at !== null && state.lastResult.at >= startedAt - 60_000;
if (!fresh) return;
window.clearInterval(timer);
- onDone();
if (!state.lastResult.ok) {
+ // A failed attempt must be visible: keep the page (a
+ // reload would wipe the note) and say what went wrong.
setNote(rollbackNote, state.lastResult.error ?? 'The last request failed.', 'error');
setNote(noteEl, state.lastResult.error ?? 'The last request failed.', 'error');
+ onDone(false);
+ return;
}
+ onDone(true);
} catch {
failures += 1;
if (failures >= 3) {
@@ -878,7 +914,12 @@ if (localCaPem) {
return;
}
setNote(noteEl, 'Queued - pulling images, then restarting. The interface goes down briefly at the end.', 'info');
- watchWebGui(Date.now(), () => window.location.reload());
+ watchWebGui(Date.now(), (ok) => {
+ // Success: the containers just changed under us - reload
+ // lands on the new version. Failure: onDone already
+ // rendered the error note; stay on the page.
+ if (ok) window.location.reload();
+ });
});
rollbackForm?.addEventListener('submit', async (ev) => {
@@ -894,7 +935,9 @@ if (localCaPem) {
return;
}
setNote(rollbackNote, 'Queued - restoring previous images, then restarting.', 'info');
- watchWebGui(Date.now(), () => window.location.reload());
+ watchWebGui(Date.now(), (ok) => {
+ if (ok) window.location.reload();
+ });
});
autoForm?.addEventListener('submit', async (ev) => {
diff --git a/app/src/pages/management/wallet.astro b/app/src/pages/management/wallet.astro
index c0c07d0..41769d5 100644
--- a/app/src/pages/management/wallet.astro
+++ b/app/src/pages/management/wallet.astro
@@ -118,20 +118,32 @@ if (Astro.request.method === 'POST') {
}
}
} else if (action === 'lock') {
+ // Mirror the UI guard server-side: locking while staking is running
+ // silently stalls block signing.
+ if ((await getStakingStatus(0).catch(() => 'NotStaking')) === 'Staking') {
+ actionError = 'Cannot lock while staking is running. Stop staking first.';
+ } else {
await walletLockPrivateKeys();
isLocked = true;
actionSuccess = 'Private keys locked.';
- } else if (action === 'unlock') {
+ }
+ } else if (action === 'unlock') {
const password = form.get('password') as string;
await walletUnlockPrivateKeys(password);
isLocked = false;
actionSuccess = 'Private keys unlocked.';
} else if (action === 'set_lookahead') {
- const size = parseInt(form.get('lookahead_size') as string, 10);
- await walletSetLookaheadSize(size);
- lookaheadSize = size;
- setPref('wallet.lookahead_size', size);
- actionSuccess = `Lookahead size set to ${size}.`;
+ // Client-side min/max are not enforcement - validate here before the
+ // RPC call and the pref write.
+ const parsed = Number(form.get('lookahead_size'));
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 1000) {
+ actionError = 'Lookahead size must be a whole number between 1 and 1000.';
+ } else {
+ await walletSetLookaheadSize(parsed);
+ lookaheadSize = parsed;
+ setPref('wallet.lookahead_size', parsed);
+ actionSuccess = `Lookahead size set to ${parsed}.`;
+ }
} else if (action === 'close_wallet') {
await walletClose();
info = null;
@@ -181,13 +193,17 @@ if (Astro.request.method === 'POST') {
}
}
-// Probe lock state on initial GET (or if action didn't resolve it)
-if (isLocked === null) {
+// Probe lock state on initial GET (or if an action didn't resolve it).
+// Never probe with a seed-revealing RPC on every page view: staking_status
+// needs the private keys loaded, so a "locked" failure marks the keys as
+// locked without touching seed material. Any other error stays 'unknown'
+// (same as before) and the unlock form is shown either way.
+if (isLocked === null && sessionState === 'open') {
try {
- await walletShowSeedPhrase(); // succeeds only when keys are unlocked
+ await getStakingStatus(0);
isLocked = false;
- } catch {
- isLocked = true;
+ } catch (err) {
+ isLocked = /lock/i.test((err as Error).message) ? true : null;
}
}
// The show_seed action renders seed-phrase material - never cache this page.
From 674b53e47479e19dad825bd9ec5d752b18c55c46 Mon Sep 17 00:00:00 2001
From: Enrico Rubboli
Date: Wed, 21 Oct 2026 00:58:34 +0200
Subject: [PATCH 07/52] fix: findings in foundation-lib (cycle 1)
- Signet addresses now use the tb human-readable part (BIP-0326).
- P2WSH payloads pass validation instead of falling into the typo
corrector, which could rewrite a valid address.
- depositToBridge verifies the wallet is still on the expected chain
right before signing; USDT-style approvals reset to zero first;
missing-chain errors are retried via wallet_addEthereumChain.
- Plugin installs use unique temp dirs, clear stale targets and import
entries through properly encoded file URLs.
- Browser RPC proxy drops transaction_abandon (now behind 2FA at
/api/transaction-abandon) and no longer hides transport failures.
- Mempool capability probe negotiates JSON, keeping detection honest.
- CSP stays report-only until inline scripts carry nonces.
---
app/src/components/BridgePanel.tsx | 3 ++
app/src/lib/bech32-correct.test.ts | 2 +-
app/src/lib/bech32-correct.ts | 12 ++++-
app/src/lib/bech32.ts | 2 +-
app/src/lib/client-rpc.test.ts | 2 +
app/src/lib/client-rpc.ts | 31 ++++++++++---
app/src/lib/csp.ts | 6 ++-
app/src/lib/evm.ts | 35 +++++++++++++--
app/src/lib/indexer-capabilities.ts | 10 +++--
app/src/lib/plugins.test.ts | 26 +++++++----
app/src/lib/plugins.ts | 18 ++++++--
app/src/lib/rpc-allowlist.ts | 5 ++-
app/src/middleware.ts | 13 +++---
app/src/pages/api/transaction-abandon.ts | 50 +++++++++++++++++++++
app/src/pages/management/transactions.astro | 17 ++++++-
15 files changed, 189 insertions(+), 43 deletions(-)
create mode 100644 app/src/pages/api/transaction-abandon.ts
diff --git a/app/src/components/BridgePanel.tsx b/app/src/components/BridgePanel.tsx
index a17b746..59c3fe1 100644
--- a/app/src/components/BridgePanel.tsx
+++ b/app/src/components/BridgePanel.tsx
@@ -688,6 +688,9 @@ export default function BridgePanel({ indexerEnabled = false }: { indexerEnabled
18,
receiver.trim(),
setPhase,
+ // switchChainIfNeeded already verified this resolves before we
+ // got here; default to mainnet for the type-level null only.
+ Number.parseInt(chainForFlavor(flavor)?.id ?? '0x1', 16),
);
setPhase('submitting');
const res = await sdk.broadcastBridgeRequest({
diff --git a/app/src/lib/bech32-correct.test.ts b/app/src/lib/bech32-correct.test.ts
index 61db076..c6afaf3 100644
--- a/app/src/lib/bech32-correct.test.ts
+++ b/app/src/lib/bech32-correct.test.ts
@@ -148,7 +148,7 @@ describe("hrpForNetwork", () => {
expect(hrpForNetwork("btc", "mainnet")).toBe("bc");
expect(hrpForNetwork("btc", "testnet")).toBe("tb");
expect(hrpForNetwork("btc", "regtest")).toBe("bcrt");
- expect(hrpForNetwork("btc", "signet")).toBe("sb");
+ expect(hrpForNetwork("btc", "signet")).toBe("tb");
});
it("maps ML networks", () => {
diff --git a/app/src/lib/bech32-correct.ts b/app/src/lib/bech32-correct.ts
index 1044536..7f5d4b0 100644
--- a/app/src/lib/bech32-correct.ts
+++ b/app/src/lib/bech32-correct.ts
@@ -45,10 +45,13 @@ function isValidChainPayload(_hrp: string, data: number[], encoding: Bech32Encod
const version = data[0];
if (version === undefined || version > 16) return false;
if (chain === "btc") {
+ // Lengths are counted in 5-bit symbols (the checksum is 6 symbols),
+ // so a 20-byte P2WPKH program is 32 symbols and a 32-byte P2WSH is
+ // 52 - comparing against byte counts rejected valid P2WSH addresses.
const programLen = data.length - 7;
if (version === 0) {
if (encoding !== "bech32") return false;
- if (programLen !== 20 && programLen !== 32) return false;
+ if (programLen !== 32 && programLen !== 52) return false;
} else {
if (encoding !== "bech32m") return false;
// program length in symbols: 2..40 bytes -> ceil(bytes*8/5) symbols
@@ -86,6 +89,13 @@ export function suggestAddressCorrection(
return { status: "invalid", reason: "invalid characters" };
}
+ // Bech32 addresses are at most 90 chars and decode() rejects anything
+ // over 1023; without this cap a long paste runs a quadratic syndrome
+ // build on every keystroke and freezes the tab.
+ if (lower.length > 1023) {
+ return { status: "invalid", reason: "too long" };
+ }
+
// separator = the LAST '1'; the hrp region must equal the expected hrp
// exactly (hrp symbols are never correction candidates, so a fuzzy scan
// could only ever lock onto a "tmt1"-shaped coincidence inside the data
diff --git a/app/src/lib/bech32.ts b/app/src/lib/bech32.ts
index 1e83162..6c7049c 100644
--- a/app/src/lib/bech32.ts
+++ b/app/src/lib/bech32.ts
@@ -130,7 +130,7 @@ export function hrpForNetwork(chain: Bech32Chain, network: string): string | nul
case 'mainnet': return 'bc';
case 'testnet': return 'tb';
case 'regtest': return 'bcrt';
- case 'signet': return 'sb';
+ case 'signet': return 'tb'; // signet shares the testnet HRP (BIP-0326)
default: return null;
}
}
diff --git a/app/src/lib/client-rpc.test.ts b/app/src/lib/client-rpc.test.ts
index af8e420..03503a9 100644
--- a/app/src/lib/client-rpc.test.ts
+++ b/app/src/lib/client-rpc.test.ts
@@ -32,6 +32,7 @@ describe('rpc', () => {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ method: 'get_blockchain_info', params: { verbose: true } }),
+ signal: expect.any(AbortSignal),
});
});
@@ -45,6 +46,7 @@ describe('rpc', () => {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ method: 'get_height', params: {} }),
+ signal: expect.any(AbortSignal),
});
});
diff --git a/app/src/lib/client-rpc.ts b/app/src/lib/client-rpc.ts
index fc3baab..4aec037 100644
--- a/app/src/lib/client-rpc.ts
+++ b/app/src/lib/client-rpc.ts
@@ -3,12 +3,31 @@
* Throws with the RPC error message when the call fails.
*/
export async function rpc(method: string, params: Record = {}): Promise {
- const res = await fetch('/api/rpc', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ method, params }),
- });
- const data = await res.json() as { ok: boolean; result?: T; error?: { message: string } };
+ let res: Response;
+ try {
+ res = await fetch('/api/rpc', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ method, params }),
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch (err) {
+ if (err instanceof Error && err.name === 'TimeoutError') {
+ throw new Error('The wallet service took too long to answer.');
+ }
+ throw new Error('Could not reach the wallet service.');
+ }
+ // A proxy or error page can answer with HTML - report the status
+ // instead of a JSON parse error.
+ let data: { ok: boolean; result?: T; error?: { message: string } };
+ try {
+ data = await res.json();
+ } catch {
+ throw new Error(`Wallet service error (HTTP ${res.status}).`);
+ }
+ if (!res.ok) {
+ throw new Error(data.error?.message ?? `Wallet service error (HTTP ${res.status}).`);
+ }
if (!data.ok) throw new Error(data.error?.message ?? 'RPC error');
return data.result as T;
}
diff --git a/app/src/lib/csp.ts b/app/src/lib/csp.ts
index c26c008..009c0a0 100644
--- a/app/src/lib/csp.ts
+++ b/app/src/lib/csp.ts
@@ -14,8 +14,10 @@
* are dropped, so a stray value cannot widen the policy into
* `connect-src *`.
*
- * Rollout stays report-only by default (see middleware.ts); enforcement
- * still requires the inline-script nonce work.
+ * Rollout stays report-only - middleware.ts never flips this into an
+ * enforcing header. Enforcement still requires the inline-script nonce
+ * work: script-src currently carries 'unsafe-inline', so enforcing as-is
+ * would not contain injected scripts while breaking nothing else.
*/
import { getBridgeApiUrl, getMintlayerApiUrl } from '@/lib/bridge-sdk/config';
diff --git a/app/src/lib/evm.ts b/app/src/lib/evm.ts
index 1995d62..5c7dd2a 100644
--- a/app/src/lib/evm.ts
+++ b/app/src/lib/evm.ts
@@ -126,8 +126,11 @@ export async function switchChain(
});
} catch (err) {
const code = (err as { code?: number }).code;
- // 4902 = chain not added to the wallet
- if (code === 4902 && chainParams) {
+ const msg = (err as { message?: string }).message ?? '';
+ // 4902 = chain not added to the wallet; some MetaMask versions
+ // (mobile especially) report -32603 "Unrecognized chain" instead.
+ const missing = code === 4902 || (code === -32603 && /unrecognized chain/i.test(msg));
+ if (missing && chainParams) {
await eth().request({
method: 'wallet_addEthereumChain',
params: [{ chainId: chainIdHex, ...chainParams }],
@@ -164,6 +167,7 @@ export async function depositToBridge(
decimals: number,
mintlayerAddress: string,
onProgress?: (phase: 'approve' | 'deposit') => void,
+ expectedChainId?: number,
): Promise {
if (!bridgeContractAddress) {
throw new Error('Bridge contract address is not configured.');
@@ -171,6 +175,19 @@ export async function depositToBridge(
const p = provider();
const signer = await p.getSigner();
+ // Signing happens against whatever chain the wallet currently has
+ // active (another tab or a mobile app can switch it): verify right
+ // before the money moves. A codeless address on the wrong chain would
+ // otherwise "mine" a deposit that never exists.
+ if (typeof expectedChainId === 'number') {
+ const { chainId } = await p.getNetwork();
+ if (chainId !== BigInt(expectedChainId)) {
+ throw new EvmError(
+ 'Your wallet switched to a different network. Switch back to the bridge network and try again.',
+ );
+ }
+ }
+
const token = new Contract(tokenAddress, ERC20_ABI, signer);
// The chain is the source of truth for decimals - many bridgeable
// tokens (USDC et al.) are not 18, and the config carries no value.
@@ -200,8 +217,18 @@ export async function depositToBridge(
}
if (needsApproval) {
onProgress?.('approve');
- const approveTx = await token.approve(bridgeContractAddress, amountWei);
- await approveTx.wait();
+ try {
+ const approveTx = await token.approve(bridgeContractAddress, amountWei);
+ await approveTx.wait();
+ } catch (err) {
+ // USDT-class tokens revert on a non-zero -> non-zero approve; the
+ // fix is a zero-reset first, then the real allowance.
+ if (normalizeEvmRejection(err).code === 4001) throw err;
+ const resetTx = await token.approve(bridgeContractAddress, 0);
+ await resetTx.wait();
+ const approveTx = await token.approve(bridgeContractAddress, amountWei);
+ await approveTx.wait();
+ }
}
const bridge = new Contract(bridgeContractAddress, BRIDGE_DEPOSIT_ABI, signer);
diff --git a/app/src/lib/indexer-capabilities.ts b/app/src/lib/indexer-capabilities.ts
index bcfc1cc..d04a5f8 100644
--- a/app/src/lib/indexer-capabilities.ts
+++ b/app/src/lib/indexer-capabilities.ts
@@ -31,10 +31,10 @@ let cache: { capabilities: IndexerCapabilities; expiresAt: number } | null = nul
* aborted as soon as the response headers arrive only costs one HTTP round
* trip and no event delivery.
*/
-async function probeEndpoint(path: string): Promise {
+async function probeEndpoint(path: string, accept: string): Promise {
try {
const res = await fetch(`${INDEXER_URL}/api/v2${path}`, {
- headers: { accept: 'text/event-stream' },
+ headers: { accept },
signal: AbortSignal.timeout(5_000),
});
// Release the connection immediately - we only care about the status.
@@ -54,8 +54,10 @@ export async function getIndexerCapabilities(force = false): Promise ({
deletePref: vi.fn(),
}));
-vi.mock('node:fs', () => ({
- existsSync: vi.fn(),
- mkdirSync: vi.fn(),
- readFileSync: vi.fn(),
- readdirSync: vi.fn(),
- realpathSync: vi.fn(),
- rmSync: vi.fn(),
- statSync: vi.fn(),
- writeFileSync: vi.fn(),
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ existsSync: vi.fn(),
+ mkdirSync: vi.fn(),
+ mkdtempSync: vi.fn(() => actual.mkdtempSync('/tmp/plugin-test-')),
+ readFileSync: vi.fn(),
+ readdirSync: vi.fn(),
+ realpathSync: vi.fn(),
+ rmSync: vi.fn(),
+ statSync: vi.fn(),
+ writeFileSync: vi.fn(),
+ };
+});
+
+vi.mock('node:url', () => ({
+ pathToFileURL: (p: string) => ({ href: `file://${p}` }),
}));
vi.mock('node:child_process', () => ({
diff --git a/app/src/lib/plugins.ts b/app/src/lib/plugins.ts
index 1d10b25..3c481ac 100644
--- a/app/src/lib/plugins.ts
+++ b/app/src/lib/plugins.ts
@@ -10,6 +10,7 @@ import { execFileSync } from 'node:child_process';
import {
existsSync,
mkdirSync,
+ mkdtempSync,
readFileSync,
readdirSync,
realpathSync,
@@ -18,6 +19,8 @@ import {
writeFileSync,
} from 'node:fs';
import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { pathToFileURL } from 'node:url';
import { getPref, setPref, deletePref } from './prefs-db';
import { rpcCall } from './wallet-rpc';
import { ALLOWED_RPC_METHODS } from './rpc-allowlist';
@@ -107,8 +110,10 @@ export function togglePlugin(id: string, enabled: boolean): void {
// ── Install / Uninstall ───────────────────────────────────────────────────────
export async function installPlugin(buffer: Buffer): Promise {
- const tmpTgz = `/tmp/plugin-upload-${Date.now()}.tgz`;
- const tmpDir = `/tmp/plugin-extract-${Date.now()}`;
+ // mkdtemp gives a unique directory per install - two same-millisecond
+ // uploads must not share an extraction target.
+ const tmpDir = mkdtempSync(join(tmpdir(), 'plugin-install-'));
+ const tmpTgz = join(tmpDir, 'plugin.tgz');
try {
writeFileSync(tmpTgz, buffer);
@@ -177,6 +182,10 @@ export async function installPlugin(buffer: Buffer): Promise {
const destDir = join(PLUGINS_DIR, manifest.id);
mkdirSync(PLUGINS_DIR, { recursive: true });
+ // A crashed prior install can leave the directory without a registry
+ // entry; POSIX cp -r into an existing dir would nest the tree one
+ // level down and the plugin could never load. Clear first.
+ rmSync(destDir, { recursive: true, force: true });
execFileSync('cp', ['-r', pluginRoot, destDir], { timeout: 10_000 });
existing.push(manifest);
@@ -228,8 +237,9 @@ export async function loadPluginHandler(id: string): Promise {
}
const entryPath = join(PLUGINS_DIR, id, manifest.entry);
- // Query parameter busts Node's ESM cache after reinstall
- const url = `file://${entryPath}?gen=${gen}`;
+ // pathToFileURL percent-encodes reserved characters ('#', '?') so the
+ // cache-busting query can't swallow part of the path.
+ const url = `${pathToFileURL(entryPath).href}?gen=${gen}`;
const module = await import(/* @vite-ignore */ url) as PluginModule;
if (typeof module.handler !== 'function') {
diff --git a/app/src/lib/rpc-allowlist.ts b/app/src/lib/rpc-allowlist.ts
index 5f6d8fe..9a56dca 100644
--- a/app/src/lib/rpc-allowlist.ts
+++ b/app/src/lib/rpc-allowlist.ts
@@ -52,7 +52,10 @@ export const ALLOWED_RPC_METHODS = new Set([
// Transactions
'transaction_list_by_address',
'transaction_list_pending',
- 'transaction_abandon',
+ // transaction_abandon removed: un-reserving a pending tx's inputs is
+ // fund-affecting (a hijacked session could clobber a payment the user
+ // just approved) - same policy as address_send/token_send. If the UI
+ // needs it, expose it behind requireStepUp.
// UTXOs
'account_utxos',
// address_sweep_spendable removed: with `all: true` (or empty from_addresses)
diff --git a/app/src/middleware.ts b/app/src/middleware.ts
index 0264e3e..00e46b4 100644
--- a/app/src/middleware.ts
+++ b/app/src/middleware.ts
@@ -46,8 +46,6 @@ const SECURITY_HEADERS: Record = {
*/
const CSP_POLICY = buildCsp();
-const CSP_ENABLED = process.env.CSP_ENABLED === 'true';
-
export const onRequest = defineMiddleware(async (context, next) => {
const { pathname } = new URL(context.request.url);
@@ -137,12 +135,11 @@ function applySecurityHeaders(response: Response): void {
response.headers.set(key, value);
}
}
- // CSP: report-only by default; opt into enforcement with CSP_ENABLED=true.
- if (CSP_ENABLED) {
- if (!response.headers.has('Content-Security-Policy')) {
- response.headers.set('Content-Security-Policy', CSP_POLICY);
- }
- } else if (!response.headers.has('Content-Security-Policy-Report-Only')) {
+ // CSP: report-only by default, and CSP_ENABLED=true keeps it that way
+ // for scripts: the policy still carries 'unsafe-inline' in script-src
+ // (no nonce plumbing yet), so enforcing it today would change connect
+ // behavior without containing any injected script.
+ if (!response.headers.has('Content-Security-Policy-Report-Only')) {
response.headers.set('Content-Security-Policy-Report-Only', CSP_POLICY);
}
}
diff --git a/app/src/pages/api/transaction-abandon.ts b/app/src/pages/api/transaction-abandon.ts
new file mode 100644
index 0000000..a5ade2b
--- /dev/null
+++ b/app/src/pages/api/transaction-abandon.ts
@@ -0,0 +1,50 @@
+import type { APIRoute } from 'astro';
+import { json } from '@/lib/api-utils';
+import { rpcCall, WalletRpcError } from '@/lib/wallet-rpc';
+import { requireStepUp, totpFromBody } from '@/lib/step-up';
+
+/**
+ * POST /api/transaction-abandon - TOTP-gated abandon of a pending transaction.
+ *
+ * Abandoning un-reserves a pending transaction's inputs for re-spend, so it
+ * is fund-affecting: it requires a fresh TOTP code (step-up) on top of the
+ * session cookie, exactly like /api/send and /api/stake-trade. The method is
+ * intentionally absent from the browser/plugin RPC allowlist - this endpoint
+ * is the only path.
+ *
+ * Body: { totp_code, transaction_id }. The account is fixed server-side.
+ */
+
+export const POST: APIRoute = async ({ request, clientAddress }) => {
+ let body: Record = {};
+ try {
+ const parsed: unknown = await request.json();
+ if (parsed !== null && typeof parsed === 'object') body = parsed as Record;
+ } catch {
+ return json({ ok: false, error: 'Invalid request body.' }, 400);
+ }
+
+ const transactionId = typeof body.transaction_id === 'string' ? body.transaction_id.trim() : '';
+ // ML transaction ids are hex; refuse anything else before burning a code.
+ if (!/^[0-9a-f]{16,80}$/i.test(transactionId)) {
+ return json({ ok: false, error: 'A valid transaction id is required.' }, 400);
+ }
+
+ const stepUp = requireStepUp(totpFromBody(body), request, clientAddress as string | undefined);
+ if (!stepUp.ok) {
+ return json({ ok: false, error: stepUp.error }, stepUp.status);
+ }
+
+ try {
+ await rpcCall('transaction_abandon', { account: 0, transaction_id: transactionId });
+ return json({ ok: true }, 200);
+ } catch (err) {
+ if (err instanceof WalletRpcError) {
+ return json({ ok: false, error: err.message }, 502);
+ }
+ return json(
+ { ok: false, error: 'The wallet service is unavailable. Check that all services are running.' },
+ 502,
+ );
+ }
+};
diff --git a/app/src/pages/management/transactions.astro b/app/src/pages/management/transactions.astro
index a442c41..22bfd90 100644
--- a/app/src/pages/management/transactions.astro
+++ b/app/src/pages/management/transactions.astro
@@ -210,11 +210,24 @@ function outputSummary(detail: DecodedTransaction | null | undefined): string {
)}