From c3e2e37e9b0186814a5d9cc04b9c728427e4f0cd Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Wed, 2 Dec 2026 13:45:56 -0700 Subject: auth: lock PIN checks after ten wrong PINs in an hour Every PIN check answered right or wrong with no per-account limit (POST /pin, the sends that require a PIN, and the settings update), so anyone holding a stolen session could try every 6-digit PIN from rotating IPs. checkPin() now counts wrong PINs per account in pinfail:; after ten in an hour every PIN check fails, the right PIN included, until the hour is up. A missing PIN doesn't count, and the right PIN clears the count. POST /pin answers 429 while locked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VMan6SSfVopM1ZzXKZmLYU --- lib/auth.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) (limited to 'lib/auth.ts') diff --git a/lib/auth.ts b/lib/auth.ts index 107c44f4..af5de3fd 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -22,8 +22,31 @@ export const auth = { }), }; +// Wrong PINs per account. Without a limit, anyone holding a stolen session +// can try all 10^6 PINs from rotating IPs, since every PIN check answers +// right/wrong. After PIN_MAX wrong guesses in PIN_WINDOW seconds, every PIN +// check fails, the right PIN included, until the window runs out. +const PIN_MAX = 10; +const PIN_WINDOW = 3600; + +// true if the account has no PIN or `pin` is right. A missing pin is not a +// guess and doesn't count; a wrong one does. +export const checkPin = async (user, pin) => { + if (!user?.pin) return true; + const k = `pinfail:${user.id}`; + const n = Number(await db.get(k)) || 0; + if (n >= PIN_MAX) fail("Too many wrong PINs, try again in an hour"); + if (pin === undefined || pin === null || pin === "") return false; + if (pin === user.pin) { + if (n) await db.del(k); + return true; + } + if ((await db.incr(k)) === 1) await db.expire(k, PIN_WINDOW); + return false; +}; + export const requirePin = async ({ body, user }) => { - if (!user || (user.pin && user.pin !== body.pin)) fail("Invalid pin"); + if (!user || !(await checkPin(user, body?.pin))) fail("Invalid pin"); }; // A caller-supplied `aid` decides which account's node wallet composes and -- cgit v1.2.3