From 3c36bdf2a948f1453eb6df485a29f7a7153e171d Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Fri, 20 Nov 2026 10:01:47 +0000 Subject: [PATCH] security: cap MXID verification DMs per member per day --- app/main.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index 507831d..9d3f14d 100644 --- a/app/main.py +++ b/app/main.py @@ -555,6 +555,12 @@ try: MATRIX_MXID_CHANGE_DAYS = float(os.environ.get("MATRIX_MXID_CHANGE_DAYS", "7") or 7) except ValueError: MATRIX_MXID_CHANGE_DAYS = 7.0 +# Verification DMs are capped per member per rolling 24h. Without this, a +# member can make the bot DM arbitrary Matrix IDs every minute (rooms + spam). +try: + MATRIX_MXID_CODE_PER_DAY = int(os.environ.get("MATRIX_MXID_CODE_PER_DAY", "5") or 5) +except ValueError: + MATRIX_MXID_CODE_PER_DAY = 5 LOOMIO_GROUP_ID = os.environ.get("LOOMIO_GROUP_ID", "") # Operator accounts that must always remain in the Loomio group (never removed # by the remove_absent reconciliation), comma-separated. @@ -1100,9 +1106,12 @@ def get_db() -> sqlite3.Connection: conn.execute("ALTER TABLE members ADD COLUMN matrix_mxid_changed_at TEXT") # Migration: pending external-MXID verification. An external account is not # invited until a one-time code sent to that MXID is entered on the dashboard. - for col in ("mxid_pending", "mxid_code_hash", "mxid_code_expires", "mxid_code_sent_at"): + for col in ("mxid_pending", "mxid_code_hash", "mxid_code_expires", "mxid_code_sent_at", + "mxid_code_window_start"): if col not in cols: conn.execute(f"ALTER TABLE members ADD COLUMN {col} TEXT") + if "mxid_code_attempts" not in cols: + conn.execute("ALTER TABLE members ADD COLUMN mxid_code_attempts INTEGER DEFAULT 0") # Migration: credit_balance — purchased, NON-EXPIRING credits (USD). # Distinct from `balance` (the monthly allowance, which resets): credits # carry over indefinitely and are spent only after the allowance is @@ -1949,7 +1958,28 @@ def clear_mxid_pending(email: str) -> None: conn = get_db() conn.execute( "UPDATE members SET mxid_pending = '', mxid_code_hash = '', " - "mxid_code_expires = '', mxid_code_sent_at = '' WHERE email = ?", (email,) + "mxid_code_expires = '', mxid_code_sent_at = '', " + "mxid_code_attempts = 0, mxid_code_window_start = '' WHERE email = ?", (email,) + ) + conn.commit() + conn.close() + + +def get_mxid_code_window(email: str): + conn = get_db() + row = conn.execute( + "SELECT mxid_code_attempts, mxid_code_window_start FROM members WHERE email = ?", + (email,), + ).fetchone() + conn.close() + return row + + +def set_mxid_code_window(email: str, attempts: int, window_start: str) -> None: + conn = get_db() + conn.execute( + "UPDATE members SET mxid_code_attempts = ?, mxid_code_window_start = ? WHERE email = ?", + (attempts, window_start, email), ) conn.commit() conn.close() @@ -6722,6 +6752,27 @@ async def broker_set_matrix_mxid(request: Request): except ValueError: pass + attempts, window_start = get_mxid_code_window(email) or (0, "") + now = datetime.now(timezone.utc) + fresh_window = False + if window_start: + try: + start = datetime.fromisoformat(window_start.replace("Z", "+00:00")) + if start.tzinfo is None: + start = start.replace(tzinfo=timezone.utc) + fresh_window = now - start < timedelta(hours=24) + except ValueError: + fresh_window = False + if not fresh_window: + attempts = 0 + window_start = now.isoformat() + if attempts >= MATRIX_MXID_CODE_PER_DAY: + raise HTTPException( + 429, + f"Too many Matrix verification requests — try again tomorrow " + f"(limit: {MATRIX_MXID_CODE_PER_DAY} per day)", + ) + code = f"{secrets.randbelow(10 ** 6):06d}" try: await send_mxid_verification(mxid, code) @@ -6729,11 +6780,11 @@ async def broker_set_matrix_mxid(request: Request): logger.warning("matrix-mxid: verification DM failed: %s", e) raise HTTPException(502, "Could not send a verification message to that Matrix account") - now = datetime.now(timezone.utc) set_mxid_pending( email, mxid, _mxid_code_hash(email, mxid, code), (now + timedelta(minutes=10)).isoformat(), now.isoformat(), ) + set_mxid_code_window(email, attempts + 1, window_start) return { "status": "verification_required", "matrix_mxid": mxid,