From 6d6d079a3a99d3d3a922a640b6925eb2adf044de Mon Sep 17 00:00:00 2001 From: Dennis Fink Date: Tue, 17 Nov 2026 17:09:59 +0100 Subject: refactor(core)!: split forms and models by feature Replace monolithic form and model modules with focused packages for receiver, moderation, source, user, and shared validation concerns. Rename source policy concepts to domain moderation, including routes, models, tables, configuration, templates, and tests. BREAKING CHANGE: form and model import paths, moderation routes, and `SOURCE_ALLOWLIST_ENABLED` have changed; use `ALLOWLIST_ENABLED` and the new feature-specific modules. --- webmentions_ssg/models/__init__.py | 5 + webmentions_ssg/models/moderation.py | 28 +++++ webmentions_ssg/models/received.py | 131 ++++++++++++++++++++++ webmentions_ssg/models/sources.py | 208 +++++++++++++++++++++++++++++++++++ webmentions_ssg/models/user.py | 66 +++++++++++ webmentions_ssg/models/utils.py | 41 +++++++ 6 files changed, 479 insertions(+) create mode 100644 webmentions_ssg/models/__init__.py create mode 100644 webmentions_ssg/models/moderation.py create mode 100644 webmentions_ssg/models/received.py create mode 100644 webmentions_ssg/models/sources.py create mode 100644 webmentions_ssg/models/user.py create mode 100644 webmentions_ssg/models/utils.py (limited to 'webmentions_ssg/models') diff --git a/webmentions_ssg/models/__init__.py b/webmentions_ssg/models/__init__.py new file mode 100644 index 0000000..360fc71 --- /dev/null +++ b/webmentions_ssg/models/__init__.py @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Database models grouped by feature.""" diff --git a/webmentions_ssg/models/moderation.py b/webmentions_ssg/models/moderation.py new file mode 100644 index 0000000..4200c39 --- /dev/null +++ b/webmentions_ssg/models/moderation.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Domain allowlist and blocklist models.""" + +from sqlalchemy import Text +from sqlalchemy.orm import Mapped, mapped_column + +from ..extensions import Base + + +class BlockedDomain(Base): + """Source domain rejected before submission or verification.""" + + __tablename__ = "blocked_domains" + + id: Mapped[int] = mapped_column(primary_key=True) + domain: Mapped[str] = mapped_column(Text(), nullable=False, unique=True) + + +class AllowedDomain(Base): + """A domain accepted when allowlist mode is enabled.""" + + __tablename__ = "allowed_domains" + + id: Mapped[int] = mapped_column(primary_key=True) + domain: Mapped[str] = mapped_column(Text(), nullable=False, unique=True) diff --git a/webmentions_ssg/models/received.py b/webmentions_ssg/models/received.py new file mode 100644 index 0000000..a9047ad --- /dev/null +++ b/webmentions_ssg/models/received.py @@ -0,0 +1,131 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Incoming Webmention state and persistence.""" + +from datetime import UTC, datetime +from enum import StrEnum +from uuid import UUID + +from sqlalchemy import ( + DateTime, + Enum, + Index, + Integer, + String, + Text, + UniqueConstraint, + Uuid, +) +from sqlalchemy.orm import Mapped, mapped_column, validates + +from ..extensions import Base +from .utils import source_target_digest, uuid7_to_datetime + + +class ReceivedWebmentionStatus(StrEnum): + """Persisted lifecycle state of an incoming Webmention.""" + + RECEIVED = "received" + VERIFYING = "verifying" + VERIFIED = "verified" + FAILED = "failed" + SOURCE_REMOVED = "source_removed" + + +class ReceivedWebmention(Base): + """Represent a Webmention received for verification.""" + + __tablename__ = "received_webmentions" + + uuid: Mapped[UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True) + + source: Mapped[str] = mapped_column(Text(), nullable=False) + target: Mapped[str] = mapped_column(Text(), nullable=False) + source_target_digest: Mapped[str] = mapped_column(String(64), nullable=False) + + @validates("source", "target") + def _refresh_url_digest(self, key: str, value: str) -> str: + source = value if key == "source" else self.__dict__.get("source") + target = value if key == "target" else self.__dict__.get("target") + if source is not None and target is not None: + self.source_target_digest = source_target_digest(source, target) + return value + + status: Mapped[ReceivedWebmentionStatus] = mapped_column( + Enum( + ReceivedWebmentionStatus, + name="received_webmention_status", + values_callable=lambda enum_type: [member.value for member in enum_type], + native_enum=False, + ), + nullable=False, + default=ReceivedWebmentionStatus.RECEIVED, + ) + # Counts stale-row requeues, not Huey's bounded in-task retries. A fresh + # explicit submission resets this counter. + recovery_attempts: Mapped[int] = mapped_column( + Integer, nullable=False, default=0, server_default="0" + ) + failure_reason: Mapped[str | None] = mapped_column( + Text(), nullable=True, default=None + ) + + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + default=lambda: datetime.now(UTC), + onupdate=lambda: datetime.now(UTC), + nullable=False, + ) + + notification_sent_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), nullable=True, default=None + ) + + __table_args__ = ( + UniqueConstraint( + "source_target_digest", name="uq_webmention_source_target_digest" + ), + Index("ix_received_webmentions_status_updated_at", "status", "updated_at"), + ) + + def __repr__(self) -> str: + """Represent the received Webmention by source and target.""" + return f" {self.target!r}>" + + @staticmethod + def reopen_verification_values( + *, at: datetime, recovery_attempts: int = 0 + ) -> dict[str, object]: + """Return the columns to reset when verification is explicitly reopened. + + :param at: Timestamp to record for the newly opened verification. + :param recovery_attempts: Number of stale-lease recovery attempts to retain. + :returns: Column values for resetting the verification state. + """ + return { + "status": ReceivedWebmentionStatus.RECEIVED, + "failure_reason": None, + "recovery_attempts": recovery_attempts, + "updated_at": at, + } + + def reopen_verification(self) -> None: + """Reopen an existing row for manual verification. + + Clear the previous outcome and restore the received state with a fresh + timestamp. + """ + for key, value in self.reopen_verification_values(at=datetime.now(UTC)).items(): + setattr(self, key, value) + + @property + def verified(self) -> bool: + """Return whether the Webmention has been successfully verified.""" + return self.status == ReceivedWebmentionStatus.VERIFIED + + @property + def created_at(self) -> datetime: + """Return the creation time encoded in the Webmention UUID.""" + return uuid7_to_datetime(self.uuid) diff --git a/webmentions_ssg/models/sources.py b/webmentions_ssg/models/sources.py new file mode 100644 index 0000000..f0fd618 --- /dev/null +++ b/webmentions_ssg/models/sources.py @@ -0,0 +1,208 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Source documents and outgoing Webmention state.""" + +from datetime import datetime +from enum import StrEnum +from uuid import UUID, uuid7 + +import sqlalchemy as sa +from sqlalchemy import ( + Boolean, + DateTime, + Enum, + ForeignKey, + Integer, + String, + Text, + UniqueConstraint, + Uuid, +) +from sqlalchemy.ext.hybrid import hybrid_property +from sqlalchemy.orm import Mapped, mapped_column, relationship, validates + +from ..extensions import Base +from .utils import target_digest, uuid7_to_datetime + + +class SentWebmentionStatus(StrEnum): + """Represent the outcome of a Webmention send attempt.""" + + SENT = "sent" + NO_ENDPOINT = "no_endpoint" + FAILED = "failed" + + +class SourceDocument(Base): + """Represent a generated source document containing outgoing Webmentions.""" + + __tablename__ = "source_documents" + + uuid: Mapped[UUID] = mapped_column( + Uuid(as_uuid=True), primary_key=True, default=uuid7 + ) + + path: Mapped[str] = mapped_column(Text(), nullable=False, unique=True) + url: Mapped[str] = mapped_column(Text(), nullable=False, unique=True) + + content_hash: Mapped[str] = mapped_column(String(32), nullable=False) + revision: Mapped[int] = mapped_column(Integer(), nullable=False, default=1) + + last_seen_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), nullable=False + ) + revised_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), nullable=False + ) + deleted_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), nullable=True, default=None + ) + + sent_webmentions: Mapped[list[SentWebmention]] = relationship( + back_populates="source", cascade="all, delete-orphan" + ) + + def __repr__(self) -> str: + """Represent the source by its public URL.""" + return f"" + + @property + def created_at(self) -> datetime: + """Return the creation time encoded in the source UUID.""" + return uuid7_to_datetime(self.uuid) + + +class SentWebmention(Base): + """Represent an outgoing Webmention associated with a source.""" + + __tablename__ = "sent_webmentions" + + uuid: Mapped[UUID] = mapped_column( + Uuid(as_uuid=True), primary_key=True, default=uuid7 + ) + + source_uuid: Mapped[UUID] = mapped_column( + Uuid(as_uuid=True), + ForeignKey("source_documents.uuid", ondelete="CASCADE"), + nullable=False, + index=True, + ) + + target: Mapped[str] = mapped_column(Text(), nullable=False) + target_digest: Mapped[str] = mapped_column(String(64), nullable=False) + + @validates("target") + def _update_target_digest(self, key: str, value: str) -> str: + self.target_digest = target_digest(value) + return value + + linked: Mapped[bool] = mapped_column(Boolean(), nullable=False, default=True) + + desired_revision: Mapped[int] = mapped_column(Integer(), nullable=False) + processed_revision: Mapped[int | None] = mapped_column( + Integer(), nullable=True, default=None + ) + sent_revision: Mapped[int | None] = mapped_column( + Integer(), nullable=True, default=None + ) + + status: Mapped[SentWebmentionStatus | None] = mapped_column( + Enum( + SentWebmentionStatus, + name="sent_webmention_status", + values_callable=lambda enum_type: [member.value for member in enum_type], + native_enum=False, + ), + nullable=True, + default=None, + ) + + failure_reason: Mapped[str | None] = mapped_column( + Text(), nullable=True, default=None + ) + + webmention_endpoint: Mapped[str | None] = mapped_column( + Text(), nullable=True, default=None + ) + endpoint_response_status: Mapped[int | None] = mapped_column( + Integer(), nullable=True, default=None + ) + status_url: Mapped[str | None] = mapped_column(Text(), nullable=True, default=None) + + # Retry state belongs to the desired revision, not to the target forever. + attempt_count: Mapped[int] = mapped_column(Integer(), nullable=False, default=0) + next_retry_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), nullable=True, default=None + ) + + last_attempted_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), nullable=True, default=None + ) + last_sent_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), nullable=True, default=None + ) + + source: Mapped[SourceDocument] = relationship(back_populates="sent_webmentions") + + __table_args__ = ( + UniqueConstraint( + "source_uuid", + "target_digest", + name="uq_sent_webmention_source_uuid_target_digest", + ), + ) + + def __repr__(self) -> str: + """Represent the sent Webmention by its target URL.""" + return f"" + + def reset_for_revision(self, revision: int, linked: bool) -> None: + """Reopen delivery for a revision while preserving send history. + + :param revision: Source revision to make the desired delivery revision. + :param linked: Whether the target still appears in the current source. + """ + self.desired_revision = revision + self.linked = linked + self.attempt_count = 0 + self.next_retry_at = None + + def clear_result_for_resend(self) -> None: + """Retry the current revision, clearing its previous delivery result. + + Reset attempt and response state without changing the desired source revision. + """ + self.reset_for_revision(self.desired_revision, self.linked) + self.processed_revision = None + self.status = None + self.failure_reason = None + self.webmention_endpoint = None + self.endpoint_response_status = None + self.status_url = None + + @hybrid_property + def awaiting_processing(self) -> bool: + """Return whether the Webmention has an unprocessed source revision.""" + return ( + self.processed_revision is None + or self.processed_revision < self.desired_revision + ) + + @awaiting_processing.inplace.expression + @classmethod + def _awaiting_processing_expression(cls) -> sa.ColumnElement[bool]: + """Express pending-revision status in database queries. + + :returns: SQLAlchemy expression selecting unprocessed source revisions. + """ + return sa.or_( + cls.processed_revision.is_(None), + cls.processed_revision < cls.desired_revision, + ) + + @property + def created_at(self) -> datetime: + """Return the creation time encoded in the Webmention UUID.""" + return uuid7_to_datetime(self.uuid) diff --git a/webmentions_ssg/models/user.py b/webmentions_ssg/models/user.py new file mode 100644 index 0000000..b09c3d1 --- /dev/null +++ b/webmentions_ssg/models/user.py @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Application user and session identity model.""" + +from hashlib import sha256 +from typing import Never + +from flask_login import UserMixin +from sqlalchemy import Text +from sqlalchemy.orm import Mapped, mapped_column +from werkzeug.security import check_password_hash, generate_password_hash + +from ..extensions import Base + + +class User(UserMixin, Base): + """Represent an authenticated application user.""" + + __tablename__ = "users" + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(Text(), index=True, unique=True) + password_hash: Mapped[str] = mapped_column(Text(), nullable=False) + + def __repr__(self) -> str: + """Represent the user by username.""" + return f"" + + @property + def password(self) -> Never: + """Prevent access to the user's plain-text password. + + :raises AttributeError: Always, because the password is write-only. + """ + raise AttributeError("Password is write-only") + + @password.setter + def password(self, password: str) -> None: + """Hash and store a new password. + + :param password: Plain-text password to hash. + """ + self.password_hash = generate_password_hash(password) + + def get_id(self) -> str: + """Bind the login session to the current stored password hash. + + Only a one-way fingerprint is placed in Flask's signed cookie, never + the password hash itself. Rehashing the password invalidates all + previously issued session identifiers without a schema change. + + :returns: Session identifier combining the user ID and password-hash + fingerprint. + """ + fingerprint = sha256(self.password_hash.encode("utf-8")).hexdigest() + return f"{self.id}:{fingerprint}" + + def check_password(self, password: str) -> bool: + """Check a plain-text password against the stored password hash. + + :param password: Plain-text password to check. + :returns: Whether the password matches the stored hash. + """ + return check_password_hash(self.password_hash, password) diff --git a/webmentions_ssg/models/utils.py b/webmentions_ssg/models/utils.py new file mode 100644 index 0000000..e961088 --- /dev/null +++ b/webmentions_ssg/models/utils.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""URL fingerprints and UUID timestamp utilities.""" + +import json +from datetime import UTC, datetime +from hashlib import sha256 +from uuid import UUID + + +def uuid7_to_datetime(identifier: UUID) -> datetime: + """Convert a UUID version 7 timestamp to a datetime. + + :param identifier: UUID whose embedded timestamp should be converted. + :returns: Timestamp as a timezone-aware UTC datetime. + """ + return datetime.fromtimestamp(identifier.time / 1000, tz=UTC) + + +def source_target_digest(source: str, target: str) -> str: + """Fingerprint an unambiguous, ordered source/target pair. + + :param source: Webmention source URL. + :param target: Webmention target URL. + :returns: SHA-256 hexadecimal digest of the ordered URL pair. + """ + encoded = json.dumps( + [source, target], ensure_ascii=False, separators=(",", ":") + ).encode("utf-8") + return sha256(encoded).hexdigest() + + +def target_digest(target: str) -> str: + """Fingerprint an outgoing target (unique within each source ID). + + :param target: Outgoing Webmention target URL. + :returns: SHA-256 hexadecimal digest of the target URL. + """ + return sha256(target.encode("utf-8")).hexdigest() -- cgit v1.3.1