Files
StarPunk/starpunk/models.py
T
PhilandClaude Opus 5.5 ccb9f6dce2 fix: keep inline images in Micropub articles (v2.16.0)
- Content sent as both html and text is stored as the HTML; the text is
  usually a plain fallback, so images, links and headings were lost.
- Images embedded from other sites are copied into the media library
  (SSRF-checked fetcher, best effort, max 20) and the text points at the
  copies, on create and on content replace.
- HTML content is sanitized as is instead of going through Markdown, which
  added stray <br>s and empty paragraphs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:11:46 -07:00

1148 lines
34 KiB
Python

"""
Data models for StarPunk
This module provides data model classes that wrap database rows and provide
clean interfaces for working with notes, sessions, tokens, and authentication
state. All models are immutable and use dataclasses for clean structure.
"""
# Standard library imports
from dataclasses import dataclass, field, replace
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Optional
import re
import sqlite3
# Third-party imports
import markdown
import nh3
# Local imports
from starpunk.utils import (
read_note_file,
calculate_content_hash,
validate_note_path,
)
# Constants - Session configuration
DEFAULT_SESSION_EXPIRY_DAYS = 30
SESSION_EXTENSION_ON_USE = True
# Constants - Auth state configuration
DEFAULT_AUTH_STATE_EXPIRY_MINUTES = 5
# Constants - Token configuration
DEFAULT_TOKEN_EXPIRY_DAYS = 90
# Constants - Markdown rendering
from starpunk.markdown_ext import BareUrlExtension, HashtagLineExtension
MARKDOWN_EXTENSIONS = ["extra", "codehilite", "nl2br", BareUrlExtension(), HashtagLineExtension()]
# Constants - Content limits
MAX_TITLE_LENGTH = 200
# HTML allowed in rendered notes (v2.9.0). Markdown passes raw HTML through,
# and Micropub clients may send HTML, so scripts, event handlers, iframes and
# javascript: links are stripped. class keeps code highlighting and
# microformats; id keeps footnote links.
ALLOWED_TAGS = set(nh3.ALLOWED_TAGS) | {"video", "audio", "source", "track", "picture"}
ALLOWED_ATTRIBUTES = {
**{tag: set(attrs) for tag, attrs in nh3.ALLOWED_ATTRIBUTES.items()},
"*": {"class", "title", "id", "lang", "dir"},
"img": set(nh3.ALLOWED_ATTRIBUTES.get("img", ())) | {"loading", "srcset", "sizes"},
"video": {"src", "controls", "poster", "width", "height", "loop", "muted", "playsinline", "preload"},
"audio": {"src", "controls", "loop", "muted", "preload"},
"source": {"src", "type", "srcset", "media", "sizes"},
"track": {"src", "kind", "label", "srclang", "default"},
}
def render_markdown(text: str) -> str:
"""Note Markdown (or HTML) to sanitized HTML"""
html = markdown.markdown(text, extensions=MARKDOWN_EXTENSIONS)
return nh3.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES)
# Likes, reposts and bookmarks (v2.5.0, v2.9.0)
REACTION_VERBS = {"like": "Liked", "repost": "Reposted", "bookmark": "Bookmarked"}
REACTION_ICONS = {"like": "★", "repost": "🔁", "bookmark": "🔖"}
# A Markdown ATX heading: up to 6 '#', whitespace, then text
TITLE_RE = re.compile(r"#{1,6}[ \t]+(\S.*)$")
EXCERPT_LENGTH = 200
def split_title(content: str) -> tuple[Optional[str], str]:
"""
Split a '# Heading' first line off Markdown content
Before v2.16.0 an article's title was its '# Heading' first line (Q22).
Titles now live in notes.title (ADR-076); migration 023 uses this to move
the old headings there, and Micropub to drop a heading that repeats 'name'.
The first line must be a Markdown heading: 1-6 '#' then a space and text.
'#indieweb ...' (a hashtag) or a bare '#' is not a title.
Returns:
(title, remaining content); title is None if the note has no heading
"""
stripped = content.lstrip()
first_line, _, rest = stripped.partition("\n")
match = TITLE_RE.match(first_line)
if not match:
return None, content
return match.group(1).strip().rstrip("#").strip(), rest.strip()
@dataclass(frozen=True)
class Note:
"""
Represents a note/post
This is an immutable data model that wraps a database row and provides
access to note metadata and lazy-loaded content. Content is read from
files on-demand, and HTML rendering is cached.
Attributes:
id: Database ID (primary key)
slug: URL-safe slug (unique)
file_path: Path to markdown file (relative to data directory)
published: Whether note is published (visible publicly)
created_at: Creation timestamp (UTC)
updated_at: Last update timestamp (UTC)
deleted_at: Soft deletion timestamp (UTC, None if not deleted)
content_hash: SHA-256 hash of content (for integrity checking)
_data_dir: Base data directory path (used for file loading)
_cached_content: Cached markdown content (lazy-loaded)
_cached_html: Cached rendered HTML (lazy-loaded)
Properties:
content: Markdown content (loaded from file, cached)
html: Rendered HTML content (cached)
title: Extracted title (first line or slug)
excerpt: Short excerpt for previews
permalink: Public URL path
is_published: Alias for published (more readable)
Methods:
from_row: Create Note from database row
to_dict: Serialize to dictionary (for JSON)
verify_integrity: Check if file content matches hash
Examples:
>>> # Create from database row
>>> row = db.execute("SELECT * FROM notes WHERE slug = ?", (slug,)).fetchone()
>>> note = Note.from_row(row, data_dir=Path("data"))
>>> # Access metadata
>>> print(note.slug)
'my-first-note'
>>> print(note.published)
True
>>> # Lazy-load content
>>> content = note.content # Reads file on first access
>>> content = note.content # Returns cached value on subsequent access
>>> # Render HTML
>>> html = note.html # Renders markdown on first access
>>> html = note.html # Returns cached value
>>> # Extract metadata
>>> title = note.title
>>> permalink = note.permalink
"""
# Core fields from database
id: int
slug: str
file_path: str
published: bool
created_at: datetime
updated_at: datetime
# Internal fields (not from database)
_data_dir: Path = field(repr=False, compare=False)
# Optional fields
deleted_at: Optional[datetime] = None
content_hash: Optional[str] = None
in_reply_to: Optional[str] = None # v1.6.0: URL being replied to
like_of: Optional[str] = None # v2.5.0: URL liked (this note is a like)
repost_of: Optional[str] = None # v2.5.0: URL reposted (this note is a repost)
bookmark_of: Optional[str] = None # v2.9.0: URL bookmarked (this note is a bookmark)
content_format: Optional[str] = None # v2.9.0: 'html' if sent as HTML via Micropub
title: Optional[str] = None # v2.16.0: an article's title (p-name), ADR-076
summary: Optional[str] = None # v2.16.0: author-written summary (p-summary)
_cached_content: Optional[str] = field(
default=None, repr=False, compare=False, init=False
)
_cached_html: Optional[str] = field(
default=None, repr=False, compare=False, init=False
)
# Cached tags (loaded separately, not from database row)
_cached_tags: Optional[list[dict]] = field(
default=None, repr=False, compare=False, init=False
)
@classmethod
def from_row(cls, row: sqlite3.Row | dict[str, Any], data_dir: Path) -> "Note":
"""
Create Note instance from database row
Args:
row: Database row (sqlite3.Row or dict with column names)
data_dir: Base data directory path
Returns:
Note instance
Examples:
>>> row = db.execute("SELECT * FROM notes WHERE id = ?", (1,)).fetchone()
>>> note = Note.from_row(row, Path("data"))
"""
# Handle both sqlite3.Row and dict
if hasattr(row, "keys"):
data = {key: row[key] for key in row.keys()}
else:
data = dict(row)
# Convert timestamps if they are strings
created_at = data["created_at"]
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
updated_at = data["updated_at"]
if isinstance(updated_at, str):
updated_at = datetime.fromisoformat(updated_at.replace("Z", "+00:00"))
deleted_at = data.get("deleted_at")
if deleted_at and isinstance(deleted_at, str):
deleted_at = datetime.fromisoformat(deleted_at.replace("Z", "+00:00"))
return cls(
id=data["id"],
slug=data["slug"],
file_path=data["file_path"],
published=bool(data["published"]),
created_at=created_at,
updated_at=updated_at,
deleted_at=deleted_at,
_data_dir=data_dir,
content_hash=data.get("content_hash"),
in_reply_to=data.get("in_reply_to"),
like_of=data.get("like_of"),
repost_of=data.get("repost_of"),
bookmark_of=data.get("bookmark_of"),
content_format=data.get("content_format"),
title=data.get("title"),
summary=data.get("summary"),
)
@property
def content(self) -> str:
"""
Get note content (lazy-loaded from file)
Reads markdown content from file on first access, then caches.
Subsequent accesses return cached value.
Returns:
Markdown content as string
Raises:
FileNotFoundError: If note file doesn't exist
OSError: If file cannot be read
Examples:
>>> content = note.content
>>> print(content)
This is my note content...
"""
if self._cached_content is None:
# Build full path
full_path = self._data_dir / self.file_path
# Validate path for security
if not validate_note_path(full_path, self._data_dir):
raise ValueError(
f"Invalid file path: {self.file_path}. " f"Path traversal detected."
)
# Read content from file
content = read_note_file(full_path)
# Cache it (use object.__setattr__ for frozen dataclass)
object.__setattr__(self, "_cached_content", content)
return self._cached_content
@property
def html(self) -> str:
"""
Get rendered HTML content (lazy-rendered and cached)
Renders markdown to HTML on first access, then caches.
Uses Python-Markdown with extensions for code highlighting,
tables, and other features.
Returns:
Rendered HTML as string
Examples:
>>> html = note.html
>>> print(html)
<p>This is my note content...</p>
"""
if self._cached_html is None:
if self.content_format == "html":
# Sent as HTML via Micropub: sanitize it as is. Through Markdown
# it picked up stray <br>s and empty paragraphs (v2.16.0)
html = nh3.clean(self.content, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES)
else:
# Render markdown to sanitized HTML (v2.9.0)
html = render_markdown(self.content) # triggers lazy load of content
# Cache it
object.__setattr__(self, "_cached_html", html)
return self._cached_html
@property
def label(self) -> str:
"""A name for places that always need one: the title, else the excerpt, else the slug"""
return self.title or " ".join(self.excerpt.split())[:MAX_TITLE_LENGTH] or self.slug
@property
def excerpt(self) -> str:
"""
Generate short excerpt for previews
The first 200 characters of the note as plain text: Markdown (or
HTML) rendered and stripped, images left out, links as their text
(v2.16.0). Cut at a word boundary with an ellipsis if longer.
Returns:
Excerpt string
Examples:
>>> note.excerpt
'This is my note content. It has some interesting points…'
"""
from starpunk.syndication import plain_text
try:
text = " ".join(plain_text(self.content).split())
if len(text) > EXCERPT_LENGTH:
excerpt = text[:EXCERPT_LENGTH]
last_space = excerpt.rfind(" ")
text = (excerpt[:last_space] if last_space > 0 else excerpt).rstrip() + "…"
if not text and self.reacts_to:
# A like, repost or bookmark with no comment
return f"{REACTION_VERBS[self.kind]} {self.reacts_to}"
return text
except (FileNotFoundError, OSError):
# If file doesn't exist, return slug
return self.slug
@property
def kind(self) -> str:
"""'like', 'repost', 'bookmark' (v2.9.0) or 'note' (v2.5.0)"""
if self.like_of:
return "like"
if self.repost_of:
return "repost"
if self.bookmark_of:
return "bookmark"
return "note"
@property
def reacts_to(self) -> Optional[str]:
"""The URL a like, repost or bookmark points at"""
return self.like_of or self.repost_of or self.bookmark_of
@property
def feed_html(self) -> str:
"""HTML for feeds: a repost/like line, then the note's own HTML"""
from html import escape
if not self.reacts_to:
return self.html
url = escape(self.reacts_to, quote=True)
line = f'<p>{REACTION_ICONS[self.kind]} {REACTION_VERBS[self.kind]} <a href="{url}">{url}</a></p>'
return line + (self.html or "")
@property
def permalink(self) -> str:
"""
Generate permalink (public URL path)
Returns:
URL path string (e.g., '/note/my-first-note')
Examples:
>>> note.permalink
'/note/my-first-note'
"""
return f"/note/{self.slug}"
@property
def is_published(self) -> bool:
"""
Alias for published (more readable)
Returns:
True if note is published, False otherwise
"""
return self.published
@property
def tags(self) -> list[dict]:
"""
Get note tags (lazy-loaded, but prefer pre-loading in routes)
Routes should pre-load tags using:
object.__setattr__(note, '_cached_tags', tags)
This property exists as a fallback for lazy loading.
Returns:
List of tag dicts with 'name' and 'display_name'
"""
if self._cached_tags is None:
from starpunk.tags import get_note_tags
tags = get_note_tags(self.id)
object.__setattr__(self, "_cached_tags", tags)
return self._cached_tags
def to_dict(
self, include_content: bool = False, include_html: bool = False, include_tags: bool = False
) -> dict[str, Any]:
"""
Serialize note to dictionary
Converts note to dictionary for JSON serialization or template rendering.
Can optionally include content and rendered HTML.
Args:
include_content: Include markdown content in output
include_html: Include rendered HTML in output
include_tags: Include tags in output (v1.3.0)
Returns:
Dictionary with note data
Examples:
>>> note.to_dict()
{
'id': 1,
'slug': 'my-first-note',
'title': 'My First Note',
'published': True,
'created_at': '2024-11-18T14:30:00Z',
'updated_at': '2024-11-18T14:30:00Z',
'permalink': '/note/my-first-note'
}
>>> note.to_dict(include_content=True, include_html=True)
{
# ... same as above, plus:
'content': 'Markdown content...',
'html': '<p>Rendered HTML...</p>'
}
"""
data = {
"id": self.id,
"slug": self.slug,
"title": self.title,
"summary": self.summary,
"published": self.published,
"created_at": self.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"updated_at": self.updated_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"permalink": self.permalink,
"excerpt": self.excerpt,
}
if include_content:
data["content"] = self.content
if include_html:
data["html"] = self.html
if include_tags:
data["tags"] = [tag["display_name"] for tag in self.tags]
return data
def verify_integrity(self) -> bool:
"""
Verify content matches stored hash
Reads content from file, calculates hash, and compares with
stored content_hash. Used to detect external file modifications.
Returns:
True if hash matches, False otherwise
Examples:
>>> note.verify_integrity()
True # File has not been modified
>>> # Someone edits file externally
>>> note.verify_integrity()
False # Hash mismatch detected
"""
if self.content_hash is None:
# No hash stored, cannot verify
return False
try:
# Calculate hash of current content
current_hash = calculate_content_hash(self.content)
# Compare with stored hash
return current_hash == self.content_hash
except (FileNotFoundError, OSError):
# If file doesn't exist, integrity check fails
return False
@dataclass(frozen=True)
class Session:
"""
Represents an authenticated session
Sessions are created after successful IndieLogin authentication and
stored in the database. They have a configurable expiry time and can
be extended on use.
Attributes:
id: Database ID (primary key)
session_token: Unique session token (stored in cookie)
me: Authenticated user's URL (from IndieLogin)
created_at: Session creation timestamp (UTC)
expires_at: Session expiration timestamp (UTC)
last_used_at: Last activity timestamp (UTC, nullable)
Properties:
is_expired: Check if session has expired
is_active: Check if session is not expired
age: Age of session (timedelta)
time_until_expiry: Time remaining until expiry (timedelta)
Methods:
from_row: Create Session from database row
to_dict: Serialize to dictionary
is_valid: Comprehensive validation (checks expiry, token format)
with_updated_last_used: Create new session with updated last_used_at
Examples:
>>> # Create from database row
>>> row = db.execute(
... "SELECT * FROM sessions WHERE session_token = ?", (token,)
... ).fetchone()
>>> session = Session.from_row(row)
>>> # Check if expired
>>> if session.is_expired:
... print("Session expired")
>>> # Check validity
>>> if session.is_valid():
... print("Session is valid")
>>> # Update last used
>>> updated_session = session.with_updated_last_used()
"""
# Core fields from database
id: int
session_token: str
me: str
created_at: datetime
expires_at: datetime
last_used_at: Optional[datetime] = None
@classmethod
def from_row(cls, row: sqlite3.Row | dict[str, Any]) -> "Session":
"""
Create Session instance from database row
Args:
row: Database row (sqlite3.Row or dict)
Returns:
Session instance
Examples:
>>> row = db.execute("SELECT * FROM sessions WHERE id = ?", (1,)).fetchone()
>>> session = Session.from_row(row)
"""
# Handle both sqlite3.Row and dict
if hasattr(row, "keys"):
data = {key: row[key] for key in row.keys()}
else:
data = dict(row)
# Convert timestamps if they are strings
created_at = data["created_at"]
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
expires_at = data["expires_at"]
if isinstance(expires_at, str):
expires_at = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
last_used_at = data.get("last_used_at")
if last_used_at and isinstance(last_used_at, str):
last_used_at = datetime.fromisoformat(last_used_at.replace("Z", "+00:00"))
return cls(
id=data["id"],
session_token=data["session_token"],
me=data["me"],
created_at=created_at,
expires_at=expires_at,
last_used_at=last_used_at,
)
@property
def is_expired(self) -> bool:
"""
Check if session has expired
Compares expires_at with current UTC time.
Returns:
True if expired, False otherwise
Examples:
>>> session.is_expired
False
"""
return datetime.now(timezone.utc).replace(tzinfo=None) >= self.expires_at
@property
def is_active(self) -> bool:
"""
Check if session is active (not expired)
Returns:
True if not expired, False otherwise
Examples:
>>> session.is_active
True
"""
return not self.is_expired
@property
def age(self) -> timedelta:
"""
Get age of session
Returns:
Timedelta since session creation
Examples:
>>> session.age
datetime.timedelta(days=2, seconds=3600)
"""
return datetime.now(timezone.utc).replace(tzinfo=None) - self.created_at
@property
def time_until_expiry(self) -> timedelta:
"""
Get time remaining until expiry
Returns:
Timedelta until expiry (negative if already expired)
Examples:
>>> session.time_until_expiry
datetime.timedelta(days=28)
"""
return self.expires_at - datetime.now(timezone.utc).replace(tzinfo=None)
def is_valid(self) -> bool:
"""
Comprehensive session validation
Checks:
- Session is not expired
- Session token is not empty
- User 'me' URL is valid
Returns:
True if session is valid, False otherwise
Examples:
>>> session.is_valid()
True
"""
# Check if expired
if self.is_expired:
return False
# Check if token is not empty
if not self.session_token or not self.session_token.strip():
return False
# Check if 'me' URL is not empty (basic validation)
if not self.me or not self.me.strip():
return False
return True
def with_updated_last_used(self) -> "Session":
"""
Create new session with updated last_used_at
Since sessions are immutable, this returns a new Session instance
with last_used_at set to current UTC time.
Returns:
New Session instance with updated timestamp
Examples:
>>> updated = session.with_updated_last_used()
>>> updated.last_used_at
datetime.datetime(2024, 11, 18, 15, 30, 0)
"""
return replace(self, last_used_at=datetime.now(timezone.utc).replace(tzinfo=None))
def to_dict(self) -> dict[str, Any]:
"""
Serialize session to dictionary
Returns:
Dictionary with session data (excludes sensitive token)
Examples:
>>> session.to_dict()
{
'id': 1,
'me': 'https://alice.example.com',
'created_at': '2024-11-18T14:30:00Z',
'expires_at': '2024-12-18T14:30:00Z',
'is_active': True
}
"""
return {
"id": self.id,
"me": self.me,
"created_at": self.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"expires_at": self.expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"is_active": self.is_active,
}
@dataclass(frozen=True)
class Token:
"""
Represents a Micropub access token
Tokens are used to authenticate Micropub API requests. They have
associated scopes that determine what actions the token can perform.
Attributes:
token: Token string (primary key, used in Authorization header)
me: User's URL
client_id: Client application URL (optional)
scope: Space-separated scope string (e.g., "create update delete")
created_at: Token creation timestamp (UTC)
expires_at: Token expiration timestamp (UTC, nullable for no expiry)
Properties:
is_expired: Check if token has expired
is_active: Check if token is not expired
scopes: List of individual scopes
Methods:
from_row: Create Token from database row
to_dict: Serialize to dictionary
has_scope: Check if token has specific scope
is_valid: Comprehensive validation
Examples:
>>> # Create from database row
>>> row = db.execute(
... "SELECT * FROM tokens WHERE token = ?", (token,)
... ).fetchone()
>>> token_obj = Token.from_row(row)
>>> # Check scope
>>> if token_obj.has_scope('create'):
... print("Can create posts")
>>> # Check if expired
>>> if token_obj.is_active:
... print("Token is active")
"""
# Core fields from database
token: str
me: str
client_id: Optional[str] = None
scope: Optional[str] = None
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
expires_at: Optional[datetime] = None
@classmethod
def from_row(cls, row: sqlite3.Row | dict[str, Any]) -> "Token":
"""
Create Token instance from database row
Args:
row: Database row (sqlite3.Row or dict)
Returns:
Token instance
Examples:
>>> row = db.execute(
... "SELECT * FROM tokens WHERE token = ?", (token,)
... ).fetchone()
>>> token_obj = Token.from_row(row)
"""
# Handle both sqlite3.Row and dict
if hasattr(row, "keys"):
data = {key: row[key] for key in row.keys()}
else:
data = dict(row)
# Convert timestamps if they are strings
created_at = data["created_at"]
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
expires_at = data.get("expires_at")
if expires_at and isinstance(expires_at, str):
expires_at = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
return cls(
token=data["token"],
me=data["me"],
client_id=data.get("client_id"),
scope=data.get("scope"),
created_at=created_at,
expires_at=expires_at,
)
@property
def is_expired(self) -> bool:
"""
Check if token has expired
If expires_at is None, token never expires.
Otherwise, compares with current UTC time.
Returns:
True if expired, False otherwise
Examples:
>>> token_obj.is_expired
False
"""
if self.expires_at is None:
# No expiry set, token never expires
return False
return datetime.now(timezone.utc).replace(tzinfo=None) >= self.expires_at
@property
def is_active(self) -> bool:
"""
Check if token is active (not expired)
Returns:
True if not expired, False otherwise
"""
return not self.is_expired
@property
def scopes(self) -> list[str]:
"""
Get list of individual scopes
Splits scope string on whitespace.
Returns:
List of scope strings
Examples:
>>> # scope = "create update delete"
>>> token_obj.scopes
['create', 'update', 'delete']
>>> # scope = None
>>> token_obj.scopes
[]
"""
if not self.scope:
return []
return self.scope.split()
def has_scope(self, required_scope: str) -> bool:
"""
Check if token has required scope
Args:
required_scope: Scope to check for (e.g., 'create', 'update')
Returns:
True if token has scope, False otherwise
Examples:
>>> token_obj.has_scope('create')
True
>>> token_obj.has_scope('delete')
False
"""
return required_scope in self.scopes
def is_valid(self, required_scope: Optional[str] = None) -> bool:
"""
Comprehensive token validation
Checks:
- Token is not expired
- Token string is not empty
- If required_scope provided, token has that scope
Args:
required_scope: Optional scope to check
Returns:
True if token is valid, False otherwise
Examples:
>>> token_obj.is_valid()
True
>>> token_obj.is_valid(required_scope='create')
True
"""
# Check if expired
if self.is_expired:
return False
# Check if token is not empty
if not self.token or not self.token.strip():
return False
# Check required scope if provided
if required_scope is not None:
if not self.has_scope(required_scope):
return False
return True
def to_dict(self) -> dict[str, Any]:
"""
Serialize token to dictionary
Returns:
Dictionary with token data (excludes sensitive token value)
Examples:
>>> token_obj.to_dict()
{
'me': 'https://alice.example.com',
'client_id': 'https://quill.p3k.io',
'scope': 'create update',
'created_at': '2024-11-18T14:30:00Z',
'is_active': True
}
"""
data = {
"me": self.me,
"client_id": self.client_id,
"scope": self.scope,
"created_at": self.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"is_active": self.is_active,
}
if self.expires_at:
data["expires_at"] = self.expires_at.strftime("%Y-%m-%dT%H:%M:%SZ")
return data
@dataclass(frozen=True)
class AuthState:
"""
Represents an OAuth state token (CSRF protection)
State tokens are short-lived (5 minutes) and single-use. They prevent
CSRF attacks during the IndieLogin authentication flow.
Attributes:
state: Random state token string (primary key)
created_at: Token creation timestamp (UTC)
expires_at: Token expiration timestamp (UTC)
Properties:
is_expired: Check if state token has expired
is_active: Check if state token is not expired
age: Age of state token
Methods:
from_row: Create AuthState from database row
to_dict: Serialize to dictionary
is_valid: Comprehensive validation
Examples:
>>> # Create from database row
>>> row = db.execute(
... "SELECT * FROM auth_state WHERE state = ?", (state,)
... ).fetchone()
>>> auth_state = AuthState.from_row(row)
>>> # Check if expired
>>> if auth_state.is_active:
... print("State token is still valid")
>>> # Check validity
>>> if auth_state.is_valid():
... print("Valid state token")
"""
# Core fields from database
state: str
created_at: datetime
expires_at: datetime
@classmethod
def from_row(cls, row: sqlite3.Row | dict[str, Any]) -> "AuthState":
"""
Create AuthState instance from database row
Args:
row: Database row (sqlite3.Row or dict)
Returns:
AuthState instance
Examples:
>>> row = db.execute(
... "SELECT * FROM auth_state WHERE state = ?", (state,)
... ).fetchone()
>>> auth_state = AuthState.from_row(row)
"""
# Handle both sqlite3.Row and dict
if hasattr(row, "keys"):
data = {key: row[key] for key in row.keys()}
else:
data = dict(row)
# Convert timestamps if they are strings
created_at = data["created_at"]
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
expires_at = data["expires_at"]
if isinstance(expires_at, str):
expires_at = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
return cls(
state=data["state"],
created_at=created_at,
expires_at=expires_at,
)
@property
def is_expired(self) -> bool:
"""
Check if state token has expired
State tokens have short expiry (5 minutes default).
Returns:
True if expired, False otherwise
Examples:
>>> auth_state.is_expired
False
"""
return datetime.now(timezone.utc).replace(tzinfo=None) >= self.expires_at
@property
def is_active(self) -> bool:
"""
Check if state token is active (not expired)
Returns:
True if not expired, False otherwise
"""
return not self.is_expired
@property
def age(self) -> timedelta:
"""
Get age of state token
Returns:
Timedelta since token creation
Examples:
>>> auth_state.age
datetime.timedelta(seconds=120)
"""
return datetime.now(timezone.utc).replace(tzinfo=None) - self.created_at
def is_valid(self) -> bool:
"""
Comprehensive state token validation
Checks:
- Token is not expired
- Token string is not empty
Returns:
True if valid, False otherwise
Examples:
>>> auth_state.is_valid()
True
"""
# Check if expired
if self.is_expired:
return False
# Check if state is not empty
if not self.state or not self.state.strip():
return False
return True
def to_dict(self) -> dict[str, Any]:
"""
Serialize state token to dictionary
Returns:
Dictionary with state data
Examples:
>>> auth_state.to_dict()
{
'created_at': '2024-11-18T14:30:00Z',
'expires_at': '2024-11-18T14:35:00Z',
'is_active': True
}
"""
return {
"created_at": self.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"expires_at": self.expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"is_active": self.is_active,
}