Compare commits

..
16 Commits
Author SHA1 Message Date
Phil 43ec7cb8be Merge branch 'feat/v2.7.0-webmention-spec' for v2.7.0 release
Build Container / build (push) Successful in 11s
2026-11-03 08:07:12 -07:00
PhilandClaude Opus 5.5 4aaa7a8122 feat: W3C Webmention compliance (v2.7.0)
Sending: RFC 8288 Link header parsing, rel token matching and document
order for <link>/<a>, endpoint re-discovery on every send, re-send to
previous targets on update/delete/undelete, 410 Gone for deleted notes,
no redirect following on the POST, 429 retried.

Receiving: exact target match per media type, Accept header, final URL
for relative links, only published notes accepted, fragments ignored,
moderation kept on updates, transient errors keep valid mentions.

Security: every redirect hop SSRF-checked, all resolved addresses
checked, broader blocklist, total time and size limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 08:07:04 -07:00
Phil 0cfc9965df Merge branch 'fix/v2.6.9-webmention-processing' for v2.6.9 release
Build Container / build (push) Successful in 12s
2026-11-03 07:53:19 -07:00
PhilandClaude Opus 5.5 106495d114 fix: Webmention processing works end to end (v2.6.9)
- Normalise mf2 author values: u-photo with alt text is a dict in mf2py and
  broke the database update for most real senders
- Pass str(response.url) to urljoin during endpoint discovery; the TypeError
  marked every target as having no endpoint. Retry on discovery errors
- Hold a cross-process flock so only one gunicorn process runs the worker
- Keep author URL/photo only if http(s) (XSS via javascript: URLs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 07:53:19 -07:00
Phil 3c1e109358 Merge branch 'fix/v2.6.8-webmention-worker' for v2.6.8 release
Build Container / build (push) Successful in 20s
2026-11-03 07:41:11 -07:00
PhilandClaude Opus 5.5 d43361d505 fix: Webmention worker runs inside the app context (v2.6.8)
The worker thread called the SSRF checks, which read current_app.config,
without an app context, so every incoming and outgoing webmention failed with
'Working outside of application context'. A teardown_appcontext hook also
stopped the worker whenever a request ended.

Pass the app to WebmentionWorker and run each poll in app.app_context(), like
SyndicationWorker, and drop the teardown hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 07:41:06 -07:00
Phil f924413934 Merge branch 'fix/v2.6.7-admin-layout' for v2.6.7 release
Build Container / build (push) Successful in 7s
2026-11-02 18:24:15 -07:00
PhilandClaude Opus 5.5 4b2ae4c7fc fix: Admin pages line up with the header (v2.6.7)
Every page sat in the 40rem reading column, so the admin wrapper's 60rem
never applied and the notes table, which can't shrink that far, ran past
the header's right edge. Admin pages now set a 60rem frame for header,
content and footer; post previews wrap, and tables scroll sideways on
narrow screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:24:14 -07:00
Phil d3148063e3 Merge branch 'fix/v2.6.6-inline-image-crosspost' for v2.6.6 release
Build Container / build (push) Successful in 15s
2026-11-02 18:12:51 -07:00
PhilandClaude Opus 5.5 39c8259f3f fix: Crossposts include photos embedded in the post text (v2.6.6)
Some Micropub clients (OutPost) upload a photo to the media endpoint and
then embed it in content instead of sending it as `photo`. Those posts
have no attached media, so crossposts went out without the image.

Images in the text that are in this site's media library are now sent
like attached photos, with their alt text, and GoToSocial's text no
longer carries the image Markdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:11:27 -07:00
Phil 1ce88b38a5 Merge branch 'fix/v2.6.5-micropub-media' for v2.6.5 release
Build Container / build (push) Successful in 6s
2026-11-01 10:53:37 -07:00
PhilandClaude Opus 5.5 4ffe36f9d3 fix: Photos without alt text use the post's text (v2.6.5)
Uncaptioned photos rendered alt="Image", which mf2 parsers report as
the photo's alt text. They now take the post's text (excerpt, up to 150
characters), falling back to "Image" only for text-free posts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:44:54 -07:00
PhilandClaude Opus 5.5 a551770c76 fix: Replies and photo posts read as the right post type (v2.6.5)
Checked rendered pages with mf2py against W3C Post Type Discovery:

- Note pages put u-in-reply-to inside a bare h-cite, making it the
  h-cite's property, so replies parsed as notes (or photo posts). The
  reply context is now the entry's u-in-reply-to h-cite.
- Home page previews had no reply markup; they now show "In reply to"
  with u-in-reply-to.
- Previews always emit e-content, so a text-free photo post can't get
  an implied name.
- Text-free page titles follow PTD order (Repost, Like, Reply, Photo).

tests/test_post_types.py runs PTD on parsed note pages and the home page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:06:44 -07:00
PhilandClaude Opus 5.5 d0bfc80c2e fix: Micropub photo posts and failed creates (v2.6.5)
- A create that failed after the note was written (e.g. the same photo
  twice) answered 500 but left the post published without photos.
  Photos are now resolved first, and a failed note is removed.
- Pooled connections roll back unfinished writes, so one failure no
  longer locks the database for the next ~10 s.
- The same photo twice in one post is shown once.
- Photo posts no longer need text (Micropub doesn't require content,
  and q=config already advertised a photo-only post type). Updates may
  clear the text while photos remain. Crossposts start with the link;
  the page is titled "Photo".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:50:30 -07:00
PhilandClaude Opus 5.5 d16463ef8a Merge branch 'fix/v2.6.4-tag-order' for v2.6.4 release
Build Container / build (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:59:19 -07:00
PhilandClaude Opus 5.5 4b56f7cd4b fix: Tags keep the order they were entered in (v2.6.4)
add_tags_to_note() rewrites note_tags in entry order on every save, so
note_tags.id already records it; get_note_tags(entered_order=True) reads
it back. Crossposts (Threads topic, which hashtags fit on Bluesky), the
editor and Micropub q=source/update use it, so saving no longer
reorders tags alphabetically. Public pages stay alphabetical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:59:18 -07:00
37 changed files with 1847 additions and 433 deletions

No files matched your search

+82
View File
@@ -7,6 +7,88 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [2.7.0] - 2026-11-03
Webmention now follows the [W3C Recommendation](https://www.w3.org/TR/webmention/) throughout.
### Changed
- Webmentions are only accepted for published notes. Mentions of the home page or other pages were stored but never shown; they're now refused with 400
- Deleted notes answer 410 Gone with a "This post has been deleted" page instead of 404
- A received mention that is sent again keeps its moderation: one you hid stays hidden, one you approved stays approved
### Fixed
- Sending: endpoint discovery now handles `rel` values with several words (`rel="webmention other"`), any capitalisation, `rel` after other Link parameters, and several Link headers, and takes the first `<link>` or `<a>` in page order
- Sending: the endpoint is looked up again every time (the 1–24 hour cache broke the spec's rule for updated posts)
- Sending: editing a note notifies every page it mentioned before, including an old reply target and links the edit removed. Deleting or restoring a note notifies them too, so they can remove or restore the mention
- Sending: a redirect from the endpoint is no longer treated as success (the POST was turned into a GET); "429 Too Many Requests" is retried
- Receiving: the source must link to the exact target URL (in a link, image, or other HTML attribute, any JSON value, or plain text). A longer URL that starts with the target, or the target mentioned in plain text or an HTML comment, no longer counts
- Receiving: relative links in the source are resolved, using the URL after redirects
- Receiving: the source is fetched with an `Accept` header and decoded in its declared character set
- Receiving: if the source can't be reached when a mention is sent again, the existing mention stays up instead of disappearing
- Receiving: the target's host is compared without regard to case or a default port, and `#fragment`s are dropped, so one mention isn't stored twice
- Mention snippets cut at 500 characters no longer leave HTML tags open, and the "Mentions" list no longer shows raw HTML tags
- The `Link: rel="webmention"` header is added alongside other Link headers instead of replacing them
- Links at the top level of a code block were still sent webmentions
### Security
- Fetches for webmentions check every redirect, not just the first URL, so a public page can't redirect StarPunk to a private address. Every address a hostname resolves to (IPv4 and IPv6) must be public; carrier-grade NAT, `0.0.0.0/8`, multicast, reserved and IPv4-mapped addresses are blocked too. Each fetch has a total time limit and a 1 MB size limit, including endpoint discovery
## [2.6.9] - 2026-11-03
### Fixed
- Received webmentions failed when the sender's profile photo had alt text (Bridgy, Mastodon and most IndieWeb sites do this). The photo is now stored as its URL
- Outgoing webmentions were never sent: endpoint discovery crashed on every target that had an endpoint, and the target was then marked as having none. Discovery now works, and network errors during discovery are retried instead of giving up
- Each server process ran its own webmention worker, so a webmention could be processed or sent more than once. Only one process handles the queues at a time now; if it stops, another takes over
### Security
- A webmention sender could set its author link to a `javascript:` URL, which was shown as a clickable link on the note page. Author links and photos are now only kept if they are http or https URLs
## [2.6.8] - 2026-11-03
### Fixed
- Webmentions were never processed. The background worker checked URLs against this site's settings without the app loaded, so every incoming webmention was marked "error" ("Working outside of application context") and every outgoing one kept failing and retrying. The worker now runs with the app loaded. A received webmention showed up in the admin list but never on the note
- The webmention worker also stopped as soon as any request finished, so after startup it often wasn't running at all. It now runs for the life of the server process
## [2.6.7] - 2026-11-02
### Fixed
- Admin pages were misaligned: the notes table ran past the right edge of the header and admin menu, because every page sat in the 40rem reading column and the table couldn't shrink to fit it. Admin pages now use a 60rem frame for the header, menu, content and footer alike, long post previews wrap, and on narrow screens tables scroll sideways instead of spilling out
## [2.6.6] - 2026-11-02
### Fixed
- Crossposts left out photos that were embedded in the post text instead of attached. Some Micropub clients (OutPost, for one) upload a photo to the media endpoint and then put it in `content` as an image rather than sending it as `photo`; both are valid Micropub. Images in the text that are in this site's media library are now sent to GoToSocial, Bluesky and Threads like attached photos, with their alt text, after any attached ones and within each target's photo limit. GoToSocial's text no longer includes the image Markdown. Images hosted on other sites are still left out
## [2.6.5] - 2026-11-01
### Fixed
- A Micropub post that failed partway (for example, the same photo listed twice) answered "Failed to create post" but stayed published without its photos, so a client retrying would post it twice. Photos are now looked up before the post is made, and a post that fails after that is removed again
- After such a failure, every request failed with "database is locked" for about 10 seconds: database connections now roll back unfinished writes when they're returned to the pool
- The same photo listed twice in one post is shown once instead of failing the post
- Replies didn't read as replies to IndieWeb readers and webmention receivers: on note pages `u-in-reply-to` sat inside an unrelated `h-cite`, and the home page didn't mark replies at all, so [Post Type Discovery](https://www.w3.org/TR/post-type-discovery/) saw notes (or photo posts). The reply context is now the entry's `u-in-reply-to h-cite`, and home page entries show "↩ In reply to"
- Photos without alt text used "Image" as their description, which IndieWeb readers passed on as if you'd written it. They now use the post's text (up to 150 characters), and fall back to "Image" only when the post has no text
- Home page entries always have an `e-content`, so a photo post without text never gets an implied name (which readers would show as its caption)
### Changed
- Photo posts no longer need text. Micropub doesn't require `content`, and `q=config` already offered a Photo post type with only `photo`. A Micropub update may also clear the text of a post that keeps its photos. Crossposts of a photo post without text start with its link, and its page is titled "Photo"
## [2.6.4] - 2026-11-01
### Fixed
- Tags keep the order you entered them in. The first tag is the note's main tag: it's the Threads topic, and Bluesky keeps the first tags when space runs out. Before, both used the alphabetically first tag. Public pages still list tags alphabetically
- Opening a note in the editor or updating it via Micropub reordered its tags alphabetically on save; the editor and Micropub `q=source` now show, and keep, the entered order
## [2.6.3] - 2026-11-01
### Changed
@@ -0,0 +1,89 @@
# v2.6.5: Micropub media fixes
Found while adding media uploads to tuipub, a Micropub client written to the
spec rather than to StarPunk.
## Problems
1. **Failed creates left a post behind.** `handle_create` made the note, then
attached photos. Listing one photo twice broke the `note_media` unique key,
so the client got a 500 while the note stayed published without photos.
A retry would post it twice.
2. **Then the database stayed locked.** `attach_media_to_note` didn't roll
back, and `ConnectionPool.return_connection` pooled the connection with
its write transaction still open. Other requests got "database is locked"
until the 10 s timeout.
3. **Photo posts needed text.** The Micropub spec doesn't require `content`,
and `q=config` advertised a `photo` post type with only `photo`, yet
creates without content got 400 "Content is required".
## Changes
- `database/pool.py`: `return_connection` rolls back an open transaction
(or closes the connection if that fails).
- `media.py`: `attach_media_to_note` rolls back on error.
- `micropub.py`:
- `handle_create` resolves photos (by media URL, downloading remote ones)
before `create_note`. If attaching or crosspost selection fails, it
hard-deletes the note before answering 500.
- `_resolve_photos` skips repeated media.
- Content is optional when photos resolve. Content-less posts whose photos
all fail still get a 400 from `create_note`.
- `handle_update` allows `replace: {content: [""]}` and `delete: ["content"]`
while the note keeps photos (or is a like or repost). Otherwise it answers
400 "A post needs text or a photo".
- `notes.py`: `create_note` and `update_note` take `has_media`, so
empty content is allowed for photo posts.
- `syndication.py`: `compose_text` drops the leading blank line when there's
no body.
## Post types (IndieWeb standards check)
Post Type Discovery (W3C Note) has no separate "photo" type to store. A post
with a valid `photo` is a photo post, unless it's first a repost, like or
reply (step order: repost, like, reply, video, photo). Otherwise it's a note,
or an article when its `name` isn't a prefix of its content. h-entry treats
`u-photo` as the primary content, with `name` as a caption. mf2 implies a
`name` only when an entry has no other `p-*`/`e-*` properties and no nested
microformats.
StarPunk already stores photo posts as notes with media and renders
`u-photo` outside `e-content`, which is what the standards ask for. Checking
the rendered pages with mf2py found:
- **Replies weren't replies.** In `note.html`, `u-in-reply-to` was inside a
bare `h-cite`, so it was the h-cite's property, not the entry's.
`note_preview.html` had no reply markup at all. Fixed: the blockquote is
`u-in-reply-to h-cite` (with `u-url` inside), and previews show
"↩ In reply to" with `u-in-reply-to`.
- **Implied names were possible.** Previews left out `e-content` for posts
without text. They worked only because the author h-card blocked an
implied name. Previews now always emit `e-content`.
- Page title for text-free posts follows PTD order: Repost, Like, Reply,
Photo.
Photos without a caption take the post's text as alt (`partials/media.html`
`fallback_alt`) instead of the made-up "Image". The Micropub `q=source`
still reports the stored caption (`""`).
`tests/test_post_types.py` parses note pages and the home page with mf2py and
runs PTD for notes, articles, photo posts (no text, caption, title), replies
(with and without a photo) and reposts.
## Not changed (noted for later)
- Text-free photos without alt text still render `alt="Image"`. Captioned
photos use their caption, and others now use the post's text (`display_media`
`fallback_alt`, the excerpt cut to 150 characters).
- More than 4 photos are still cut to 4 without an error (ADR-057).
- `video` and `audio` are ignored. This is allowed by the spec, and they
aren't in `q=config` post-types.
- Media endpoint errors for non-images expose Python text
("cannot identify image file <_io.BytesIO …>").
## Tests
`tests/test_micropub_v265.py`. The full suite runs with
`SESSION_SECRET=test`. 8 tests in `test_media_upload.py` and
`test_migration_race_condition.py` already fail on main, and still fail here.
@@ -0,0 +1,37 @@
# v2.6.8: Webmention worker app context
## Problem
Production webmention #1 (Bridgy, reply from Mastodon to note 20261101162512)
was stored with `validation_status = 'error'`:
"Working outside of application context". Both outgoing queue items had the
same error and were on their last retry.
## Causes
1. `webmention_ssrf.safe_resolve()` reads `current_app.config['DEV_MODE']`.
`WebmentionWorker` is a plain thread with no Flask app context, so every
`validate_url_for_fetch()` call raised `RuntimeError`, for both
validation (incoming) and endpoint discovery and sending (outgoing).
2. `create_app()` registered a `teardown_appcontext` handler that called
`webmention_worker.stop()`. Teardown runs whenever any app context ends
(every request), so the worker stopped soon after startup.
## Fix
- `WebmentionWorker` takes the Flask app and runs each poll inside
`app.app_context()`, as `SyndicationWorker` already does.
- The teardown handler is removed. The worker is a daemon thread and ends with
the process.
## Tests
`tests/test_webmention_worker.py`: an outgoing send completes through the
worker thread, and the worker is still alive after an app context and a
request end. Both fail without the fix.
## Production data
After deploying, reset webmention 1 to `validation_status = 'pending'` and the
two queue items to `retry_count = 0, next_retry_at = NULL` so the worker
processes them again.
@@ -0,0 +1,36 @@
# v2.6.9: Webmention processing fixes
Found after v2.6.8 let the worker run in production, and by a review of the
implementation against the W3C Webmention Recommendation.
## Fixes
1. **Author photo with alt text** (`webmention_processor.extract_author`).
mf2py returns `u-photo` with an `alt` attribute as
`{'value': url, 'alt': ...}`; the dict was bound to SQLite and the update
failed. `_first_str()` reduces mf2 values to their `value`.
2. **Endpoint discovery** (`WebmentionWorker._discover_endpoint`).
`response.url` is an `httpx.URL`; `urljoin(str, URL)` raised `TypeError`,
which was caught and returned as "no endpoint", so every target was marked
`no_endpoint`. Pass `str(response.url)`. Fetch errors now propagate so the
caller schedules a retry, instead of being treated as "no endpoint".
3. **Duplicate processing.** gunicorn runs 4 processes, each with a worker,
and queue items were claimed by SELECT then UPDATE. The worker now takes a
non-blocking `flock` on `<data>/webmention-worker.lock` before processing;
others wait and retry each poll, so one takes over if the holder dies.
Orphan cleanup runs when the lock is acquired.
4. **XSS (spec 4.1).** `author_url` and `author_photo` are kept only if they
are absolute http(s) URLs; otherwise the source URL / no photo is used.
## Tests
`tests/test_webmention_worker.py`: the send test uses a real `httpx.Response`
(the old `MagicMock` with a string URL hid fix 2), plus tests for the lock,
an alt-text photo and a `javascript:` author URL. All fail on v2.6.8.
## Remaining spec gaps
Tracked separately: rel-token and document-order endpoint discovery, exact
target match during verification, Accept header, re-sending on delete, 410
for deleted notes, SSRF re-validation on redirects, and the others listed in
the compliance review.
@@ -0,0 +1,50 @@
# v2.7.0: Webmention W3C compliance
Review of StarPunk's Webmention support against the W3C Recommendation
(https://www.w3.org/TR/webmention/, 12 January 2017), and the changes made.
v2.6.8 and v2.6.9 fixed the bugs that stopped webmentions working at all.
## Sending
| Section | Requirement | Change |
|---|---|---|
| 3.1.2 | Link header with rel=webmention first (MUST) | RFC 8288 parsing: several links per header, several headers, `rel` in any position, token list, case-insensitive |
| 3.1.2 | Then first `<link>`/`<a>` rel=webmention in document order (MUST) | Single pass over `link` and `a` in document order; rel token match; elements without `href` skipped |
| 3.1.2 | Relative URL resolved against target; empty href is the target; query kept (MUST) | `urljoin` against the final URL after redirects |
| 3.1.2 | Follow redirects | `safe_get` follows up to 10, checking each hop |
| 3.1.2 | User-Agent with "Webmention" (MAY) | `StarPunk/<version> Webmention (+site)` |
| 3.1.3 | Form-encoded POST; any 2xx success (MUST) | Unchanged. Redirects not followed (httpx turned 301/302 POST into GET); 429 retried |
| 3.1.4 | Re-discover endpoint on update (MUST) | Discovery cache removed |
| 3.1.4 | Re-send to previously sent targets, including removed links (SHOULD) | `previous_targets()` from the queue, plus removed links; not capped |
| 3.1.5 | Deleted post returns 410 (SHOULD), tombstone (SHOULD) | `public.note` aborts 410 for soft-deleted notes and hard-deleted notes that sent webmentions; `410.html` |
| 3.1.5 | Re-send on delete (SHOULD) | `requeue_previous_webmentions()`; for a hard delete the rows are detached (`source_note_id = NULL`) first, since the foreign key cascades. Also on undelete |
## Receiving
| Section | Requirement | Change |
|---|---|---|
| 3.2 | 202 for async processing (MUST) | Unchanged |
| 3.2.1 | Valid http(s) URLs; source ≠ target; 400 on error (MUST) | Unchanged |
| 3.2.1 | Target is a valid resource (SHOULD) | Only published notes; others 400 |
| 3.2.1 | Fragment ignored | Stripped before storing (no duplicate rows) |
| 3.2.2 | GET source, follow redirects, limit redirects | `safe_get` |
| 3.2.2 | Accept header (SHOULD) | Added |
| 3.2.2 | Exact match of target, per media type (MUST) | HTML: every link attribute (`lxml iterlinks`) resolved against the final URL; JSON: any string value; `text/*`: substring; other types: no match. Fragments ignored |
| 3.2.4 | Update existing data; 410 / no link removes it (SHOULD) | Unchanged in effect. Moderation decisions kept on update; transient errors keep a valid mention |
## Security (section 4)
- 4.1 XSS: author URL/photo must be http(s) (v2.6.9); snippets re-sanitized after truncation; Mentions list uses `striptags`.
- 4.2 / 4.5: `safe_get` checks every redirect hop, checks all `getaddrinfo` addresses, blocks private, loopback, link-local, multicast, reserved, unspecified, CGNAT, `0.0.0.0/8` and IPv4-mapped forms; 1 MB and 10 s total limits.
- 4.3: endpoint URL checked before POST, no redirects followed.
## Known limits
- DNS is checked before connecting, not pinned for the connection, so a
rebinding DNS server could still answer differently on connect.
- Homepage mentions are refused rather than stored.
- `error` rows (unexpected failures) are not retried automatically.
## Tests
`tests/test_webmention_spec.py` (section-numbered), `tests/test_webmention_worker.py`.
+4 -9
View File
@@ -302,7 +302,7 @@ def create_app(config=None):
if (app.config.get('WEBMENTION_ENABLED', True) and
response.content_type and
'text/html' in response.content_type):
response.headers['Link'] = '</webmention>; rel="webmention"'
response.headers.add('Link', '</webmention>; rel="webmention"')
return response
# Register centralized error handlers
@@ -330,6 +330,7 @@ def create_app(config=None):
if app.config.get('WEBMENTION_WORKER_ENABLED', True) and not app.config.get('TESTING', False):
from starpunk.webmention_worker import WebmentionWorker
webmention_worker = WebmentionWorker(
app,
db_path=app.config['DATABASE_PATH'],
site_url=app.config['SITE_URL'],
poll_interval=app.config.get('WEBMENTION_POLL_INTERVAL', 10),
@@ -345,12 +346,6 @@ def create_app(config=None):
f"batch_size={webmention_worker.batch_size})"
)
# Register cleanup handler
@app.teardown_appcontext
def cleanup_webmention_worker(error=None):
if hasattr(app, 'webmention_worker') and app.webmention_worker.is_alive():
app.webmention_worker.stop()
# Start syndication worker when a target is configured (v2.1.0)
from starpunk.syndication import SyndicationWorker, targets_configured
if targets_configured(app.config) and not app.config.get("TESTING", False):
@@ -464,5 +459,5 @@ def create_app(config=None):
# Package version (Semantic Versioning 2.0.0)
# See docs/standards/versioning-strategy.md for details
__version__ = "2.6.3"
__version_info__ = (2, 6, 3)
__version__ = "2.7.0"
__version_info__ = (2, 7, 0)
+10
View File
@@ -107,6 +107,16 @@ class ConnectionPool:
if not conn:
return
# A request that failed mid-write must not hand an open transaction
# (and its write lock) to the next request (v2.6.5)
if conn.in_transaction:
try:
conn.rollback()
except Exception:
conn.close()
self._stats['connections_closed'] += 1
return
with self._lock:
if len(self._pool) < self.pool_size:
# Return to pool
+5
View File
@@ -82,6 +82,11 @@ def register_error_handlers(app):
return render_template('404.html'), 404
@app.errorhandler(410)
def gone(error):
"""Handle 410 Gone (deleted notes, Webmention 3.1.5)"""
return render_template('410.html'), 410
@app.errorhandler(405)
def method_not_allowed(error):
"""Handle 405 Method Not Allowed errors"""
+16 -12
View File
@@ -868,20 +868,24 @@ def attach_media_to_note(note_id: int, media_ids: List[int], captions: List[str]
db = get_db(current_app)
# Delete existing associations (for edit case)
db.execute("DELETE FROM note_media WHERE note_id = ?", (note_id,))
try:
# Delete existing associations (for edit case)
db.execute("DELETE FROM note_media WHERE note_id = ?", (note_id,))
# Insert new associations
for i, (media_id, caption) in enumerate(zip(media_ids, captions)):
db.execute(
"""
INSERT INTO note_media (note_id, media_id, display_order, caption)
VALUES (?, ?, ?, ?)
""",
(note_id, media_id, i, caption or None)
)
# Insert new associations
for i, (media_id, caption) in enumerate(zip(media_ids, captions)):
db.execute(
"""
INSERT INTO note_media (note_id, media_id, display_order, caption)
VALUES (?, ?, ?, ?)
""",
(note_id, media_id, i, caption or None)
)
db.commit()
db.commit()
except Exception:
db.rollback()
raise
def get_note_media(note_id: int) -> List[Dict]:
+50 -15
View File
@@ -195,6 +195,16 @@ def extract_content(properties: dict) -> str:
return content.strip()
def _has_text(content) -> bool:
"""Whether a content property has any text. Likes, reposts (v2.5.0) and
photo posts (v2.6.5) may come without."""
values = content if isinstance(content, list) else [content]
return any(
(c.strip() if isinstance(c, str) else (c.get("text") or c.get("html") or "").strip())
for c in values if c
)
def extract_title(properties: dict) -> Optional[str]:
"""
Extract the explicit title (Micropub 'name' property)
@@ -420,7 +430,8 @@ def _resolve_photos(photos: list[dict]) -> tuple[list[int], list[str]]:
if len(media_ids) == MAX_PHOTOS:
break
media_id = photo.get("media_id") or _media_id_for_url(photo["url"])
if media_id:
# The same photo twice is shown once (v2.6.5)
if media_id and media_id not in media_ids:
media_ids.append(media_id)
captions.append(photo.get("alt", ""))
return media_ids, captions
@@ -525,24 +536,29 @@ def handle_create(data: dict, token_info: dict, files=None):
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
has_content = _has_text(properties.get("content"))
photos = extract_photos(properties) + _save_uploads(files)
# Photo posts may have no text (v2.6.5): Micropub doesn't require content
content = (
extract_content(properties)
if has_content or not (like_of or repost_of or photos)
else ""
)
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)
# Look up and download photos before the note exists, so a bad photo
# can't leave a half-made post behind (v2.6.5)
media_ids, captions = _resolve_photos(photos)
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)}")
note = None
try:
note = create_note(
content=add_title_heading(content, title),
@@ -553,10 +569,12 @@ def handle_create(data: dict, token_info: dict, files=None):
in_reply_to=in_reply_to,
like_of=like_of,
repost_of=repost_of,
has_media=bool(media_ids),
)
if photos:
_attach_photos_to_note(note.id, photos)
if media_ids:
from starpunk.media import attach_media_to_note
attach_media_to_note(note.id, media_ids, captions)
# Crosspost after photos are attached (v2.1.0); drafts wait until published
from starpunk.syndication import get_targets, resolve_targets, select_targets
@@ -573,6 +591,13 @@ def handle_create(data: dict, token_info: dict, files=None):
raise
except Exception as e:
current_app.logger.error(f"Failed to create note via Micropub: {e}")
# The client is told it failed, so don't leave the post up (v2.6.5)
if note is not None:
try:
from starpunk.notes import delete_note
delete_note(id=note.id, soft=False)
except Exception as cleanup:
current_app.logger.error(f"Could not remove failed note {note.slug}: {cleanup}")
raise MicropubError("server_error", "Failed to create post", status_code=500)
@@ -603,8 +628,10 @@ def handle_update(data: dict, token_info: dict):
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 note.tags]
tags = [t["display_name"] for t in get_note_tags(note.id, entered_order=True)]
photos = _note_photos(note)
changes = {}
@@ -614,7 +641,7 @@ def handle_update(data: dict, token_info: dict):
if prop == "name":
title = None
elif prop == "content":
raise MicropubValidationError("content can't be deleted")
body = ""
elif prop == "category":
tags = []
elif prop == "photo":
@@ -635,7 +662,8 @@ def handle_update(data: dict, token_info: dict):
raise MicropubValidationError(f"Can't delete individual values of {prop}")
if "content" in replace:
body = extract_content(replace)
# Empty text is fine if the note keeps its photos; update_note checks (v2.6.5)
body = extract_content(replace) if _has_text(replace["content"]) else ""
if "name" in replace:
title = extract_title(replace)
if "category" in replace:
@@ -653,6 +681,10 @@ def handle_update(data: dict, token_info: dict):
if "photo" in add:
photos += extract_photos(add)
# Text may go only if photos stay (or it's a like or repost) (v2.6.5)
if not (body or "").strip() and not (photos or note.like_of or note.repost_of):
raise MicropubValidationError("A post needs text or a photo")
new_content = add_title_heading(body, title)
if new_content != note.content:
changes["content"] = new_content
@@ -661,7 +693,7 @@ def handle_update(data: dict, token_info: dict):
try:
if changes:
update_note(id=note.id, **changes)
update_note(id=note.id, has_media=bool(photos), **changes)
if "photo" in touched:
_attach_photos_to_note(note.id, photos)
note_changed(note.id)
@@ -717,8 +749,11 @@ def note_to_mf2(note, wanted: Optional[list] = None) -> dict:
}
if title:
props["name"] = [title]
if note.tags:
props["category"] = [tag["display_name"] for tag in note.tags]
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):
+23 -4
View File
@@ -142,6 +142,7 @@ def create_note(
in_reply_to: Optional[str] = None,
like_of: Optional[str] = None,
repost_of: Optional[str] = None,
has_media: bool = False,
) -> Note:
"""
Create a new note
@@ -205,11 +206,11 @@ def create_note(
- created_at and updated_at set to same value initially
"""
# 1. VALIDATION (before any changes)
# Likes and reposts may have no comment (v2.5.0)
# Likes and reposts may have no comment (v2.5.0), photo posts no text (v2.6.5)
if like_of and repost_of:
raise InvalidNoteDataError("like_of", like_of, "A note can't be both a like and a repost")
content = content or ""
if not content.strip() and not (like_of or repost_of):
if not content.strip() and not (like_of or repost_of or has_media):
raise InvalidNoteDataError(
"content", content, "Content cannot be empty or whitespace-only"
)
@@ -604,7 +605,8 @@ def update_note(
content: Optional[str] = None,
published: Optional[bool] = None,
tags: Optional[list[str]] = None,
in_reply_to: Optional[str] = None
in_reply_to: Optional[str] = None,
has_media: bool = False,
) -> Note:
"""
Update a note's content and/or published status
@@ -690,7 +692,7 @@ def update_note(
identifier = slug if slug is not None else id
raise NoteNotFoundError(identifier)
if empty_content and not (existing_note.like_of or existing_note.repost_of):
if empty_content and not (existing_note.like_of or existing_note.repost_of or has_media):
raise InvalidNoteDataError(
"content", content, "Content cannot be empty or whitespace-only"
)
@@ -987,6 +989,17 @@ def delete_note(
"Path validation failed",
)
# Re-send webmentions so receivers learn the post is gone (spec 3.1.5).
# A hard delete would cascade the queue rows away, so detach them first.
if existing_note.published:
try:
from starpunk.webmention_sender import requeue_previous_webmentions
requeue_previous_webmentions(
Path(current_app.config["DATABASE_PATH"]), existing_note.id, detach=not soft
)
except Exception as e:
current_app.logger.warning(f"Failed to queue webmentions for deleted note: {e}")
# 5. PERFORM DELETION
db = get_db(current_app)
@@ -1100,4 +1113,10 @@ def undelete_note(slug: str) -> Note:
except Exception as e:
current_app.logger.warning(f"Failed to queue syndication after undelete: {e}")
try:
from starpunk.webmention_sender import requeue_previous_webmentions
requeue_previous_webmentions(Path(current_app.config["DATABASE_PATH"]), row["id"])
except Exception as e:
current_app.logger.warning(f"Failed to queue webmentions after undelete: {e}")
return get_note(slug=slug)
+2 -2
View File
@@ -226,8 +226,8 @@ def edit_note_form(note_id: int):
flash("Note not found", "error")
return redirect(url_for("admin.dashboard")), 404
# Pre-load tags for the edit form (v1.3.0 Phase 3)
tags = get_note_tags(note.id)
# Pre-load tags for the edit form (v1.3.0 Phase 3), as entered so saving keeps the order
tags = get_note_tags(note.id, entered_order=True)
object.__setattr__(note, '_cached_tags', tags)
from starpunk.syndication import get_note_syndications, get_targets
+24 -1
View File
@@ -294,6 +294,27 @@ def likes():
return render_template("likes.html", notes=notes)
def _note_was_deleted(slug: str) -> bool:
"""
True if this slug was a note that has been deleted
Soft-deleted notes keep their row; hard-deleted notes that sent
webmentions keep their queue rows (detached from the note).
"""
from starpunk.database import get_db
from starpunk.utils import absolute_url_for
db = get_db(current_app)
if db.execute(
"SELECT 1 FROM notes WHERE slug = ? AND deleted_at IS NOT NULL", (slug,)
).fetchone():
return True
return db.execute(
"SELECT 1 FROM webmention_queue WHERE source_url = ? AND source_note_id IS NULL",
(absolute_url_for("public.note", slug=slug),),
).fetchone() is not None
@bp.route("/note/<slug>")
def note(slug: str):
"""
@@ -319,8 +340,10 @@ def note(slug: str):
# Get note by slug
note_obj = get_note(slug=slug)
# Return 404 if note doesn't exist or isn't published
# Deleted notes are 410 Gone (Webmention 3.1.5); unknown or draft 404
if not note_obj or not note_obj.published:
if not note_obj and _note_was_deleted(slug):
abort(410)
abort(404)
# Get media for note (v1.2.0 Phase 3)
+21 -13
View File
@@ -11,7 +11,7 @@ References:
"""
from flask import Blueprint, current_app, request, jsonify
from urllib.parse import urlparse
from urllib.parse import urldefrag, urlparse
from starpunk.database import get_db
from starpunk.notes import get_note, NoteNotFoundError
from starpunk.rate_limiter import check_rate_limit
@@ -107,17 +107,24 @@ def validate_url(url: str) -> tuple[bool, str | None]:
return False, "URL is malformed"
def _host_port(url: str) -> tuple[str, int | None]:
parsed = urlparse(url)
default = {'http': 80, 'https': 443}.get(parsed.scheme.lower())
try:
port = parsed.port or default
except ValueError:
port = None
return (parsed.hostname or '').lower(), port
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.
Compares host (case-insensitively) and effective port with SITE_URL.
"""
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
return _host_port(site_url) == _host_port(target_url)
def resolve_target_note(target_url: str) -> int | None:
@@ -228,16 +235,17 @@ def receive_webmention():
"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)
# The fragment is ignored (spec 3.2.1) and not stored, so target#a and
# target#b are the same mention
target = urldefrag(target)[0]
# 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:
# Only published notes accept webmentions (spec 3.2.1: target must be a
# valid resource that accepts them)
target_note_id = resolve_target_note(target)
if target_note_id is None:
return jsonify({
"error": "invalid_target",
"error_description": "Target URL not found"
"error_description": "Target URL does not accept webmentions"
}), 400
# Insert webmention into database (queued for validation)
+71 -8
View File
@@ -138,7 +138,9 @@ class MastodonClient:
def _prepare(self, post: "Post") -> tuple:
if post.kind == "repost":
return compose_repost_text(post, post.note.content, post.max_chars), []
text = compose_text(post.note, post.permalink, post.tags, post.max_chars)
# Images in the text are sent as attachments instead (v2.6.6)
text = compose_text(post.note, post.permalink, post.tags, post.max_chars,
body=strip_images(post.note.content))
media_ids = [self.upload_media(f["path"], f["mime_type"], f["description"]) for f in post.media]
return text, media_ids
@@ -1003,7 +1005,8 @@ def compose_text(note, permalink: str, tags: List[str], max_chars: int,
if len(body) + len(tail) > max_chars:
room = max_chars - len(tail) - 1
body = body[:room].rsplit(" ", 1)[0].rstrip() + "…"
return body + tail
# A photo post may have no text: start with the link (v2.6.5)
return (body + tail).lstrip()
_BLOCKS = ["p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "blockquote", "ul", "ol", "hr", "table"]
@@ -1134,25 +1137,84 @@ def bluesky_facets(text: str, anchors: List[tuple] = ()) -> List[dict]:
return facets
def _media_files(note_id: int, limit: int) -> List[dict]:
"""Image files for a note: the 'large' variant when there is one"""
_MD_IMAGE_RE = re.compile(r"!\[[^\]]*\]\([^)]*\)")
_HTML_IMAGE_RE = re.compile(r"<img\b[^>]*>", re.IGNORECASE)
def inline_images(markdown_text: str) -> List[tuple]:
"""(url, alt) for each image embedded in a note's text, in reading order"""
images = []
for img in _note_soup(markdown_text).find_all("img"):
if img.get("src"):
images.append((img["src"], img.get("alt") or ""))
return images
def strip_images(markdown_text: str) -> str:
"""A note's Markdown without its embedded images"""
text = _HTML_IMAGE_RE.sub("", _MD_IMAGE_RE.sub("", markdown_text))
return re.sub(r"\n{3,}", "\n\n", text).strip()
def _own_media_path(url: str) -> Optional[str]:
"""Path in the media library for one of this site's /media/ URLs"""
site = current_app.config["SITE_URL"].rstrip("/")
if url.startswith(site):
url = url[len(site):]
return url[len("/media/"):] if url.startswith("/media/") else None
def _media_files(note_id: int, limit: int, content: str = "") -> List[dict]:
"""
Image files for a note: the 'large' variant when there is one.
Attached photos come first, then images embedded in the text that are in
this site's media library. Some Micropub clients (OutPost, for one)
upload a photo and put it in the content rather than in `photo` (v2.6.6).
"""
from starpunk.media import get_note_media
media_dir = Path(current_app.config["DATA_PATH"]) / "media"
site = current_app.config["SITE_URL"].rstrip("/")
items = [(m, m.get("caption") or "") for m in get_note_media(note_id)]
seen = {m["path"] for m, _ in items}
for url, alt in inline_images(content) if content else []:
path = _own_media_path(url)
if not path or path in seen:
continue
media = _media_by_path(path)
if media:
seen.add(path)
items.append((media, alt or media.get("caption") or ""))
files = []
for media in get_note_media(note_id)[:limit]:
for media, description in items[:limit]:
variant = (media.get("variants") or {}).get("large")
rel = variant["path"] if variant else media["path"]
files.append({
"path": media_dir / rel,
"url": f"{site}/media/{rel}", # for targets that fetch images themselves
"mime_type": media.get("mime_type") or "image/jpeg",
"description": media.get("caption") or "",
"description": description,
})
return files
def _media_by_path(path: str) -> Optional[dict]:
"""A media row with its variants, found by its path in the library"""
db = get_db(current_app)
row = db.execute("SELECT id, path, mime_type FROM media WHERE path = ?", (path,)).fetchone()
if not row:
return None
variants = {
v["variant_type"]: {"path": v["path"]}
for v in db.execute(
"SELECT variant_type, path FROM media_variants WHERE media_id = ?", (row["id"],)
)
}
return {"path": row["path"], "mime_type": row["mime_type"], "variants": variants, "caption": ""}
# --- Worker -----------------------------------------------------------------
def _claim(db, row_id: int) -> bool:
@@ -1239,9 +1301,10 @@ def _reconcile(row, target: Target) -> tuple:
post = Post(
note=note,
permalink=f"{site}/note/{note.slug}",
tags=[t["display_name"] for t in get_note_tags(note.id)],
tags=[t["display_name"] for t in get_note_tags(note.id, entered_order=True)],
max_chars=target.max_chars,
media=_media_files(note.id, target.max_media) if note.kind == "note" else [],
media=_media_files(note.id, target.max_media, note.content)
if note.kind == "note" else [],
kind=note.kind,
target_url=note.reacts_to,
target_title=_target_title(note.reacts_to),
+11 -6
View File
@@ -115,27 +115,32 @@ def add_tags_to_note(note_id: int, tags: list[str]) -> None:
db.commit()
def get_note_tags(note_id: int) -> list[dict]:
def get_note_tags(note_id: int, entered_order: bool = False) -> list[dict]:
"""
Get all tags for a note
Args:
note_id: Note database ID
entered_order: In the order they were entered (the first is the
note's main tag, e.g. its Threads topic) instead of alphabetical.
add_tags_to_note() rewrites the links in entry order on every
save, so note_tags.id records it. Use this wherever the tags are
saved back (editor, Micropub update) so the order survives.
Returns:
List of tag dicts with 'name' and 'display_name'
Ordered alphabetically by display_name (case-insensitive)
Query should use: ORDER BY LOWER(tags.display_name) ASC
Ordered alphabetically by display_name (case-insensitive), unless
entered_order
"""
db = get_db(current_app)
order = "note_tags.id" if entered_order else "LOWER(tags.display_name)"
tags = db.execute(
"""
f"""
SELECT tags.name, tags.display_name
FROM tags
JOIN note_tags ON tags.id = note_tags.tag_id
WHERE note_tags.note_id = ?
ORDER BY LOWER(tags.display_name) ASC
ORDER BY {order} ASC
""",
(note_id,)
).fetchall()
+127 -88
View File
@@ -14,15 +14,18 @@ References:
- W3C Webmention: https://www.w3.org/TR/webmention/
"""
import json
import logging
import mf2py
import nh3
import httpx
from datetime import datetime
from typing import Dict, Any, Optional
from urllib.parse import urlparse
from urllib.parse import urldefrag, urlparse
from starpunk.webmention_ssrf import validate_url_for_fetch, SSRFBlockedError
from starpunk.webmention_ssrf import (
FetchTooLargeError, SSRFBlockedError, safe_get, user_agent,
)
logger = logging.getLogger(__name__)
@@ -33,103 +36,113 @@ class ValidationError(Exception):
pass
def fetch_source(url: str, site_url: str, timeout: int = 10, max_size: int = 1048576) -> tuple[str, str]:
ACCEPT = ('text/html, application/xhtml+xml;q=0.9, application/json;q=0.8, '
'text/plain;q=0.7, */*;q=0.1')
class TransientError(ValidationError):
"""Source could not be checked right now (network error, 5xx)"""
pass
def fetch_source(url: str, site_url: str) -> tuple[str, str, str]:
"""
Fetch source URL content with SSRF protection.
Per spec 3.2.2: GET following redirects (limited), with an Accept header.
Args:
url: Source URL to fetch
site_url: Site URL for User-Agent header
timeout: Request timeout in seconds (default: 10)
max_size: Maximum content size in bytes (default: 1MB)
Returns:
Tuple of (content, content_type)
Tuple of (content, content_type, final_url)
Raises:
SSRFBlockedError: If URL points to private IP
ValidationError: If fetch fails or content too large
ValidationError: Source is blocked, too large, or returned 4xx
TransientError: Network error, timeout or 5xx
"""
# SSRF protection
try:
validate_url_for_fetch(url)
result = safe_get(url, headers={'User-Agent': user_agent(site_url), 'Accept': ACCEPT})
except (SSRFBlockedError, ValueError) as e:
logger.warning(f"SSRF protection blocked URL {url}: {e}")
raise ValidationError(f"Blocked request: {e}")
# Fetch URL
try:
# Use streaming to check size before downloading entire content
with httpx.stream(
'GET',
url,
timeout=timeout,
headers={'User-Agent': f'StarPunk/1.6.0 (+{site_url})'},
follow_redirects=True
) as response:
response.raise_for_status()
# Check content length if provided
content_length = response.headers.get('Content-Length')
if content_length and int(content_length) > max_size:
raise ValidationError(f"Source exceeds size limit ({max_size} bytes)")
# Read content with size limit
content = b''
for chunk in response.iter_bytes(chunk_size=8192):
content += chunk
if len(content) > max_size:
raise ValidationError(f"Source exceeds size limit ({max_size} bytes)")
content_type = response.headers.get('Content-Type', '')
return content.decode('utf-8', errors='replace'), content_type
except FetchTooLargeError as e:
raise ValidationError(f"Source {e}")
except httpx.TimeoutException:
raise ValidationError("Source fetch timed out")
except httpx.HTTPStatusError as e:
if 400 <= e.response.status_code < 500:
raise ValidationError(f"Source returned {e.response.status_code}")
else:
raise ValidationError(f"Source server error: {e.response.status_code}")
raise TransientError("Source fetch timed out")
except httpx.HTTPError as e:
raise ValidationError(f"Failed to fetch source: {e}")
except UnicodeDecodeError:
raise ValidationError("Source content encoding is not supported")
raise TransientError(f"Failed to fetch source: {e}")
if 400 <= result.status_code < 500:
raise ValidationError(f"Source returned {result.status_code}")
if result.status_code >= 300:
raise TransientError(f"Source server error: {result.status_code}")
return result.text, result.headers.get('Content-Type', ''), result.url
def verify_link_presence(content: str, target_url: str, content_type: str) -> bool:
def _strip_fragment(url: str) -> str:
return urldefrag(url.strip())[0]
def _json_strings(value):
"""Yield every string in a parsed JSON document"""
if isinstance(value, str):
yield value
elif isinstance(value, dict):
for item in value.values():
yield from _json_strings(item)
elif isinstance(value, list):
for item in value:
yield from _json_strings(item)
def verify_link_presence(content: str, target_url: str, content_type: str,
source_url: str = '') -> bool:
"""
Verify that source content contains a link to target URL.
Verify the source links to the target (spec 3.2.2).
The source MUST have an exact match of the target URL, checked per media
type: in HTML, any link-bearing attribute (a/link href, img/video/audio
src, ...) resolved against the source URL; in JSON, any string value; in
other text, the URL anywhere. Fragments are ignored on both sides.
Args:
content: Source content (HTML or text)
content: Source content
target_url: Target URL to find
content_type: Content type of source
source_url: Final source URL, for resolving relative links
Returns:
True if target link found, False otherwise
True if the target is linked, False otherwise
"""
# Normalize URLs for comparison (remove fragments, trailing slashes)
target_normalized = urlparse(target_url)._replace(fragment='').geturl().rstrip('/')
target = _strip_fragment(target_url)
media_type = content_type.split(';')[0].strip().lower()
# For HTML, parse and check all links
if 'html' in content_type.lower():
if 'html' in media_type:
from lxml import html as lxml_html
try:
from lxml import html as lxml_html
doc = lxml_html.fromstring(content)
links = doc.xpath('//a/@href')
for link in links:
# Make absolute if relative
link_normalized = urlparse(link)._replace(fragment='').geturl().rstrip('/')
if link_normalized == target_normalized:
return True
doc = lxml_html.document_fromstring(content)
except Exception as e:
logger.debug(f"HTML parsing failed, falling back to string search: {e}")
logger.debug(f"HTML parsing failed: {e}")
return False
if source_url:
doc.make_links_absolute(source_url, resolve_base_href=True,
handle_failures='ignore')
return any(_strip_fragment(link) == target for _, _, link, _ in doc.iterlinks())
# Fallback: simple string search
return target_normalized in content
if media_type == 'application/json' or media_type.endswith('+json'):
try:
data = json.loads(content)
except ValueError:
return False
return any(_strip_fragment(s) == target for s in _json_strings(data))
if media_type.startswith('text/'):
return target in content
return False
def detect_mention_type(parsed_mf2: Dict, target_url: str) -> str:
@@ -182,6 +195,28 @@ def detect_mention_type(parsed_mf2: Dict, target_url: str) -> str:
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
def _is_http_url(value: Optional[str]) -> bool:
"""True if value is an absolute http or https URL"""
if not value:
return False
parsed = urlparse(value.strip())
return parsed.scheme.lower() in ('http', 'https') and bool(parsed.netloc)
def extract_author(parsed_mf2: Dict, source_url: str) -> Dict[str, Optional[str]]:
"""
Extract author information from h-card.
@@ -212,26 +247,29 @@ def extract_author(parsed_mf2: Dict, source_url: str) -> Dict[str, Optional[str]
if isinstance(author_data, dict):
# h-card object
props = author_data.get('properties', {})
author_name = props.get('name', [None])[0]
author_url = props.get('url', [None])[0]
author_photo = props.get('photo', [None])[0]
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 = props.get('name', [None])[0]
author_url = props.get('url', [None])[0]
author_photo = props.get('photo', [None])[0]
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
if not author_url:
# 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
return {
'author_name': author_name,
@@ -267,12 +305,7 @@ def extract_content(parsed_mf2: Dict) -> Optional[str]:
content = content_data
if content:
# Sanitize HTML
sanitized = sanitize_content(content)
# Truncate to 500 chars
if len(sanitized) > 500:
sanitized = sanitized[:497] + '...'
return sanitized
return _snippet(content)
# Try p-summary as fallback
summary = props.get('summary', [])
@@ -281,14 +314,20 @@ def extract_content(parsed_mf2: Dict) -> Optional[str]:
if isinstance(content, dict):
content = content.get('value', '')
if content:
sanitized = sanitize_content(content)
if len(sanitized) > 500:
sanitized = sanitized[:497] + '...'
return sanitized
return _snippet(content)
return None
def _snippet(html: str, limit: int = 500) -> str:
"""Sanitized HTML of at most ~limit characters, with tags closed"""
sanitized = sanitize_content(html)
if len(sanitized) > limit:
# Cutting can leave a tag or attribute open; sanitizing again closes it
sanitized = sanitize_content(sanitized[:limit - 3] + '...')
return sanitized
def sanitize_content(html: str) -> str:
"""
Sanitize HTML content using nh3.
@@ -337,17 +376,17 @@ def process_webmention(source_url: str, target_url: str, site_url: str) -> Dict[
ValidationError: If validation fails with specific error
"""
# Fetch source content
content, content_type = fetch_source(source_url, site_url)
content, content_type, final_url = fetch_source(source_url, site_url)
# Verify target link presence
if not verify_link_presence(content, target_url, content_type):
if not verify_link_presence(content, target_url, content_type, final_url):
raise ValidationError("Source does not link to target")
# Parse microformats (only for HTML)
parsed_mf2 = None
if 'html' in content_type.lower():
try:
parsed_mf2 = mf2py.parse(doc=content, url=source_url)
parsed_mf2 = mf2py.parse(doc=content, url=final_url)
except Exception as e:
logger.debug(f"Microformat parsing failed for {source_url}: {e}")
+80 -61
View File
@@ -14,9 +14,8 @@ References:
import logging
import sqlite3
from datetime import datetime
from pathlib import Path
from typing import Optional, Set
from typing import Optional
from lxml import html as lxml_html
from urllib.parse import urlparse
@@ -45,16 +44,16 @@ def extract_links_from_html(html_content: str, exclude_code_blocks: bool = True)
return []
try:
# Parse HTML
doc = lxml_html.fromstring(html_content)
# Parse HTML inside a wrapper, so a top-level <pre> can be removed too
doc = lxml_html.fragment_fromstring(html_content, create_parent='div')
if exclude_code_blocks:
# Remove <pre> and <code> elements before extracting links
for element in doc.xpath('//pre | //code'):
element.getparent().remove(element)
for element in doc.xpath('.//pre | .//code'):
element.drop_tree()
# Extract all <a href> attributes in document order
links = doc.xpath('//a/@href')
links = doc.xpath('.//a/@href')
# Filter to valid absolute URLs (http/https)
absolute_links = []
@@ -70,6 +69,66 @@ def extract_links_from_html(html_content: str, exclude_code_blocks: bool = True)
return []
def _dedupe(urls: list) -> list:
"""Drop empty and repeated URLs, keeping the first occurrence"""
seen = set()
result = []
for url in urls:
if url and url not in seen:
seen.add(url)
result.append(url)
return result
def previous_targets(db_path: Path, note_id: int) -> list[str]:
"""Targets this note has been queued to send webmentions to before"""
conn = sqlite3.connect(db_path)
try:
rows = conn.execute(
"SELECT target_url FROM webmention_queue WHERE source_note_id = ? ORDER BY id",
(note_id,),
).fetchall()
finally:
conn.close()
return [row[0] for row in rows]
def requeue_previous_webmentions(db_path: Path, note_id: int, detach: bool = False) -> int:
"""
Re-send every webmention this note has sent (spec 3.1.5 deleted posts)
Args:
db_path: Path to SQLite database
note_id: Note being deleted or restored
detach: Clear source_note_id so the rows survive a hard delete
(the foreign key cascades)
Returns:
Number of webmentions queued
"""
conn = sqlite3.connect(db_path)
try:
cursor = conn.execute(f"""
UPDATE webmention_queue
SET status = 'pending',
retry_count = 0,
next_retry_at = NULL,
last_error = NULL,
endpoint_url = NULL,
created_at = CURRENT_TIMESTAMP
{', source_note_id = NULL' if detach else ''}
WHERE source_note_id = ?
""", (note_id,))
conn.commit()
queued = cursor.rowcount
finally:
conn.close()
if queued:
logger.info(f"Re-queued {queued} webmentions for note {note_id}")
return queued
def queue_webmentions_for_note(
db_path: Path,
note_id: int,
@@ -83,10 +142,9 @@ def queue_webmentions_for_note(
Per architect's answers (Phase 6):
- Called from notes.py AFTER successful database commit
- For updates: diff old vs new URLs, queue for new/existing/removed
- For creates: queue for all URLs in content
- Max 10 webmentions per operation
- Priority: in_reply_to URL first, then document order
- For creates: reply target first, then links in document order (max 10)
- For updates: the same, plus every previously sent target and links
removed by the edit (spec 3.1.4)
- Webmention sending is best-effort; failures do not affect note creation
Args:
@@ -100,58 +158,19 @@ def queue_webmentions_for_note(
Returns:
Number of webmentions queued
"""
# Phase 6: Implement URL diffing for updates
# Targets for the current content: reply target first, then links in
# document order, at most 10
links = extract_links_from_html(content_html) if content_html else []
current = _dedupe(([in_reply_to] if in_reply_to else []) + links)[:10]
if old_content_html is not None:
# This is an update - compute URL diff
old_links = set(extract_links_from_html(old_content_html))
# Handle unpublishing case (content_html is None)
if content_html is None:
# Unpublishing - queue for all old URLs (they're all removed)
new_links = set()
else:
new_links = set(extract_links_from_html(content_html))
# Compute sets for URL diffing
new_urls = new_links - old_links # In new, not in old
existing_urls = new_links & old_links # In both (re-validate)
removed_urls = old_links - new_links # In old, not in new
# Build target list: new + existing + removed
# (All need webmentions per W3C spec)
all_update_urls = list(new_urls) + list(existing_urls) + list(removed_urls)
# Add in_reply_to if changed
target_urls = []
if in_reply_to and in_reply_to not in all_update_urls:
target_urls.append(in_reply_to)
# Add the diffed URLs
target_urls.extend(all_update_urls)
# Limit to 10
target_urls = target_urls[:10]
# Update (spec 3.1.4): also re-send to every target notified before,
# and to links the edit removed, so they can update or remove the
# mention. These are not capped.
removed = [u for u in extract_links_from_html(old_content_html) if u not in links]
target_urls = _dedupe(current + previous_targets(db_path, note_id) + removed)
else:
# This is a create (no old content) - use original logic
links = extract_links_from_html(content_html) if content_html else []
# Build priority-ordered list of target URLs
target_urls = []
# 1. in_reply_to gets highest priority
if in_reply_to:
target_urls.append(in_reply_to)
# 2. Add extracted links in document order (deduplicated)
seen = {in_reply_to} if in_reply_to else set()
for link in links:
if link not in seen:
target_urls.append(link)
seen.add(link)
# 3. Limit to 10 webmentions per operation
target_urls = target_urls[:10]
target_urls = current
if not target_urls:
logger.debug(f"No links to send webmentions for note {note_id}")
+142 -52
View File
@@ -1,113 +1,203 @@
"""
SSRF protection utilities for webmention processing
SSRF protection for webmention fetches
Per ADR-063 Decision 9 and background-worker.md:
- Block private IP address ranges
- Resolve hostname before making requests
Per ADR-063 Decision 9 and Webmention sections 4.2, 4.3 and 4.5:
- Every address a hostname resolves to must be public
- Redirects are followed by hand so each hop is checked
- Redirect count, response size and total time are limited
- DEV_MODE exception for localhost testing
- Applied to all outgoing HTTP requests
References:
- ADR-063: Webmention Implementation
- Background Worker Design: /docs/design/v1.6.0/background-worker.md
- W3C Webmention: https://www.w3.org/TR/webmention/#security-considerations
"""
import ipaddress
import socket
import time
from dataclasses import dataclass
from urllib.parse import urljoin, urlparse
import httpx
from flask import current_app
MAX_REDIRECTS = 10
MAX_BYTES = 1024 * 1024
TIMEOUT = 10
# Tests can set an httpx transport here (e.g. httpx.MockTransport)
TRANSPORT = None
CGNAT = ipaddress.ip_network('100.64.0.0/10')
THIS_NETWORK = ipaddress.ip_network('0.0.0.0/8')
class SSRFBlockedError(Exception):
"""Raised when SSRF protection blocks a request"""
pass
# Private IP ranges per RFC 1918 and link-local ranges
BLOCKED_NETWORKS = [
ipaddress.ip_network('10.0.0.0/8'), # RFC 1918 private
ipaddress.ip_network('172.16.0.0/12'), # RFC 1918 private
ipaddress.ip_network('192.168.0.0/16'), # RFC 1918 private
ipaddress.ip_network('127.0.0.0/8'), # Localhost
ipaddress.ip_network('169.254.0.0/16'), # Link-local
ipaddress.ip_network('::1/128'), # IPv6 localhost
ipaddress.ip_network('fc00::/7'), # IPv6 unique local
ipaddress.ip_network('fe80::/10'), # IPv6 link-local
]
class FetchTooLargeError(Exception):
"""Raised when a response is larger than the limit"""
pass
def user_agent(site_url: str) -> str:
"""User-Agent for webmention requests (spec 3.1.2 suggests including 'Webmention')"""
from starpunk import __version__
return f"StarPunk/{__version__} Webmention (+{site_url})"
def is_private_ip(ip: str) -> bool:
"""
Check if IP address is in a private/blocked range.
Check if an IP address must not be fetched.
Blocks private, loopback, link-local, multicast, reserved, unspecified,
carrier-grade NAT and IPv4-mapped forms of these.
Args:
ip: IP address string (IPv4 or IPv6)
Returns:
True if IP is private/blocked, False otherwise
True if IP is blocked, False otherwise
"""
try:
addr = ipaddress.ip_address(ip)
return any(addr in network for network in BLOCKED_NETWORKS)
addr = ipaddress.ip_address(ip.split('%')[0])
except ValueError:
# Invalid IP format, treat as blocked
return True
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped:
addr = addr.ipv4_mapped
if isinstance(addr, ipaddress.IPv4Address) and (addr in CGNAT or addr in THIS_NETWORK):
return True
return (
addr.is_private
or addr.is_loopback
or addr.is_link_local
or addr.is_multicast
or addr.is_reserved
or addr.is_unspecified
)
def safe_resolve(hostname: str) -> str:
"""
Resolve hostname and validate IP is not private.
Resolve hostname and check every address is public.
Per background-worker.md: DEV_MODE exception for localhost testing.
Args:
hostname: Hostname to resolve
Returns:
Resolved IP address if safe
First resolved IP address
Raises:
SSRFBlockedError: If hostname resolves to private IP
SSRFBlockedError: If any address is blocked
socket.gaierror: If hostname cannot be resolved
"""
# DEV_MODE exception for localhost
if current_app.config.get('DEV_MODE') and hostname in ('localhost', '127.0.0.1', '::1'):
return '127.0.0.1'
# Resolve hostname
ip = socket.gethostbyname(hostname)
addresses = sorted({info[4][0] for info in socket.getaddrinfo(hostname, None)})
for ip in addresses:
if is_private_ip(ip):
raise SSRFBlockedError(f"Blocked request to private IP: {ip}")
# Check if resolved IP is private
if is_private_ip(ip):
raise SSRFBlockedError(f"Blocked request to private IP: {ip}")
return ip
return addresses[0]
def validate_url_for_fetch(url: str) -> None:
"""
Validate URL is safe to fetch (not private IP).
Args:
url: URL to validate
Validate URL is safe to fetch (http(s), public addresses only).
Raises:
SSRFBlockedError: If URL points to private IP
ValueError: If URL is malformed
SSRFBlockedError: If URL points to a blocked address
ValueError: If URL is malformed or its host does not resolve
"""
from urllib.parse import urlparse
parsed = urlparse(url)
if not parsed.scheme in ('http', 'https'):
if parsed.scheme not in ('http', 'https'):
raise ValueError(f"Unsupported URL scheme: {parsed.scheme}")
if not parsed.netloc:
if not parsed.hostname:
raise ValueError("URL must include a hostname")
# Extract hostname (remove port if present)
hostname = parsed.hostname
if not hostname:
raise ValueError("Could not extract hostname from URL")
try:
safe_resolve(parsed.hostname)
except socket.gaierror as e:
raise ValueError(f"Could not resolve {parsed.hostname}: {e}")
# Validate hostname resolves to public IP
safe_resolve(hostname)
@dataclass
class FetchResult:
"""A fetched response, after redirects"""
url: str
status_code: int
headers: httpx.Headers
content: bytes
encoding: str
@property
def text(self) -> str:
try:
return self.content.decode(self.encoding, errors='replace')
except LookupError:
return self.content.decode('utf-8', errors='replace')
def safe_get(url: str, headers: dict, max_bytes: int = MAX_BYTES,
max_redirects: int = MAX_REDIRECTS, timeout: float = TIMEOUT) -> FetchResult:
"""
GET a URL, following redirects by hand and checking each hop.
Args:
url: URL to fetch
headers: Request headers
max_bytes: Response body limit
max_redirects: Redirect limit
timeout: Total time limit in seconds
Returns:
FetchResult for the final response (any status code)
Raises:
SSRFBlockedError, ValueError: URL or a redirect target is not allowed
FetchTooLargeError: Body exceeds max_bytes
httpx.HTTPError: Network errors, too many redirects, time limit
"""
deadline = time.monotonic() + timeout
with httpx.Client(follow_redirects=False, transport=TRANSPORT) as client:
for _ in range(max_redirects + 1):
validate_url_for_fetch(url)
remaining = deadline - time.monotonic()
if remaining <= 0:
raise httpx.TimeoutException("Fetch exceeded time limit")
with client.stream('GET', url, headers=headers, timeout=remaining) as response:
location = response.headers.get('Location')
if response.is_redirect and location:
url = urljoin(url, location)
continue
content_length = response.headers.get('Content-Length', '')
if content_length.isdigit() and int(content_length) > max_bytes:
raise FetchTooLargeError(f"Response exceeds size limit ({max_bytes} bytes)")
content = b''
for chunk in response.iter_bytes(chunk_size=8192):
content += chunk
if len(content) > max_bytes:
raise FetchTooLargeError(f"Response exceeds size limit ({max_bytes} bytes)")
if time.monotonic() > deadline:
raise httpx.TimeoutException("Fetch exceeded time limit")
return FetchResult(
url=url,
status_code=response.status_code,
headers=response.headers,
content=content,
encoding=response.charset_encoding or 'utf-8',
)
raise httpx.TooManyRedirects(f"More than {max_redirects} redirects")
+174 -147
View File
@@ -12,30 +12,32 @@ References:
- ADR-063: Webmention Implementation
"""
import fcntl
import logging
import re
import threading
import time
import sqlite3
import httpx
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, Any, Optional, TypedDict
from urllib.parse import urlparse
from typing import Dict, Any, Optional
from urllib.parse import urljoin
from lxml import html as lxml_html
from starpunk.webmention_processor import process_webmention, ValidationError
from starpunk.webmention_ssrf import validate_url_for_fetch, SSRFBlockedError
from flask import has_app_context
from starpunk.webmention_processor import process_webmention, TransientError, ValidationError
from starpunk.webmention_ssrf import (
FetchTooLargeError, SSRFBlockedError, safe_get, user_agent, validate_url_for_fetch,
)
logger = logging.getLogger(__name__)
# Link header (RFC 8288): <uri> then ;-separated params; quoted values may
# contain , and ;
LINK_RE = re.compile(r'<([^>]*)>((?:\s*;\s*[^;,"=\s]+\s*(?:=\s*(?:"[^"]*"|[^;,]*))?)*)')
LINK_PARAM_RE = re.compile(r';\s*([^;,"=\s]+)\s*(?:=\s*(?:"([^"]*)"|([^;,]*)))?')
# Discovery cache entry type
class DiscoveryCacheEntry(TypedDict):
"""Cache entry for endpoint discovery results"""
endpoint: Optional[str] # None = negative cache (no endpoint found)
expires_at: datetime
class WebmentionWorker(threading.Thread):
@@ -47,6 +49,7 @@ class WebmentionWorker(threading.Thread):
def __init__(
self,
app,
db_path: Path,
site_url: str,
poll_interval: int = 10,
@@ -58,6 +61,7 @@ class WebmentionWorker(threading.Thread):
Initialize webmention worker thread
Args:
app: Flask app (the SSRF checks read its config)
db_path: Path to SQLite database
site_url: Site URL for User-Agent header
poll_interval: Seconds between queue checks (default: 10)
@@ -66,6 +70,7 @@ class WebmentionWorker(threading.Thread):
auto_approve: Auto-approve valid webmentions (default: True)
"""
super().__init__(daemon=True, name="webmention-worker")
self.app = app
self.db_path = db_path
self.site_url = site_url
self.poll_interval = poll_interval
@@ -74,10 +79,7 @@ class WebmentionWorker(threading.Thread):
self.auto_approve = auto_approve
self._stop_event = threading.Event()
self._last_processed = None
# Phase 3: Discovery cache (worker instance variable)
# Per architect's answer to Q4
self._discovery_cache: Dict[str, DiscoveryCacheEntry] = {}
self._lock_file = None
def run(self):
"""
@@ -92,19 +94,23 @@ class WebmentionWorker(threading.Thread):
try:
logger.info("Webmention worker started")
# Cleanup orphaned items from previous crashes
self._cleanup_orphaned_items()
# Main processing loop
while not self._stop_event.is_set():
# Every gunicorn process starts a worker; only the one holding
# the lock processes queues, so nothing is sent twice
if not self._acquire_lock():
self._stop_event.wait(self.poll_interval)
continue
try:
processed = 0
# Process incoming webmentions
processed += self._process_pending_validations()
with self.app.app_context():
# Process incoming webmentions
processed += self._process_pending_validations()
# Phase 3: Process outgoing webmentions
processed += self._process_pending_sends()
# Phase 3: Process outgoing webmentions
processed += self._process_pending_sends()
# Update last processed time
if processed > 0:
@@ -121,8 +127,40 @@ class WebmentionWorker(threading.Thread):
except Exception as e:
logger.error(f"Webmention worker thread failed: {e}", exc_info=True)
finally:
self._release_lock()
logger.info("Webmention worker stopped")
def _acquire_lock(self) -> bool:
"""
Take the cross-process worker lock (non-blocking)
On first acquisition, also reset items left mid-send by a previous
holder. The OS releases the lock if this process dies.
Returns:
True if this worker holds the lock
"""
if self._lock_file:
return True
lock_file = open(Path(self.db_path).parent / "webmention-worker.lock", "w")
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
lock_file.close()
return False
self._lock_file = lock_file
logger.info("Webmention worker holds the queue lock")
self._cleanup_orphaned_items()
return True
def _release_lock(self):
"""Release the cross-process worker lock if held"""
if self._lock_file:
self._lock_file.close()
self._lock_file = None
def _cleanup_orphaned_items(self):
"""
Clean up orphaned 'sending' status items on startup
@@ -226,25 +264,34 @@ class WebmentionWorker(threading.Thread):
moderation_status = 'approved' if self.auto_approve else 'pending'
# An update to an existing mention (spec 3.2.4) keeps the admin's
# moderation decision; only a first-time valid mention gets the
# default. Previously valid = validated with no error.
cursor.execute("""
UPDATE webmentions
SET validation_status = 'valid',
SET moderation_status = CASE
WHEN moderation_status IN ('hidden', 'deleted') THEN moderation_status
WHEN validated_at IS NOT NULL AND validation_error IS NULL
THEN moderation_status
ELSE ?
END,
validation_status = 'valid',
validation_error = NULL,
validated_at = CURRENT_TIMESTAMP,
mention_type = ?,
author_name = ?,
author_url = ?,
author_photo = ?,
content_snippet = ?,
moderation_status = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""", (
moderation_status,
result['mention_type'],
result['author_name'],
result['author_url'],
result['author_photo'],
result['content_snippet'],
moderation_status,
webmention_id
))
@@ -253,11 +300,17 @@ class WebmentionWorker(threading.Thread):
logger.info(
f"Validated webmention: {source_url} -> {target_url} "
f"(type={result['mention_type']}, status={moderation_status})"
f"(type={result['mention_type']})"
)
except TransientError as e:
# Source unreachable right now: keep a previously valid mention
self._mark_validation_failed(webmention_id, source_url, target_url, str(e),
transient=True)
except ValidationError as e:
# Validation failed - update with error
# Validation failed (410/4xx, no link): the mention is removed
# from display (spec 3.2.4)
self._mark_validation_failed(webmention_id, source_url, target_url, str(e))
except Exception as e:
@@ -275,11 +328,15 @@ class WebmentionWorker(threading.Thread):
webmention_id: int,
source_url: str,
target_url: str,
error: str
error: str,
transient: bool = False
):
"""
Mark webmention validation as failed/invalid
A transient failure of a mention that was valid before restores it to
valid with its previous data, rather than hiding it.
Args:
webmention_id: Database ID
source_url: Source URL
@@ -289,7 +346,9 @@ class WebmentionWorker(threading.Thread):
# Determine if error or invalid
# Per background-worker.md: HTTP 4xx and "no link" are invalid
# All other errors are 'error' status
if any(x in error.lower() for x in ['does not link', 'returned 4']):
if transient:
status = 'error'
elif any(x in error.lower() for x in ['does not link', 'returned 4']):
status = 'invalid'
else:
status = 'error'
@@ -298,6 +357,22 @@ class WebmentionWorker(threading.Thread):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
if transient:
cursor.execute("""
UPDATE webmentions
SET validation_status = 'valid',
updated_at = CURRENT_TIMESTAMP
WHERE id = ? AND validated_at IS NOT NULL AND validation_error IS NULL
""", (webmention_id,))
if cursor.rowcount:
conn.commit()
conn.close()
logger.warning(
f"Could not re-check webmention, keeping it: "
f"{source_url} -> {target_url}: {error}"
)
return
cursor.execute("""
UPDATE webmentions
SET validation_status = ?,
@@ -418,11 +493,13 @@ class WebmentionWorker(threading.Thread):
conn.commit()
conn.close()
# Send webmention POST
# Send webmention POST (spec 3.1.3)
try:
# SSRF protection for endpoint URL
# SSRF protection for endpoint URL (spec 4.3)
validate_url_for_fetch(endpoint)
# Redirects are not followed: httpx would turn a 301/302 POST
# into a GET without the body
response = httpx.post(
endpoint,
data={
@@ -430,25 +507,24 @@ class WebmentionWorker(threading.Thread):
'target': target_url
},
timeout=10,
headers={'User-Agent': f'StarPunk/1.6.0 (+{self.site_url})'},
follow_redirects=True
headers={'User-Agent': user_agent(self.site_url)},
follow_redirects=False
)
# Check response
# Any 2xx is success (spec 3.1.3)
if 200 <= response.status_code < 300:
# Success
self._mark_send_success(queue_id, source_url, target_url)
elif 400 <= response.status_code < 500:
# Permanent failure (4xx)
error = f"HTTP {response.status_code}: {response.text[:200]}"
self._mark_send_failed(queue_id, source_url, target_url, error)
else:
# Temporary failure (5xx) - retry
elif response.status_code == 429 or response.status_code >= 500:
# Rate limited or server error - retry
error = f"HTTP {response.status_code}: {response.text[:200]}"
self._mark_send_retry(queue_id, source_url, target_url, retry_count, error)
else:
# Permanent failure (3xx, 4xx)
error = f"HTTP {response.status_code}: {response.text[:200]}"
self._mark_send_failed(queue_id, source_url, target_url, error)
except (httpx.TimeoutException, httpx.HTTPError) as e:
# Connection error - retry
self._mark_send_retry(queue_id, source_url, target_url, retry_count, str(e))
@@ -464,100 +540,81 @@ class WebmentionWorker(threading.Thread):
def _discover_endpoint(self, target_url: str) -> Optional[str]:
"""
Discover webmention endpoint for target URL with caching
Discover the webmention endpoint for a target URL (spec 3.1.2)
Per architect's answers to Q3, Q4, Q10:
- GET only (no HEAD)
- Check Link header → <link rel="webmention"> → <a rel="webmention">
- First match wins
- Cache results: 1h for found, 24h for not found
- SSRF protection on target URL
Args:
target_url: Target URL to discover endpoint for
- GET the target, following redirects (each hop SSRF-checked)
- The first Link header with rel=webmention wins, then the first
<link> or <a> with rel=webmention and an href, in document order
- rel is a space-separated token list, matched case-insensitively
- Relative endpoints resolve against the final URL; an empty href
is the target itself; query strings are kept
- Not cached: an updated post must re-discover (spec 3.1.4)
Returns:
Endpoint URL if found, None otherwise
"""
# Check cache first
cached = self._discovery_cache.get(target_url)
if cached and cached['expires_at'] > datetime.utcnow():
logger.debug(f"Using cached endpoint for {target_url}: {cached['endpoint']}")
return cached['endpoint']
Endpoint URL, or None if the target has none (or is blocked/4xx)
# SSRF protection
Raises:
httpx.HTTPError: Network errors and 5xx, so the caller retries
"""
try:
validate_url_for_fetch(target_url)
result = safe_get(target_url, headers={'User-Agent': user_agent(self.site_url)})
except (SSRFBlockedError, ValueError) as e:
logger.warning(f"SSRF protection blocked target {target_url}: {e}")
# Cache negative result
self._cache_endpoint(target_url, None, hours=24)
return None
except FetchTooLargeError:
logger.info(f"Target too large for discovery: {target_url}")
return None
# Fetch target URL
try:
response = httpx.get(
target_url,
timeout=10,
headers={'User-Agent': f'StarPunk/1.6.0 (+{self.site_url})'},
follow_redirects=True
)
response.raise_for_status()
# 1. Check Link header
link_header = response.headers.get('Link', '')
if link_header:
endpoint = self._parse_link_header(link_header, response.url)
if endpoint:
self._cache_endpoint(target_url, endpoint, hours=1)
return endpoint
# 2. Parse HTML for <link> and <a> elements
content_type = response.headers.get('Content-Type', '')
if 'html' in content_type.lower():
endpoint = self._parse_html_for_endpoint(response.text, response.url)
if endpoint:
self._cache_endpoint(target_url, endpoint, hours=1)
return endpoint
# No endpoint found - cache negative result
logger.info(f"No webmention endpoint found for {target_url}")
self._cache_endpoint(target_url, None, hours=24)
if result.status_code >= 500:
raise httpx.HTTPError(f"Target returned {result.status_code}")
if result.status_code >= 400:
logger.info(f"Target returned {result.status_code}: {target_url}")
return None
except Exception as e:
logger.warning(f"Failed to discover endpoint for {target_url}: {e}")
# Don't cache on error - allow retry
return None
for link_header in result.headers.get_list('Link'):
endpoint = self._parse_link_header(link_header, result.url)
if endpoint is not None:
return endpoint
content_type = result.headers.get('Content-Type', '')
if 'html' in content_type.lower():
endpoint = self._parse_html_for_endpoint(result.text, result.url)
if endpoint is not None:
return endpoint
logger.info(f"No webmention endpoint found for {target_url}")
return None
@staticmethod
def _has_webmention_rel(rel: str) -> bool:
return 'webmention' in rel.lower().split()
def _parse_link_header(self, link_header: str, base_url: str) -> Optional[str]:
"""
Parse Link header for webmention endpoint
Parse a Link header (RFC 8288) for a rel=webmention link
Args:
link_header: Raw Link header value
link_header: Link header value (may hold several links)
base_url: Base URL for resolving relative URLs
Returns:
Absolute endpoint URL if found, None otherwise
Absolute endpoint URL of the first match, None otherwise
"""
# Simple parsing - look for rel="webmention"
# Format: <URL>; rel="webmention"
import re
pattern = r'<([^>]+)>\s*;\s*rel\s*=\s*["\']?webmention["\']?'
match = re.search(pattern, link_header, re.IGNORECASE)
if match:
endpoint = match.group(1)
# Make absolute if relative
from urllib.parse import urljoin
return urljoin(base_url, endpoint)
for match in LINK_RE.finditer(link_header):
uri, params = match.group(1), match.group(2)
for param in LINK_PARAM_RE.finditer(params):
if param.group(1).lower() != 'rel':
continue
rel = param.group(2) if param.group(2) is not None else (param.group(3) or '')
if self._has_webmention_rel(rel):
return urljoin(base_url, uri.strip())
break # only the first rel parameter counts (RFC 8288)
return None
def _parse_html_for_endpoint(self, html_content: str, base_url: str) -> Optional[str]:
"""
Parse HTML for webmention endpoint in <link> or <a> elements
Find the first <link> or <a> with rel=webmention, in document order
Args:
html_content: HTML content
@@ -567,48 +624,18 @@ class WebmentionWorker(threading.Thread):
Absolute endpoint URL if found, None otherwise
"""
try:
doc = lxml_html.fromstring(html_content)
# Check <link rel="webmention"> first
links = doc.xpath('//link[@rel="webmention"]/@href')
if links:
from urllib.parse import urljoin
return urljoin(base_url, links[0])
# Check <a rel="webmention">
anchors = doc.xpath('//a[@rel="webmention"]/@href')
if anchors:
from urllib.parse import urljoin
return urljoin(base_url, anchors[0])
doc = lxml_html.document_fromstring(html_content)
except Exception as e:
logger.debug(f"HTML parsing failed: {e}")
return None
for element in doc.iter('link', 'a'):
href = element.get('href')
if href is not None and self._has_webmention_rel(element.get('rel', '')):
return urljoin(base_url, href.strip())
return None
def _cache_endpoint(self, target_url: str, endpoint: Optional[str], hours: int):
"""
Cache endpoint discovery result
Args:
target_url: Target URL
endpoint: Discovered endpoint (None = negative cache)
hours: TTL in hours
"""
self._discovery_cache[target_url] = {
'endpoint': endpoint,
'expires_at': datetime.utcnow() + timedelta(hours=hours)
}
# Optional: Evict old entries (keep cache bounded)
if len(self._discovery_cache) > 1000:
# Remove expired entries
now = datetime.utcnow()
self._discovery_cache = {
k: v for k, v in self._discovery_cache.items()
if v['expires_at'] > now
}
def _mark_send_success(self, queue_id: int, source_url: str, target_url: str):
"""Mark webmention send as successful"""
try:
+3 -2
View File
@@ -136,7 +136,8 @@ small { display: block; margin-top: var(--spacing-xs); color: var(--color-text-l
.button-warning { background: var(--color-warning); color: #333; border-color: var(--color-warning); }
.button-small { padding: 0.25rem 0.5rem; font-size: 0.875rem; }
.admin-container { max-width: 60rem; }
.admin-page { --max-width: 60rem; }
.table-scroll { overflow-x: auto; }
.admin-nav { display: flex; gap: var(--spacing-md); padding: var(--spacing-md); background: var(--color-bg-alt); border-radius: var(--border-radius); margin-bottom: var(--spacing-lg); flex-wrap: wrap; align-items: center; }
.admin-nav .logout-form { margin-left: auto; }
.admin-nav .logout-form button { margin: 0; }
@@ -147,7 +148,7 @@ small { display: block; margin-top: var(--spacing-xs); color: var(--color-text-l
.note-table { width: 100%; border-collapse: collapse; margin-top: var(--spacing-md); }
.note-table th, .note-table td { padding: var(--spacing-md); text-align: left; border-bottom: 1px solid var(--color-border); }
.note-table th { background: var(--color-bg-alt); font-weight: 600; }
.note-content-preview { max-width: 30rem; }
.note-content-preview { min-width: 14rem; overflow-wrap: anywhere; }
.note-excerpt { margin-bottom: var(--spacing-xs); }
.note-slug { color: var(--color-text-light); font-family: var(--font-mono); font-size: 0.75rem; }
.note-date { white-space: nowrap; color: var(--color-text-light); }
+11
View File
@@ -0,0 +1,11 @@
{% extends "base.html" %}
{% block title %}Post Deleted - {{ config.SITE_NAME }}{% endblock %}
{% block content %}
<article class="error-page">
<h1>410 - Post Deleted</h1>
<p>This post has been deleted.</p>
<p><a href="/">Return to homepage</a></p>
</article>
{% endblock %}
+3
View File
@@ -1,5 +1,8 @@
{% extends "base.html" %}
{# Admin pages use a wider frame so tables fit under the header #}
{% block body_class %} class="admin-page"{% endblock %}
{% block content %}
<div class="admin-container">
<nav class="admin-nav">
+2
View File
@@ -21,6 +21,7 @@
</div>
{% if notes %}
<div class="table-scroll">
<table class="note-table">
<thead>
<tr>
@@ -67,6 +68,7 @@
{% endfor %}
</tbody>
</table>
</div>
{# Pagination (v1.6.0) #}
{% if total_pages > 1 %}
+2
View File
@@ -8,6 +8,7 @@
<p>Micropub apps you have approved. Revoke any you no longer use.</p>
{% if tokens %}
<div class="table-scroll">
<table class="note-table">
<thead>
<tr>
@@ -37,6 +38,7 @@
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p>No apps connected.</p>
{% endif %}
+2
View File
@@ -43,6 +43,7 @@
</button>
</div>
<div class="table-scroll">
<table class="webmention-table">
<thead>
<tr>
@@ -85,6 +86,7 @@
{% endfor %}
</tbody>
</table>
</div>
</form>
{# Pagination #}
+1 -1
View File
@@ -27,7 +27,7 @@
{% block head %}{% endblock %}
</head>
<body>
<body{% block body_class %}{% endblock %}>
{% if config.DEV_MODE %}
<div class="dev-mode-warning">
WARNING: DEVELOPMENT MODE - Authentication bypassed
+7 -6
View File
@@ -2,7 +2,7 @@
{% from "partials/media.html" import display_media %}
{% from "partials/reaction.html" import reaction %}
{% block title %}{% if note.content.strip().startswith('#') %}{{ note.title }}{% else %}{{ note.excerpt|truncate(60) }}{% endif %} · {{ config.SITE_NAME }}{% endblock %}
{% 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 content %}
<article class="h-entry">
@@ -18,13 +18,14 @@
{% if note.in_reply_to %}
<div class="reply-context">
<span class="reply-label">In reply to:</span>
<blockquote class="h-cite">
{# u-in-reply-to on the h-cite itself makes it the entry's property (Post Type Discovery) #}
<blockquote class="u-in-reply-to h-cite">
{% if reply_context and reply_context.fetch_status == 'fetched' %}
{% if reply_context.content_snippet %}
<p class="p-content">{{ reply_context.content_snippet }}</p>
{% endif %}
<cite>
<a class="u-in-reply-to" href="{{ note.in_reply_to }}">
<a class="u-url" href="{{ note.in_reply_to }}">
{% if reply_context.author_name %}{{ reply_context.author_name }}{% endif %}
{% if reply_context.site_name %} on {{ reply_context.site_name }}{% endif %}
{% if not reply_context.author_name and not reply_context.site_name %}{{ note.in_reply_to }}{% endif %}
@@ -32,7 +33,7 @@
</cite>
{% else %}
<cite>
<a class="u-in-reply-to" href="{{ note.in_reply_to }}">{{ note.in_reply_to }}</a>
<a class="u-url" href="{{ note.in_reply_to }}">{{ note.in_reply_to }}</a>
</cite>
{% endif %}
</blockquote>
@@ -43,7 +44,7 @@
{# u-photo placement: Per draft spec, u-photo must be direct child of h-entry, #}
{# NOT inside e-content. Media is rendered ABOVE e-content to meet this requirement. #}
{{ display_media(note.media) }}
{{ display_media(note.media, note.excerpt|truncate(150)) }}
{# e-content: note content BELOW media (per ADR-057) #}
<div class="e-content">
@@ -184,7 +185,7 @@
<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|truncate(200) }}</p>
<p>{{ mention.content_snippet|striptags|truncate(200) }}</p>
{% endif %}
</div>
{% endfor %}
+3 -2
View File
@@ -1,11 +1,12 @@
{# Reusable media display macro #}
{% macro display_media(media_items) %}
{# fallback_alt: for photos without a caption, usually the post's text (v2.6.5) #}
{% macro display_media(media_items, fallback_alt='') %}
{% if media_items %}
<div class="note-media">
{% for item in media_items %}
<figure class="media-item">
<img src="{{ url_for('public.media_file', path=item.path) }}"
alt="{{ item.caption or 'Image' }}"
alt="{{ item.caption or fallback_alt or 'Image' }}"
class="u-photo"
loading="lazy">
{# No figcaption - caption is for alt text only #}
+7 -2
View File
@@ -9,9 +9,13 @@
<h2 class="p-name"><a href="{{ absolute_url_for('public.note', slug=note.slug) }}">{{ note.title }}</a></h2>
{% endif %}
{% if note.in_reply_to %}
<p class="reaction reply-to"><span class="reaction-verb">↩ In reply to</span> <a class="u-in-reply-to" href="{{ note.in_reply_to }}">{{ note.in_reply_to }}</a></p>
{% endif %}
{{ reaction(note) }}
{{ display_media(note.media) }}
{{ display_media(note.media, note.excerpt|truncate(150)) }}
{% if has_explicit_title %}
{# Titled notes are articles: show a summary and link through #}
@@ -19,7 +23,8 @@
<p>{{ note.excerpt }}</p>
</div>
<p class="read-more"><a href="{{ absolute_url_for('public.note', slug=note.slug) }}">Read more →</a></p>
{% elif note.html %}
{% else %}
{# Always present, even empty: without it a text-free photo post gets an implied name (mf2) #}
<div class="e-content">
{{ note.html|safe }}
</div>
+2 -2
View File
@@ -118,7 +118,7 @@ class TestUpdate:
def test_categories(self, app, client, h):
url = create(client, h, category=["one", "two"])
self.update(client, h, url, add={"category": ["three", "One"]})
assert source(client, h, url)["properties"]["category"] == ["one", "three", "two"]
assert source(client, h, url)["properties"]["category"] == ["one", "two", "three"] # entered order (v2.6.4)
self.update(client, h, url, delete={"category": ["two"]})
assert source(client, h, url)["properties"]["category"] == ["one", "three"]
self.update(client, h, url, delete=["category"])
@@ -161,7 +161,7 @@ class TestDelete:
url = create(client, h, category=["kept"])
path = url.replace(SITE, "")
assert client.post("/micropub", data={"action": "delete", "url": url}, headers=h).status_code == 204
assert client.get(path).status_code == 404
assert client.get(path).status_code == 410 # Gone (Webmention 3.1.5)
response = client.post("/micropub", json={"action": "undelete", "url": url}, headers=h)
assert response.status_code == 204
assert client.get(path).status_code == 200
+105
View File
@@ -0,0 +1,105 @@
"""
Micropub media fixes (v2.6.5): photo posts without text, the same photo
twice, and failed creates that left a post (and a database lock) behind.
"""
import io
from starpunk.database.pool import ConnectionPool
from starpunk.notes import list_notes
from starpunk.syndication import compose_text
from tests.test_micropub_v240 import SITE, app, client, h, jpeg, note_at, source # noqa: F401
def upload(client, h, color="red"):
response = client.post("/micropub/media", data={"file": (io.BytesIO(jpeg(color)), "a.jpg")},
headers=h, content_type="multipart/form-data")
assert response.status_code == 201
return response.headers["Location"]
def post(client, h, props):
return client.post("/micropub", json={"type": ["h-entry"], "properties": props}, headers=h)
def update(client, h, url, **ops):
return client.post("/micropub", json={"action": "update", "url": url, **ops}, headers=h)
class TestPhotoWithoutText:
def test_json_photo_only(self, app, client, h):
photo = upload(client, h)
response = post(client, h, {"photo": [{"value": photo, "alt": "Red"}]})
assert response.status_code == 201, response.get_json()
url = response.headers["Location"]
assert note_at(app, url).content == ""
assert source(client, h, url, "photo")["properties"]["photo"] == [{"value": photo, "alt": "Red"}]
page = client.get(url.replace(SITE, ""))
assert page.status_code == 200 and b"<title>Photo \xc2\xb7 " in page.data
def test_multipart_photo_only(self, client, h):
response = client.post("/micropub", data={"h": "entry", "photo": (io.BytesIO(jpeg()), "p.jpg")},
headers=h, content_type="multipart/form-data")
assert response.status_code == 201, response.get_json()
def test_nothing_at_all_is_still_rejected(self, client, h):
assert post(client, h, {}).status_code == 400
# A photo that can't be found doesn't count
assert post(client, h, {"photo": [f"{SITE}/media/nope.jpg"]}).status_code == 400
def test_text_can_be_cleared_while_photos_remain(self, app, client, h):
photo = upload(client, h)
url = post(client, h, {"content": ["Hi"], "photo": [photo]}).headers["Location"]
assert update(client, h, url, replace={"content": [""]}).status_code == 204
assert note_at(app, url).content == ""
assert update(client, h, url, replace={"content": ["Back"]}).status_code == 204
assert update(client, h, url, delete=["content"]).status_code == 204
assert note_at(app, url).content == ""
# Without photos the text has to stay
response = update(client, h, url, delete=["content", "photo"])
assert response.status_code == 400
def test_text_is_required_without_photos(self, client, h):
url = post(client, h, {"content": ["Hi"]}).headers["Location"]
assert update(client, h, url, replace={"content": [""]}).status_code == 400
assert update(client, h, url, delete=["content"]).status_code == 400
def test_crosspost_text_starts_with_the_link(self, app, client, h):
url = post(client, h, {"photo": [upload(client, h)]}).headers["Location"]
with app.app_context():
note = note_at(app, url)
assert compose_text(note, url, ["cats"], 500) == f"{url}\n\n#cats"
class TestFailures:
def test_same_photo_twice_is_shown_once(self, client, h):
photo = upload(client, h)
response = post(client, h, {"content": ["Twice"], "photo": [photo, photo]})
assert response.status_code == 201, response.get_json()
assert source(client, h, response.headers["Location"], "photo")["properties"]["photo"] == [{"value": photo, "alt": ""}]
def test_failed_create_leaves_no_post_and_no_lock(self, app, client, h, monkeypatch):
import starpunk.syndication as syndication
def boom(*args, **kwargs):
raise RuntimeError("crosspost store down")
monkeypatch.setattr(syndication, "select_targets", boom)
response = post(client, h, {"content": ["Doomed"], "photo": [upload(client, h)]})
assert response.status_code == 500
with app.app_context():
assert list_notes(published_only=False) == []
monkeypatch.undo()
# The database is usable straight away
assert post(client, h, {"content": ["Next"]}).status_code == 201
def test_pool_rolls_back_open_transactions(self, tmp_path):
pool = ConnectionPool(str(tmp_path / "x.db"), pool_size=1, timeout=1)
conn = pool.get_connection()
conn.execute("CREATE TABLE t (x)")
conn.commit()
conn.execute("INSERT INTO t VALUES (1)")
assert conn.in_transaction
pool.return_connection(conn)
assert not conn.in_transaction
assert pool.get_connection().execute("SELECT count(*) FROM t").fetchone()[0] == 0
+98
View File
@@ -0,0 +1,98 @@
"""
Rendered posts read as the right post type (v2.6.5).
Parses note pages and the home page with mf2py, then runs W3C Post Type
Discovery (https://www.w3.org/TR/post-type-discovery/) on what a consumer
sees. A photo post is any post with a photo, unless it's first a repost,
like or reply.
"""
import pytest
import mf2py
import starpunk.reply_context as reply_context
from tests.test_micropub_v240 import SITE, app, client, h, jpeg # noqa: F401
from tests.test_micropub_v265 import upload
def post_type(props):
"""W3C Post Type Discovery, section 5 (no events or RSVPs here)."""
for prop, kind in [("repost-of", "repost"), ("like-of", "like"), ("in-reply-to", "reply"),
("video", "video"), ("photo", "photo")]:
if props.get(prop):
return kind
def first(prop):
for v in props.get(prop, []):
v = v.get("value", "") if isinstance(v, dict) else v
if v.strip():
return " ".join(v.split())
return ""
content = first("content") or first("summary")
name = first("name")
if not content or not name or content.startswith(name):
return "note"
return "article"
def entries(items):
for item in items:
if "h-entry" in item.get("type", []):
yield item
yield from entries(item.get("children", []))
def value(v):
"""A u-* value, or the url of a nested microformat (h-cite)."""
return v.get("value") or v.get("properties", {}).get("url", [None])[0] if isinstance(v, dict) else v
CASES = {
"note": ({"content": ["Just a note"]}, "note"),
"article": ({"name": ["A Title"], "content": ["Body text here"]}, "article"),
"photo without text": ({"photo": ["PHOTO"]}, "photo"),
"photo with caption": ({"content": ["Sunset"], "photo": [{"value": "PHOTO", "alt": "Orange sky"}]}, "photo"),
"photo with title": ({"name": ["Trip"], "content": ["Day one"], "photo": ["PHOTO"]}, "photo"),
"reply": ({"content": ["Agreed"], "in-reply-to": ["https://other.example/post/1"]}, "reply"),
"reply with photo": ({"content": ["Mine"], "in-reply-to": ["https://other.example/post/2"],
"photo": ["PHOTO"]}, "reply"),
"repost": ({"repost-of": ["https://other.example/post/4"]}, "repost"),
}
@pytest.mark.parametrize("case", CASES)
def test_post_type(app, client, h, monkeypatch, case):
monkeypatch.setattr(reply_context, "fetch_reply_context", lambda *a, **k: None, raising=False)
props, want = CASES[case]
photo = upload(client, h) if "PHOTO" in str(props) else None
props = {k: [photo if v == "PHOTO" else ({**v, "value": photo} if isinstance(v, dict) else v)
for v in vs] for k, vs in props.items()}
response = client.post("/micropub", json={"type": ["h-entry"], "properties": props}, headers=h)
assert response.status_code == 201, response.get_json()
url = response.headers["Location"]
(entry,) = entries(mf2py.parse(doc=client.get(url.replace(SITE, "")).data.decode(), url=url)["items"])
home = mf2py.parse(doc=client.get("/").data.decode(), url=f"{SITE}/")
(listed,) = [e for e in entries(home["items"]) if e["properties"].get("url") == [url]]
for e in (entry, listed):
assert post_type(e["properties"]) == want
if want == "reply":
assert value(e["properties"]["in-reply-to"][0]) == props["in-reply-to"][0]
if want == "photo" and "name" not in props:
assert "name" not in e["properties"], "no implied name to show as a caption"
def test_photo_alt_text(app, client, h):
"""Alt text is the caption, else the post's text, never made up (v2.6.5)."""
def alts(props):
url = client.post("/micropub", json={"type": ["h-entry"], "properties": props},
headers=h).headers["Location"]
(entry,) = entries(mf2py.parse(doc=client.get(url.replace(SITE, "")).data.decode(), url=url)["items"])
return [p["alt"] for p in entry["properties"]["photo"]]
assert alts({"content": ["Beach day"], "photo": [{"value": upload(client, h), "alt": "Waves"}]}) == ["Waves"]
assert alts({"content": ["Beach day"], "photo": [upload(client, h, "blue")]}) == ["Beach day"]
assert alts({"name": ["Trip"], "content": ["Day one"], "photo": [upload(client, h, "green")]}) == ["Day one"]
assert alts({"photo": [upload(client, h, "gray")]}) == ["Image"]
+47
View File
@@ -32,6 +32,7 @@ class FakeServer:
self.statuses = {}
self.calls = []
self.media = 0
self.uploads = [] # raw multipart bodies
self.fail_next = None # status code to return once
def __call__(self, request: httpx.Request) -> httpx.Response:
@@ -43,6 +44,7 @@ class FakeServer:
path = request.url.path
if path == "/api/v2/media":
self.media += 1
self.uploads.append(request.read())
return httpx.Response(200, json={"id": f"m{self.media}"})
if path == "/api/v1/statuses" and request.method == "POST":
body = json.loads(request.content)
@@ -271,6 +273,51 @@ class TestMedia:
assert server.statuses["1"]["media_ids"] == ["m1"]
class TestInlineImages:
"""Clients like OutPost upload a photo and embed it in the content (v2.6.6)"""
def _upload(self, app):
from starpunk.media import save_media
buf = io.BytesIO()
Image.new("RGB", (800, 600), "orange").save(buf, format="JPEG")
with app.test_request_context():
return save_media(buf.getvalue(), "cat.jpg")
def test_embedded_own_image_is_attached(self, app, server):
media = self._upload(app)
url = f"https://blog.example.com/media/{media['path']}"
publish(app, content=f"![Tortie cat on a chair]({url})")
status = server.statuses["1"]
assert status["media_ids"] == ["m1"]
assert b"Tortie cat on a chair" in server.uploads[0]
assert "![" not in status["status"] and url not in status["status"]
assert status["status"].startswith("https://blog.example.com/note/")
def test_text_around_image_is_kept(self, app, server):
media = self._upload(app)
publish(app, content=f"Look\n\n<img src=\"/media/{media['path']}\" alt=\"cat\">\n\nNice")
status = server.statuses["1"]
assert status["media_ids"] == ["m1"]
assert status["status"].startswith("Look\n\nNice")
def test_image_both_attached_and_embedded_is_sent_once(self, app, server):
from starpunk.media import attach_media_to_note
media = self._upload(app)
with app.test_request_context():
note = create_note(content=f"![x](/media/{media['path']})", published=True)
attach_media_to_note(note.id, [media["id"]], ["caption"])
select_targets(note.id, ["gotosocial"])
process_due()
assert server.statuses["1"]["media_ids"] == ["m1"]
def test_other_sites_images_are_ignored(self, app, server):
publish(app, content="![x](https://elsewhere.example/cat.jpg) hi")
assert server.statuses["1"]["media_ids"] == []
assert server.uploads == []
class TestEntryPoints:
@pytest.fixture
def admin(self, app):
+86
View File
@@ -0,0 +1,86 @@
"""
Tags keep the order they were entered in (v2.6.4)
Public pages list tags alphabetically; crossposts (the Threads topic, which
tags fit on Bluesky), the editor and Micropub use the entered order, and
saving from the editor or Micropub keeps it.
"""
import pytest
from starpunk import create_app
from starpunk.auth import create_session
from starpunk.indieauth import create_access_token
from starpunk.notes import create_note, get_note
from starpunk.tags import get_note_tags
ENTERED = ["Zebra", "apple", "Mango"]
@pytest.fixture
def app(tmp_path):
data = tmp_path / "data"
data.mkdir()
yield create_app(config={
"TESTING": True, "DATABASE_PATH": data / "starpunk.db", "DATA_PATH": data,
"NOTES_PATH": data / "notes", "SESSION_SECRET": "s", "ADMIN_ME": "https://test.example.com",
"SITE_URL": "http://localhost:5000", "DEV_MODE": False,
})
@pytest.fixture
def note(app):
with app.test_request_context():
return create_note(content="Tagged", published=True, tags=ENTERED)
def names(app, note_id, **kw):
with app.app_context():
return [t["display_name"] for t in get_note_tags(note_id, **kw)]
def test_alphabetical_by_default_entered_on_request(app, note):
assert names(app, note.id) == ["apple", "Mango", "Zebra"]
assert names(app, note.id, entered_order=True) == ENTERED
def test_public_page_stays_alphabetical(app, note):
html = app.test_client().get(f"/note/{note.slug}").data.decode()
assert html.index(">apple<") < html.index(">Mango<") < html.index(">Zebra<")
def test_editor_shows_and_keeps_entered_order(app, note):
client = app.test_client()
with app.test_request_context():
client.set_cookie("starpunk_session", create_session("https://test.example.com"))
html = client.get(f"/admin/edit/{note.id}").data.decode()
assert 'value="Zebra, apple, Mango"' in html
# Saving the form unchanged keeps the order
response = client.post(f"/admin/edit/{note.id}", data={
"content": "Tagged, edited", "published": "on", "tags": "Zebra, apple, Mango"})
assert response.status_code in (200, 302)
assert names(app, note.id, entered_order=True) == ENTERED
def test_micropub_source_and_update_keep_entered_order(app, note):
with app.test_request_context():
token = create_access_token("https://quill.example/", "create update")["access_token"]
client = app.test_client()
auth = {"Authorization": f"Bearer {token}"}
url = f"http://localhost:5000/note/{note.slug}"
source = client.get(f"/micropub?q=source&url={url}", headers=auth).get_json()
assert source["properties"]["category"] == ENTERED
response = client.post("/micropub", headers=auth, json={
"action": "update", "url": url, "add": {"category": ["Kiwi"]}})
assert response.status_code in (200, 204), response.get_data(as_text=True)
assert names(app, note.id, entered_order=True) == ENTERED + ["Kiwi"]
def test_crossposts_use_entered_order(app, note):
from starpunk.syndication import compose_text, threads_topic
tags = names(app, note.id, entered_order=True)
assert threads_topic(tags) == "Zebra"
with app.app_context():
text = compose_text(get_note(id=note.id, load_content=True),
"https://x.example/note/1", tags, 25)
assert "#Zebra" in text and "#Mango" not in text # room for the first tags only
+283
View File
@@ -0,0 +1,283 @@
"""
W3C Webmention conformance tests (v2.7.0)
https://www.w3.org/TR/webmention/ — section numbers in test names.
"""
import sqlite3
from unittest.mock import patch
import httpx
import pytest
from starpunk import webmention_ssrf
from starpunk.webmention_processor import (
TransientError, ValidationError, fetch_source, verify_link_presence,
)
from starpunk.webmention_worker import WebmentionWorker
PUBLIC = [(2, 1, 6, '', ('93.184.216.34', 0))]
BASE = 'https://t.example/test/1?x=1'
@pytest.fixture
def worker(app):
return WebmentionWorker(app, db_path=app.config["DATABASE_PATH"],
site_url=app.config["SITE_URL"])
@pytest.fixture
def mock_web():
"""Route safe_get through a MockTransport; all hosts resolve public"""
routes = {}
def handler(request):
return routes[str(request.url)](request)
with patch("starpunk.webmention_ssrf.socket.getaddrinfo", return_value=PUBLIC), \
patch("starpunk.webmention_ssrf.TRANSPORT", httpx.MockTransport(handler)):
yield routes
# 3.1.2 Sender discovers receiver Webmention endpoint
@pytest.mark.parametrize("header,expected", [
('<https://e.example/wm>; rel="webmention"', 'https://e.example/wm'),
('</wm>; rel=webmention', 'https://t.example/wm'),
('<wm>; rel="other webmention"', 'https://t.example/test/wm'),
('<wm>; title="a;b,c"; rel="webmention"', 'https://t.example/test/wm'),
('<wm>; REL="WebMention"', 'https://t.example/test/wm'),
('<a>; rel="other", </wm?q=1>; rel="webmention"', 'https://t.example/wm?q=1'),
('<x>; rel="webmention-not"', None),
('<x>; rel="not-webmention"', None),
])
def test_3_1_2_link_header(worker, header, expected):
assert worker._parse_link_header(header, BASE) == expected
@pytest.mark.parametrize("html,expected", [
# <a> before <link>: first in document order wins
('<a rel="webmention" href="/a">x</a><link rel="webmention" href="/l">', 'https://t.example/a'),
('<link rel="webmention somethingelse" href="/l">', 'https://t.example/l'),
('<link rel="Webmention" href="/l">', 'https://t.example/l'),
# empty href is the target itself
('<link rel="webmention" href="">', BASE),
# no href: skipped
('<link rel="webmention"><a rel="webmention" href="/a">', 'https://t.example/a'),
# comments, escaped markup and other rels are ignored
('<!-- <link rel="webmention" href="/bad"> -->'
'<a rel="not-webmention" href="/bad"></a>'
'<code>&lt;a rel="webmention" href="/bad"&gt;</code>'
'<link rel="webmention" href="/ok">', 'https://t.example/ok'),
('<p>nothing</p>', None),
])
def test_3_1_2_html(worker, html, expected):
assert worker._parse_html_for_endpoint(html, BASE) == expected
def test_3_1_2_header_before_html_and_relative_to_final_url(app, worker, mock_web):
mock_web['https://t.example/old'] = lambda r: httpx.Response(
301, headers={'Location': 'https://t.example/new/page'})
mock_web['https://t.example/new/page'] = lambda r: httpx.Response(
200, headers={'Link': '<wm>; rel="webmention"', 'Content-Type': 'text/html'},
text='<link rel="webmention" href="/html">')
with app.app_context():
assert worker._discover_endpoint('https://t.example/old') == 'https://t.example/new/wm'
def test_3_1_2_multiple_link_headers(app, worker, mock_web):
mock_web['https://t.example/p'] = lambda r: httpx.Response(
200, headers=[('Link', '</other>; rel="other"'), ('Link', '</wm>; rel="webmention"')])
with app.app_context():
assert worker._discover_endpoint('https://t.example/p') == 'https://t.example/wm'
def test_3_1_2_server_error_is_retried_not_final(app, worker, mock_web):
mock_web['https://t.example/p'] = lambda r: httpx.Response(503)
with app.app_context(), pytest.raises(httpx.HTTPError):
worker._discover_endpoint('https://t.example/p')
# 4.5 SSRF: every redirect hop is checked
def test_4_5_redirect_to_private_address_blocked(app):
def resolve(host, *a, **k):
ip = '169.254.169.254' if host == 'metadata.internal' else '93.184.216.34'
return [(2, 1, 6, '', (ip, 0))]
def handler(request):
return httpx.Response(302, headers={'Location': 'http://metadata.internal/'})
with app.app_context(), \
patch("starpunk.webmention_ssrf.socket.getaddrinfo", side_effect=resolve), \
patch("starpunk.webmention_ssrf.TRANSPORT", httpx.MockTransport(handler)):
with pytest.raises(ValidationError, match="Blocked"):
fetch_source('https://evil.example/', 'http://localhost:5000')
@pytest.mark.parametrize("ip", [
'127.0.0.1', '10.1.2.3', '169.254.169.254', '0.0.0.0', '100.64.0.1',
'::1', '::ffff:127.0.0.1', 'fe80::1', '224.0.0.1',
])
def test_4_5_blocked_addresses(ip):
assert webmention_ssrf.is_private_ip(ip)
def test_4_5_any_blocked_address_blocks(app):
mixed = PUBLIC + [(10, 1, 6, '', ('::1', 0, 0, 0))]
with app.app_context(), patch("starpunk.webmention_ssrf.socket.getaddrinfo", return_value=mixed):
with pytest.raises(webmention_ssrf.SSRFBlockedError):
webmention_ssrf.validate_url_for_fetch('https://x.example/')
# 3.2.2 Webmention verification
TARGET = 'https://me.example/note/abc'
@pytest.mark.parametrize("content,content_type,expected", [
('<a href="/note/abc#c">x</a>', 'text/html', True),
('<img src="https://me.example/note/abc">', 'text/html; charset=utf-8', True),
('<a href="https://me.example/note/abcdef">x</a>', 'text/html', False),
('<p>https://me.example/note/abc</p>', 'text/html', False),
('<!-- <a href="https://me.example/note/abc"> -->', 'text/html', False),
('{"a": ["https://me.example/note/abc"]}', 'application/json', True),
('{"a": "https://me.example/note/abcdef"}', 'application/json', False),
('see https://me.example/note/abc', 'text/plain', True),
])
def test_3_2_2_exact_match(content, content_type, expected):
assert verify_link_presence(content, TARGET, content_type, 'https://me.example/x') is expected
def test_3_2_2_accept_header_and_status(app, mock_web):
seen = {}
def page(request):
seen['accept'] = request.headers.get('Accept')
return httpx.Response(410)
mock_web['https://s.example/p'] = page
with app.app_context():
with pytest.raises(ValidationError, match="410"):
fetch_source('https://s.example/p', 'http://localhost:5000')
assert 'text/html' in seen['accept']
mock_web['https://s.example/p'] = lambda r: httpx.Response(500)
with app.app_context(), pytest.raises(TransientError):
fetch_source('https://s.example/p', 'http://localhost:5000')
# 3.2.1 Request verification
def _post(client, source, target):
return client.post('/webmention', data={'source': source, 'target': target})
def test_3_2_1_target_must_be_a_note(app, client, sample_note):
note_url = f"http://localhost:5000/note/{sample_note.slug}"
assert _post(client, 'https://s.example/a', note_url).status_code == 202
assert _post(client, 'https://s.example/a', 'http://localhost:5000/nope').status_code == 400
assert _post(client, 'https://s.example/a', 'http://localhost:5000/').status_code == 400
assert _post(client, 'https://s.example/a', 'https://other.example/note/x').status_code == 400
assert _post(client, note_url, note_url).status_code == 400
assert _post(client, 'ftp://s.example/a', note_url).status_code == 400
def test_3_2_1_host_case_and_fragment(app, client, sample_note):
note_url = f"http://LOCALHOST:5000/note/{sample_note.slug}"
assert _post(client, 'https://s.example/a', note_url + '#one').status_code == 202
assert _post(client, 'https://s.example/a', note_url + '#two').status_code == 202
db = sqlite3.connect(app.config['DATABASE_PATH'])
rows = db.execute("SELECT target_url FROM webmentions").fetchall()
assert rows == [(note_url,)]
# 3.2.4 Updating existing Webmentions
def _insert_mention(app, note_id, **cols):
db = sqlite3.connect(app.config['DATABASE_PATH'])
fields = {'source_url': 'https://s.example/a', 'target_url': 'http://localhost:5000/n',
'target_note_id': note_id, **cols}
db.execute(f"INSERT INTO webmentions ({', '.join(fields)}) VALUES ({', '.join('?' * len(fields))})",
tuple(fields.values()))
db.commit()
return db
VALID = {'valid': True, 'mention_type': 'reply', 'author_name': 'A', 'author_url': 'https://a.example/',
'author_photo': None, 'content_snippet': 'hi'}
def test_3_2_4_update_keeps_moderation(app, worker, sample_note):
db = _insert_mention(app, sample_note.id, validation_status='valid', moderation_status='hidden',
validated_at='2026-01-01')
with patch("starpunk.webmention_worker.process_webmention", return_value=VALID):
worker._validate_webmention(1, 'https://s.example/a', 'http://localhost:5000/n', sample_note.id)
assert db.execute("SELECT validation_status, moderation_status FROM webmentions").fetchone() == ('valid', 'hidden')
def test_3_2_4_new_mention_gets_default_moderation(app, worker, sample_note):
db = _insert_mention(app, sample_note.id)
with patch("starpunk.webmention_worker.process_webmention", return_value=VALID):
worker._validate_webmention(1, 'https://s.example/a', 'http://localhost:5000/n', sample_note.id)
assert db.execute("SELECT validation_status, moderation_status FROM webmentions").fetchone() == ('valid', 'approved')
def test_3_2_4_transient_error_keeps_valid_mention(app, worker, sample_note):
db = _insert_mention(app, sample_note.id, validation_status='pending', moderation_status='approved',
validated_at='2026-01-01', content_snippet='kept')
with patch("starpunk.webmention_worker.process_webmention", side_effect=TransientError("timeout")):
worker._validate_webmention(1, 'https://s.example/a', 'http://localhost:5000/n', sample_note.id)
assert db.execute("SELECT validation_status, content_snippet FROM webmentions").fetchone() == ('valid', 'kept')
def test_3_2_4_gone_source_removes_mention(app, worker, sample_note):
db = _insert_mention(app, sample_note.id, validation_status='pending', moderation_status='approved',
validated_at='2026-01-01')
with patch("starpunk.webmention_worker.process_webmention",
side_effect=ValidationError("Source returned 410")):
worker._validate_webmention(1, 'https://s.example/a', 'http://localhost:5000/n', sample_note.id)
assert db.execute("SELECT validation_status FROM webmentions").fetchone() == ('invalid',)
# 3.1.4 Updated posts / 3.1.5 Deleted posts
def _queue(app):
db = sqlite3.connect(app.config['DATABASE_PATH'])
return db.execute(
"SELECT target_url, status, source_note_id FROM webmention_queue ORDER BY target_url"
).fetchall()
def _sent(app):
db = sqlite3.connect(app.config['DATABASE_PATH'])
db.execute("UPDATE webmention_queue SET status = 'sent'")
db.commit()
def test_3_1_4_update_resends_previous_targets(app):
from starpunk.notes import create_note, update_note
with app.test_request_context():
note = create_note("Reply", published=True, in_reply_to="https://a.example/post")
_sent(app)
update_note(id=note.id, content="Now about [b](https://b.example/x)", in_reply_to="")
targets = {t: s for t, s, _ in _queue(app)}
assert targets == {'https://a.example/post': 'pending', 'https://b.example/x': 'pending'}
@pytest.mark.parametrize("soft", [True, False])
def test_3_1_5_delete_resends_and_returns_410(app, client, soft):
from starpunk.notes import create_note, delete_note
with app.test_request_context():
note = create_note("See [a](https://a.example/x)", published=True)
_sent(app)
delete_note(id=note.id, soft=soft)
rows = _queue(app)
assert [(t, s) for t, s, _ in rows] == [('https://a.example/x', 'pending')]
if not soft:
assert rows[0][2] is None # detached, so it survives the delete
assert client.get(f"/note/{note.slug}").status_code == 410
assert client.get("/note/never-existed").status_code == 404
+131
View File
@@ -0,0 +1,131 @@
"""
Webmention worker regression tests (v2.6.8)
The worker thread used Flask's current_app (via the SSRF checks) without an
app context, so every send and validation failed. It was also stopped
whenever any app context ended.
"""
import sqlite3
import httpx
import time
from unittest.mock import MagicMock, patch
from starpunk.webmention_worker import WebmentionWorker
PUBLIC = [(2, 1, 6, '', ('93.184.216.34', 0))]
def _wait_for(predicate, timeout=5):
deadline = time.time() + timeout
while time.time() < deadline:
if predicate():
return True
time.sleep(0.05)
return False
def test_worker_sends_queued_webmention(app):
db_path = app.config["DATABASE_PATH"]
conn = sqlite3.connect(db_path)
conn.execute(
"INSERT INTO webmention_queue (source_url, target_url, status) "
"VALUES (?, ?, 'pending')",
("http://localhost:5000/note/1", "https://example.org/post"),
)
conn.commit()
conn.close()
def target_site(request):
return httpx.Response(200, headers={"Link": '</wm>; rel="webmention"'})
accepted = MagicMock(status_code=202, text="")
worker = WebmentionWorker(app, db_path=db_path, site_url=app.config["SITE_URL"],
poll_interval=0.05)
with patch("starpunk.webmention_ssrf.socket.getaddrinfo", return_value=PUBLIC), \
patch("starpunk.webmention_ssrf.TRANSPORT", httpx.MockTransport(target_site)), \
patch("starpunk.webmention_worker.httpx.post", return_value=accepted) as post:
worker.start()
try:
def status():
c = sqlite3.connect(db_path)
row = c.execute("SELECT status, last_error FROM webmention_queue").fetchone()
c.close()
return row
assert _wait_for(lambda: status()[0] != "pending"), status()
assert status() == ("sent", None)
post.assert_called_once()
assert post.call_args.args[0] == "https://example.org/wm"
finally:
worker.stop()
worker.join(timeout=2)
def test_worker_survives_app_context_teardown(app):
worker = WebmentionWorker(app, db_path=app.config["DATABASE_PATH"],
site_url=app.config["SITE_URL"], poll_interval=0.05)
worker.start()
try:
with app.app_context():
pass
app.test_client().get("/")
time.sleep(0.2)
assert worker.is_alive()
finally:
worker.stop()
worker.join(timeout=2)
def test_only_one_worker_processes_queues(app):
"""Each gunicorn process starts a worker; only one may hold the queue lock"""
kwargs = dict(db_path=app.config["DATABASE_PATH"], site_url=app.config["SITE_URL"])
first = WebmentionWorker(app, **kwargs)
second = WebmentionWorker(app, **kwargs)
try:
assert first._acquire_lock()
assert not second._acquire_lock()
first._release_lock()
assert second._acquire_lock()
finally:
first._release_lock()
second._release_lock()
def test_author_photo_with_alt_text_is_a_string():
"""mf2py returns u-photo with alt as a dict; the database needs a URL string"""
import mf2py
from starpunk.webmention_processor import extract_author
html = """
<div class="h-entry">
<span class="p-author h-card">
<a class="u-url p-name" href="https://a.example/">A Person</a>
<img class="u-photo" src="https://a.example/me.jpg" alt=""></span>
<a href="https://site.example/note/1">target</a>
</div>"""
author = extract_author(mf2py.parse(doc=html, url="https://src.example/"),
"https://src.example/")
assert author == {
"author_name": "A Person",
"author_url": "https://a.example/",
"author_photo": "https://a.example/me.jpg",
}
def test_author_urls_must_be_http():
"""A javascript: author URL would be rendered as a clickable link (XSS)"""
import mf2py
from starpunk.webmention_processor import extract_author
html = """
<div class="h-entry">
<span class="p-author h-card">
<a class="u-url p-name" href="javascript:alert(1)">Evil</a>
<img class="u-photo" src="data:image/svg+xml,x" alt=""></span>
</div>"""
author = extract_author(mf2py.parse(doc=html, url="https://src.example/"),
"https://src.example/")
assert author["author_url"] == "https://src.example/"
assert author["author_photo"] is None