Merge branch 'feat/v2.8.0-microformats' for v2.8.0 release
Build Container / build (push) Successful in 9m35s

This commit is contained in:
Phil committed 2026-11-03 09:36:53 -07:00
commit 42c77e34b7
21 files changed
+793 -277

No files matched your search

+22
View File
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [2.8.0] - 2026-11-03
Microformats2 review: the markup now matches the [microformats2](https://microformats.org/wiki/microformats2) vocabularies, so IndieWeb readers and tools see what the page shows.
### Fixed
- Replies to a note weren't marked up as its comments, so readers and threading tools saw none. They are now `u-comment h-cite`s with the replier's h-card (name, link, photo) and the reply's HTML
- Likes, reposts, bookmarks and mentions on a note had no microformats at all. Each is now a `u-like`, `u-repost`, `u-bookmark` or `u-mention` h-cite with its author, including likes past the eight faces shown
- Responses link to and are dated by the original post (its own URL and published time) instead of the address that sent the webmention and when it arrived. New database columns hold these (migration 014)
- Post times had no time zone (and production showed microseconds), so readers could shift them by hours. Times on pages and in Micropub `q=source` are now UTC with a `Z`, matching the Atom feed
- A note starting with a hashtag (`#indieweb is great…`) was treated as a titled article: its text became a heading and the body was empty, and a note starting with a bare `#` line got its slug as a title. Only a Markdown heading (`#` then a space) makes a title now
- A webmention from one of a note's own crossposts (for example your GoToSocial copy, sent back through Bridgy) showed up as a response on the note. It is now ignored
- Micropub and IndieAuth discovery links disappeared from pages when webmentions were turned off
- A new site had no `rel="me"` link to its author, so readers couldn't tell whose site it was; pages now always link `rel="me"` and `rel="author"` to the author's home page
- Finding the author's profile could pick someone else's h-card from their home page. It now follows the [representative h-card](https://microformats.org/wiki/representative-h-card-parsing) rules
- A webmention's author is found by the [authorship algorithm](https://indieweb.org/authorship-spec), from the entry on the source page that actually responds to the note: an author given as a name or link, and the author of a feed the entry is in, now count
### Added
- Tag pages and the likes page have a feed URL and author, like the home page
- Note previews have `u-uid`
## [2.7.2] - 2026-11-03
### Added
@@ -0,0 +1,38 @@
# v2.8.0: Microformats2 review
Review of StarPunk's published and consumed microformats against
microformats2, h-entry, h-card, h-feed, h-cite, representative h-card
parsing, the authorship spec and Post Type Discovery. Every page type was
rendered, parsed with mf2py and checked with mf2util.
Posts (h-entry) were largely correct: no implied names, PTD right for
note/article/reply/like/repost/photo, author h-card, u-url/u-uid,
p-category, u-syndication.
## Fixes
| # | Problem | Fix |
|---|---|---|
| 1 | Replies were unattached `h-cite` children with a plain-text author | `u-comment h-cite`, `p-author h-card` (u-url on an inner link, u-photo, p-name), `e-content` (`templates/partials/responses.html`) |
| 2 | Likes/reposts/bookmarks/mentions had no mf2 | `u-like` / `u-repost` / `u-bookmark` / `u-mention` h-cites; faces past 8 are `hidden`, not omitted |
| 3 | `dt-*` naive, with microseconds | `iso_utc` filter/helper: RFC 3339 UTC `Z`, no fraction; Micropub `q=source` too |
| 4 | `#hashtag` first line = title; bare `#` = slug title | `split_title` requires an ATX heading (`#{1,6}` + space); templates use `Note.has_title` |
| 5 | Note's own syndicated copy shown as a mention | Worker rejects a source whose url/uid (or URL) is one of the note's `syndications.remote_url` as invalid |
| 6 | Micropub/IndieAuth links gated on WEBMENTION_ENABLED | Only `rel=webmention` is gated |
| 7 | No rel=me on a fresh install | `rel=me` and `rel=author` to `author.url or author.me or ADMIN_ME`, always |
| 8 | Author discovery guessed h-cards | `mf2_utils.representative_hcard` (uid+url, rel=me, single h-card); parsed with the URL after redirects |
| 9 | Webmention entry/author/time | `mf2_utils.responding_entry` (entry whose in-reply-to/like-of/... or content refers to the target), `entry_author` (author property as h-card/URL/name, parent h-feed author, rel=author, representative h-card), `source_post_url` and `source_published` stored (migration 014) |
Also: tag and likes h-feeds have `u-url` and `p-author`; previews have `u-uid`.
## Not done
- Reply-context h-cite does not carry the cached author h-card, name or published time.
- Photo alt falls back to "Image" when a photo-only post has no caption.
- Person tags (`p-category h-card`) are not supported.
- Existing webmentions keep NULL source details until they are re-validated.
## Tests
`tests/test_microformats_v280.py`. `tests/test_microformats.py`
`test_no_relme_without_author` became `test_relme_to_admin_me_without_author`.
@@ -0,0 +1,6 @@
-- Migration 014: Source details for received webmentions (v2.8.0)
-- The source's own u-url and dt-published, so a response links to and dates
-- the original post rather than the URL that sent it and when it arrived.
ALTER TABLE webmentions ADD COLUMN source_post_url TEXT;
ALTER TABLE webmentions ADD COLUMN source_published TIMESTAMP;
+6 -2
View File
@@ -219,6 +219,10 @@ def create_app(config=None):
return {'author': author}
# Template filter - RFC 3339 UTC for dt-* properties (v2.8.0)
from starpunk.utils import iso_utc
app.add_template_filter(iso_utc, 'iso_utc')
# Template filter - URL to color for facepile (v1.6.0)
@app.template_filter('url_to_color')
def url_to_color_filter(url):
@@ -459,5 +463,5 @@ def create_app(config=None):
# Package version (Semantic Versioning 2.0.0)
# See docs/standards/versioning-strategy.md for details
__version__ = "2.7.2"
__version_info__ = (2, 7, 2)
__version__ = "2.8.0"
__version_info__ = (2, 8, 0)
+13 -37
View File
@@ -82,10 +82,12 @@ def discover_author_profile(me_url: str) -> Optional[Dict]:
response.raise_for_status()
# Parse microformats from HTML
parsed = mf2py.parse(doc=response.text, url=me_url)
# Relative URLs and the representative h-card use the URL after redirects
page_url = str(response.url) if isinstance(response.url, (str, httpx.URL)) else me_url
parsed = mf2py.parse(doc=response.text, url=page_url)
# Extract h-card (per Q16: first representative h-card)
hcard = _find_representative_hcard(parsed, me_url)
# Representative h-card (v2.8.0: per the parsing spec)
hcard = _find_representative_hcard(parsed, page_url)
if not hcard:
current_app.logger.warning(f"No h-card found at {me_url}")
@@ -132,47 +134,21 @@ def discover_author_profile(me_url: str) -> Optional[Dict]:
def _find_representative_hcard(parsed: dict, me_url: str) -> Optional[dict]:
"""
Find representative h-card from parsed microformats
Find the representative h-card of the author's page (v2.8.0)
Per Q16: First representative h-card = first h-card with p-name
Per Q18: First h-card with url property matching profile URL
Follows https://microformats.org/wiki/representative-h-card-parsing
(uid+url match, rel=me match, or the only h-card with a matching url).
Other h-cards on the page may be other people, so none is guessed.
Args:
parsed: Parsed microformats data from mf2py
me_url: Profile URL for matching
me_url: Profile URL (the page that was parsed)
Returns:
h-card dict or None if not found
h-card dict or None if the page has no representative h-card
"""
items = parsed.get('items', [])
# First try: h-card with matching URL (most specific)
for item in items:
if 'h-card' in item.get('type', []):
properties = item.get('properties', {})
urls = properties.get('url', [])
# Check if any URL matches the profile URL
for url in urls:
if isinstance(url, dict):
url = url.get('value', '')
if _normalize_url(url) == _normalize_url(me_url):
# Found matching h-card
return item
# Second try: First h-card with p-name (representative h-card)
for item in items:
if 'h-card' in item.get('type', []):
properties = item.get('properties', {})
if properties.get('name'):
return item
# Third try: Just use first h-card if any
for item in items:
if 'h-card' in item.get('type', []):
return item
return None
from starpunk.mf2_utils import representative_hcard
return representative_hcard(parsed, me_url)
def _get_property(hcard: dict, prop_name: str) -> Optional[str]:
+168
View File
@@ -0,0 +1,168 @@
"""
Microformats2 consuming helpers (v2.8.0)
Shared by Webmention processing and author discovery:
- representative h-card of a page
- the h-entry on a page that responds to a given URL
- the author of an h-entry (authorship algorithm)
References:
- https://microformats.org/wiki/representative-h-card-parsing
- https://indieweb.org/authorship-spec
"""
from typing import Iterator, Optional
from urllib.parse import urldefrag, urlparse
RESPONSE_PROPERTIES = ('in-reply-to', 'like-of', 'repost-of', 'bookmark-of')
def normalize_url(url: str) -> str:
"""URL for comparison: no fragment, no trailing slash, lowercase scheme/host"""
if not url:
return ''
url = urldefrag(url.strip())[0]
parsed = urlparse(url)
url = parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower()).geturl()
return url.rstrip('/')
def value_of(value) -> Optional[str]:
"""Plain value of an mf2 property value (strings, {'value':...}, {'html':...})"""
if isinstance(value, dict):
value = value.get('value')
return value if isinstance(value, str) and value else None
def first(item: dict, prop: str) -> Optional[str]:
"""First plain value of an item's property"""
for value in item.get('properties', {}).get(prop, []):
result = value_of(value)
if result:
return result
return None
def values(item: dict, prop: str) -> list[str]:
"""All plain values of an item's property"""
return [v for v in (value_of(x) for x in item.get('properties', {}).get(prop, [])) if v]
def walk(items: list) -> Iterator[dict]:
"""Every microformat in items, depth first: top level, children, nested properties"""
for item in items:
if not isinstance(item, dict) or 'type' not in item:
continue
yield item
yield from walk(item.get('children', []))
for prop_values in item.get('properties', {}).values():
yield from walk([v for v in prop_values if isinstance(v, dict)])
def is_type(item: dict, mf_type: str) -> bool:
return mf_type in item.get('type', [])
def representative_hcard(parsed: dict, page_url: str) -> Optional[dict]:
"""
The page's representative h-card, per the parsing spec, in order:
1. An h-card whose uid and url both match the page URL
2. An h-card whose url matches one of the page's rel=me URLs
3. The only h-card on the page, if its url matches the page URL
Otherwise the page has none.
"""
page = normalize_url(page_url)
cards = [item for item in walk(parsed.get('items', [])) if is_type(item, 'h-card')]
for card in cards:
if page in map(normalize_url, values(card, 'uid')) and \
page in map(normalize_url, values(card, 'url')):
return card
rel_me = {normalize_url(u) for u in parsed.get('rels', {}).get('me', [])}
for card in cards:
if rel_me & set(map(normalize_url, values(card, 'url'))):
return card
if len(cards) == 1 and page in map(normalize_url, values(cards[0], 'url')):
return cards[0]
return None
def responding_entry(parsed: dict, target_url: str) -> Optional[dict]:
"""
The h-entry on a page that refers to target_url
Prefers an entry whose in-reply-to / like-of / repost-of / bookmark-of
is the target, then one whose content links to it, then the first
top-level h-entry.
"""
target = normalize_url(target_url)
entries = [item for item in walk(parsed.get('items', [])) if is_type(item, 'h-entry')]
top = [item for item in parsed.get('items', []) if is_type(item, 'h-entry')]
if not target:
return top[0] if top else (entries[0] if entries else None)
for entry in entries:
for prop in RESPONSE_PROPERTIES:
if target in map(normalize_url, values(entry, prop)):
return entry
for entry in entries:
for content in entry.get('properties', {}).get('content', []):
html = content.get('html', '') if isinstance(content, dict) else str(content)
if target_url in html or target in html:
return entry
return top[0] if top else (entries[0] if entries else None)
def response_type(entry: dict, target_url: str) -> str:
"""reply / like / repost / bookmark if the entry is one to target_url, else mention"""
target = normalize_url(target_url)
for prop, kind in zip(RESPONSE_PROPERTIES, ('reply', 'like', 'repost', 'bookmark')):
if target in map(normalize_url, values(entry, prop)):
return kind
return 'mention'
def entry_author(parsed: dict, entry: Optional[dict], page_url: str) -> dict:
"""
Author of an h-entry, following the authorship algorithm without fetching
1. The entry's author property (an h-card, a URL, or a name)
2. The author of an h-feed that contains the entry
3. The page's rel=author link
4. The page's representative h-card
Returns:
{'name', 'url', 'photo'}; values may be None
"""
author = None
if entry:
author = (entry.get('properties', {}).get('author') or [None])[0]
if author is None:
for feed in walk(parsed.get('items', [])):
if is_type(feed, 'h-feed') and entry in feed.get('children', []):
author = (feed.get('properties', {}).get('author') or [None])[0]
break
if author is None:
rel_author = parsed.get('rels', {}).get('author', [])
author = rel_author[0] if rel_author else representative_hcard(parsed, page_url)
if isinstance(author, dict) and 'type' in author:
return {
'name': first(author, 'name'),
'url': first(author, 'url'),
'photo': first(author, 'photo'),
}
text = value_of(author)
if text and urlparse(text).scheme in ('http', 'https'):
return {'name': None, 'url': text, 'photo': None}
return {'name': text, 'url': None, 'photo': None}
+2 -2
View File
@@ -36,7 +36,7 @@ from starpunk.notes import (
InvalidNoteDataError, NoteNotFoundError,
)
from starpunk.indieauth import check_scope
from starpunk.utils import absolute_url_for
from starpunk.utils import absolute_url_for, iso_utc
# Custom Exceptions
@@ -743,7 +743,7 @@ def note_to_mf2(note, wanted: Optional[list] = None) -> dict:
title, content = split_title(note.content)
props = {
"content": [content],
"published": [note.created_at.isoformat()],
"published": [iso_utc(note.created_at)],
"url": [absolute_url_for("public.note", slug=note.slug)],
"post-status": ["published" if note.published else "draft"],
}
+19 -5
View File
@@ -11,6 +11,7 @@ from dataclasses import dataclass, field, replace
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Optional
import re
import sqlite3
# Third-party imports
@@ -40,6 +41,9 @@ MARKDOWN_EXTENSIONS = ["extra", "codehilite", "nl2br", BareUrlExtension()]
# Constants - Content limits
MAX_TITLE_LENGTH = 200
# A Markdown ATX heading: up to 6 '#', whitespace, then text
TITLE_RE = re.compile(r"#{1,6}[ \t]+(\S.*)$")
EXCERPT_LENGTH = 200
@@ -47,17 +51,19 @@ def split_title(content: str) -> tuple[Optional[str], str]:
"""
Split a note's '# Heading' first line (its title, per Q22) off its content
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. This is the one
place that decides whether a note has a title (templates use has_title).
Returns:
(title, remaining content); title is None if the note has no heading
"""
stripped = content.lstrip()
if not stripped.startswith("#"):
return None, content
first_line, _, rest = stripped.partition("\n")
title = first_line.lstrip("#").strip()
if not title:
match = TITLE_RE.match(first_line)
if not match:
return None, content
return title, rest.strip()
return match.group(1).strip().rstrip("#").strip(), rest.strip()
@dataclass(frozen=True)
@@ -278,6 +284,14 @@ class Note:
return self.html
return markdown.markdown(body, extensions=MARKDOWN_EXTENSIONS)
@property
def has_title(self) -> bool:
"""True if the note starts with a '# Heading' title (an article)"""
try:
return split_title(self.content)[0] is not None
except (FileNotFoundError, OSError):
return False
@property
def title(self) -> str:
"""
+24 -1
View File
@@ -11,7 +11,7 @@ import hashlib
import re
import secrets
import shutil
from datetime import datetime
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
@@ -693,3 +693,26 @@ def absolute_url_for(endpoint: str, **values) -> str:
from flask import current_app, url_for
return current_app.config["SITE_URL"].rstrip("/") + url_for(endpoint, **values)
def iso_utc(value) -> str:
"""
Format a timestamp as RFC 3339 UTC for dt-* and Micropub (v2.8.0)
Stored times are naive UTC. Without an offset, microformats parsers read
them as local time, so this adds 'Z' and drops microseconds (HTML
<time datetime> allows at most 3 fractional digits).
Args:
value: datetime (naive = UTC) or ISO 8601 string
Returns:
e.g. '2026-11-01T16:25:12Z', or '' for empty values
"""
if not value:
return ''
if isinstance(value, str):
value = datetime.fromisoformat(value.strip().replace('Z', '+00:00'))
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
+69 -137
View File
@@ -19,10 +19,11 @@ import logging
import mf2py
import nh3
import httpx
from datetime import datetime
from typing import Dict, Any, Optional
from urllib.parse import urldefrag, urlparse
from starpunk import mf2_utils
from starpunk.utils import iso_utc
from starpunk.webmention_ssrf import (
FetchTooLargeError, SSRFBlockedError, safe_get, user_agent,
)
@@ -147,66 +148,13 @@ def verify_link_presence(content: str, target_url: str, content_type: str,
def detect_mention_type(parsed_mf2: Dict, target_url: str) -> str:
"""
Detect mention type from microformats.
Priority: reply > like > repost > bookmark > mention
Args:
parsed_mf2: Parsed microformats data from mf2py
target_url: Target URL being mentioned
Detect mention type from the h-entry that responds to the target
Returns:
Mention type: 'reply', 'like', 'repost', 'bookmark', or 'mention'
'reply', 'like', 'repost', 'bookmark', or 'mention'
"""
target_normalized = urlparse(target_url)._replace(fragment='').geturl().rstrip('/')
# Find h-entry that references target
for item in parsed_mf2.get('items', []):
if 'h-entry' not in item.get('type', []):
continue
props = item.get('properties', {})
# Check in-reply-to (highest priority)
for reply_to in props.get('in-reply-to', []):
url = reply_to if isinstance(reply_to, str) else reply_to.get('value', '')
if urlparse(url)._replace(fragment='').geturl().rstrip('/') == target_normalized:
return 'reply'
# Check like-of
for like in props.get('like-of', []):
url = like if isinstance(like, str) else like.get('value', '')
if urlparse(url)._replace(fragment='').geturl().rstrip('/') == target_normalized:
return 'like'
# Check repost-of
for repost in props.get('repost-of', []):
url = repost if isinstance(repost, str) else repost.get('value', '')
if urlparse(url)._replace(fragment='').geturl().rstrip('/') == target_normalized:
return 'repost'
# Check bookmark-of
for bookmark in props.get('bookmark-of', []):
url = bookmark if isinstance(bookmark, str) else bookmark.get('value', '')
if urlparse(url)._replace(fragment='').geturl().rstrip('/') == target_normalized:
return 'bookmark'
# Default fallback
return 'mention'
def _first_str(props: Dict, name: str) -> Optional[str]:
"""
First value of an mf2 property as a string
mf2py gives u-photo with alt text as {'value': url, 'alt': ...} and nested
microformats as dicts with a 'value'; reduce those to the plain value.
"""
values = props.get(name) or [None]
value = values[0]
if isinstance(value, dict):
value = value.get('value')
return value if isinstance(value, str) and value else None
entry = mf2_utils.responding_entry(parsed_mf2, target_url)
return mf2_utils.response_type(entry, target_url) if entry else 'mention'
def _is_http_url(value: Optional[str]) -> bool:
@@ -217,59 +165,27 @@ def _is_http_url(value: Optional[str]) -> bool:
return parsed.scheme.lower() in ('http', 'https') and bool(parsed.netloc)
def extract_author(parsed_mf2: Dict, source_url: str) -> Dict[str, Optional[str]]:
def extract_author(parsed_mf2: Dict, source_url: str,
entry: Optional[Dict] = None) -> Dict[str, Optional[str]]:
"""
Extract author information from h-card.
Author of the source's h-entry (authorship algorithm, without fetching)
Args:
parsed_mf2: Parsed microformats data from mf2py
source_url: Source URL (fallback for author URL)
source_url: Source URL (fallback for author URL and name)
entry: The h-entry to attribute (default: first top-level h-entry)
Returns:
Dict with author_name, author_url, author_photo
Dict with author_name, author_url, author_photo; only http(s) URLs
are kept, so they are safe to render as links (XSS)
"""
author_name = None
author_url = None
author_photo = None
if entry is None:
entry = mf2_utils.responding_entry(parsed_mf2, '')
author = mf2_utils.entry_author(parsed_mf2, entry, source_url)
# Find h-entry first
entry = None
for item in parsed_mf2.get('items', []):
if 'h-entry' in item.get('type', []):
entry = item
break
# Check for author property in h-entry
if entry:
author_prop = entry.get('properties', {}).get('author', [])
if author_prop:
author_data = author_prop[0]
if isinstance(author_data, dict):
# h-card object
props = author_data.get('properties', {})
author_name = _first_str(props, 'name')
author_url = _first_str(props, 'url')
author_photo = _first_str(props, 'photo')
# If no author in h-entry, find representative h-card
if not author_name:
for item in parsed_mf2.get('items', []):
if 'h-card' in item.get('type', []):
props = item.get('properties', {})
author_name = _first_str(props, 'name')
author_url = _first_str(props, 'url')
author_photo = _first_str(props, 'photo')
break
# Fallback to hostname if no author found
if not author_name:
author_name = urlparse(source_url).netloc
# Only http(s) URLs are rendered as links (blocks javascript: and data:)
if not _is_http_url(author_url):
author_url = source_url
if not _is_http_url(author_photo):
author_photo = None
author_url = author['url'] if _is_http_url(author['url']) else source_url
author_photo = author['photo'] if _is_http_url(author['photo']) else None
author_name = author['name'] or urlparse(author_url).netloc
return {
'author_name': author_name,
@@ -278,46 +194,57 @@ def extract_author(parsed_mf2: Dict, source_url: str) -> Dict[str, Optional[str]
}
def extract_content(parsed_mf2: Dict) -> Optional[str]:
def extract_content(parsed_mf2: Dict, entry: Optional[Dict] = None) -> Optional[str]:
"""
Extract content snippet from h-entry.
Content snippet of an h-entry (e-content, else p-summary)
Args:
parsed_mf2: Parsed microformats data from mf2py
entry: The h-entry (default: first top-level h-entry)
Returns:
Sanitized content snippet (max 500 chars) or None
"""
# Find h-entry
for item in parsed_mf2.get('items', []):
if 'h-entry' not in item.get('type', []):
continue
props = item.get('properties', {})
# Try e-content first (HTML)
content_prop = props.get('content', [])
if content_prop:
content_data = content_prop[0]
if isinstance(content_data, dict):
content = content_data.get('html', '') or content_data.get('value', '')
else:
content = content_data
if content:
return _snippet(content)
# Try p-summary as fallback
summary = props.get('summary', [])
if summary:
content = summary[0]
if isinstance(content, dict):
content = content.get('value', '')
if content:
return _snippet(content)
if entry is None:
entry = mf2_utils.responding_entry(parsed_mf2, '')
if not entry:
return None
props = entry.get('properties', {})
for content in props.get('content', []):
html = (content.get('html') or content.get('value')) if isinstance(content, dict) else content
if html:
return _snippet(html)
summary = mf2_utils.first(entry, 'summary')
return _snippet(summary) if summary else None
def extract_source_details(entry: Optional[Dict]) -> Dict[str, Optional[str]]:
"""
The source post's own URL, uid and published time
Returns:
source_post_url, source_uid (http(s) only) and source_published
(RFC 3339 UTC, or None if missing or unparseable)
"""
if not entry:
return {'source_post_url': None, 'source_uid': None, 'source_published': None}
url = mf2_utils.first(entry, 'url')
uid = mf2_utils.first(entry, 'uid')
published = mf2_utils.first(entry, 'published')
try:
published = iso_utc(published) or None
except (ValueError, TypeError):
published = None
return {
'source_post_url': url if _is_http_url(url) else None,
'source_uid': uid,
'source_published': published,
}
def _snippet(html: str, limit: int = 500) -> str:
"""Sanitized HTML of at most ~limit characters, with tags closed"""
@@ -399,14 +326,19 @@ def process_webmention(source_url: str, target_url: str, site_url: str) -> Dict[
}
content_snippet = None
source_details = extract_source_details(None)
if parsed_mf2:
mention_type = detect_mention_type(parsed_mf2, target_url)
author_info = extract_author(parsed_mf2, source_url)
content_snippet = extract_content(parsed_mf2)
entry = mf2_utils.responding_entry(parsed_mf2, target_url)
mention_type = mf2_utils.response_type(entry, target_url) if entry else 'mention'
author_info = extract_author(parsed_mf2, final_url, entry)
content_snippet = extract_content(parsed_mf2, entry)
source_details = extract_source_details(entry)
return {
'valid': True,
'mention_type': mention_type,
**author_info,
'content_snippet': content_snippet
'content_snippet': content_snippet,
**source_details,
}
+7 -3
View File
@@ -74,9 +74,13 @@ def get_webmentions_for_note(note_id: int) -> Dict[str, List[Dict[str, Any]]]:
for row in rows:
wm = dict(row)
# Parse received_at timestamp
if isinstance(wm.get('received_at'), str):
wm['received_at'] = datetime.fromisoformat(wm['received_at'].replace('Z', '+00:00'))
# Parse timestamps (source_published may be missing or malformed)
for key in ('received_at', 'source_published'):
if isinstance(wm.get(key), str):
try:
wm[key] = datetime.fromisoformat(wm[key].replace('Z', '+00:00'))
except ValueError:
wm[key] = None
mention_type = wm.get('mention_type', 'mention')
if mention_type == 'reply':
+28 -1
View File
@@ -27,6 +27,7 @@ from lxml import html as lxml_html
from starpunk.webmention_processor import process_webmention, TransientError, ValidationError
from starpunk.webmention_sender import note_responses_changed
from starpunk.mf2_utils import normalize_url
from starpunk.webmention_ssrf import (
FetchTooLargeError, SSRFBlockedError, safe_get, safe_post, user_agent,
)
@@ -263,6 +264,23 @@ class WebmentionWorker(threading.Thread):
except Exception as e:
logger.warning(f"Failed to re-send webmentions for note {target_note_id}: {e}")
def _is_own_syndicated_copy(self, note_id: Optional[int], source_url: str,
result: Dict[str, Any]) -> bool:
"""True if the source is one of the note's own u-syndication copies"""
if note_id is None:
return False
conn = sqlite3.connect(self.db_path)
try:
copies = {normalize_url(row[0]) for row in conn.execute(
"SELECT remote_url FROM syndications WHERE note_id = ? AND remote_url IS NOT NULL",
(note_id,),
)}
finally:
conn.close()
source = {normalize_url(u) for u in (
source_url, result.get('source_post_url'), result.get('source_uid')) if u}
return bool(copies & source)
def _display_state(self, webmention_id: int) -> Optional[tuple]:
"""
What the note page shows for this webmention, or None if hidden
@@ -305,6 +323,11 @@ class WebmentionWorker(threading.Thread):
# Process webmention (fetch, validate, extract)
result = process_webmention(source_url, target_url, self.site_url)
# A copy of this very note on a silo (e.g. backfed by Bridgy) is
# not a response to it
if self._is_own_syndicated_copy(target_note_id, source_url, result):
raise ValidationError("Source is this note's own syndicated copy")
# Update database with successful validation
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -330,6 +353,8 @@ class WebmentionWorker(threading.Thread):
author_url = ?,
author_photo = ?,
content_snippet = ?,
source_post_url = ?,
source_published = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""", (
@@ -339,6 +364,8 @@ class WebmentionWorker(threading.Thread):
result['author_url'],
result['author_photo'],
result['content_snippet'],
result.get('source_post_url'),
result.get('source_published'),
webmention_id
))
@@ -395,7 +422,7 @@ class WebmentionWorker(threading.Thread):
# All other errors are 'error' status
if transient:
status = 'error'
elif any(x in error.lower() for x in ['does not link', 'returned 4']):
elif any(x in error.lower() for x in ['does not link', 'returned 4', 'own syndicated copy']):
status = 'invalid'
else:
status = 'error'
+16
View File
@@ -332,6 +332,9 @@ small { display: block; margin-top: var(--spacing-xs); color: var(--color-text-l
}
.webmention-author a {
display: inline-flex;
align-items: center;
gap: var(--spacing-sm);
font-weight: bold;
}
@@ -361,6 +364,13 @@ small { display: block; margin-top: var(--spacing-xs); color: var(--color-text-l
margin-left: 0;
}
.facepile .face > .h-card,
.facepile .face > .h-card > a {
display: block;
width: 100%;
height: 100%;
}
.facepile .face img {
width: 100%;
height: 100%;
@@ -392,6 +402,12 @@ small { display: block; margin-top: var(--spacing-xs); color: var(--color-text-l
border-radius: 4px;
}
.webmention-mention .h-card img {
border-radius: 50%;
vertical-align: middle;
margin-right: var(--spacing-xs);
}
.webmention-mention p {
margin: var(--spacing-xs) 0 0 0;
font-size: 0.875rem;
+11 -1
View File
@@ -12,15 +12,25 @@
{# Webmention endpoint (v1.6.0) #}
{% if config.WEBMENTION_ENABLED %}
<link rel="webmention" href="/webmention">
{% endif %}
{# Micropub and IndieAuth discovery (independent of Webmention, v2.8.0) #}
<link rel="micropub" href="{{ absolute_url_for('micropub.micropub_endpoint') }}">
<link rel="indieauth-metadata" href="{{ absolute_url_for('indieauth.metadata') }}">
<link rel="authorization_endpoint" href="{{ absolute_url_for('indieauth.authorize') }}">
<link rel="token_endpoint" href="{{ absolute_url_for('indieauth.token') }}">
{# Author's home page: rel=me makes the h-card linking to it this site's
representative h-card; rel=author is the authorship fallback (v2.8.0) #}
{% set author_home = (author.url or author.me) if author else config.ADMIN_ME %}
{% if author_home %}
<link rel="me" href="{{ author_home }}">
<link rel="author" href="{{ author_home }}">
{% endif %}
{# rel-me links from discovered author profile (v1.2.0 Phase 2) #}
{% if author and author.rel_me_links %}
{% for profile_url in author.rel_me_links %}
{% for profile_url in author.rel_me_links if profile_url != author_home %}
<link rel="me" href="{{ profile_url }}">
{% endfor %}
{% endif %}
+6
View File
@@ -7,6 +7,12 @@
<div class="h-feed">
<h1 class="p-name page-title">Likes</h1>
{# Feed URL and author, as on the home page (v2.8.0) #}
<a class="u-url" href="{{ absolute_url_for(request.endpoint, **request.view_args) }}" hidden>Feed URL</a>
{% if author %}
<span class="p-author h-card" hidden><a class="p-name u-url" href="{{ author.url or author.me }}">{{ author.name or author.url or author.me }}</a></span>
{% endif %}
{% if notes %}
{% for note in notes %}
{{ note_preview(note, author) }}
+11 -81
View File
@@ -1,13 +1,14 @@
{% extends "base.html" %}
{% from "partials/media.html" import display_media %}
{% from "partials/reaction.html" import reaction %}
{% import "partials/responses.html" as responses with context %}
{% block title %}{% if note.content.strip().startswith('#') %}{{ note.title }}{% elif note.excerpt.strip() %}{{ note.excerpt|truncate(60) }}{% elif note.repost_of %}Repost{% elif note.like_of %}Like{% elif note.in_reply_to %}Reply{% else %}Photo{% endif %} · {{ config.SITE_NAME }}{% endblock %}
{% block title %}{% if note.has_title %}{{ note.title }}{% elif note.excerpt.strip() %}{{ note.excerpt|truncate(60) }}{% elif note.repost_of %}Repost{% elif note.like_of %}Like{% elif note.in_reply_to %}Reply{% else %}Photo{% endif %} · {{ config.SITE_NAME }}{% endblock %}
{% block content %}
<article class="h-entry">
{# Detect if note has explicit title (starts with # heading) - per Q22 #}
{% set has_explicit_title = note.content.strip().startswith('#') %}
{# Notes starting with a '# Heading' have a title (Q22; Note.has_title) #}
{% set has_explicit_title = note.has_title %}
{# p-name only if note has explicit title (per Q22) #}
{% if has_explicit_title %}
@@ -53,9 +54,9 @@
<footer class="note-meta">
{# u-url and u-uid same for notes (per Q23) #}
<a class="u-url u-uid" href="{{ absolute_url_for('public.note', slug=note.slug) }}"><time class="dt-published" datetime="{{ note.created_at.isoformat() }}">{{ note.created_at.strftime('%B %-d, %Y · %-I:%M %p') }}</time></a>
<a class="u-url u-uid" href="{{ absolute_url_for('public.note', slug=note.slug) }}"><time class="dt-published" datetime="{{ note.created_at|iso_utc }}">{{ note.created_at.strftime('%B %-d, %Y · %-I:%M %p') }}</time></a>
{% if note.updated_at and note.updated_at != note.created_at %}
<span class="updated">Updated <time class="dt-updated" datetime="{{ note.updated_at.isoformat() }}">{{ note.updated_at.strftime('%b %-d, %Y') }}</time></span>
<span class="updated">Updated <time class="dt-updated" datetime="{{ note.updated_at|iso_utc }}">{{ note.updated_at.strftime('%b %-d, %Y') }}</time></span>
{% endif %}
{# rel="tag" per microformats2 p-category #}
{% if note.tags %}
@@ -89,106 +90,35 @@
{% if replies %}
<div class="webmention-group webmention-replies">
<h3>{{ replies|length }} {{ 'Reply' if replies|length == 1 else 'Replies' }}</h3>
{% for reply in replies %}
<article class="webmention webmention-reply h-cite">
<div class="webmention-author">
{% if reply.author_photo %}
<img src="{{ reply.author_photo }}" alt="" width="48" height="48" loading="lazy">
{% endif %}
<a class="p-author" href="{{ reply.author_url or reply.source_url }}">
{{ reply.author_name or 'Anonymous' }}
</a>
</div>
{% if reply.content_snippet %}
<div class="p-content">{{ reply.content_snippet|safe }}</div>
{% endif %}
<a class="u-url webmention-date" href="{{ reply.source_url }}">
<time class="dt-published" datetime="{{ reply.received_at.isoformat() }}">
{{ reply.received_at.strftime('%B %d, %Y') }}
</time>
</a>
</article>
{% endfor %}
{% for wm in replies %}{{ responses.reply(wm) }}{% endfor %}
</div>
{% endif %}
{% if likes %}
<div class="webmention-group webmention-likes">
<h3>{{ likes|length }} {{ 'Like' if likes|length == 1 else 'Likes' }}</h3>
<div class="facepile">
{% for wm in likes[:8] %}
<a href="{{ wm.author_url or wm.source_url }}" class="face" title="{{ wm.author_name or 'Anonymous' }}">
{% if wm.author_photo %}
<img src="{{ wm.author_photo }}" alt="{{ wm.author_name or '' }}" width="32" height="32" loading="lazy">
{% else %}
<span class="face-initial" style="background-color: {{ wm.author_url|url_to_color }}">
{{ (wm.author_name or '?')[0]|upper }}
</span>
{% endif %}
</a>
{% endfor %}
{% if likes|length > 8 %}
<span class="face-overflow">+{{ likes|length - 8 }} others</span>
{% endif %}
</div>
{{ responses.facepile(likes, 'u-like') }}
</div>
{% endif %}
{% if reposts %}
<div class="webmention-group webmention-reposts">
<h3>{{ reposts|length }} {{ 'Repost' if reposts|length == 1 else 'Reposts' }}</h3>
<div class="facepile">
{% for wm in reposts[:8] %}
<a href="{{ wm.author_url or wm.source_url }}" class="face" title="{{ wm.author_name or 'Anonymous' }}">
{% if wm.author_photo %}
<img src="{{ wm.author_photo }}" alt="{{ wm.author_name or '' }}" width="32" height="32" loading="lazy">
{% else %}
<span class="face-initial" style="background-color: {{ wm.author_url|url_to_color }}">
{{ (wm.author_name or '?')[0]|upper }}
</span>
{% endif %}
</a>
{% endfor %}
{% if reposts|length > 8 %}
<span class="face-overflow">+{{ reposts|length - 8 }} others</span>
{% endif %}
</div>
{{ responses.facepile(reposts, 'u-repost') }}
</div>
{% endif %}
{% if bookmarks %}
<div class="webmention-group webmention-bookmarks">
<h3>{{ bookmarks|length }} {{ 'Bookmark' if bookmarks|length == 1 else 'Bookmarks' }}</h3>
<div class="facepile">
{% for wm in bookmarks[:8] %}
<a href="{{ wm.author_url or wm.source_url }}" class="face" title="{{ wm.author_name or 'Anonymous' }}">
{% if wm.author_photo %}
<img src="{{ wm.author_photo }}" alt="{{ wm.author_name or '' }}" width="32" height="32" loading="lazy">
{% else %}
<span class="face-initial" style="background-color: {{ wm.author_url|url_to_color }}">
{{ (wm.author_name or '?')[0]|upper }}
</span>
{% endif %}
</a>
{% endfor %}
{% if bookmarks|length > 8 %}
<span class="face-overflow">+{{ bookmarks|length - 8 }} others</span>
{% endif %}
</div>
{{ responses.facepile(bookmarks, 'u-bookmark') }}
</div>
{% endif %}
{% if mentions %}
<div class="webmention-group webmention-mentions">
<h3>{{ mentions|length }} {{ 'Mention' if mentions|length == 1 else 'Mentions' }}</h3>
{% for mention in mentions %}
<div class="webmention webmention-mention">
<a href="{{ mention.source_url }}">{{ mention.author_name or mention.source_url }}</a>
{% if mention.content_snippet %}
<p>{{ mention.content_snippet|striptags|truncate(200) }}</p>
{% endif %}
</div>
{% endfor %}
{% for wm in mentions %}{{ responses.mention(wm) }}{% endfor %}
</div>
{% endif %}
</section>
+3 -3
View File
@@ -3,8 +3,8 @@
{% from "partials/reaction.html" import reaction %}
{% macro note_preview(note, author) %}
<article class="h-entry note-preview">
{# Notes starting with a # heading have a title (Q22) #}
{% set has_explicit_title = note.content.strip().startswith('#') %}
{# Notes starting with a '# Heading' have a title (Q22; Note.has_title) #}
{% set has_explicit_title = note.has_title %}
{% if has_explicit_title %}
<h2 class="p-name"><a href="{{ absolute_url_for('public.note', slug=note.slug) }}">{{ note.title }}</a></h2>
{% endif %}
@@ -31,7 +31,7 @@
{% endif %}
<footer class="note-meta">
<a class="u-url" href="{{ absolute_url_for('public.note', slug=note.slug) }}"><time class="dt-published" datetime="{{ note.created_at.isoformat() }}">{{ note.created_at.strftime('%b %-d, %Y') }}</time></a>
<a class="u-url u-uid" href="{{ absolute_url_for('public.note', slug=note.slug) }}"><time class="dt-published" datetime="{{ note.created_at|iso_utc }}">{{ note.created_at.strftime('%b %-d, %Y') }}</time></a>
{% if note.tags %}
<span class="note-tags">
{% for tag in note.tags %}<a class="p-category" rel="tag" href="{{ url_for('public.tag', tag=tag.name) }}">{{ tag.display_name }}</a>{% endfor %}
+62
View File
@@ -0,0 +1,62 @@
{# Received webmentions as microformats2 responses (v2.8.0)
Each response is an h-cite in a property of the note's h-entry:
u-comment (replies), u-like, u-repost, u-bookmark, u-mention.
See https://indieweb.org/comments-presentation and microformats.org/wiki/h-entry #}
{# When the source said when it was posted, use that; else when we received it #}
{% macro response_time(wm, fmt='%B %-d, %Y') %}
{% set when = wm.source_published or wm.received_at %}
<time class="dt-published" datetime="{{ when|iso_utc }}">{{ when.strftime(fmt) if when.strftime is defined else when }}</time>
{%- endmacro %}
{# The response's own URL: the source's u-url if it gave one #}
{% macro response_url(wm) %}{{ wm.source_post_url or wm.source_url }}{% endmacro %}
{# Author h-card: name, URL and photo. u-url is on an inner link: on the
h-card element itself it would belong to the enclosing h-cite #}
{% macro author_card(wm, class='', photo_size=48, show_name=True) %}
<span class="p-author h-card {{ class }}"><a class="u-url" href="{{ wm.author_url or wm.source_url }}" title="{{ wm.author_name or 'Anonymous' }}">
{%- if wm.author_photo %}<img class="u-photo" src="{{ wm.author_photo }}" alt="" width="{{ photo_size }}" height="{{ photo_size }}" loading="lazy">
{%- elif not show_name %}<span class="face-initial" style="background-color: {{ wm.author_url|url_to_color }}" aria-hidden="true">{{ (wm.author_name or '?')[0]|upper }}</span>
{%- endif %}
<span class="p-name{{ '' if show_name else ' visually-hidden' }}">{{ wm.author_name or 'Anonymous' }}</span>
</a></span>
{%- endmacro %}
{# A reply, shown as a comment #}
{% macro reply(wm) %}
<article class="webmention webmention-reply u-comment h-cite">
<div class="webmention-author">{{ author_card(wm) }}</div>
{% if wm.content_snippet %}
<div class="e-content">{{ wm.content_snippet|safe }}</div>
{% endif %}
<a class="u-url webmention-date" href="{{ response_url(wm) }}">{{ response_time(wm) }}</a>
</article>
{%- endmacro %}
{# Likes, reposts or bookmarks as a facepile; prop is u-like / u-repost / u-bookmark.
Faces past `shown` are hidden on screen but kept for parsers. #}
{% macro facepile(items, prop, shown=8) %}
<div class="facepile">
{% for wm in items %}
<span class="face {{ prop }} h-cite"{% if loop.index > shown %} hidden{% endif %}>
{{ author_card(wm, photo_size=32, show_name=False) }}
<a class="u-url" href="{{ response_url(wm) }}" hidden>{{ response_time(wm) }}</a>
</span>
{% endfor %}
{% if items|length > shown %}
<span class="face-overflow">+{{ items|length - shown }} others</span>
{% endif %}
</div>
{%- endmacro %}
{# A post that mentions this note without replying #}
{% macro mention(wm) %}
<div class="webmention webmention-mention u-mention h-cite">
{{ author_card(wm, photo_size=24) }}
{% if wm.content_snippet %}
<p class="p-content">{{ wm.content_snippet|striptags|truncate(200) }}</p>
{% endif %}
<a class="u-url webmention-date" href="{{ response_url(wm) }}">{{ response_time(wm) }}</a>
</div>
{%- endmacro %}
+6
View File
@@ -7,6 +7,12 @@
<div class="h-feed">
<h1 class="p-name page-title">Notes tagged <span class="tag-name">{{ tag.display_name }}</span></h1>
{# Feed URL and author, as on the home page (v2.8.0) #}
<a class="u-url" href="{{ absolute_url_for(request.endpoint, **request.view_args) }}" hidden>Feed URL</a>
{% if author %}
<span class="p-author h-card" hidden><a class="p-name u-url" href="{{ author.url or author.me }}">{{ author.name or author.url or author.me }}</a></span>
{% endif %}
{% if notes %}
{% for note in notes %}
{{ note_preview(note, author) }}
+8 -4
View File
@@ -289,16 +289,20 @@ class TestRelMe:
assert 'https://github.com/testuser' in rels['me']
assert 'https://mastodon.social/@testuser' in rels['me']
def test_no_relme_without_author(self, client, app):
"""No rel=me links if no author profile"""
def test_relme_to_admin_me_without_author(self, client, app):
"""Without a discovered profile, rel=me and rel=author still point at ADMIN_ME (v2.8.0)
The home page's p-author h-card links to the author's site; rel=me to
the same URL makes it the representative h-card.
"""
with patch('starpunk.author_discovery.get_author_profile', return_value=None):
response = client.get('/')
parsed = mf2py.parse(doc=response.data.decode(), url='http://localhost/')
rels = parsed.get('rels', {})
# Should not have rel=me, or it should be empty
assert len(rels.get('me', [])) == 0, "Should not have rel=me without author"
assert rels.get('me') == [app.config['ADMIN_ME']]
assert rels.get('author') == [app.config['ADMIN_ME']]
class TestV130Microformats:
+268
View File
@@ -0,0 +1,268 @@
"""
Microformats2 fixes (v2.8.0)
Pages are rendered and parsed with mf2py; assertions are on the parsed data,
which is what IndieWeb readers and Webmention receivers see.
"""
import re
import sqlite3
from unittest.mock import patch
import mf2py
import pytest
from starpunk import mf2_utils
from starpunk.models import split_title
from starpunk.webmention_processor import extract_author, extract_source_details
from starpunk.webmention_worker import WebmentionWorker
BASE = 'http://localhost:5000'
def parse(client, path):
response = client.get(path)
assert response.status_code == 200
return mf2py.parse(doc=response.data.decode(), url=BASE + path)
def entry_of(parsed):
return next(i for i in parsed['items'] if 'h-entry' in i['type'])
def make_note(app, content, **kw):
from starpunk.notes import create_note
with app.test_request_context():
return create_note(content, published=True, **kw)
def add_mention(app, note, kind, n, photo=True, **cols):
db = sqlite3.connect(app.config['DATABASE_PATH'])
fields = {
'source_url': f'https://src.example/{kind}/{n}',
'target_url': f'{BASE}/note/{note.slug}',
'target_note_id': note.id,
'mention_type': kind,
'author_name': f'{kind.title()} Person {n}',
'author_url': f'https://{kind}{n}.example/',
'author_photo': f'https://{kind}{n}.example/me.jpg' if photo else None,
'content_snippet': f'<p>{kind} text <a href="https://x.example/">link</a></p>',
'validation_status': 'valid',
'moderation_status': 'approved',
**cols,
}
db.execute(f"INSERT INTO webmentions ({', '.join(fields)}) VALUES ({', '.join('?' * len(fields))})",
tuple(fields.values()))
db.commit()
db.close()
# A1/A2: received responses are properties of the entry
def test_responses_are_entry_properties(app, client):
note = make_note(app, "A note")
add_mention(app, note, 'reply', 1, source_post_url='https://src.example/reply/1#canonical',
source_published='2026-11-01T10:00:00Z')
for n in range(10):
add_mention(app, note, 'like', n, photo=n % 2 == 0)
add_mention(app, note, 'repost', 1)
add_mention(app, note, 'bookmark', 1)
add_mention(app, note, 'mention', 1)
props = entry_of(parse(client, f'/note/{note.slug}'))['properties']
assert 'children' not in entry_of(parse(client, f'/note/{note.slug}'))
(comment,) = props['comment']
assert comment['type'] == ['h-cite']
author = comment['properties']['author'][0]
assert author['type'] == ['h-card']
assert author['properties']['name'] == ['Reply Person 1']
assert author['properties']['url'] == ['https://reply1.example/']
assert author['properties']['photo'][0] in ('https://reply1.example/me.jpg',
{'value': 'https://reply1.example/me.jpg', 'alt': ''})
assert '<a href="https://x.example/"' in comment['properties']['content'][0]['html']
# the source's own URL and published time, not ours
assert comment['properties']['url'] == ['https://src.example/reply/1#canonical']
assert comment['properties']['published'] == ['2026-11-01T10:00:00Z']
# all ten likes, including the ones past the visible eight
assert len(props['like']) == 10
names = {like['properties']['author'][0]['properties']['name'][0] for like in props['like']}
assert names == {f'Like Person {n}' for n in range(10)}
assert props['like'][0]['properties']['url'] == ['https://src.example/like/0']
assert props['repost'][0]['properties']['author'][0]['properties']['name'] == ['Repost Person 1']
assert props['bookmark'][0]['type'] == ['h-cite']
assert props['mention'][0]['properties']['author'][0]['properties']['url'] == ['https://mention1.example/']
# A3: dt-* are RFC 3339 UTC
UTC = re.compile(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$')
def test_dates_are_utc(app, client):
from starpunk.notes import update_note
note = make_note(app, "Dated")
with app.test_request_context():
update_note(id=note.id, content="Dated, edited")
add_mention(app, note, 'reply', 1)
props = entry_of(parse(client, f'/note/{note.slug}'))['properties']
assert UTC.match(props['published'][0]), props['published']
assert UTC.match(props['updated'][0]), props['updated']
assert UTC.match(props['comment'][0]['properties']['published'][0])
home = parse(client, '/')['items'][0]['children'][0]['properties']
assert UTC.match(home['published'][0])
def test_micropub_source_published_is_utc():
from datetime import datetime, timezone, timedelta
from starpunk.utils import iso_utc
assert iso_utc(datetime(2026, 11, 1, 16, 25, 12, 921768)) == '2026-11-01T16:25:12Z'
assert iso_utc(datetime(2026, 11, 1, 9, 0, tzinfo=timezone(timedelta(hours=-7)))) == '2026-11-01T16:00:00Z'
assert iso_utc('2026-11-01T16:25:15+0000') == '2026-11-01T16:25:15Z'
# A4: only a real Markdown heading is a title
@pytest.mark.parametrize("content,title", [
("# Title\n\nBody", "Title"),
("## Sub title ##\n\nBody", "Sub title"),
("#indieweb is great", None),
("#\n\nbody text", None),
("####### seven", None),
("Plain note", None),
])
def test_split_title(content, title):
assert split_title(content)[0] == title
@pytest.mark.parametrize("content,kind", [
("#indieweb is great, posting from my phone", "note"),
("#\n\nbody text", "note"),
("# A Title\n\nThe body", "article"),
])
def test_post_type_of_hash_notes(app, client, content, kind):
note = make_note(app, content)
for path in (f'/note/{note.slug}', '/'):
parsed = parse(client, path)
entry = entry_of(parsed) if path != '/' else parsed['items'][0]['children'][0]
props = entry['properties']
if kind == 'note':
assert 'name' not in props
assert props['content'][0]['value'].strip()
else:
assert props['name'] == ['A Title']
# A5: the note's own syndicated copy is not a response
def test_own_syndicated_copy_rejected(app):
note = make_note(app, "Crossposted")
db = sqlite3.connect(app.config['DATABASE_PATH'])
db.execute("INSERT INTO syndications (note_id, target, remote_url) VALUES (?, 'gotosocial', ?)",
(note.id, 'https://social.example/@me/statuses/1'))
db.execute("INSERT INTO webmentions (source_url, target_url, target_note_id) VALUES (?, ?, ?)",
('https://brid.gy/post/mastodon/@someone/1', f'{BASE}/note/{note.slug}', note.id))
db.commit()
result = {'valid': True, 'mention_type': 'mention', 'author_name': 'Me', 'author_url': 'https://me.example/',
'author_photo': None, 'content_snippet': 'x',
'source_post_url': 'https://social.example/@me/statuses/1', 'source_uid': None,
'source_published': None}
worker = WebmentionWorker(app, db_path=app.config['DATABASE_PATH'], site_url=BASE)
with patch("starpunk.webmention_worker.process_webmention", return_value=result):
worker._validate_webmention(1, 'https://brid.gy/post/mastodon/@someone/1', 'x', note.id)
status, error = db.execute("SELECT validation_status, validation_error FROM webmentions").fetchone()
assert status == 'invalid' and 'own syndicated copy' in error
# B1/B3: discovery links
def test_head_links_without_webmention(app, client):
app.config['WEBMENTION_ENABLED'] = False
rels = parse(client, '/')['rels']
assert 'webmention' not in rels
for rel in ('micropub', 'indieauth-metadata', 'authorization_endpoint', 'token_endpoint'):
assert rels.get(rel), rel
def test_home_has_representative_hcard(app, client):
# Fresh install: discovery fails, the fallback profile is used
parsed = parse(client, '/')
card = mf2_utils.representative_hcard(parsed, BASE + '/')
assert card and card['properties']['url'] == [app.config['ADMIN_ME']]
@pytest.mark.parametrize("path", ['/likes', '/tag/python'])
def test_list_feeds_have_url_and_author(app, client, path):
make_note(app, "Tagged", tags=["python"])
feed = parse(client, path)['items'][0]
assert feed['type'] == ['h-feed']
assert feed['properties']['url'] == [BASE + path]
assert feed['properties']['author'][0]['type'] == ['h-card']
# B2: representative h-card
def _cards(html, url='https://me.example/'):
return mf2py.parse(doc=html, url=url)
def test_representative_hcard_rules():
other = '<div class="h-card"><a class="p-name u-url" href="https://bob.example/">Bob</a></div>'
# someone else's h-card only: none
assert mf2_utils.representative_hcard(_cards(other), 'https://me.example/') is None
# uid + url
me = '<div class="h-card"><a class="p-name u-url u-uid" href="/">Me</a></div>'
assert mf2_utils.first(mf2_utils.representative_hcard(_cards(other + me), 'https://me.example/'), 'name') == 'Me'
# rel=me
relme = ('<a rel="me" href="https://social.example/@me">x</a>'
'<div class="h-card"><a class="p-name u-url" href="https://social.example/@me">Me</a></div>')
assert mf2_utils.first(mf2_utils.representative_hcard(_cards(other + relme), 'https://me.example/'), 'name') == 'Me'
# only one h-card, url = page
single = '<div class="h-card"><a class="p-name u-url" href="/">Me</a></div>'
assert mf2_utils.first(mf2_utils.representative_hcard(_cards(single), 'https://me.example/'), 'name') == 'Me'
# B4: the responding entry and its author
FEED_PAGE = '''
<div class="h-feed">
<div class="p-author h-card"><a class="p-name u-url" href="https://feed.example/">Feed Owner</a></div>
<div class="h-entry"><a class="u-url" href="https://feed.example/1">one</a>
<div class="e-content">unrelated</div></div>
<div class="h-entry"><a class="u-url" href="https://feed.example/2">two</a>
<time class="dt-published" datetime="2026-11-01T09:00:00-07:00">x</time>
<a class="u-in-reply-to" href="https://me.example/note/a">re</a>
<div class="e-content">my reply</div></div>
</div>'''
def test_responding_entry_and_feed_author():
parsed = mf2py.parse(doc=FEED_PAGE, url='https://feed.example/')
entry = mf2_utils.responding_entry(parsed, 'https://me.example/note/a#frag')
assert mf2_utils.first(entry, 'url') == 'https://feed.example/2'
assert mf2_utils.response_type(entry, 'https://me.example/note/a') == 'reply'
author = extract_author(parsed, 'https://feed.example/', entry)
assert author['author_name'] == 'Feed Owner'
assert author['author_url'] == 'https://feed.example/'
details = extract_source_details(entry)
assert details['source_post_url'] == 'https://feed.example/2'
assert details['source_published'] == '2026-11-01T16:00:00Z'
def test_author_as_url_or_name():
url_author = '<div class="h-entry"><a class="u-author" href="https://al.example/">al</a></div>'
parsed = mf2py.parse(doc=url_author, url='https://s.example/')
assert extract_author(parsed, 'https://s.example/')['author_url'] == 'https://al.example/'
name_author = '<div class="h-entry"><span class="p-author">Al Smith</span></div>'
parsed = mf2py.parse(doc=name_author, url='https://s.example/')
author = extract_author(parsed, 'https://s.example/')
assert author['author_name'] == 'Al Smith' and author['author_url'] == 'https://s.example/'