""" Micropub endpoint implementation for StarPunk This module handles Micropub protocol requests, providing a standard IndieWeb interface for creating posts via external clients. Functions: normalize_properties: Convert form/JSON data to Micropub properties format extract_content: Get content from Micropub properties extract_title: Get the explicit title (name) from Micropub properties extract_tags: Get category tags from Micropub properties handle_create: Process Micropub create action handle_update: Process Micropub update action (v2.4.0) handle_delete: Process Micropub delete / undelete actions (v2.4.0) handle_query: Process Micropub query endpoints extract_bearer_token: Get token from Authorization header or form Exceptions: MicropubError: Base exception for Micropub operations MicropubAuthError: Authentication/authorization errors MicropubValidationError: Invalid request data References: - W3C Micropub Specification: https://www.w3.org/TR/micropub/ - IndieAuth Specification: https://www.w3.org/TR/indieauth/ """ from datetime import datetime from typing import Optional from flask import Request, current_app, jsonify from starpunk.models import split_title from starpunk.notes import ( create_note, delete_note, get_note, list_notes, undelete_note, update_note, InvalidNoteDataError, NoteNotFoundError, ) from starpunk.indieauth import check_scope from starpunk.utils import absolute_url_for # Custom Exceptions class MicropubError(Exception): """Base exception for Micropub operations""" def __init__(self, error: str, error_description: str, status_code: int = 400): self.error = error self.error_description = error_description self.status_code = status_code super().__init__(error_description) class MicropubAuthError(MicropubError): """Authentication or authorization error""" def __init__(self, error_description: str, status_code: int = 401): super().__init__("unauthorized", error_description, status_code) class MicropubValidationError(MicropubError): """Invalid request data""" def __init__(self, error_description: str): super().__init__("invalid_request", error_description, 400) # Response Helpers def error_response(error: str, error_description: str, status_code: int = 400): """ Generate OAuth 2.0 compliant error response Args: error: Error code (e.g., "invalid_request") error_description: Human-readable error description status_code: HTTP status code Returns: Tuple of (response, status_code) """ return ( jsonify({"error": error, "error_description": error_description}), status_code, ) # Token Extraction def extract_bearer_token(request: Request) -> Optional[str]: """ Extract bearer token from Authorization header or form parameter Micropub spec allows token in either location: - Authorization: Bearer - access_token form parameter Args: request: Flask request object Returns: Token string if found, None otherwise """ # Try Authorization header first auth_header = request.headers.get("Authorization", "") if auth_header.startswith("Bearer "): return auth_header[7:] # Remove "Bearer " prefix # Try form parameter if request.method == "POST": return request.form.get("access_token") elif request.method == "GET": return request.args.get("access_token") return None # Property Normalization def normalize_properties(data: dict) -> dict: """ Normalize Micropub properties from both form and JSON formats Handles two input formats: - JSON: {"type": ["h-entry"], "properties": {"content": ["value"]}} - Form: {content: ["value"], "category[]": ["tag1", "tag2"]} Args: data: Raw request data (form dict or JSON dict) Returns: Normalized properties dict with all values as lists """ # JSON format has properties nested if "properties" in data: return data["properties"] # Form format - convert to properties dict properties = {} for key, value in data.items(): if hasattr(value, "filename") or (isinstance(value, list) and value and hasattr(value[0], "filename")): continue # uploaded files are handled separately # Skip reserved Micropub parameters if key.startswith("mp-") or key in ["action", "url", "access_token", "h"]: continue # Handle array notation: property[] -> property clean_key = key.rstrip("[]") # Ensure value is always a list if not isinstance(value, list): value = [value] properties[clean_key] = value return properties # Property Extraction def extract_content(properties: dict) -> str: """ Extract content from Micropub properties Args: properties: Normalized Micropub properties dict Returns: Content string Raises: MicropubValidationError: If content is missing or empty """ content_list = properties.get("content", []) # Handle both plain text and HTML/text objects if not content_list: raise MicropubValidationError("Content is required") content = content_list[0] # Handle structured content ({"html": "...", "text": "..."}) if isinstance(content, dict): # Prefer text over html for markdown storage content = content.get("text") or content.get("html", "") if not content or not content.strip(): raise MicropubValidationError("Content cannot be empty") return content.strip() def extract_title(properties: dict) -> Optional[str]: """ Extract the explicit title (Micropub 'name' property) StarPunk has no title field: a note's title is a '# Heading' first line (see Note.title), so the caller stores the name as that heading. Args: properties: Normalized Micropub properties dict Returns: Title on a single line, or None if no name was sent """ name = (properties.get("name") or [""])[0] if not isinstance(name, str): return None return " ".join(name.split()) or None def add_title_heading(content: str, title: Optional[str]) -> str: """Prefix content with '# title' unless it already starts with that heading""" if not title: return content first_line = content.lstrip().split("\n", 1)[0] if first_line.startswith("#") and first_line.lstrip("#").strip() == title: return content return f"# {title}\n\n{content}" def extract_tags(properties: dict) -> list[str]: """ Extract tags from Micropub category property Args: properties: Normalized Micropub properties dict Returns: List of tag strings """ categories = properties.get("category", []) # Filter out empty strings and strip whitespace return [tag.strip() for tag in categories if tag and tag.strip()] def extract_published_date(properties: dict) -> Optional[datetime]: """ Extract published date from Micropub properties Args: properties: Normalized Micropub properties dict Returns: Datetime object if published date provided, None otherwise """ published = properties.get("published", [""])[0] if not published: return None try: # Parse ISO 8601 datetime # datetime.fromisoformat handles most ISO formats return datetime.fromisoformat(published.replace("Z", "+00:00")) except (ValueError, AttributeError): # If parsing fails, log and return None (will use current time) current_app.logger.warning(f"Failed to parse published date: {published}") return None # Action Handlers MAX_PHOTOS = 4 # ADR-057 MAX_REMOTE_PHOTO_BYTES = 20 * 1024 * 1024 # Properties we can store, and so can be updated (v2.4.0) UPDATABLE = {"content", "name", "category", "in-reply-to", "post-status", "photo"} def _first(value): if isinstance(value, list): return value[0] if value else None return value def _require_scope(token_info: dict, *scopes: str) -> None: granted = token_info.get("scope", "") if not any(check_scope(s, granted) for s in scopes): raise MicropubError( "insufficient_scope", f"Token lacks {' or '.join(scopes)} scope", status_code=403 ) def extract_post_status(properties: dict) -> bool: """post-status: 'draft' -> unpublished; 'published' or absent -> published""" status = _first(properties.get("post-status")) if status in (None, "", "published"): return True if status == "draft": return False raise MicropubValidationError(f"Unsupported post-status: {status}") def extract_url_property(properties: dict, name: str) -> Optional[str]: """A URL property (in-reply-to, like-of, repost-of): string or h-cite""" value = _first(properties.get(name)) if isinstance(value, dict): # h-cite value = _first((value.get("properties") or {}).get("url")) or value.get("value") value = (value or "").strip() if isinstance(value, str) else "" if value and not value.startswith(("http://", "https://")): raise MicropubValidationError(f"{name} must be an http(s) URL") return value or None def extract_in_reply_to(properties: dict) -> Optional[str]: return extract_url_property(properties, "in-reply-to") def extract_photos(properties: dict) -> list[dict[str, str]]: """ Extract photo URLs and alt text from Micropub properties Handles both simple URL strings and structured photo objects with alt text. Examples: >>> extract_photos({'photo': ['https://example.com/photo.jpg']}) [{'url': 'https://example.com/photo.jpg', 'alt': ''}] >>> extract_photos({'photo': [{'value': 'https://example.com/photo.jpg', 'alt': 'Sunset'}]}) [{'url': 'https://example.com/photo.jpg', 'alt': 'Sunset'}] """ result = [] for photo in properties.get("photo", []): if isinstance(photo, str): result.append({'url': photo, 'alt': ''}) elif isinstance(photo, dict): url = photo.get('value') or photo.get('url', '') if url: result.append({'url': url, 'alt': photo.get('alt', '')}) return result def _public_address(host: str) -> bool: """True if every address the host resolves to is public (no SSRF into the LAN)""" import ipaddress import socket try: infos = socket.getaddrinfo(host, None) except socket.gaierror: return False for info in infos: ip = ipaddress.ip_address(info[4][0]) if not ip.is_global: return False return bool(infos) def _fetch_remote_photo(url: str) -> Optional[int]: """Download a photo hosted elsewhere into the media library. Returns media id.""" from urllib.parse import urlparse import httpx from starpunk.media import save_media parsed = urlparse(url) if parsed.scheme not in ("http", "https") or not parsed.hostname: return None if not current_app.config.get("TESTING") and not _public_address(parsed.hostname): current_app.logger.warning(f"Refusing to fetch photo from non-public address: {url}") return None try: with httpx.stream("GET", url, timeout=20.0, follow_redirects=True) as response: response.raise_for_status() data = bytearray() for chunk in response.iter_bytes(): data += chunk if len(data) > MAX_REMOTE_PHOTO_BYTES: raise ValueError("photo too large") name = parsed.path.rsplit("/", 1)[-1] or "photo.jpg" return save_media(bytes(data), name)["id"] except Exception as e: current_app.logger.warning(f"Could not fetch photo {url}: {e}") return None def _media_id_for_url(url: str) -> Optional[int]: """Media id for a photo URL: ours by path, or downloaded if hosted elsewhere""" from starpunk.database import get_db site_url = current_app.config.get("SITE_URL", "http://localhost:5000").rstrip('/') if url.startswith(site_url) or url.startswith('/media/'): path = url[len(site_url):] if url.startswith(site_url) else url if path.startswith('/media/'): path = path[len('/media/'):] row = get_db(current_app).execute("SELECT id FROM media WHERE path = ?", (path,)).fetchone() if row: return row[0] current_app.logger.warning(f"Photo URL not found in media: {url}") return None return _fetch_remote_photo(url) def _save_uploads(files) -> list[dict]: """Photos uploaded in a multipart create request -> [{'media_id', 'alt'}]""" from starpunk.media import save_media result = [] for key in ("photo", "photo[]"): for upload in (files.getlist(key) if files else []): if upload and upload.filename: try: result.append({"media_id": save_media(upload.read(), upload.filename)["id"], "alt": ""}) except ValueError as e: raise MicropubValidationError(f"Invalid photo {upload.filename}: {e}") return result def _resolve_photos(photos: list[dict]) -> tuple[list[int], list[str]]: """Photo dicts ({'url'|'media_id', 'alt'}) -> (media ids, captions), max 4""" if len(photos) > MAX_PHOTOS: current_app.logger.warning( f"Micropub received {len(photos)} photos, truncating to {MAX_PHOTOS} per ADR-057" ) media_ids, captions = [], [] for photo in photos: if len(media_ids) == MAX_PHOTOS: break media_id = photo.get("media_id") or _media_id_for_url(photo["url"]) if media_id: media_ids.append(media_id) captions.append(photo.get("alt", "")) return media_ids, captions def _attach_photos_to_note(note_id: int, photos: list[dict]) -> None: """Attach photos (by URL or uploaded media id) to a note, replacing any others""" from starpunk.media import attach_media_to_note media_ids, captions = _resolve_photos(photos) if media_ids or not photos: attach_media_to_note(note_id, media_ids, captions) def _note_photos(note) -> list[dict]: """A note's current photos as Micropub photo dicts""" from starpunk.media import get_note_media site_url = current_app.config.get("SITE_URL", "http://localhost:5000").rstrip('/') return [ {"url": f"{site_url}/media/{m['path']}", "alt": m.get("caption") or "", "media_id": m["id"]} for m in get_note_media(note.id) ] def _check_type(data: dict) -> None: """Only h-entry is supported""" h = _first(data.get("h")) kind = _first(data.get("type")) if (h and h != "entry") or (kind and kind != "h-entry"): raise MicropubValidationError(f"Only h-entry posts are supported (got {h or kind})") def _note_from_url(url: Optional[str], deleted: bool = False): """Find the note a URL points at (/note/ on this site)""" from urllib.parse import urlparse from starpunk.database import get_db if not url: raise MicropubValidationError("No url provided") site = urlparse(current_app.config.get("SITE_URL", "")) parsed = urlparse(url) if parsed.netloc and site.netloc and parsed.netloc != site.netloc: raise MicropubValidationError("URL is not on this site") parts = [p for p in parsed.path.split("/") if p] if len(parts) != 2 or parts[0] not in ("note", "notes"): raise MicropubValidationError("URL is not a post on this site") slug = parts[1] if deleted: row = get_db(current_app).execute( "SELECT id FROM notes WHERE slug = ? AND deleted_at IS NOT NULL", (slug,) ).fetchone() if row is None: raise MicropubError("not_found", "No deleted post at that URL", 404) return slug note = get_note(slug=slug) if note is None: raise MicropubError("not_found", "Post not found", 404) return note def handle_create(data: dict, token_info: dict, files=None): """ Handle Micropub create action Creates a note using StarPunk's notes.py CRUD functions after mapping Micropub properties to StarPunk's note format. Args: data: Raw request data (form or JSON) token_info: Authenticated token information (me, client_id, scope) files: Uploaded files for multipart requests (v2.4.0) Returns: Tuple of (response_body, status_code, headers) """ _require_scope(token_info, "create") _check_type(data) # mp-slug and mp-syndicate-to are server commands, not properties custom_slug = None if isinstance(data, dict) and 'mp-slug' in data: slug_value = data.get('mp-slug') if isinstance(slug_value, list) and slug_value: custom_slug = slug_value[0] elif isinstance(slug_value, str): custom_slug = slug_value # Absent means "all targets"; present means exactly those (v2.1.0) requested_targets = None if isinstance(data, dict): for key in ("mp-syndicate-to", "mp-syndicate-to[]"): if key in data: value = data[key] requested_targets = (requested_targets or []) + ( value if isinstance(value, list) else [value] ) try: properties = normalize_properties(data) like_of = extract_url_property(properties, "like-of") repost_of = extract_url_property(properties, "repost-of") if like_of and repost_of: raise MicropubValidationError("A post can't be both a like and a repost") # Likes and reposts may come without a comment (v2.5.0) has_content = any( (c.strip() if isinstance(c, str) else (c.get("text") or c.get("html") or "").strip()) for c in properties.get("content", []) if c ) content = extract_content(properties) if has_content or not (like_of or repost_of) else "" title = extract_title(properties) tags = extract_tags(properties) published_date = extract_published_date(properties) published = extract_post_status(properties) in_reply_to = extract_in_reply_to(properties) photos = extract_photos(properties) + _save_uploads(files) except MicropubError: raise except Exception as e: current_app.logger.error(f"Property extraction failed: {e}") raise MicropubValidationError(f"Failed to parse request: {str(e)}") try: note = create_note( content=add_title_heading(content, title), published=published, created_at=published_date, custom_slug=custom_slug, tags=tags if tags else None, in_reply_to=in_reply_to, like_of=like_of, repost_of=repost_of, ) if photos: _attach_photos_to_note(note.id, photos) # Crosspost after photos are attached (v2.1.0); drafts wait until published from starpunk.syndication import get_targets, resolve_targets, select_targets if requested_targets is None: select_targets(note.id, list(get_targets())) else: select_targets(note.id, resolve_targets(requested_targets)) return "", 201, {"Location": absolute_url_for("public.note", slug=note.slug)} except InvalidNoteDataError as e: raise MicropubValidationError(str(e)) except MicropubError: raise except Exception as e: current_app.logger.error(f"Failed to create note via Micropub: {e}") raise MicropubError("server_error", "Failed to create post", status_code=500) def handle_update(data: dict, token_info: dict): """ Handle Micropub update action (v2.4.0) JSON body: {"action": "update", "url": ..., "replace": {...}, "add": {...}, "delete": [...] or {...}}. Edits follow to crossposts. """ from starpunk.syndication import note_changed _require_scope(token_info, "update") note = _note_from_url(_first(data.get("url"))) replace = data.get("replace") or {} add = data.get("add") or {} delete = data.get("delete") or {} if not isinstance(replace, dict) or not isinstance(add, dict) or not isinstance(delete, (dict, list)): raise MicropubValidationError("replace and add must be objects; delete an object or list") for prop, values in list(replace.items()) + list(add.items()): if not isinstance(values, list): raise MicropubValidationError(f"Values for {prop} must be an array") touched = set(replace) | set(add) | set(delete) unsupported = sorted(touched - UPDATABLE) if unsupported: raise MicropubValidationError(f"Updating {', '.join(unsupported)} is not supported") if set(add) - {"category", "photo"}: raise MicropubValidationError("Only category and photo can be added to") from starpunk.tags import get_note_tags title, body = split_title(note.content) tags = [t["display_name"] for t in get_note_tags(note.id, entered_order=True)] photos = _note_photos(note) changes = {} # Removals first, then replacements, then additions if isinstance(delete, list): for prop in delete: if prop == "name": title = None elif prop == "content": raise MicropubValidationError("content can't be deleted") elif prop == "category": tags = [] elif prop == "photo": photos = [] elif prop == "in-reply-to": changes["in_reply_to"] = "" elif prop == "post-status": changes["published"] = True else: for prop, values in delete.items(): if prop == "category": drop = {v.lower() for v in values} tags = [t for t in tags if t.lower() not in drop] elif prop == "photo": drop = {p["url"] for p in extract_photos({"photo": values})} photos = [p for p in photos if p["url"] not in drop] else: raise MicropubValidationError(f"Can't delete individual values of {prop}") if "content" in replace: body = extract_content(replace) if "name" in replace: title = extract_title(replace) if "category" in replace: tags = extract_tags(replace) if "photo" in replace: photos = extract_photos(replace) if "in-reply-to" in replace: changes["in_reply_to"] = extract_in_reply_to(replace) or "" if "post-status" in replace: changes["published"] = extract_post_status(replace) if "category" in add: known = {t.lower() for t in tags} tags += [t for t in extract_tags(add) if t.lower() not in known] if "photo" in add: photos += extract_photos(add) new_content = add_title_heading(body, title) if new_content != note.content: changes["content"] = new_content if {"category"} & touched: changes["tags"] = tags try: if changes: update_note(id=note.id, **changes) if "photo" in touched: _attach_photos_to_note(note.id, photos) note_changed(note.id) except InvalidNoteDataError as e: raise MicropubValidationError(str(e)) except MicropubError: raise except Exception as e: current_app.logger.error(f"Failed to update note via Micropub: {e}") raise MicropubError("server_error", "Failed to update post", status_code=500) return "", 204 def handle_delete(data: dict, token_info: dict, undelete: bool = False): """Handle Micropub delete / undelete (v2.4.0). Deletes are soft so they can be undone.""" _require_scope(token_info, "delete") url = _first(data.get("url")) try: if undelete: undelete_note(_note_from_url(url, deleted=True)) else: delete_note(id=_note_from_url(url).id, soft=True) except MicropubError: raise except Exception as e: current_app.logger.error(f"Micropub {'undelete' if undelete else 'delete'} failed: {e}") raise MicropubError("server_error", "Failed to change post", status_code=500) return "", 204 def _syndicate_to() -> list: """Configured crosspost targets in Micropub syndicate-to form""" from starpunk.syndication import get_targets return [{"uid": t.uid, "name": t.name} for t in get_targets().values()] def note_to_mf2(note, wanted: Optional[list] = None) -> dict: """ A note as Microformats2 JSON, the inverse of create A '# Heading' first line is the title, returned as name. """ from starpunk.syndication import get_note_syndications title, content = split_title(note.content) props = { "content": [content], "published": [note.created_at.isoformat()], "url": [absolute_url_for("public.note", slug=note.slug)], "post-status": ["published" if note.published else "draft"], } if title: props["name"] = [title] from starpunk.tags import get_note_tags tags = get_note_tags(note.id, entered_order=True) if tags: props["category"] = [tag["display_name"] for tag in tags] if getattr(note, "in_reply_to", None): props["in-reply-to"] = [note.in_reply_to] if getattr(note, "like_of", None): props["like-of"] = [note.like_of] if getattr(note, "repost_of", None): props["repost-of"] = [note.repost_of] photos = _note_photos(note) if photos: props["photo"] = [{"value": p["url"], "alt": p["alt"]} for p in photos] synced = [s["remote_url"] for s in get_note_syndications(note.id) if s.get("remote_url")] if synced: props["syndication"] = synced if wanted: return {"properties": {k: v for k, v in props.items() if k in wanted}} return {"type": ["h-entry"], "properties": props} def _all_categories(prefix: str = "") -> list: """Tags in use, most used first (q=category)""" from starpunk.database import get_db rows = get_db(current_app).execute( """ SELECT t.display_name, COUNT(nt.note_id) AS uses FROM tags t LEFT JOIN note_tags nt ON nt.tag_id = t.id GROUP BY t.id ORDER BY uses DESC, t.display_name """ ).fetchall() prefix = prefix.lower() return [r["display_name"] for r in rows if not prefix or prefix in r["display_name"].lower()] QUERIES = ["config", "source", "syndicate-to", "category"] def handle_query(args, token_info: dict): """ Handle Micropub query endpoints Supports: - q=config: Server configuration - q=source&url=...[&properties[]=...]: One post in Microformats2 JSON - q=source (no url) [&limit=N&offset=N]: Recent posts, drafts included - q=syndicate-to: Crosspost targets - q=category[&filter=...]: Tags in use Args: args: Query arguments (werkzeug MultiDict or plain dict) """ def get_list(key): if hasattr(args, "getlist"): return args.getlist(key) + args.getlist(f"{key}[]") value = args.get(key) or args.get(f"{key}[]") return value if isinstance(value, list) else ([value] if value else []) q = args.get("q") if q == "config": site_url = current_app.config.get("SITE_URL", "http://localhost:5000").rstrip('/') return jsonify({ "media-endpoint": f"{site_url}/micropub/media", "syndicate-to": _syndicate_to(), "q": QUERIES, "post-types": [ {"type": "note", "name": "Note", "properties": ["content"]}, {"type": "article", "name": "Article", "properties": ["name", "content"]}, {"type": "photo", "name": "Photo", "properties": ["photo"]}, {"type": "reply", "name": "Reply", "properties": ["in-reply-to", "content"]}, {"type": "like", "name": "Like", "properties": ["like-of"]}, {"type": "repost", "name": "Repost", "properties": ["repost-of", "content"]}, ], }), 200 if q == "source": url = args.get("url") wanted = get_list("properties") if url: try: note = _note_from_url(url) except MicropubError as e: return error_response("invalid_request" if e.status_code == 400 else e.error, e.error_description, e.status_code) return jsonify(note_to_mf2(note, wanted)), 200 try: limit = max(1, min(int(args.get("limit", 10)), 50)) offset = max(0, int(args.get("offset", 0))) except ValueError: return error_response("invalid_request", "limit and offset must be numbers") notes = list_notes(published_only=False, limit=limit, offset=offset) items = [note_to_mf2(n, wanted) for n in notes] return jsonify({"items": items}), 200 if q == "syndicate-to": return jsonify({"syndicate-to": _syndicate_to()}), 200 if q == "category": return jsonify({"categories": _all_categories(args.get("filter") or "")}), 200 return error_response("invalid_request", f"Unknown query: {q}")