chore: Recover v1.6.0-rc.2 source from production image
The v1.6.0 work (webmentions, reply contexts, rate limiter, migration 010) was built and deployed as git.thesatelliteoflove.com/phil/starpunk:v1.6.0-rc.2 but never committed. This restores the application code from /app in the running container so later work builds on what production runs. Tests and docs for v1.6.0 were not in the image and are not recovered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
06a8aabc01
commit
d3fa5b7a2a
24 files changed
+3982
-78
No files matched your search
@@ -7,7 +7,7 @@ admin, auth, and (conditionally) dev auth routes.
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from starpunk.routes import admin, auth, micropub, public, search
|
||||
from starpunk.routes import admin, auth, micropub, public, search, webmention
|
||||
|
||||
|
||||
def register_routes(app: Flask) -> None:
|
||||
@@ -39,6 +39,10 @@ def register_routes(app: Flask) -> None:
|
||||
# Register search routes
|
||||
app.register_blueprint(search.bp)
|
||||
|
||||
# Register webmention routes (v1.6.0)
|
||||
if app.config.get("WEBMENTION_ENABLED", True):
|
||||
app.register_blueprint(webmention.bp)
|
||||
|
||||
# Conditionally register dev auth routes
|
||||
if app.config.get("DEV_MODE"):
|
||||
app.logger.warning(
|
||||
|
||||
+220
-4
@@ -6,10 +6,13 @@ editing, and deletion. All routes require authentication.
|
||||
"""
|
||||
|
||||
from flask import Blueprint, flash, g, jsonify, redirect, render_template, request, url_for
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from starpunk.auth import require_auth
|
||||
from starpunk.notes import (
|
||||
create_note,
|
||||
@@ -32,17 +35,51 @@ def dashboard():
|
||||
Displays all notes (published and drafts) with management controls.
|
||||
Requires authentication.
|
||||
|
||||
Per v1.6.0: Added pagination (25 items per page)
|
||||
|
||||
Returns:
|
||||
Rendered dashboard template with complete note list
|
||||
Rendered dashboard template with paginated note list
|
||||
|
||||
Decorator: @require_auth
|
||||
Template: templates/admin/dashboard.html
|
||||
Access: g.user_me (set by require_auth decorator)
|
||||
"""
|
||||
# Get all notes (published and drafts)
|
||||
notes = list_notes()
|
||||
from flask import current_app
|
||||
import math
|
||||
|
||||
return render_template("admin/dashboard.html", notes=notes, user_me=g.me)
|
||||
# Get pagination params (v1.6.0)
|
||||
page = int(request.args.get('page', 1))
|
||||
per_page = 25
|
||||
|
||||
# Get all notes (published and drafts)
|
||||
all_notes = list_notes()
|
||||
|
||||
# Calculate pagination
|
||||
total_notes = len(all_notes)
|
||||
total_pages = math.ceil(total_notes / per_page) if total_notes > 0 else 1
|
||||
|
||||
# Slice for current page
|
||||
start_idx = (page - 1) * per_page
|
||||
end_idx = start_idx + per_page
|
||||
notes = all_notes[start_idx:end_idx]
|
||||
|
||||
# Get pending webmention count (v1.6.0)
|
||||
webmention_pending_count = 0
|
||||
if current_app.config.get('WEBMENTION_ENABLED', False):
|
||||
try:
|
||||
from starpunk.webmention_queries import count_webmentions
|
||||
webmention_pending_count = count_webmentions(status_filter='pending')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return render_template(
|
||||
"admin/dashboard.html",
|
||||
notes=notes,
|
||||
page=page,
|
||||
total_pages=total_pages,
|
||||
webmention_pending_count=webmention_pending_count,
|
||||
user_me=g.me
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/new", methods=["GET"])
|
||||
@@ -600,3 +637,182 @@ def health_diagnostics():
|
||||
diagnostics["status"] = "healthy" if overall_healthy else "unhealthy"
|
||||
|
||||
return jsonify(diagnostics), 200 if overall_healthy else 500
|
||||
|
||||
|
||||
# Webmention Admin Routes (v1.6.0)
|
||||
|
||||
@bp.route("/webmentions")
|
||||
@require_auth
|
||||
def webmentions():
|
||||
"""
|
||||
Webmention list with filtering and pagination (v1.6.0 Phase 5)
|
||||
|
||||
Lists all webmentions with status filters and pagination.
|
||||
|
||||
Query params:
|
||||
status: Filter by moderation_status ('pending', 'approved', 'hidden')
|
||||
page: Page number (default: 1)
|
||||
|
||||
Returns:
|
||||
Rendered webmentions list template
|
||||
|
||||
Decorator: @require_auth
|
||||
Template: templates/admin/webmentions.html
|
||||
"""
|
||||
from starpunk.webmention_queries import list_webmentions
|
||||
|
||||
status_filter = request.args.get('status')
|
||||
page = int(request.args.get('page', 1))
|
||||
|
||||
webmentions, total_pages = list_webmentions(
|
||||
status_filter=status_filter,
|
||||
page=page,
|
||||
per_page=25
|
||||
)
|
||||
|
||||
return render_template(
|
||||
"admin/webmentions.html",
|
||||
webmentions=webmentions,
|
||||
status_filter=status_filter,
|
||||
page=page,
|
||||
total_pages=total_pages,
|
||||
user_me=g.me
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/webmentions/<int:id>")
|
||||
@require_auth
|
||||
def webmention_detail(id: int):
|
||||
"""
|
||||
Webmention detail view (v1.6.0 Phase 5)
|
||||
|
||||
Shows full details of a single webmention with moderation actions.
|
||||
|
||||
Args:
|
||||
id: Webmention database ID
|
||||
|
||||
Returns:
|
||||
Rendered webmention detail template or 404 if not found
|
||||
|
||||
Decorator: @require_auth
|
||||
Template: templates/admin/webmention_detail.html
|
||||
"""
|
||||
from starpunk.webmention_queries import get_webmention
|
||||
|
||||
webmention = get_webmention(id)
|
||||
|
||||
if not webmention:
|
||||
flash("Webmention not found", "error")
|
||||
return redirect(url_for("admin.webmentions")), 404
|
||||
|
||||
return render_template(
|
||||
"admin/webmention_detail.html",
|
||||
webmention=webmention,
|
||||
user_me=g.me
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/webmentions/<int:id>/action", methods=["POST"])
|
||||
@require_auth
|
||||
def webmention_action(id: int):
|
||||
"""
|
||||
Individual webmention moderation action (v1.6.0 Phase 5)
|
||||
|
||||
Approve, hide, or delete a single webmention.
|
||||
|
||||
Args:
|
||||
id: Webmention database ID
|
||||
|
||||
Form data:
|
||||
action: 'approve', 'hide', or 'delete'
|
||||
|
||||
Returns:
|
||||
Redirect to webmention detail or list
|
||||
|
||||
Decorator: @require_auth
|
||||
"""
|
||||
from starpunk.webmention_queries import update_webmention_status, delete_webmentions
|
||||
|
||||
action = request.form.get('action')
|
||||
|
||||
if action not in ('approve', 'hide', 'delete'):
|
||||
flash("Invalid action", "error")
|
||||
return redirect(url_for("admin.webmention_detail", id=id))
|
||||
|
||||
try:
|
||||
if action == 'delete':
|
||||
deleted = delete_webmentions([id])
|
||||
if deleted > 0:
|
||||
flash("Webmention deleted", "success")
|
||||
else:
|
||||
flash("Webmention not found", "error")
|
||||
return redirect(url_for("admin.webmentions"))
|
||||
else:
|
||||
# Approve or hide
|
||||
status = 'approved' if action == 'approve' else 'hidden'
|
||||
updated = update_webmention_status([id], status)
|
||||
if updated > 0:
|
||||
flash(f"Webmention {status}", "success")
|
||||
else:
|
||||
flash("Webmention not found", "error")
|
||||
return redirect(url_for("admin.webmention_detail", id=id))
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error performing webmention action: {e}")
|
||||
flash(f"Error: {e}", "error")
|
||||
return redirect(url_for("admin.webmention_detail", id=id))
|
||||
|
||||
|
||||
@bp.route("/webmentions/bulk-action", methods=["POST"])
|
||||
@require_auth
|
||||
def webmention_bulk_action():
|
||||
"""
|
||||
Bulk webmention moderation actions (v1.6.0 Phase 5)
|
||||
|
||||
Approve, hide, or delete multiple webmentions at once.
|
||||
|
||||
Form data:
|
||||
action: 'approve', 'hide', or 'delete'
|
||||
ids[]: List of webmention IDs
|
||||
|
||||
Returns:
|
||||
Redirect to webmentions list
|
||||
|
||||
Decorator: @require_auth
|
||||
"""
|
||||
from starpunk.webmention_queries import update_webmention_status, delete_webmentions
|
||||
|
||||
action = request.form.get('action')
|
||||
ids = request.form.getlist('ids')
|
||||
|
||||
if not ids:
|
||||
flash("No webmentions selected", "warning")
|
||||
return redirect(url_for("admin.webmentions"))
|
||||
|
||||
# Convert IDs to integers
|
||||
try:
|
||||
webmention_ids = [int(id) for id in ids]
|
||||
except ValueError:
|
||||
flash("Invalid webmention IDs", "error")
|
||||
return redirect(url_for("admin.webmentions"))
|
||||
|
||||
if action not in ('approve', 'hide', 'delete'):
|
||||
flash("Invalid action", "error")
|
||||
return redirect(url_for("admin.webmentions"))
|
||||
|
||||
try:
|
||||
if action == 'delete':
|
||||
deleted = delete_webmentions(webmention_ids)
|
||||
flash(f"Deleted {deleted} webmention(s)", "success")
|
||||
else:
|
||||
# Approve or hide
|
||||
status = 'approved' if action == 'approve' else 'hidden'
|
||||
updated = update_webmention_status(webmention_ids, status)
|
||||
flash(f"Updated {updated} webmention(s) to {status}", "success")
|
||||
|
||||
return redirect(url_for("admin.webmentions"))
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error performing bulk action: {e}")
|
||||
flash(f"Error: {e}", "error")
|
||||
return redirect(url_for("admin.webmentions"))
|
||||
@@ -281,6 +281,8 @@ def note(slug: str):
|
||||
|
||||
Template: templates/note.html
|
||||
Microformats: h-entry
|
||||
|
||||
Per v1.6.0: Added webmentions and reply context display
|
||||
"""
|
||||
from starpunk.media import get_note_media
|
||||
from starpunk.tags import get_note_tags
|
||||
@@ -303,7 +305,39 @@ def note(slug: str):
|
||||
tags = get_note_tags(note_obj.id)
|
||||
object.__setattr__(note_obj, '_cached_tags', tags)
|
||||
|
||||
return render_template("note.html", note=note_obj)
|
||||
# Get webmentions for note (v1.6.0 Phase 5)
|
||||
webmentions = None
|
||||
reply_context = None
|
||||
|
||||
if current_app.config.get('WEBMENTION_ENABLED', False):
|
||||
try:
|
||||
from starpunk.webmention_queries import get_webmentions_for_note, get_reply_context
|
||||
|
||||
# Get approved webmentions grouped by type
|
||||
grouped = get_webmentions_for_note(note_obj.id)
|
||||
|
||||
# Check if there are any webmentions
|
||||
has_webmentions = any(grouped.values())
|
||||
if has_webmentions:
|
||||
webmentions = grouped
|
||||
|
||||
# Get reply context if this is a reply post
|
||||
if note_obj.in_reply_to:
|
||||
reply_context = get_reply_context(note_obj.in_reply_to)
|
||||
|
||||
except Exception as e:
|
||||
# Log error but don't fail page load
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.error(f"Error loading webmentions for note {slug}: {e}")
|
||||
|
||||
return render_template(
|
||||
"note.html",
|
||||
note=note_obj,
|
||||
webmentions=webmentions,
|
||||
reply_context=reply_context,
|
||||
**grouped if webmentions else {}
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/tag/<tag>")
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
"""
|
||||
Webmention routes for StarPunk
|
||||
|
||||
Per W3C Webmention Recommendation and ADR-063:
|
||||
- POST /webmention - Receive webmention notifications
|
||||
- GET /webmention - Optional endpoint information
|
||||
|
||||
References:
|
||||
- W3C Webmention Specification: https://www.w3.org/TR/webmention/
|
||||
- ADR-063: Webmention Implementation
|
||||
"""
|
||||
|
||||
from flask import Blueprint, current_app, request, jsonify
|
||||
from urllib.parse import urlparse
|
||||
from starpunk.database import get_db
|
||||
from starpunk.notes import get_note, NoteNotFoundError
|
||||
from starpunk.rate_limiter import check_rate_limit
|
||||
|
||||
bp = Blueprint("webmention", __name__)
|
||||
|
||||
|
||||
def get_client_ip() -> str:
|
||||
"""
|
||||
Get client IP address, accounting for reverse proxy.
|
||||
|
||||
If TRUSTED_PROXY is enabled, uses X-Forwarded-For header.
|
||||
Otherwise uses request.remote_addr directly.
|
||||
"""
|
||||
if current_app.config.get('TRUSTED_PROXY', False):
|
||||
forwarded = request.headers.get('X-Forwarded-For')
|
||||
if forwarded:
|
||||
# First IP in chain is the client
|
||||
return forwarded.split(',')[0].strip()
|
||||
return request.remote_addr or '0.0.0.0'
|
||||
|
||||
|
||||
@bp.before_request
|
||||
def rate_limit_webmention():
|
||||
"""
|
||||
Check rate limits before processing webmention requests.
|
||||
|
||||
Per ADR-064, checks:
|
||||
1. IP rate limit (60/min by default)
|
||||
2. Source domain rate limit (10/min by default)
|
||||
|
||||
Returns 429 with Retry-After header if rate limited.
|
||||
"""
|
||||
# Only rate limit POST requests (the actual webmention submission)
|
||||
if request.method != 'POST':
|
||||
return None
|
||||
|
||||
# Get client IP
|
||||
ip = get_client_ip()
|
||||
|
||||
# Get source domain from request (if available)
|
||||
source_domain = None
|
||||
content_type = request.headers.get("Content-Type", "")
|
||||
|
||||
if "application/json" in content_type:
|
||||
data = request.get_json(silent=True) or {}
|
||||
source = data.get('source')
|
||||
else:
|
||||
source = request.form.get('source')
|
||||
|
||||
if source:
|
||||
try:
|
||||
source_domain = urlparse(source).netloc
|
||||
except Exception:
|
||||
# Invalid URL, domain check will be skipped
|
||||
# This is acceptable - IP limit still applies
|
||||
current_app.logger.debug(f"Could not parse source URL for domain extraction: {source}")
|
||||
|
||||
# Check rate limits
|
||||
allowed, error = check_rate_limit(ip, source_domain)
|
||||
if not allowed:
|
||||
current_app.logger.warning(
|
||||
f"Rate limit exceeded - IP: {ip}, Domain: {source_domain or 'N/A'}"
|
||||
)
|
||||
return jsonify({
|
||||
"error": "rate_limit_exceeded",
|
||||
"error_description": error
|
||||
}), 429, {'Retry-After': str(current_app.config.get('WEBMENTION_RATE_LIMIT_WINDOW', 60))}
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def validate_url(url: str) -> tuple[bool, str | None]:
|
||||
"""
|
||||
Validate a URL is well-formed and uses http/https scheme.
|
||||
|
||||
Returns:
|
||||
(is_valid, error_message)
|
||||
"""
|
||||
if not url:
|
||||
return False, "URL is required"
|
||||
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ('http', 'https'):
|
||||
return False, "Only http and https URLs are supported"
|
||||
if not parsed.netloc:
|
||||
return False, "URL must include a hostname"
|
||||
if len(url) > 2048:
|
||||
return False, "URL exceeds maximum length of 2048 characters"
|
||||
return True, None
|
||||
except Exception:
|
||||
return False, "URL is malformed"
|
||||
|
||||
|
||||
def is_target_on_site(target_url: str) -> bool:
|
||||
"""
|
||||
Check if target URL is on this site.
|
||||
|
||||
Compares hostname of target_url with SITE_URL configuration.
|
||||
"""
|
||||
site_url = current_app.config.get('SITE_URL', '')
|
||||
site_parsed = urlparse(site_url)
|
||||
target_parsed = urlparse(target_url)
|
||||
|
||||
return site_parsed.netloc == target_parsed.netloc
|
||||
|
||||
|
||||
def resolve_target_note(target_url: str) -> int | None:
|
||||
"""
|
||||
Resolve target URL to a note ID if it points to a note.
|
||||
|
||||
Returns:
|
||||
Note ID if target is a valid note, None otherwise
|
||||
"""
|
||||
target_parsed = urlparse(target_url)
|
||||
|
||||
# Strip query params and fragments for matching
|
||||
target_path = target_parsed.path.rstrip('/')
|
||||
|
||||
# Check if it's a note URL pattern: /note/{slug}
|
||||
if target_path.startswith('/note/'):
|
||||
slug = target_path[6:] # Remove '/note/' prefix
|
||||
if slug:
|
||||
try:
|
||||
note = get_note(slug=slug)
|
||||
# get_note() returns None if not found, or a Note object
|
||||
if note and note.published:
|
||||
return note.id
|
||||
except NoteNotFoundError:
|
||||
pass
|
||||
|
||||
# Homepage or other valid page (not a note)
|
||||
return None
|
||||
|
||||
|
||||
@bp.route("/webmention", methods=["GET"])
|
||||
def webmention_info():
|
||||
"""
|
||||
Optional endpoint information.
|
||||
|
||||
Returns basic information about the webmention endpoint.
|
||||
"""
|
||||
return jsonify({
|
||||
"name": "Webmention endpoint",
|
||||
"spec": "https://www.w3.org/TR/webmention/"
|
||||
})
|
||||
|
||||
|
||||
@bp.route("/webmention", methods=["POST"])
|
||||
def receive_webmention():
|
||||
"""
|
||||
Receive webmention notification per W3C spec.
|
||||
|
||||
Accepts application/x-www-form-urlencoded (required) and
|
||||
application/json (optional extension).
|
||||
|
||||
Returns:
|
||||
202 Accepted with JSON body on success
|
||||
400 Bad Request with error details on failure
|
||||
"""
|
||||
# Parse request based on content type
|
||||
content_type = request.headers.get("Content-Type", "")
|
||||
|
||||
if "application/json" in content_type:
|
||||
data = request.get_json() or {}
|
||||
source = data.get("source")
|
||||
target = data.get("target")
|
||||
else:
|
||||
# Default to form-encoded (required by W3C spec)
|
||||
source = request.form.get("source")
|
||||
target = request.form.get("target")
|
||||
|
||||
# Validate required parameters
|
||||
if not source:
|
||||
return jsonify({
|
||||
"error": "invalid_request",
|
||||
"error_description": "Missing required parameter: source"
|
||||
}), 400
|
||||
|
||||
if not target:
|
||||
return jsonify({
|
||||
"error": "invalid_request",
|
||||
"error_description": "Missing required parameter: target"
|
||||
}), 400
|
||||
|
||||
# Validate source URL
|
||||
source_valid, source_error = validate_url(source)
|
||||
if not source_valid:
|
||||
return jsonify({
|
||||
"error": "invalid_request",
|
||||
"error_description": f"Source must be a valid URL"
|
||||
}), 400
|
||||
|
||||
# Validate target URL
|
||||
target_valid, target_error = validate_url(target)
|
||||
if not target_valid:
|
||||
return jsonify({
|
||||
"error": "invalid_request",
|
||||
"error_description": f"Target must be a valid URL"
|
||||
}), 400
|
||||
|
||||
# Validate source and target are different
|
||||
if source == target:
|
||||
return jsonify({
|
||||
"error": "invalid_request",
|
||||
"error_description": "Source and target must be different"
|
||||
}), 400
|
||||
|
||||
# Validate target is on this site
|
||||
if not is_target_on_site(target):
|
||||
return jsonify({
|
||||
"error": "invalid_target",
|
||||
"error_description": "Target URL is not on this site"
|
||||
}), 400
|
||||
|
||||
# Resolve target to note (may be None for homepage/other pages)
|
||||
target_note_id = resolve_target_note(target)
|
||||
|
||||
# If target looks like a note URL but doesn't resolve, it's not found
|
||||
target_parsed = urlparse(target)
|
||||
target_path = target_parsed.path.rstrip('/')
|
||||
if target_path.startswith('/note/') and target_note_id is None:
|
||||
return jsonify({
|
||||
"error": "invalid_target",
|
||||
"error_description": "Target URL not found"
|
||||
}), 400
|
||||
|
||||
# Insert webmention into database (queued for validation)
|
||||
# Use INSERT ... ON CONFLICT to handle duplicate webmentions
|
||||
db = get_db()
|
||||
try:
|
||||
db.execute("""
|
||||
INSERT INTO webmentions (source_url, target_url, target_note_id)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(source_url, target_url) DO UPDATE SET
|
||||
validation_status = 'pending',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""", (source, target, target_note_id))
|
||||
db.commit()
|
||||
|
||||
current_app.logger.info(
|
||||
f"Webmention received: {source} -> {target}"
|
||||
f"{' (note_id=' + str(target_note_id) + ')' if target_note_id else ''}"
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
"status": "accepted",
|
||||
"message": "Webmention queued for verification"
|
||||
}), 202
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
current_app.logger.error(f"Failed to queue webmention: {e}")
|
||||
return jsonify({
|
||||
"error": "server_error",
|
||||
"error_description": "Failed to queue webmention"
|
||||
}), 500
|
||||
Reference in new issue
Block a user