docs: Bring all documentation up to date for v2.10.1

- architecture/: overview, technology stack, auth (OIDC + built-in
  IndieAuth), syndication (POSSE) rewritten; new database.md,
  deployment.md and indieweb-protocols.md; legacy stack marked historical
- decisions/: reconstructed ADR-060 and ADR-063; 31 status corrections
  (superseded auth ADRs, proposed -> accepted); INDEX rebuilt
- design/: reconstructed the v1.6.0 documents the webmention code cites;
  reports for 18 v2 releases without a design folder; INDEX rebuilt
- projectplan/: BACKLOG rewritten (shipped items removed, open issues from
  the reviews added); RELEASE.md for v2.0.0-v2.10.1; INDEX
- standards/: development setup (uv, tests, DEV_MODE), testing (CI test
  stage), git and release flow, versioning, coding standards, cookies
- README, CLAUDE.md, .env.example (every setting the code reads, with
  defaults) brought up to date
- 137 broken links repaired (old absolute paths, moved files); stale ADR
  references in code comments corrected (comments only)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
PhilandClaude Opus 5.5 committed 2026-11-03 12:40:19 -07:00
1 parent fa551de197
commit 0716984958
143 files changed
+6222 -8660

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
# v1.6.0 Design: Webmention API Contract
> Reconstructed on 2026-11-03 from the implementation; the original v1.6.0 document was lost. Later changes: v2.6.8–v2.7.2 (see CHANGELOG).
> This describes the code as of v2.10.1 (`starpunk/routes/webmention.py`, `starpunk/webmention_processor.py`, `starpunk/__init__.py`).
Related: ADR-063, [background-worker.md](background-worker.md),
[rate-limiting.md](rate-limiting.md), W3C Webmention (https://www.w3.org/TR/webmention/).
## Endpoint discovery (what we advertise)
- Every `text/html` response gets `Link: </webmention>; rel="webmention"`
when `WEBMENTION_ENABLED` (default true). It is added alongside other
`Link` headers (v2.7.0; it used to replace them, e.g. the WebSub links).
- The endpoint URL is relative to the site root.
## `POST /webmention` (receiving)
Blueprint `webmention`, no authentication.
### Request
- `application/x-www-form-urlencoded` (spec) with `source` and `target`.
- `application/json` with the same keys is accepted as an extension.
### Processing order
1. **Rate limit** (`before_request`, POST only): see
[rate-limiting.md](rate-limiting.md). 429 if exceeded.
2. `source` and `target` present.
3. Both are http(s) URLs with a host, at most 2,048 characters.
4. `source != target`.
5. Target host and effective port equal `SITE_URL`'s (host compared
case-insensitively, default ports filled in; v2.7.0).
6. The fragment is removed from `target` (spec 3.2.1), so `#a` and `#b` are
one mention.
7. Target must be a published note: path `/note/<slug>` resolving to a
published note. Anything else (home page, tag pages, drafts, unknown
slugs) is refused (v2.7.0; before, such mentions were stored but never
shown).
8. UPSERT into `webmentions` on `(source_url, target_url)`: a new row is
`pending`/`pending`; an existing row is set back to
`validation_status = 'pending'` (an update or removal, spec 3.2.4),
keeping its moderation status.
All fetching happens later in the worker (spec 3.2: asynchronous
verification).
### Responses (JSON)
| Status | Body | When |
|---|---|---|
| 202 | `{"status": "accepted", "message": "Webmention queued for verification"}` | Stored |
| 400 | `{"error": "invalid_request", "error_description": "Missing required parameter: source"}` (or `target`) | Missing parameter |
| 400 | `invalid_request` / "Source must be a valid URL", "Target must be a valid URL" | Bad URL |
| 400 | `invalid_request` / "Source and target must be different" | Same URL |
| 400 | `invalid_target` / "Target URL is not on this site" | Other host |
| 400 | `invalid_target` / "Target URL does not accept webmentions" | Not a published note |
| 429 | `rate_limit_exceeded` with `Retry-After` | Rate limited |
| 500 | `server_error` / "Failed to queue webmention" | Database error |
## `GET /webmention`
Returns `{"name": "Webmention endpoint", "spec": "https://www.w3.org/TR/webmention/"}`.
Not rate limited.
## Deleted targets
A soft-deleted note's page answers **410 Gone** ("This post has been
deleted", v2.7.0), so senders can tell the post is gone. New webmentions to
it are refused (step 7).
## Content sanitisation (stored snippets)
`webmention_processor.sanitize_content()` uses `nh3`:
- Allowed tags: `p, br, strong, em, b, i, a, code, pre, blockquote`.
- Allowed attributes: `a[href]`; nh3 adds `rel="nofollow noopener"` to links
(the original contract listed `a[href, rel]`; `rel` is set by nh3 rather
than passed through).
- Snippets are cut to ~500 characters and sanitised again so a cut never
leaves a tag open (v2.7.0).
- Author URL and photo are stored only if http(s) (v2.6.9); everything is
rendered through Jinja autoescaping except the sanitised snippet.
## Extracted fields
`process_webmention()` returns: `mention_type` (`reply`, `like`, `repost`,
`bookmark`, `mention`), `author_name`, `author_url`, `author_photo`,
`content_snippet`, `source_post_url`, `source_uid`, `source_published`
(RFC 3339 UTC). See [background-worker.md](background-worker.md) for how
each is derived and [database-schema.md](database-schema.md) for storage.
## Sending (our requests to others)
- Endpoint discovery and POST as in [background-worker.md](background-worker.md).
- Body: `source=<note permalink>&target=<url>`, form-encoded.
- `User-Agent: StarPunk/<version> Webmention (+<SITE_URL>)`.
- Any 2xx is success; redirects from the endpoint are not followed and
count as failure (v2.7.0).
+196
View File
@@ -0,0 +1,196 @@
# v1.6.0 Design: Webmention Background Worker
> Reconstructed on 2026-11-03 from the implementation; the original v1.6.0 document was lost. Later changes: v2.6.8–v2.7.2 (see CHANGELOG).
> Also affected by v2.8.0 (source details, authorship, own-crosspost filter) and v2.10.1 (hard time limit on fetches). This describes the code as of v2.10.1.
Related: ADR-063 (Webmention implementation), [api-contract.md](api-contract.md),
[database-schema.md](database-schema.md), [rate-limiting.md](rate-limiting.md),
[display-moderation.md](display-moderation.md).
## Purpose
Webmention work that involves fetching remote URLs never happens inside a
request. `POST /webmention` only stores a row; a background thread validates
incoming webmentions and sends outgoing ones.
## Modules
| Module | Role |
|---|---|
| `starpunk/webmention_worker.py` | `WebmentionWorker` thread: queue loop, validation bookkeeping, endpoint discovery, sending, retries |
| `starpunk/webmention_processor.py` | Fetch source, verify link, parse mf2, extract type/author/content |
| `starpunk/webmention_sender.py` | Extract links from a note and queue outgoing webmentions |
| `starpunk/webmention_ssrf.py` | `safe_get` / `safe_post`: SSRF-checked, address-pinned HTTP |
| `starpunk/reply_context.py` | Fetch context for reply/like/repost targets (synchronous, see below) |
## Thread lifecycle
- Started in `create_app()` (`starpunk/__init__.py`) when
`WEBMENTION_WORKER_ENABLED` is true and `TESTING` is false. Stored as
`app.webmention_worker`. Daemon thread named `webmention-worker`, following
the `MemoryMonitor` pattern (a `threading.Event` for stop).
- There is no teardown hook: until v2.6.8 a `teardown_appcontext` handler
stopped the worker after the first request.
- Each poll runs inside `app.app_context()` (v2.6.8), because the SSRF checks
read `current_app.config` (`DEV_MODE`).
- `stop()` sets the event; the loop exits after the current pass.
### One worker across processes (v2.6.9)
Every gunicorn process starts a worker. Only the one holding an exclusive,
non-blocking `fcntl.flock` on `<db dir>/webmention-worker.lock` processes the
queues; the others poll the lock every `poll_interval`. The OS releases the
lock when the holder dies, so another process takes over.
### Orphan cleanup
When a worker first acquires the lock it resets `webmention_queue` rows stuck
in `sending` for more than 5 minutes back to `pending` (a previous holder
crashed mid-send).
## Main loop
```
while not stopped:
if not lock acquired: wait poll_interval; continue
with app.app_context():
n = process pending validations (incoming, oldest received first, batch_size)
n += process pending sends (outgoing, due rows, oldest first, batch_size)
if n == 0: wait poll_interval
on unexpected error: log, wait error_backoff
```
| Setting | Default | Meaning |
|---|---|---|
| `WEBMENTION_WORKER_ENABLED` | true | Start the thread |
| `WEBMENTION_POLL_INTERVAL` | 10 s | Sleep when idle / lock not held |
| `WEBMENTION_ERROR_BACKOFF` | 60 s | Sleep after a loop error |
| `WEBMENTION_BATCH_SIZE` | 5 | Rows per queue per pass |
| `WEBMENTION_AUTO_APPROVE` | true | New valid mentions start `approved` (else `pending`) |
`get_stats()` (running, last_processed, pending_validations, pending_sends)
is included in the basic (unauthenticated) `/health` response. Note it reports
the worker of whichever process answers, which may not hold the lock.
## Incoming: validation
For each `webmentions` row with `validation_status = 'pending'`:
1. `process_webmention(source, target, SITE_URL)`:
- `fetch_source`: `safe_get` with an `Accept` header preferring HTML,
following redirects (each hop checked). 4xx, SSRF block or >1 MB is a
`ValidationError`; network error, timeout, 3xx without location or 5xx is
a `TransientError`.
- `verify_link_presence` (spec 3.2.2): exact target match, fragments
ignored. HTML: any link-bearing attribute after resolving relative URLs
against the final URL; JSON: any string value; other `text/*`:
substring. Fails with "Source does not link to target".
- HTML only: `mf2py.parse`, then `mf2_utils.responding_entry` picks the
h-entry that responds to the target; `response_type` gives `reply`,
`like`, `repost`, `bookmark` or `mention`; `entry_author` applies the
authorship algorithm without extra fetches; `extract_content` takes
`e-content` (else `p-summary`) as a sanitized snippet of at most ~500
characters; `extract_source_details` gives the entry's `u-url`, `u-uid`
and `dt-published` (v2.8.0).
- Author URL and photo are kept only if they are http(s) URLs (v2.6.9);
the author URL falls back to the source, the name to its host.
2. If the source is one of the target note's own `u-syndication` copies
(`syndications.remote_url`, compared normalised), it is rejected (v2.8.0).
3. Success: the row becomes `valid` with the extracted fields. Moderation:
a first-time valid mention gets `approved`/`pending` per
`WEBMENTION_AUTO_APPROVE`; a mention that was valid before keeps its
moderation status, and `hidden`/`deleted` are never overwritten (v2.7.0).
4. Failure (`_mark_validation_failed`):
- Transient error and the mention was valid before (`validated_at` set,
no `validation_error`): restored to `valid` with its old data; nothing
disappears because the source was briefly down (v2.7.0).
- "does not link", "returned 4xx" or own syndicated copy: `invalid`.
- Anything else: `error`. Either way the error text is stored and the
mention is no longer displayed (spec 3.2.4 for 410/no link).
### Displayed responses are an update (v2.7.2, spec 3.1.4)
`_validate_webmention` compares `_display_state()` (what the note shows for
this mention: type, author, photo, snippet; `None` if hidden) before and
after validation. If it changed, `webmention_sender.note_responses_changed`
re-queues the target note's previously sent webmentions. A re-validation
that changes nothing sends nothing, so two sites doing the same don't
ping-pong.
## Outgoing: queueing
`webmention_sender.queue_webmentions_for_note()` is called by `notes.py`
after the note is committed, best-effort (failures are logged, never fail the
note):
- **Create** (published only): the response target first (`in_reply_to`,
else `like_of`, `repost_of`, `bookmark_of`), then `<a href>` links from the
rendered HTML in document order; links inside `<pre>`/`<code>` are skipped
(including a top-level `<pre>`, v2.7.0); only absolute http(s) URLs;
de-duplicated; at most 10 ("architect's answer to Q1").
- **Update** ("Phase 6" answers): queued when a note is published or
unpublished, or a published note's content or reply target changes. The
current targets (capped at 10) plus every target this note was queued for
before and every link the edit removed (not capped), so receivers can
update or remove the mention (v2.7.0).
- **Delete / undelete** (spec 3.1.5): `requeue_previous_webmentions` resets
all of the note's queue rows to `pending`; on hard delete with
`detach=True` the `source_note_id` is cleared so the rows survive the
cascade.
- Rows are UPSERTed on `(source_url, target_url)`; re-queueing resets
status, retry count, error and `endpoint_url`.
## Outgoing: sending
For each due `webmention_queue` row (`pending`, `next_retry_at` null or
past):
1. Mark `sending` with `started_at`.
2. Discover the endpoint (spec 3.1.2), every time (the v1.6.0 1–24 h
discovery cache was removed in v2.7.0): `safe_get` the target; 5xx raises
(retry); 4xx, blocked or too large means no endpoint. The first `Link`
header with `rel` containing the token `webmention` (case-insensitive,
several headers and multi-value rels handled) wins, then the first
`<link>`/`<a>` with that rel and an `href`, in document order. Relative
URLs resolve against the final URL; an empty `href` is the target itself.
No endpoint: status `no_endpoint` (permanent).
3. POST `source`/`target` form-encoded with `safe_post` (no redirects).
2xx: `sent`. 429 or 5xx: retry. Other (3xx, 4xx): `failed`. Network
error: retry. SSRF block: `failed`.
### Retries ("architect's answer to Q5")
`retry_count` is incremented after the failed attempt; at 4 the row is
`failed`. Delays after attempt 1, 2, 3: 1 h, 6 h, 24 h.
## Outbound safety (`webmention_ssrf.py`)
Used for every fetch and send (and since v2.9.0/v2.10.0 by Micropub photo
fetches and the WebSub hub):
- http(s) only; every address the host resolves to must be public (blocks
private, loopback, link-local, multicast, reserved, unspecified, CGNAT,
`0.0.0.0/8`, IPv4-mapped forms). `DEV_MODE` allows `localhost`.
- The connection goes to the checked address; the hostname is sent in
`Host` and TLS SNI so certificates are still verified (v2.7.2). IPv4
preferred.
- Redirects followed by hand, each hop checked, at most 10; 1 MB body
limit; 10 s total time limit enforced by a watchdog that closes the client
(v2.10.1).
- User-Agent `StarPunk/<version> Webmention (+SITE_URL)`.
## Reply context
`reply_context.fetch_reply_context()` is not run by the worker: `notes.py`
calls it synchronously after creating a reply/like/repost/bookmark (or when
an update sets `in_reply_to`). See [database-schema.md](database-schema.md).
## Known limits
- A DNS failure while fetching a source (`ResolutionError`, a `ValueError`)
is treated as a blocked request, i.e. a permanent `error`, not a transient
one; the WebSub worker retries DNS failures, the webmention worker does not.
- Between receipt of a re-sent webmention and its re-validation the row is
`pending` and not shown on the note (`get_webmentions_for_note` requires
`valid`), although `_display_state` counts it as shown.
- The worker opens its own `sqlite3` connections (not the request pool).
+102
View File
@@ -0,0 +1,102 @@
# v1.6.0 Design: Webmention Database Schema
> Reconstructed on 2026-11-03 from the implementation; the original v1.6.0 document was lost. Later changes: v2.6.8–v2.7.2 (see CHANGELOG).
> Schema from `migrations/010_add_webmentions.sql` plus `014_webmention_source_details.sql` (v2.8.0). The original document's story numbering is only known for Story 2.4 (reply context), cited in `starpunk/reply_context.py`.
Related: ADR-063, [background-worker.md](background-worker.md),
[display-moderation.md](display-moderation.md).
## Migration 010 (v1.6.0)
### `notes.in_reply_to TEXT`
URL the note replies to. Later migrations added `like_of`, `repost_of`
(013, v2.5.0) and `bookmark_of` (015, v2.9.0); `Note.reacts_to` is the first
of these that is set.
### `webmentions` (received)
| Column | Notes |
|---|---|
| `id` | PK |
| `source_url`, `target_url` | NOT NULL; `UNIQUE(source_url, target_url)`; target stored without fragment (v2.7.0) |
| `target_note_id` | FK `notes(id)` ON DELETE SET NULL; always set for new rows since v2.7.0 (only notes accept webmentions) |
| `mention_type` | `reply`, `like`, `repost`, `bookmark`, `mention` (default `mention`) |
| `author_name`, `author_url`, `author_photo` | From the authorship algorithm; URLs http(s) only |
| `content_snippet` | Sanitised HTML, ~500 chars max |
| `validation_status` | `pending` (default), `valid`, `invalid`, `error` |
| `moderation_status` | `pending` (default), `approved`, `hidden`, `deleted` |
| `validation_error` | Last error text, NULL when valid |
| `validated_at` | Last validation attempt; with `validation_error IS NULL` it means "was valid before" |
| `received_at`, `updated_at` | Timestamps |
| `source_post_url`, `source_published` | Migration 014 (v2.8.0): the source h-entry's `u-url` and `dt-published` (UTC) |
Indexes: `target_note_id`, `moderation_status`, `validation_status`,
`received_at DESC`.
Notes:
- `moderation_status = 'deleted'` is allowed by the CHECK but unused: admin
delete removes the row (`DELETE`). Validation never overwrites `hidden` or
`deleted`.
- A row is shown on a note only if `valid` and `approved`.
### `webmention_queue` (sent)
| Column | Notes |
|---|---|
| `source_url` | Our note's permalink (built from `SITE_URL`) |
| `target_url` | `UNIQUE(source_url, target_url)` |
| `source_note_id` | FK `notes(id)` ON DELETE CASCADE; cleared (`detach`) before a hard delete so the re-sent rows survive |
| `endpoint_url` | Endpoint found by the current attempt; reset on every re-queue (no cross-attempt cache since v2.7.0) |
| `status` | `pending`, `sending`, `sent`, `failed`, `no_endpoint` |
| `retry_count`, `next_retry_at`, `last_error` | Retry schedule 1 h / 6 h / 24 h, failed at 4 |
| `created_at`, `started_at`, `sent_at` | `started_at` drives orphan cleanup (>5 min in `sending`) |
Indexes: `status`, `next_retry_at`, `source_note_id`.
### `reply_contexts` (cache of what a note responds to)
| Column | Notes |
|---|---|
| `url` | UNIQUE; the `in_reply_to` / `like_of` / `repost_of` / `bookmark_of` URL |
| `title` | h-entry `p-name`, max 200 chars |
| `content_snippet` | Via `extract_content` |
| `published_at` | h-entry `dt-published` parsed with dateutil |
| `author_name`, `author_url`, `author_photo` | Via `extract_author` |
| `site_name` | First top-level h-card's name |
| `fetch_status` | `pending`, `fetched`, `error` |
| `fetch_error`, `fetched_at`, `created_at` | |
## Story 2.4: reply context
`starpunk/reply_context.py`, called synchronously from `notes.create_note`
(for any response URL) and `notes.update_note` (when `in_reply_to` is set),
best-effort:
1. If a row for the URL exists, return it (never refreshed).
2. Fetch with `webmention_processor.fetch_source` (SSRF-safe).
3. Non-HTML: store an `error` row ("Not HTML content").
4. Parse mf2; take the first top-level h-entry's name, content and
published time, and the author; store as `fetched` (`INSERT OR REPLACE`).
5. Any failure stores an `error` row; note creation is never affected.
Read side: `webmention_queries.get_reply_context(url)` for the note page
(`in_reply_to` h-cite), `routes.public.attach_contexts` for likes/reposts
(title and author lines, v2.5.0) and `syndication._target_title` for
crosspost text.
### Known defect (found during reconstruction)
Since v2.7.0, `fetch_source()` returns `(content, content_type, final_url)`,
but `fetch_reply_context()` still unpacks two values. The resulting
`ValueError` is caught by the generic handler, so every new URL gets an
`error` row ("Unexpected error: too many values to unpack") and no context.
Rows fetched before v2.7.0 are unaffected (they are never refreshed).
Tests replace `fetch_reply_context` with a stub, so this is not covered.
## Later schema touching webmentions
- 012 (v2.1.0) `syndications`: used to reject a note's own crossposts as
sources (v2.8.0).
- 013 / 015: response URL columns on `notes`, which become the first
outgoing webmention target.
+89
View File
@@ -0,0 +1,89 @@
# v1.6.0 Design: Webmention Display and Moderation
> Reconstructed on 2026-11-03 from the implementation; the original v1.6.0 document was lost. Later changes: v2.6.8–v2.7.2 (see CHANGELOG).
> Display markup was reworked in v2.8.0 (microformats2 review). Describes `starpunk/webmention_queries.py`, `starpunk/routes/admin.py`, `starpunk/routes/public.py`, `templates/note.html` and `templates/partials/responses.html` as of v2.10.1.
Related: ADR-063, [background-worker.md](background-worker.md),
[database-schema.md](database-schema.md).
## States
A received webmention has two independent states:
- `validation_status` (set by the worker): `pending`, `valid`, `invalid`, `error`.
- `moderation_status` (set by the worker on first validation, then by the
admin): `pending`, `approved`, `hidden` (`deleted` exists in the schema but
deleting removes the row).
A webmention is **shown** only when `valid` AND `approved`.
`WEBMENTION_AUTO_APPROVE=true` (default) makes a first-time valid mention
`approved`; with `false` it waits as `pending` for the admin. Re-validation
of a previously valid mention keeps the admin's decision (v2.7.0).
## Public display
`get_webmentions_for_note(note_id)` returns shown webmentions for a note,
ordered by type (reply, like, repost, bookmark, mention) then `received_at`
ascending, grouped into `replies`, `likes`, `reposts`, `bookmarks`,
`mentions`. `received_at` and `source_published` are parsed to datetimes
(unparseable `source_published` becomes `None`).
`routes/public.note` loads them only when `WEBMENTION_ENABLED`; errors are
logged and the page renders without them. The "Webmentions" section is
rendered only if at least one group is non-empty, with a heading and count
per group.
Markup (v2.8.0, `partials/responses.html`), each response an `h-cite` in a
property of the note's `h-entry`:
| Group | Property | Presentation |
|---|---|---|
| Replies | `u-comment h-cite` | Author card (name, link, 48px photo), sanitised `e-content` snippet, date link |
| Likes, reposts, bookmarks | `u-like` / `u-repost` / `u-bookmark` `h-cite` | Facepile of 32px photos (or a coloured initial); faces after the 8th are `hidden` on screen but stay in the markup for parsers, with "+N others" |
| Mentions | `u-mention h-cite` | Small author card, snippet with tags stripped and truncated to 200 chars |
- The response's link is the source's `u-url` (`source_post_url`) if given,
else the webmention source; its date is `source_published`, else
`received_at`, in UTC with `Z`.
- The author `h-card` puts `u-url` on an inner link, so it isn't read as the
`h-cite`'s URL.
- Snippets are stored sanitised (see [api-contract.md](api-contract.md)) and
output with `|safe`; all other fields are autoescaped.
## Admin moderation
All routes `@require_auth`, under `/admin`:
| Route | Purpose |
|---|---|
| `GET /admin/webmentions?status=&page=` | List, newest received first, 25 per page; filter tabs All / Pending / Approved / Hidden (by `moderation_status`) |
| `GET /admin/webmentions/<id>` | Detail: source, target (note link), type, author, snippet, validation status and error, timestamps, actions |
| `POST /admin/webmentions/<id>/action` | `action` = `approve` / `hide` / `delete` |
| `POST /admin/webmentions/bulk-action` | Same actions for `ids` (checkboxes) |
The dashboard shows a badge with the number of `pending` (moderation)
webmentions.
Query functions: `list_webmentions`, `get_webmention`, `count_webmentions`,
`update_webmention_status(ids, status)` (only `approved`, `hidden`,
`pending`), `delete_webmentions(ids)` (hard delete).
### Moderation changes re-send webmentions (v2.7.2, spec 3.1.4)
Before an update or delete, `_visibility_changes()` finds the target notes
of valid webmentions whose shown/not-shown state changes. After the commit,
`_notify_responses_changed()` calls
`webmention_sender.note_responses_changed()`, which re-queues every
webmention the (published, undeleted) note sent before. Best effort:
failures are logged.
## Known limits
- The admin list filters and shows only moderation status; validation
status and error appear on the detail page. A mention that never
validated keeps the default `moderation_status = 'pending'`, so it is
listed under Pending and counted in the dashboard badge although there is
nothing to approve.
- A webmention re-sent by its source is `pending` until the worker
re-validates it (seconds), and is not shown during that time.
- Hidden or invalid webmentions are kept indefinitely; there is no pruning.
+84
View File
@@ -0,0 +1,84 @@
# v1.6.0 Design: Webmention Rate Limiting
> Reconstructed on 2026-11-03 from the implementation; the original v1.6.0 document was lost. Later changes: v2.6.8–v2.7.2 (see CHANGELOG).
> The rate limiter itself has not changed since v1.6.0; v2.10.0 reused `RateLimiter` for the WebSub hub. Describes `starpunk/rate_limiter.py` and `starpunk/routes/webmention.py` as of v2.10.1.
Related: ADR-063, [api-contract.md](api-contract.md).
**Note on ADR numbering:** the code cites "ADR-064: Webmention Rate
Limiting". In this repository ADR-064 is the OIDC admin login decision
(v2.0.0); the webmention rate-limiting ADR from v1.6.0 was lost with the
other v1.6.0 documents and its number was reused. This document is the
surviving description of that decision.
## Goal
Stop `POST /webmention` from being used to fill the database or the
validation queue (each accepted webmention costs one outbound fetch).
## Algorithm
`RateLimiter(limit, window_seconds)`: sliding-window log, in memory.
- Per key, a list of request timestamps (`time.time()`), guarded by one
`threading.Lock`.
- `is_allowed(key)`: drop timestamps older than the window; if the count is
`>= limit` refuse (not recorded); otherwise record and allow.
- `get_retry_after(key)`: seconds until the oldest timestamp leaves the
window, clamped to 1..window.
- `cleanup(max_idle_seconds=300)`: drop keys with no recent requests.
- `get_request_count(key)`: current count (tests/logging).
In-memory state was chosen to match the other in-process caches (the
v1.6.0 code cites the worker's endpoint `_discovery_cache`, removed in
v2.7.0); no new table, no Redis.
## Webmention limits
Two module-level limiters, created by `init_rate_limiters(app)` in
`create_app()`:
| Setting | Default | Key |
|---|---|---|
| `WEBMENTION_RATE_LIMIT_ENABLED` | true | Off: both limiters are `None`, everything allowed |
| `WEBMENTION_RATE_LIMIT_IP` | 60 | Client IP |
| `WEBMENTION_RATE_LIMIT_DOMAIN` | 10 | Host (`netloc`) of the `source` URL |
| `WEBMENTION_RATE_LIMIT_WINDOW` | 60 s | Both |
`check_rate_limit(ip, source_domain)` checks the IP first, then the source
domain (if one could be parsed). Only POST is limited, in the webmention
blueprint's `before_request`, before any validation, reading `source` from
the form or JSON body.
Client IP (`get_client_ip`): the first `X-Forwarded-For` entry when
`TRUSTED_PROXY=true`, else `request.remote_addr`. Behind Caddy without
`TRUSTED_PROXY` every client shares the proxy's address (documented in
`.env.example` since v2.10.1).
## Response
```
HTTP/1.1 429
Retry-After: <WEBMENTION_RATE_LIMIT_WINDOW>
{"error": "rate_limit_exceeded",
"error_description": "Too many requests from your IP. Please retry after N seconds."}
```
The description carries the computed wait; the `Retry-After` header carries
the full window.
## Other users
`routes/websub.py` (v2.10.0) has its own `RateLimiter(30, 60)` per client
IP for subscription requests, calling `cleanup()` every 500 requests.
## Known limits
- Counters are per gunicorn process, so the effective limit is up to
limit × processes, and they reset on restart.
- `cleanup_rate_limiters()` exists but nothing calls it, so the webmention
limiters never drop a key (old timestamps are trimmed when the key is
checked again, but the key stays); memory grows slowly with distinct
client IPs and source domains until the process restarts.
- Requests refused by the IP limit are not recorded, and a request refused
by the domain limit has already been counted against the IP.