# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Authenticated domain moderation views and operations.""" from http import HTTPStatus from typing import cast import sqlalchemy as sa from flask import abort, current_app, flash, redirect, render_template, url_for from flask.typing import ResponseReturnValue from flask_login import login_required from sqlalchemy.exc import IntegrityError from ..extensions import db from ..forms.admin import ConfirmActionForm from ..forms.moderation import ModerateDomainForm from ..models.moderation import AllowedDomain, BlockedDomain from .blueprint import webmentions_bp MODERATION_DOMAIN_MODELS = {"blocked": BlockedDomain, "allowed": AllowedDomain} def block_domains(domains: set[str]) -> int: """Persist distinct source domains, tolerating concurrent blocklist inserts. Savepoints isolate unique-constraint races so one preexisting entry cannot prevent other selected domains from being blocked. """ existing = set( db.session.scalars( sa.select(BlockedDomain.domain).where(BlockedDomain.domain.in_(domains)) ) ) added = 0 for domain in sorted(domains - existing): try: with db.session.begin_nested(): db.session.add(BlockedDomain(domain=domain)) db.session.flush() except IntegrityError: # A concurrent admin action has already blocked this hostname. continue added += 1 db.session.commit() return added @webmentions_bp.get("/moderation") @login_required def moderation() -> ResponseReturnValue: """Manage blocklist and allowlist entries used by the receiver.""" return render_template( "moderation.html", title="Source domain rules", blocked=db.session.scalars( sa.select(BlockedDomain).order_by(BlockedDomain.domain) ).all(), allowed=db.session.scalars( sa.select(AllowedDomain).order_by(AllowedDomain.domain) ).all(), allowlist_enabled=current_app.config["ALLOWLIST_ENABLED"], ) @webmentions_bp.post("/moderation//add") @login_required def moderation_domain_add(kind: str) -> ResponseReturnValue: """Validate and add a normalized hostname to the selected domain list.""" if (model := MODERATION_DOMAIN_MODELS.get(kind)) is None: abort(HTTPStatus.NOT_FOUND) form = ModerateDomainForm() if not form.validate_on_submit(): abort(HTTPStatus.BAD_REQUEST) domain = cast(str, form.domain.data) if db.session.scalar(sa.select(model.id).where(model.domain == domain)) is None: db.session.add(model(domain=domain)) try: db.session.commit() except IntegrityError: db.session.rollback() flash(f"Source domain {domain} added to {kind} list.", "success") return redirect(url_for("webmentions.moderation")) @webmentions_bp.post("/moderation///delete") @login_required def moderation_domain_delete(kind: str, entry_id: int) -> ResponseReturnValue: """Remove a rule; unblocked domains become eligible for submissions again.""" if (model := MODERATION_DOMAIN_MODELS.get(kind)) is None: abort(HTTPStatus.NOT_FOUND) if not ConfirmActionForm().validate_on_submit(): abort(HTTPStatus.BAD_REQUEST) entry = db.get_or_404(model, entry_id) domain = entry.domain db.session.delete(entry) db.session.commit() flash(f"Source domain {domain} removed from {kind} list.", "success") return redirect(url_for("webmentions.moderation"))