Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a0d82bab2 | ||
|
|
84411a16d9 | ||
|
|
4ed2033cf9 | ||
|
|
d354dc9733 | ||
|
|
88aea09e04 | ||
|
|
7e2cdef150 | ||
|
|
058b1959f9 | ||
|
|
ceef048003 |
No files matched your search
+9
-6
@@ -1,4 +1,4 @@
|
||||
# StarPunk configuration template (v2.10.1)
|
||||
# StarPunk configuration template (v2.14.0)
|
||||
#
|
||||
# Copy to .env and fill in your values. DO NOT commit .env.
|
||||
# Every variable here is read by starpunk/config.py. Uncommented lines are
|
||||
@@ -124,10 +124,11 @@ CSRF_ENABLED=true
|
||||
# WEBMENTION
|
||||
# =============================================================================
|
||||
|
||||
# Receive webmentions at /webmention (default: true)
|
||||
# Webmention endpoint at /webmention, its Link header, and showing responses
|
||||
# (webmentions and backfeed) on notes; sending is not affected (default: true)
|
||||
# WEBMENTION_ENABLED=true
|
||||
# Background worker that verifies received webmentions and sends outgoing
|
||||
# ones (default: true)
|
||||
# Background worker that verifies received webmentions, sends outgoing ones,
|
||||
# and sends response notifications (v2.14.0) (default: true)
|
||||
# WEBMENTION_WORKER_ENABLED=true
|
||||
# Seconds between queue checks (default: 10) and after an error (default: 60)
|
||||
# WEBMENTION_POLL_INTERVAL=10
|
||||
@@ -201,7 +202,8 @@ THREADS_USERNAME=
|
||||
# SYNDICATION_POLL_INTERVAL=10
|
||||
|
||||
# Backfeed (v2.13.0, ADR-073): bring likes, reposts, quotes and replies to the
|
||||
# crossposts back to the note as responses. Needs the read scopes above.
|
||||
# crossposts back to the note as responses. Needs the read scopes above, and
|
||||
# runs in the syndication worker, so at least one target must be configured.
|
||||
# BACKFEED_ENABLED=false
|
||||
# Stop checking a note's responses after this many days (default: 90)
|
||||
# BACKFEED_MAX_AGE_DAYS=90
|
||||
@@ -216,7 +218,8 @@ THREADS_USERNAME=
|
||||
# apprises://apprise.example.com/KEY (an apprise-api server)
|
||||
# NOTIFY_URLS=
|
||||
# What to notify: reply, mention, quote, like, repost, bookmark, problems
|
||||
# (a crosspost that failed for good, a silo refusing backfeed)
|
||||
# (a crosspost that failed for good, a silo refusing backfeed). Names are
|
||||
# case-insensitive; unknown ones are ignored.
|
||||
# NOTIFY_EVENTS=reply,mention,quote,problems
|
||||
# Priority of every message, added to URLs that don't set one:
|
||||
# low, moderate, normal, high, emergency (Gotify also takes 0-10)
|
||||
|
||||
+35
-5
@@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.15.0] - 2026-11-11
|
||||
|
||||
MCP server for AI clients (ADR-075).
|
||||
|
||||
### Added
|
||||
|
||||
- An [MCP](https://modelcontextprotocol.io/) server at `SITE_URL/mcp`. AI assistants such as claude.ai custom connectors and Claude Code can search, list and read notes and drafts, list tags, create notes (drafts by default), update, delete and undelete them, and upload photos. Writes go through the Micropub handlers, so scopes, crossposting, webmentions and WebSub behave the same as with any Micropub app
|
||||
- The MCP server runs as a sidecar from the same image (`uvicorn starpunk.mcp_server.app:app --port 8001`) with `BACKGROUND_WORKERS_ENABLED=false`; the proxy sends `/mcp*` and `/.well-known/oauth-protected-resource*` to it. New dependencies: `mcp` 2.3 and `uvicorn` 0.54
|
||||
- The IndieAuth server accepts RFC 8707 `resource` for the MCP endpoint and binds codes and tokens to it (migration 022). Its metadata advertises client ID metadata documents and public clients (`token_endpoint_auth_methods_supported: ["none"]`), so Claude connects without dynamic client registration. The consent screen says when an AI assistant is asking, and Connected Apps marks MCP tokens
|
||||
- `BACKGROUND_WORKERS_ENABLED` (default `true`) turns off the webmention, WebSub and syndication workers
|
||||
|
||||
### Fixed
|
||||
|
||||
- `scopes_supported` in the IndieAuth metadata lists `draft`, which Micropub already honoured
|
||||
|
||||
## [2.14.2] - 2026-11-10
|
||||
|
||||
### Added
|
||||
|
||||
- Quotes have a count in the line under each note (❝) and in the counts on the home, tag and Likes pages. It includes quotes a silo reports without names (Threads, and people who opted out of backfeed), which were stored but shown nowhere
|
||||
|
||||
### Removed
|
||||
|
||||
- The editor pages no longer load `marked` from a CDN and an empty `static/js/preview.js`; nothing used them
|
||||
- The empty `templates/feed.xml`, the v1 `static/indielogin-test.html`, and the `THREADS_API` setting that crossposting read but nothing could set
|
||||
|
||||
## [2.14.1] - 2026-11-10
|
||||
|
||||
### Fixed
|
||||
|
||||
- Clearing the Tags field in the note editor removes all of the note's tags. It used to leave them unchanged, so a note's last tags couldn't be removed from the editor
|
||||
- Image captions are escaped in the HTML of RSS, Atom and JSON Feed items. A caption containing `"`, `<` or `&` broke the item's image markup (the Atom enclosure's title was already escaped)
|
||||
|
||||
## [2.14.0] - 2026-11-10
|
||||
|
||||
Notifications (ADR-074).
|
||||
@@ -634,7 +667,7 @@ Webmention now follows the [W3C Recommendation](https://www.w3.org/TR/webmention
|
||||
- Successful uploads logged at INFO level with file details
|
||||
- Removed duplicate logging in Micropub media endpoint
|
||||
|
||||
## [1.4.0rc1] - 2025-12-16
|
||||
## [1.4.0-rc.1] - 2025-12-16
|
||||
|
||||
### Added
|
||||
|
||||
@@ -2177,7 +2210,4 @@ This is a release candidate for testing. Stable 1.0.0 will be released after tes
|
||||
- ADR-007: Slug generation algorithm
|
||||
- ADR-008: Versioning strategy
|
||||
|
||||
[Unreleased]: https://github.com/YOUR_USERNAME/starpunk/compare/v0.4.0...HEAD
|
||||
[0.4.0]: https://github.com/YOUR_USERNAME/starpunk/compare/v0.3.0...v0.4.0
|
||||
[0.3.0]: https://github.com/YOUR_USERNAME/starpunk/compare/v0.1.0...v0.3.0
|
||||
[0.1.0]: https://github.com/YOUR_USERNAME/starpunk/releases/tag/v0.1.0
|
||||
Releases are tagged `vX.Y.Z` in https://git.thesatelliteoflove.com/phil/StarPunk
|
||||
@@ -8,7 +8,7 @@ This file contains operational instructions for Claude agents working on this pr
|
||||
- All Python commands must be run with `uv run` prefix
|
||||
- Example: `uv run pytest`, `uv run flask --app app.py run --debug`
|
||||
- There is no `pyproject.toml`: create the environment with `uv venv --python 3.14 && uv pip install -r requirements-dev.txt`
|
||||
- Tests need `SESSION_SECRET` set: `SESSION_SECRET=test uv run pytest`. The full suite takes about 6 minutes, 5 of them in `tests/test_migration_race_condition.py`; add `--ignore=tests/test_migration_race_condition.py` while iterating, but run everything before a release
|
||||
- Tests need `SESSION_SECRET` set. Locally, run only the tests for the area you changed (`SESSION_SECRET=test uv run pytest tests/test_<area>.py`); CI runs the full suite (about 6 minutes) on every `vX.Y.Z` tag, so don't run the whole suite yourself unless asked
|
||||
- Local login without OIDC: `DEV_MODE=true` and `DEV_ADMIN_ME` in `.env`, then `/dev/login`
|
||||
- Setup details: `docs/standards/development-setup.md`
|
||||
|
||||
@@ -50,12 +50,12 @@ When invoking the agent-developer, always remind it to:
|
||||
|
||||
5. **Follow git protocol**
|
||||
- Adhere to git branching strategy in `docs/standards/git-branching-strategy.md`
|
||||
- Create feature branches for non-trivial changes, in their own git worktree (`<prefix>/vX.Y.Z-description`, prefixes `feat/`, `fix/`, `ci/`, `docs/`)
|
||||
- Create feature branches for non-trivial changes, in their own git worktree (`<prefix>/vX.Y.Z-description`, prefixes `feat/`, `fix/`, `ci/`, `chore/`, `docs/`)
|
||||
- Write clear commit messages (`feat: ... (vX.Y.Z)`)
|
||||
|
||||
## Release Process
|
||||
|
||||
Follow "Release process" in `docs/standards/git-branching-strategy.md`. In short: work in a worktree on a `feat/`/`fix/` branch → bump `__version__` and `__version_info__` → `CHANGELOG.md` entry → design note in `docs/design/vX.Y.Z/` (or ADR amendment) → full test suite → commit → `git merge --no-ff` into `main` ("Merge branch '<branch>' for vX.Y.Z release") → annotated tag `vX.Y.Z` → push `main` and the tag. CI (`.gitea/workflows/build-container.yml`) runs the tests and publishes the image; production is then updated from the separate Ansible deployment repository. Back up the database before deploying a release with a migration.
|
||||
Follow "Release process" in `docs/standards/git-branching-strategy.md`. In short: work in a worktree on a `feat/`/`fix/`/`chore/` branch → bump `__version__` and `__version_info__` → `CHANGELOG.md` entry → design note in `docs/design/vX.Y.Z/` (or ADR amendment) → tests for the changed area → commit → `git merge --no-ff` into `main` ("Merge branch '<branch>' for vX.Y.Z release") → annotated tag `vX.Y.Z` → push `main` and the tag. CI (`.gitea/workflows/build-container.yml`) runs the full test suite and publishes the image; production is then updated from the separate Ansible deployment repository. Back up the database before deploying a release with a migration.
|
||||
|
||||
Merging to `main`, tagging, pushing and deploying happen only when the project owner asks for a release.
|
||||
|
||||
|
||||
@@ -78,6 +78,8 @@ USER starpunk
|
||||
|
||||
# Expose application port
|
||||
EXPOSE 8000
|
||||
# MCP sidecar (same image, run with: uvicorn starpunk.mcp_server.app:app --host 0.0.0.0 --port 8001)
|
||||
EXPOSE 8001
|
||||
|
||||
# Health check
|
||||
# Uses httpx (already in requirements) to verify app is responding
|
||||
|
||||
@@ -23,9 +23,13 @@ what changed in each release is in [CHANGELOG.md](CHANGELOG.md).
|
||||
- Built-in [IndieAuth](https://indieauth.spec.indieweb.org/) server for
|
||||
Micropub apps (consent screen, tokens, revocation, Connected Apps page)
|
||||
- Admin login through any OpenID Connect provider (e.g. Pocket ID)
|
||||
- [MCP](https://modelcontextprotocol.io/) server at `/mcp` so AI assistants
|
||||
(claude.ai connectors, Claude Code…) can search, read and write notes
|
||||
after you approve them, run as an optional sidecar (ADR-075)
|
||||
- [Webmention](https://www.w3.org/TR/webmention/): receiving (verified,
|
||||
moderated, rate-limited) and sending; replies, likes and reposts shown on
|
||||
each note
|
||||
moderated, rate-limited) and sending; replies, quotes and mentions shown
|
||||
on each note, with likes, reposts and replies as a line of counts with
|
||||
hover cards and `<indie-action>` web actions
|
||||
- [WebSub](https://www.w3.org/TR/websub/) with a built-in hub, so readers get
|
||||
new posts within seconds
|
||||
- [Microformats2](https://microformats.org/wiki/h-entry): h-entry, h-feed and
|
||||
@@ -38,10 +42,15 @@ what changed in each release is in [CHANGELOG.md](CHANGELOG.md).
|
||||
- POSSE crossposting to GoToSocial/Mastodon, Bluesky and Threads, with
|
||||
`u-syndication` links back; edits and deletes follow, native likes and
|
||||
boosts where the target supports them
|
||||
- Backfeed: likes, reposts and replies to crossposts on GoToSocial and
|
||||
Bluesky (and Bluesky quotes), and replies on Threads (with its like and
|
||||
repost counts), come back as responses (`BACKFEED_ENABLED`, ADR-073)
|
||||
|
||||
**Operations**
|
||||
- Migrations applied automatically at startup
|
||||
- `/health` endpoint, `/admin/health` diagnostics, structured logs
|
||||
- Notifications of new responses and crossposting problems through
|
||||
Apprise (Gotify, ntfy, email…; `NOTIFY_URLS`, ADR-074)
|
||||
- Fetches of user-supplied URLs are limited to public addresses, size and
|
||||
time
|
||||
|
||||
@@ -54,7 +63,6 @@ git clone https://git.thesatelliteoflove.com/phil/StarPunk.git && cd StarPunk
|
||||
cp .env.example .env # set SITE_URL, ADMIN_ME, SESSION_SECRET, OIDC_*
|
||||
docker build -t starpunk -f Containerfile .
|
||||
docker run -d --name starpunk -p 127.0.0.1:8000:8000 --env-file .env \
|
||||
-e FLASK_ENV=production -e FLASK_DEBUG=0 \
|
||||
-v ./starpunk-data:/data starpunk
|
||||
```
|
||||
|
||||
@@ -72,8 +80,8 @@ redirect URI with your OIDC provider. Details:
|
||||
uv venv --python 3.14
|
||||
uv pip install -r requirements-dev.txt
|
||||
cp .env.example .env # set SESSION_SECRET; add DEV_MODE=true and DEV_ADMIN_ME
|
||||
uv run flask --app app.py run --debug # http://localhost:5000
|
||||
SESSION_SECRET=test uv run pytest # tests (about 6 minutes)
|
||||
uv run flask --app app.py run --debug # http://localhost:5000
|
||||
SESSION_SECRET=test uv run pytest tests/test_<area>.py # tests for what you changed; CI runs the full suite
|
||||
```
|
||||
|
||||
With `DEV_MODE=true`, `/dev/login` logs you in without OIDC. Never enable
|
||||
@@ -86,13 +94,15 @@ All settings are environment variables (or a `.env` file), each listed with
|
||||
its default in [`.env.example`](.env.example). Required in production:
|
||||
`SESSION_SECRET`, `SITE_URL`, `ADMIN_ME`, `OIDC_ISSUER`, `OIDC_CLIENT_ID`,
|
||||
`OIDC_CLIENT_SECRET` and `OIDC_ADMIN_SUB`. Crossposting is enabled by
|
||||
setting a target's credentials.
|
||||
setting a target's credentials. Backfeed is off unless
|
||||
`BACKFEED_ENABLED=true`; notifications start when `NOTIFY_URLS` is set.
|
||||
|
||||
## Data and backups
|
||||
|
||||
Everything lives in the data directory (`/data` in the container): the
|
||||
SQLite database, note files in `notes/`, uploaded media and logs. Back it
|
||||
up regularly, and always before upgrading to a release with a migration.
|
||||
SQLite database, note files in `notes/`, uploaded media, saved response
|
||||
avatars in `avatars/`, the Threads token (`threads_token.json`) and logs.
|
||||
Back it up regularly, and always before upgrading to a release with a migration.
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
# Architecture Documentation Index
|
||||
|
||||
This directory describes the **current** design of StarPunk (v2.10.1). Per
|
||||
This directory describes the **current** design of StarPunk (v2.14.0). Per
|
||||
[../DOCUMENTATION.md](../DOCUMENTATION.md) it is updated at the end of each
|
||||
release. Decisions and their history are in [../decisions/](../decisions/);
|
||||
per-release designs and reports are in [../design/](../design/).
|
||||
per-release designs and reports are in [../design/](../design/). The
|
||||
original v0.x technology choices are kept in
|
||||
[../design/v0.x/technology-stack-legacy.md](../design/v0.x/technology-stack-legacy.md).
|
||||
|
||||
## Documents
|
||||
|
||||
@@ -11,12 +13,12 @@ per-release designs and reports are in [../design/](../design/).
|
||||
|----------|-------------|
|
||||
| [overview.md](overview.md) | System overview: purpose, request flow, modules and routes, background workers, storage, auth model, URL surface, caching, security posture |
|
||||
| [technology-stack.md](technology-stack.md) | Current runtime, Python dependencies, standards implemented, testing and CI |
|
||||
| [database.md](database.md) | SQLite schema after migrations 001–019, migration runner and its lock, connection pool |
|
||||
| [database.md](database.md) | SQLite schema after migrations 001–022, migration runner and its lock, connection pool |
|
||||
| [deployment.md](deployment.md) | Container image stages, CI workflow, release process, `/data` layout, reverse proxy, all environment variables |
|
||||
| [simplified-auth-architecture.md](simplified-auth-architecture.md) | Admin login via OpenID Connect and the built-in IndieAuth server that issues Micropub tokens (ADR-064) |
|
||||
| [indieweb-protocols.md](indieweb-protocols.md) | How Micropub, IndieAuth, Webmention, microformats2, WebSub and the feeds are implemented, with compliance status and known gaps |
|
||||
| [syndication-architecture.md](syndication-architecture.md) | Crossposting (POSSE) to GoToSocial, Bluesky and Threads: syndications table, worker, reconcile rules |
|
||||
| [technology-stack-legacy.md](technology-stack-legacy.md) | Historical: the original v0.x technology choices (IndieLogin era); not current |
|
||||
| [indieweb-protocols.md](indieweb-protocols.md) | How Micropub, IndieAuth, Webmention, microformats2, WebSub and the feeds are implemented (including backfeed responses, web actions and notifications), with compliance status and known gaps |
|
||||
| [mcp.md](mcp.md) | The MCP server for AI clients: sidecar, authorization flow, tools (ADR-075) |
|
||||
| [syndication-architecture.md](syndication-architecture.md) | Crossposting (POSSE) to GoToSocial, Bluesky and Threads: syndications table, worker, reconcile rules, backfeed of responses (ADR-073) |
|
||||
|
||||
## Where to start
|
||||
|
||||
@@ -37,4 +39,4 @@ per-release designs and reports are in [../design/](../design/).
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
@@ -1,8 +1,8 @@
|
||||
# Database Architecture
|
||||
|
||||
**Version**: 2.11.0 (2026-11-03)
|
||||
**Version**: 2.14.0 (2026-11-10)
|
||||
**Status**: Current. Verified against a database created by `create_app()`
|
||||
with migrations 001–019.
|
||||
with migrations 001–022.
|
||||
|
||||
StarPunk uses one SQLite file, `starpunk.db` under `DATA_PATH` (`/data` in
|
||||
the container), in WAL mode. Note *content* is not in the database: it lives
|
||||
@@ -73,6 +73,9 @@ Background: [ADR-031](../decisions/ADR-031-database-migration-system-redesign.md
|
||||
| `017_websub_hardening.sql` | 2.10.1 | `websub_intents.request_id`, `requested_topic`, `callback_ip`; `websub_subscriptions.callback_ip` |
|
||||
| `018_foreign_key_cleanup.sql` | 2.11.0 | Removes rows orphaned while foreign keys weren't enforced |
|
||||
| `019_shared_rate_limits.sql` | 2.11.0 | `rate_limits` (counters shared by all processes) |
|
||||
| `020_backfeed.sql` | 2.13.0 | Rebuilds `webmentions` adding `origin`, `remote_id`, the `quote` type and an index on (`target_note_id`, `origin`); `syndications.backfeed_next_at`, `backfeed_checked_at`, `backfeed_claimed_until`, `backfeed_attempts`, `backfeed_error`, `backfeed_backfill`, `likes_count`, `reposts_count`, `quotes_count` |
|
||||
| `021_notifications.sql` | 2.14.0 | `webmentions.notified_at`; existing rows are marked as notified |
|
||||
| `022_indieauth_resource.sql` | 2.15.0 | `indieauth_codes.resource` and `indieauth_tokens.resource` (RFC 8707, MCP tokens; ADR-075) |
|
||||
|
||||
New migrations are numbered `NNN_description.sql`, must be safe to run inside
|
||||
one transaction, and should use `IF NOT EXISTS` where SQLite allows it.
|
||||
@@ -126,12 +129,12 @@ value), `me`, `created_at`, `expires_at`, `last_used_at`, `user_agent`,
|
||||
(primary key), `nonce`, `code_verifier` (PKCE), `next_url`, `expires_at`.
|
||||
Consumed once on callback.
|
||||
|
||||
**`indieauth_codes`**: authorization codes issued to Micropub clients:
|
||||
**`indieauth_codes`**: authorization codes issued to Micropub and MCP clients:
|
||||
`code_hash`, `client_id`, `redirect_uri`, `scope`, `code_challenge`,
|
||||
`expires_at`, `used_at` (single use).
|
||||
`resource` (`SITE_URL/mcp` or NULL), `expires_at`, `used_at` (single use).
|
||||
|
||||
**`indieauth_tokens`**: access tokens: `token_hash`, `client_id`, `scope`,
|
||||
`created_at`, `expires_at`, `last_used_at`, `revoked_at`. Listed and revoked
|
||||
`resource` (`SITE_URL/mcp` for MCP tokens, NULL for Micropub), `created_at`, `expires_at`, `last_used_at`, `revoked_at`. Listed and revoked
|
||||
in `/admin/tokens`.
|
||||
|
||||
**Legacy tables, unused**: `auth_state` (v1 IndieLogin login state), `tokens`
|
||||
@@ -143,17 +146,20 @@ above.
|
||||
|
||||
### IndieWeb interactions
|
||||
|
||||
**`webmentions`**: received webmentions, one per (`source_url`,
|
||||
`target_url`).
|
||||
**`webmentions`**: received webmentions and backfed silo responses
|
||||
(v2.13.0), one per (`source_url`, `target_url`).
|
||||
|
||||
| Column | Purpose |
|
||||
|--------|---------|
|
||||
| `target_note_id` | The note mentioned (SET NULL if the note is deleted) |
|
||||
| `mention_type` | `reply`, `like`, `repost`, `bookmark`, `mention` |
|
||||
| `mention_type` | `reply`, `like`, `repost`, `bookmark`, `mention`, `quote` |
|
||||
| `author_name`, `author_url`, `author_photo`, `content_snippet` | From the source's mf2 (content sanitised) |
|
||||
| `source_post_url`, `source_published` | The source entry's own `u-url` and `dt-published` |
|
||||
| `validation_status` | `pending`, `valid`, `invalid`, `error` (set by the worker) |
|
||||
| `moderation_status` | `pending`, `approved`, `hidden`, `deleted` (auto-approved when `WEBMENTION_AUTO_APPROVE`) |
|
||||
| `moderation_status` | `pending`, `approved`, `hidden`, `deleted` (auto-approved when `WEBMENTION_AUTO_APPROVE`). `deleted` is a tombstone: deleting in the admin keeps the row, so a re-sent webmention or the next backfeed check doesn't bring it back; re-validation keeps `hidden` and `deleted` |
|
||||
| `origin` | `webmention`, or the silo it was backfed from (`gotosocial`, `bluesky`, `threads`) |
|
||||
| `remote_id` | Silo id of a backfed response (or of the person, for likes and reposts) |
|
||||
| `notified_at` | When the owner was notified of it (v2.14.0); NULL means not yet |
|
||||
| `validation_error`, `validated_at`, `received_at`, `updated_at` | Bookkeeping |
|
||||
|
||||
**`webmention_queue`**: outgoing webmentions, one per (`source_url`,
|
||||
@@ -178,7 +184,12 @@ the note should be on that target; `remote_id` and `remote_url` identify the
|
||||
remote post. `state` (`pending`, `synced`, `failed`), `version` (bumped on
|
||||
every note change, so an edit made during a send is not lost), `attempts`,
|
||||
`last_error`, `next_attempt_at` and `claimed_until` (a 5-minute lease that
|
||||
lets any gunicorn process take the row exclusively) drive the worker. See
|
||||
lets any gunicorn process take the row exclusively) drive the worker.
|
||||
Backfeed (v2.13.0) adds `backfeed_next_at`, `backfeed_checked_at`,
|
||||
`backfeed_claimed_until` (its own lease), `backfeed_attempts`,
|
||||
`backfeed_error` and `backfeed_backfill` (set while a backfill is due), and
|
||||
`likes_count`, `reposts_count`, `quotes_count`: silo-only counts (all of
|
||||
Threads; elsewhere people who opted out). See
|
||||
[syndication-architecture.md](syndication-architecture.md).
|
||||
|
||||
### WebSub
|
||||
@@ -201,7 +212,10 @@ pending row of each kind. `attempts`, `next_attempt_at`, `last_error`.
|
||||
|
||||
**`site_state`**: key/value pairs. `content_version` is bumped whenever a
|
||||
public note changes; every gunicorn process compares it to decide whether
|
||||
its cached feed data is stale.
|
||||
its cached feed data is stale. Backfeed keeps `backfeed_backfill_last` (spacing
|
||||
backfill checks across processes), `backfeed_backfill_started` and
|
||||
`backfeed_backfill_finished`; notifications keep `notify_last_error` (shown
|
||||
in the admin, cleared by a successful send).
|
||||
|
||||
### Bookkeeping
|
||||
|
||||
@@ -223,7 +237,8 @@ server process enforces one shared limit. Old windows are pruned as it goes.
|
||||
it goes back to the pool, rolled back first if a transaction was left
|
||||
open.
|
||||
- **Direct connections**: the migration runner, the FTS start-up check, the
|
||||
webmention worker and sender, reply-context fetching and search helpers
|
||||
webmention worker and sender, the notification sweep (`notifications.py`),
|
||||
avatar upkeep (`avatars.py`), reply-context fetching and search helpers
|
||||
open their own `sqlite3.connect(db_path)` connections.
|
||||
- WAL mode lets readers carry on while one writer writes. The four gunicorn
|
||||
processes and the worker threads share the one file; writes are short, so
|
||||
@@ -233,9 +248,9 @@ server process enforces one shared limit. Old windows are pruned as it goes.
|
||||
|
||||
The application does not back itself up. A consistent copy needs the
|
||||
database (use SQLite's online backup, e.g. `sqlite3 starpunk.db ".backup …"`,
|
||||
because of WAL) together with `notes/` and `media/`; see
|
||||
[deployment.md](deployment.md).
|
||||
because of WAL) together with `notes/` and `media/`. `avatars/` is optional:
|
||||
missing avatars are fetched again. See [deployment.md](deployment.md).
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Deployment Architecture
|
||||
|
||||
**Version**: 2.10.1 (2026-11-03)
|
||||
**Version**: 2.14.0 (2026-11-10)
|
||||
**Status**: Current
|
||||
|
||||
How StarPunk is built, configured and run in production. The production site
|
||||
@@ -70,21 +70,18 @@ authentication.
|
||||
lower case.
|
||||
4. Remove the builder and log out, even after a failure.
|
||||
|
||||
There is no CI on branches or pull requests; run the tests locally before
|
||||
merging (see [technology-stack.md](technology-stack.md#testing)).
|
||||
There is no CI on branches or pull requests. Locally, run the tests for the
|
||||
area you changed; CI runs the full suite on the tag (see
|
||||
[technology-stack.md](technology-stack.md#testing)).
|
||||
|
||||
## Release process
|
||||
|
||||
1. Finish the change on a branch, including the version bump in
|
||||
`starpunk/__init__.py` (`__version__`, `__version_info__`) and a
|
||||
`CHANGELOG.md` entry.
|
||||
2. Merge to `main`.
|
||||
3. Tag the merge commit `vX.Y.Z` and push the tag. CI tests, builds and
|
||||
pushes the image.
|
||||
4. In the Ansible-managed deployment, change the StarPunk image tag to the new
|
||||
version and apply it. The container is recreated from the new image; new
|
||||
migrations run automatically at start-up.
|
||||
5. Check `/health` reports the new version.
|
||||
Branching, version bump, changelog, merge and tagging are in
|
||||
[git-branching-strategy.md](../standards/git-branching-strategy.md#release-process).
|
||||
Pushing a `vX.Y.Z` tag makes CI test, build and push the image. Then, in the
|
||||
Ansible-managed deployment, set `starpunk_version` to the new tag and deploy
|
||||
the `starpunk` service: the container is recreated from the new image and new
|
||||
migrations run at start-up. Check that `/health` reports the new version.
|
||||
|
||||
Rolling back means deploying the previous tag. Migrations are not reversed
|
||||
automatically, so a release with a migration needs a database backup first
|
||||
@@ -105,6 +102,7 @@ persistent is there; the image itself holds no state.
|
||||
| `media/YYYY/MM/` | Uploaded images and their variants; `media/.tmp/` while processing |
|
||||
| `logs/starpunk.log` | Application log, rotated at 10 MB, 10 files kept |
|
||||
| `webmention-worker.lock`, `websub-worker.lock` | `flock` files choosing the process that runs each worker |
|
||||
| `avatars/<sha256>.webp` | Saved copies of response authors' avatars (v2.13.0), served at `/avatars/`; unused ones removed weekly |
|
||||
| `threads_token.json` (+ `.lock`) | Current Threads access token, refreshed daily (only with Threads configured) |
|
||||
| `debug/` | Failed uploads, only with `DEBUG_SAVE_FAILED_UPLOADS=true`; cleaned up after `DEBUG_FILE_MAX_AGE_DAYS` |
|
||||
|
||||
@@ -127,6 +125,14 @@ WebSub rate limits need; without it, every client appears as the proxy's
|
||||
address and shares one limit. Do not set it if the container port can be
|
||||
reached without the proxy, because the header could then be forged.
|
||||
|
||||
The MCP sidecar (v2.15.0, ADR-075) is a second container from the same
|
||||
image, with the same environment and `/data` volume plus
|
||||
`BACKGROUND_WORKERS_ENABLED=false`, running
|
||||
`uvicorn starpunk.mcp_server.app:app --host 0.0.0.0 --port 8001`. The proxy
|
||||
sends `/mcp*` and `/.well-known/oauth-protected-resource*` to it, keeping the
|
||||
`Host` header; everything else goes to port 8000. Without the sidecar the
|
||||
site simply has no MCP endpoint. See [mcp.md](mcp.md).
|
||||
|
||||
`SITE_URL` must be the public `https://` URL: it is used for absolute links,
|
||||
feed and WebSub topic URLs, the IndieAuth issuer and redirect URIs, and to
|
||||
decide whether the session cookie is `Secure`.
|
||||
@@ -161,6 +167,7 @@ unless noted.
|
||||
| `INDIEAUTH_TOKEN_LIFETIME_DAYS` | `90` | Lifetime of Micropub access tokens |
|
||||
| `DEV_MODE` | `false` | Enables `/dev/login`; never in production |
|
||||
| `DEV_ADMIN_ME` | empty | Required when `DEV_MODE=true` |
|
||||
| `CSRF_ENABLED` | `true` | CSRF tokens on admin forms, logout and IndieAuth consent; leave on |
|
||||
|
||||
`TOKEN_ENDPOINT` and `INDIELOGIN_URL` are v1 settings; if present they are
|
||||
ignored with a warning.
|
||||
@@ -176,6 +183,7 @@ ignored with a warning.
|
||||
| `FLASK_DEBUG` | `0` | Debug off unless `1` (`flask run --debug` sets it locally); the image sets `0` |
|
||||
| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` |
|
||||
| `VERSION` | package `__version__` | Overrides the reported version; normally unset |
|
||||
| `BACKGROUND_WORKERS_ENABLED` | `true` | `false` stops the webmention, WebSub and syndication workers; set in the MCP sidecar (v2.15.0) |
|
||||
|
||||
### Feeds
|
||||
|
||||
@@ -190,8 +198,8 @@ ignored with a warning.
|
||||
|
||||
| Variable | Default | Notes |
|
||||
|----------|---------|-------|
|
||||
| `WEBMENTION_ENABLED` | `true` | Endpoint, `Link` header and sending |
|
||||
| `WEBMENTION_WORKER_ENABLED` | `true` | |
|
||||
| `WEBMENTION_ENABLED` | `true` | Endpoint, `Link` header, showing responses on notes (not sending) |
|
||||
| `WEBMENTION_WORKER_ENABLED` | `true` | Verifies received and sends outgoing webmentions; saves avatars; sends response notifications |
|
||||
| `WEBMENTION_POLL_INTERVAL` | `10` | Seconds |
|
||||
| `WEBMENTION_ERROR_BACKOFF` | `60` | Seconds after a worker error |
|
||||
| `WEBMENTION_BATCH_SIZE` | `5` | Items per pass |
|
||||
@@ -219,7 +227,7 @@ starts only if at least one is.
|
||||
|
||||
| Variable | Default | Notes |
|
||||
|----------|---------|-------|
|
||||
| `GOTOSOCIAL_URL`, `GOTOSOCIAL_ACCESS_TOKEN` | empty | GoToSocial or any Mastodon-API server |
|
||||
| `GOTOSOCIAL_URL`, `GOTOSOCIAL_ACCESS_TOKEN` | empty | GoToSocial or any Mastodon-API server. Token scopes: `write:statuses write:media read:search write:favourites`, plus `read:statuses read:accounts` (or `read`) for backfeed |
|
||||
| `GOTOSOCIAL_NAME` | `GoToSocial` | Label in the UI and `syndicate-to` |
|
||||
| `GOTOSOCIAL_VISIBILITY` | `public` | |
|
||||
| `GOTOSOCIAL_MAX_CHARS` | `5000` | |
|
||||
@@ -228,12 +236,22 @@ starts only if at least one is.
|
||||
| `BLUESKY_SERVICE` | `https://bsky.social` | |
|
||||
| `BLUESKY_NAME` | `Bluesky` | |
|
||||
| `BLUESKY_MAX_CHARS` | `300` | |
|
||||
| `THREADS_ACCESS_TOKEN` | empty | Long-lived token; refreshed automatically into `threads_token.json` |
|
||||
| `THREADS_ACCESS_TOKEN` | empty | Long-lived token; refreshed automatically into `threads_token.json`. Backfeed also needs `threads_read_replies` and `threads_manage_insights` |
|
||||
| `THREADS_USERNAME` | empty | |
|
||||
| `THREADS_NAME` | `Threads` | |
|
||||
| `THREADS_MAX_CHARS` | `500` | |
|
||||
| `THREADS_MAX_MEDIA` | `4` | |
|
||||
| `SYNDICATION_POLL_INTERVAL` | `10` | Seconds |
|
||||
| `BACKFEED_ENABLED` | `false` | Bring responses to crossposts back to notes (v2.13.0); needs read scopes on the GoToSocial and Threads tokens |
|
||||
| `BACKFEED_MAX_AGE_DAYS` | `90` | Days after posting to keep checking a crosspost's responses |
|
||||
|
||||
### Notifications
|
||||
|
||||
| Variable | Default | Notes |
|
||||
|----------|---------|-------|
|
||||
| `NOTIFY_URLS` | empty (off) | Apprise URLs, space- or comma-separated (v2.14.0) |
|
||||
| `NOTIFY_EVENTS` | `reply,mention,quote,problems` | Also `like`, `repost`, `bookmark` |
|
||||
| `NOTIFY_PRIORITY` | `normal` | Added to URLs that don't set a priority |
|
||||
|
||||
### Debugging
|
||||
|
||||
@@ -252,15 +270,14 @@ from the environment.
|
||||
## Running locally
|
||||
|
||||
```bash
|
||||
uv venv && uv pip install -r requirements-dev.txt
|
||||
uv venv --python 3.14 && uv pip install -r requirements-dev.txt
|
||||
cp .env.example .env # set SESSION_SECRET; DEV_MODE=true and DEV_ADMIN_ME for local login
|
||||
flask --app app.py run # or: gunicorn app:app
|
||||
uv run flask --app app.py run --debug # or: uv run gunicorn app:app
|
||||
```
|
||||
|
||||
`compose.yaml` builds and runs the image with `./container-data` mounted at
|
||||
`/data`; its image tag and `VERSION` values are out of date, so override them
|
||||
or build with `podman build -t starpunk .`.
|
||||
`compose.yaml` builds the image from this checkout (`starpunk:local`) and runs
|
||||
it with `./container-data` mounted at `/data`.
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
@@ -1,6 +1,6 @@
|
||||
# IndieWeb and W3C Protocols
|
||||
|
||||
How StarPunk implements each protocol it speaks, as of v2.10.1, with its
|
||||
How StarPunk implements each protocol it speaks, as of v2.14.0, with its
|
||||
compliance status and the gaps that remain. Each section links to the
|
||||
decision records and review documents behind it.
|
||||
|
||||
@@ -12,6 +12,8 @@ decision records and review documents behind it.
|
||||
| [Microformats2](#microformats2) | Publisher and consumer | Reviewed in v2.8.0 | `templates/`, `starpunk/mf2_utils.py`, `starpunk/author_discovery.py` |
|
||||
| [WebSub](#websub) | Publisher and built-in hub (own topics only) | Adversarial review in v2.10.1 | `starpunk/websub.py`, `starpunk/websub_worker.py`, `starpunk/routes/websub.py` |
|
||||
| [Feeds](#feeds) | RSS 2.0, Atom 1.0, JSON Feed 1.1, OPML 2.0 | Stable | `starpunk/feeds/`, `starpunk/routes/public.py` |
|
||||
| Backfeed | Responses to crossposts read from the silo APIs and stored as webmentions (v2.13.0); see [syndication-architecture.md](syndication-architecture.md#backfeed-v2130-adr-073) | ADR-073 | `starpunk/backfeed.py` |
|
||||
| [Web actions](#moderation-and-display) | `<indie-action>` on the like, repost and reply counts (v2.13.2) | Markup only | `templates/partials/responses.html` |
|
||||
|
||||
Crossposting to other networks (POSSE) is covered in
|
||||
[syndication-architecture.md](syndication-architecture.md).
|
||||
@@ -19,8 +21,10 @@ Crossposting to other networks (POSSE) is covered in
|
||||
## Shared infrastructure: the SSRF-safe fetcher
|
||||
|
||||
Webmention (fetching sources, discovering endpoints, sending), WebSub
|
||||
(verification and delivery) and Micropub (downloading remote photos) all
|
||||
make requests to URLs chosen by someone else. They use
|
||||
(verification and delivery), Micropub (downloading remote photos), IndieAuth
|
||||
(client pages), reply contexts, crosspost link cards (v2.11.0) and response
|
||||
avatars (v2.13.0; except those on StarPunk's own GoToSocial) all make
|
||||
requests to URLs chosen by someone else. They use
|
||||
`starpunk/webmention_ssrf.py`:
|
||||
|
||||
- `validate_url_for_fetch()`: http(s) only. Every address from
|
||||
@@ -128,7 +132,7 @@ repost, bookmark.
|
||||
| `q=syndicate-to` | any token | `{"syndicate-to": [{"uid", "name"}]}` |
|
||||
| `q=source&url=...[&properties[]=...]` | create/update/delete/draft | One post as mf2 JSON. Content comes back as `{"html": ...}` if it was authored as HTML. Includes `syndication` URLs and `post-status` |
|
||||
| `q=source` without `url` | same | `{"items": [...]}`, drafts included, `limit` (default 10, max 50) and `offset` |
|
||||
| `q=category[&filter=...]` | same | Tags in use, most used first |
|
||||
| `q=category[&filter=...]` | same | Tags on notes that aren't deleted (drafts count), most used first (v2.12.1) |
|
||||
|
||||
Unknown or missing `q` gets 400.
|
||||
|
||||
@@ -171,8 +175,7 @@ Full description, scopes and gaps:
|
||||
Decision: [ADR-064](../decisions/ADR-064-oidc-admin-login-and-builtin-indieauth-server.md).
|
||||
|
||||
Known gaps: `scopes_supported` doesn't list `draft`. There are no
|
||||
introspection, userinfo or refresh tokens. The client metadata fetch
|
||||
doesn't use the pinned SSRF fetcher.
|
||||
introspection, userinfo or refresh tokens.
|
||||
|
||||
---
|
||||
|
||||
@@ -239,25 +242,46 @@ Verification is asynchronous (`WebmentionWorker`, poll
|
||||
- Valid: `validation_status = 'valid'`. A first-time mention gets
|
||||
`moderation_status = 'approved'` if `WEBMENTION_AUTO_APPROVE` (default
|
||||
true), otherwise `pending`. An update keeps the admin's earlier
|
||||
moderation decision.
|
||||
moderation decision, including `hidden` and `deleted`.
|
||||
- Source returns 4xx (including 410), or no longer links: `invalid`,
|
||||
which hides it (3.2.4 deletion).
|
||||
- Network error, timeout or 5xx: a mention that was valid before stays
|
||||
valid with its old data. A new one becomes `error`.
|
||||
- A source that is one of the note's own syndicated copies
|
||||
(`syndications.remote_url`) is `invalid` (v2.8.0).
|
||||
- A source that backfeed has already stored for the note is `invalid`
|
||||
("Already backfed from the silo", v2.13.0).
|
||||
- **Re-send on display change** (3.1.4, v2.7.2): if what the note shows
|
||||
for this webmention changed, the note's own outgoing webmentions are
|
||||
re-queued. That covers a new response, a changed author or snippet, or a
|
||||
change of shown/hidden. Unchanged re-validations send nothing, so two
|
||||
sites doing the same don't ping-pong.
|
||||
|
||||
**Moderation and display.** `/admin/webmentions` lists, filters, and
|
||||
approves, hides or deletes mentions, one at a time or in bulk. Changes that
|
||||
alter what is shown also re-send the note's webmentions. Note pages show
|
||||
approved, valid mentions grouped as replies (`u-comment h-cite`), likes,
|
||||
reposts and bookmarks (facepiles), and mentions. See
|
||||
[Microformats2](#microformats2).
|
||||
### Moderation and display
|
||||
|
||||
`/admin/webmentions` lists, filters (by status, including Deleted, and by
|
||||
origin), and approves, hides or deletes responses, one at a time or in bulk;
|
||||
it also has the Backfill button. Deleting keeps the row as a `deleted`
|
||||
tombstone, so a re-sent webmention or backfeed doesn't bring it back.
|
||||
Changes that alter what is shown also re-send the note's webmentions.
|
||||
|
||||
Note pages show approved, valid responses. Under the note, a line of counts
|
||||
(♥ likes, 🔁 reposts, 💬 replies, ❝ quotes (v2.14.2), bookmarks) opens a card on hover or focus
|
||||
listing who responded and where from, including anonymous silo counts. Each
|
||||
like, repost and reply count holds an `<indie-action do with>` web action
|
||||
whose fallback links to the note's crossposts (v2.13.2). The Responses
|
||||
section below holds replies (`u-comment h-cite`), quotes and mentions;
|
||||
backfed ones say "via <silo>". See [Microformats2](#microformats2).
|
||||
|
||||
### Notifications (v2.14.0, ADR-074)
|
||||
|
||||
With `NOTIFY_URLS` set, new valid responses (received and backfed) are sent
|
||||
to the owner once through Apprise by a sweep in the webmention worker, which
|
||||
sets `webmentions.notified_at` (migration 021). Likes, reposts and bookmarks
|
||||
are grouped per note; which kinds are sent is set by `NOTIFY_EVENTS`
|
||||
(default replies, mentions, quotes and problems). Items still unsent after
|
||||
24 hours are dropped. Responses found by a backfill, or by a copy's first
|
||||
check on a note older than a day, are never notified.
|
||||
|
||||
### Sending
|
||||
|
||||
@@ -339,8 +363,9 @@ representative h-card, authorship, Post Type Discovery. Decisions:
|
||||
| `/note/<slug>` | `h-entry`: `p-name` only when the note starts with a `# Heading` (so plain notes have no implied name); `u-photo` as direct children above `e-content`; `u-url u-uid` with `dt-published` (RFC 3339 UTC `Z`); `dt-updated`; `p-category` with `rel=tag`; `u-syndication` links; hidden `p-author h-card` |
|
||||
| Replies | `u-in-reply-to h-cite` holding the cached reply context (`p-content`, `u-url`) |
|
||||
| Likes / reposts / bookmarks | `u-like-of` / `u-repost-of` / `u-bookmark-of` link with "★ Liked" / "🔁 Reposted" / "🔖 Bookmarked" |
|
||||
| Received responses | `u-comment h-cite` (replies: `p-author h-card` with `u-url` on an inner link, `u-photo`, `p-name`; `e-content`; `u-url`; `dt-published`), and `u-like`, `u-repost`, `u-bookmark`, `u-mention` h-cites. Faces beyond 8 are `hidden`, not omitted |
|
||||
| Received responses | `u-comment h-cite` (replies: `p-author h-card` with `u-url` on an inner link, `u-photo`, `p-name`; `e-content`; `u-url`; `dt-published`), likes, reposts and bookmarks as `u-like`, `u-repost`, `u-bookmark` h-cites in the counts line card; mentions and quotes as `u-mention` h-cites |
|
||||
| `/likes`, `/tag/<tag>` | `h-feed` with `p-name`, `u-url`, `p-author h-card` |
|
||||
| Response counts | `/`, `/tag/<tag>` and `/likes` show each note's like, repost and reply counts, linking to its `#responses` (v2.13.4) |
|
||||
|
||||
Post Type Discovery gives note, article, reply, like, repost, bookmark and
|
||||
photo correctly.
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# MCP server (v2.15.0)
|
||||
|
||||
How AI clients use StarPunk through the
|
||||
[Model Context Protocol](https://modelcontextprotocol.io/). The decision and
|
||||
alternatives are in [ADR-075](../decisions/ADR-075-mcp-server.md).
|
||||
|
||||
## Shape
|
||||
|
||||
```
|
||||
client ──HTTPS──> reverse proxy
|
||||
/mcp*, /.well-known/oauth-protected-resource* ──> starpunk-mcp:8001 (uvicorn, MCP SDK)
|
||||
everything else (incl. /auth/*, /.well-known/oauth-authorization-server)
|
||||
──> starpunk:8000 (gunicorn, Flask)
|
||||
starpunk and starpunk-mcp: same image, same environment, same /data volume
|
||||
```
|
||||
|
||||
| Module | Role |
|
||||
|---|---|
|
||||
| `starpunk/mcp_server/app.py` | ASGI entry: `uvicorn starpunk.mcp_server.app:app --host 0.0.0.0 --port 8001` |
|
||||
| `starpunk/mcp_server/server.py` | `create_mcp_server(app)` and `create_asgi_app(app=None)`: stateless Streamable HTTP, JSON responses, 16 MB request limit, DNS rebinding protection |
|
||||
| `starpunk/mcp_server/auth.py` | `StarPunkTokenVerifier`: StarPunk tokens to SDK `AccessToken`s |
|
||||
| `starpunk/mcp_server/tools.py` | The tools; each runs in a thread inside `app.test_request_context(base_url=SITE_URL)` |
|
||||
|
||||
`create_asgi_app()` with no argument builds the Flask app from the
|
||||
environment with `BACKGROUND_WORKERS_ENABLED=false`. The sidecar container
|
||||
should also set that variable, for clarity.
|
||||
|
||||
## Authorization flow
|
||||
|
||||
1. The client POSTs to `/mcp` without a token and gets `401` with
|
||||
`WWW-Authenticate: Bearer ... resource_metadata="SITE_URL/.well-known/oauth-protected-resource/mcp"`.
|
||||
2. That document names `SITE_URL/mcp` as the resource and `SITE_URL/` as
|
||||
the authorization server. The client reads
|
||||
`/.well-known/oauth-authorization-server`, which says it accepts client ID
|
||||
metadata documents and public clients.
|
||||
3. The client sends the owner to `/auth/authorize` with its `client_id` URL,
|
||||
PKCE and `resource=SITE_URL/mcp`. StarPunk fetches the client's metadata
|
||||
document to check `redirect_uri` (unless it has the same origin as the
|
||||
`client_id`), and the owner logs in with OIDC and approves. With no
|
||||
`scope`, the default MCP scopes are offered.
|
||||
4. The token endpoint exchanges the code. The token is bound to the
|
||||
resource.
|
||||
5. Each MCP request carries the token. The verifier looks it up and the SDK
|
||||
refuses it unless its resource is `SITE_URL/mcp`.
|
||||
|
||||
Details of codes, tokens and scopes are in
|
||||
[simplified-auth-architecture.md](simplified-auth-architecture.md).
|
||||
|
||||
## Tools
|
||||
|
||||
| Tool | Does | Scope |
|
||||
|---|---|---|
|
||||
| `search_notes(query, include_drafts, limit)` | FTS5 search, with snippets | any; drafts need a posting scope |
|
||||
| `list_notes(include_drafts, limit, offset)` | Newest first, summaries | any; drafts need a posting scope |
|
||||
| `get_note(url_or_slug)` | Microformats2 properties (as Micropub `q=source`) | any; drafts need a posting scope |
|
||||
| `list_tags(filter)` | Tags in use, most used first | posting scope |
|
||||
| `get_site_config()` | Micropub `q=config`, including `syndicate-to` targets | any |
|
||||
| `create_note(content, title, tags, draft=True, photos, in_reply_to, like_of, repost_of, bookmark_of, syndicate_to, slug, published_at)` | Micropub create | `create` or `draft` |
|
||||
| `update_note(url, content, title, tags, add_tags, remove_tags, draft, photos, in_reply_to)` | Micropub update | `update` |
|
||||
| `delete_note(url)`, `undelete_note(url)` | Soft delete and restore | `delete` |
|
||||
| `upload_media(filename, data_base64)` | Save an image, return its URL | `media` or `create` |
|
||||
|
||||
"Posting scope" means `create`, `update`, `delete` or `draft`. Limits are
|
||||
capped at 100. Micropub errors come back as tool errors (`isError`) with the
|
||||
Micropub error description.
|
||||
|
||||
## Operating it
|
||||
|
||||
- Environment: the same as the main container, plus
|
||||
`BACKGROUND_WORKERS_ENABLED=false`.
|
||||
- Proxy: route `/mcp*` and `/.well-known/oauth-protected-resource*` to port
|
||||
8001, keeping the `Host` header (DNS rebinding protection checks it
|
||||
against `SITE_URL`).
|
||||
- Connecting: claude.ai Settings → Connectors → Add custom connector with
|
||||
`SITE_URL/mcp`; Claude Code: `claude mcp add --transport http starpunk
|
||||
SITE_URL/mcp`, then `/mcp` to authenticate.
|
||||
- Revoking: Admin → Connected Apps (MCP tokens are marked "(MCP)").
|
||||
@@ -1,6 +1,6 @@
|
||||
# StarPunk Architecture Overview
|
||||
|
||||
**Version**: 2.10.1 (2026-11-03)
|
||||
**Version**: 2.14.0 (2026-11-10)
|
||||
**Status**: Current. Describes the system as it is in the code today.
|
||||
|
||||
## Purpose
|
||||
@@ -10,7 +10,9 @@ owner) writes short notes, which are published as microformats2-marked HTML
|
||||
pages and as RSS, Atom and JSON feeds. The site takes part in the IndieWeb:
|
||||
it accepts posts from Micropub clients, issues its own IndieAuth tokens for
|
||||
them, sends and receives Webmentions, pushes feed updates with WebSub, and
|
||||
crossposts (POSSE) to GoToSocial, Bluesky and Threads.
|
||||
crossposts (POSSE) to GoToSocial, Bluesky and Threads. Responses to those
|
||||
crossposts are pulled back and shown on the note (backfeed), and the owner
|
||||
can be notified of new responses.
|
||||
|
||||
Guiding principle: "every line of code must justify its existence". It is a
|
||||
single Flask application with server-side rendering, SQLite and plain files.
|
||||
@@ -39,6 +41,9 @@ Key decisions:
|
||||
[ADR-067](../decisions/ADR-067-micropub-update-delete.md) (Micropub update/delete),
|
||||
[ADR-068](../decisions/ADR-068-likes-and-reposts.md) (likes and reposts),
|
||||
[ADR-071](../decisions/ADR-071-websub.md) (WebSub),
|
||||
[ADR-072](../decisions/ADR-072-remove-metrics-dashboard.md) (metrics dashboard removed),
|
||||
[ADR-073](../decisions/ADR-073-backfeed.md) (backfeed),
|
||||
[ADR-074](../decisions/ADR-074-notifications.md) (notifications),
|
||||
[ADR-057](../decisions/ADR-057-media-attachment-model.md) and
|
||||
[ADR-058](../decisions/ADR-058-image-optimization-strategy.md) (media),
|
||||
[ADR-034](../decisions/ADR-034-full-text-search.md) (search),
|
||||
@@ -70,8 +75,9 @@ Key decisions:
|
||||
│ starpunk.db │ │ OIDC provider, IndieAuth │
|
||||
│ notes/*.md │ │ client pages, webmention │
|
||||
│ media/ │ │ sources/targets, WebSub │
|
||||
│ logs/, locks │ │ callbacks, GoToSocial, │
|
||||
└────────────────┘ │ Bluesky, Threads │
|
||||
│ avatars/ │ │ callbacks, GoToSocial, │
|
||||
│ logs/, locks │ │ Bluesky, Threads, avatars, │
|
||||
└────────────────┘ │ notifications (Apprise) │
|
||||
└─────────────────────────────┘
|
||||
```
|
||||
|
||||
@@ -127,12 +133,16 @@ wait for outbound network calls; the workers make them later.
|
||||
| `reply_context.py` | Fetches and caches the post a reply responds to |
|
||||
| `webmention_sender.py` | Extracts links from rendered notes and queues outgoing webmentions |
|
||||
| `webmention_processor.py` | Validates incoming webmentions: fetch source, parse mf2, classify, sanitise content |
|
||||
| `webmention_worker.py` | Background thread working the incoming and outgoing webmention queues |
|
||||
| `webmention_worker.py` | Background thread working the incoming and outgoing webmention queues; also runs avatar upkeep and the notification sweep |
|
||||
| `webmention_queries.py` | Webmention queries for display and moderation |
|
||||
| `webmention_ssrf.py` | SSRF-safe fetcher: public-address checks, pinned connections, manual redirects, size and time limits |
|
||||
| `websub.py` | WebSub publisher (discovery headers and links, `content_version`, queueing) and hub request handling |
|
||||
| `websub_worker.py` | Background thread: verification of intent, content delivery, publish pings to an external hub |
|
||||
| `syndication.py` | POSSE clients (Mastodon API/GoToSocial, Bluesky, Threads), reconcile logic, syndication worker |
|
||||
| `syndication.py` | POSSE clients (Mastodon API/GoToSocial, Bluesky, Threads), reconcile logic, syndication worker (its loop also calls `backfeed.process_due()`) |
|
||||
| `backfeed.py` | Backfeed: reads responses to crossposts from the silos, stores them as webmentions, schedules checks and backfills |
|
||||
| `avatars.py` | Saves response authors' avatars as 96 px WebP files in `avatars/`; fills missing ones and removes unused ones |
|
||||
| `notifications.py` | Notifications through Apprise: the sweep of new responses and immediate problem messages |
|
||||
| `csrf.py` | CSRF tokens (HMAC of the session cookie) for admin forms, logout and the IndieAuth consent |
|
||||
| `rate_limiter.py` | In-memory sliding-window rate limiter |
|
||||
| `errors.py` | Central error handlers |
|
||||
| `feeds/` | `rss.py` (feedgen), `atom.py`, `json_feed.py`, `opml.py`, `negotiation.py` (Accept header), `cache.py` (LRU + TTL feed cache with ETags) |
|
||||
@@ -144,7 +154,7 @@ wait for outbound network calls; the workers make them later.
|
||||
|
||||
| Blueprint | File | Paths |
|
||||
|-----------|------|-------|
|
||||
| `public` | `public.py` | `/`, `/note/<slug>`, `/tag/<tag>`, `/likes`, `/media/<path>`, feeds, `/opml.xml` |
|
||||
| `public` | `public.py` | `/`, `/note/<slug>`, `/tag/<tag>`, `/likes`, `/media/<path>`, `/avatars/<name>`, feeds, `/opml.xml` |
|
||||
| `auth` | `auth.py` | `/auth/login` (GET, POST), `/auth/callback`, `/auth/logout` (POST) |
|
||||
| `indieauth` | `indieauth.py` | `/.well-known/oauth-authorization-server`, `/auth/authorize` (GET, POST), `/auth/authorize/approve`, `/auth/token` (GET, POST), `/auth/revoke` |
|
||||
| `micropub` | `micropub.py` | `/micropub` (GET, POST), `/micropub/media` (POST), `/media` (POST, legacy alias) |
|
||||
@@ -163,20 +173,20 @@ Jinja2 templates live in `templates/`: public pages, `admin/`, `partials/`
|
||||
reposts and bookmarks) and one page per HTTP error. `templates/base.html`
|
||||
carries the discovery links (`rel=micropub`, `indieauth-metadata`,
|
||||
`authorization_endpoint`, `token_endpoint`, `webmention`, `hub`/`self`, `me`,
|
||||
feeds). Static assets are one stylesheet (`static/css/style.css`) and one
|
||||
script (`static/js/preview.js`, the Markdown preview in the admin editor).
|
||||
Everything works without JavaScript.
|
||||
feeds). Static assets are one stylesheet (`static/css/style.css`); admin
|
||||
pages have small inline scripts. Everything works without JavaScript.
|
||||
|
||||
## Public URL surface
|
||||
|
||||
| Path | Purpose |
|
||||
|------|---------|
|
||||
| `/` | Home page: recent published notes (h-feed); likes are kept off it |
|
||||
| `/note/<slug>` | Note permalink (h-entry), with approved webmentions and reply context |
|
||||
| `/note/<slug>` | Note permalink (h-entry), with approved responses (webmentions and backfed silo responses), a counts line with web actions, and reply context |
|
||||
| `/tag/<tag>` | Notes with a tag |
|
||||
| `/likes` | Likes |
|
||||
| `/search`, `/api/search` | Full-text search page and JSON API |
|
||||
| `/media/<path>` | Uploaded images and their variants |
|
||||
| `/avatars/<name>` | Saved copies of response authors' avatars |
|
||||
| `/feed` | Feed chosen by the `Accept` header (RSS by default; `Vary: Accept`) |
|
||||
| `/feed.rss`, `/feed.atom`, `/feed.json` | RSS 2.0, Atom 1.0, JSON Feed 1.1 |
|
||||
| `/feed.xml` | Legacy alias of `/feed.rss` |
|
||||
@@ -191,8 +201,15 @@ Everything works without JavaScript.
|
||||
| `/admin/webmentions`, `/admin/webmentions/<id>`, `…/action`, `…/bulk-action` | Webmention moderation |
|
||||
| `/admin/tokens`, `/admin/tokens/<id>/revoke` | Issued IndieAuth tokens |
|
||||
| `/admin/syndication/<id>/retry` | Retry a failed crosspost |
|
||||
| `/admin/syndication/<id>/check` (POST) | Check one crosspost for responses now |
|
||||
| `/admin/backfeed/backfill` (POST) | Check every crosspost for responses once (backfill) |
|
||||
| `/admin/notifications/test` (POST) | Send a test notification |
|
||||
| `/admin/health` | Full diagnostics (JSON): database, pool statistics, filesystem, disk |
|
||||
| `/health` | Public liveness check (`{"status": "ok", "version": …}`); `?detailed=true` requires login |
|
||||
| `/dev/login` | Development login; only when `DEV_MODE=true` |
|
||||
|
||||
`/`, `/tag/<tag>` and `/likes` show each note's response counts, linking to
|
||||
its responses (v2.13.4).
|
||||
|
||||
## Background workers
|
||||
|
||||
@@ -202,9 +219,12 @@ coordinated through the data volume:
|
||||
|
||||
| Thread | Started when | Coordination | Work |
|
||||
|--------|--------------|--------------|------|
|
||||
| Webmention worker (`webmention_worker.py`) | `WEBMENTION_WORKER_ENABLED` and not testing | Non-blocking `fcntl.flock` on `webmention-worker.lock` next to the database. Only the holder works the queues; the others try again each poll interval. The OS releases the lock if the holder dies, and the new holder resets rows stuck in `sending`. | Validates received webmentions; discovers endpoints and sends queued outgoing webmentions, with retries; saves response avatars (v2.13.0); sends notifications of new responses (v2.14.0, `notifications.py`, ADR-074) |
|
||||
| Webmention worker (`webmention_worker.py`) | `WEBMENTION_WORKER_ENABLED` and not testing | Non-blocking `fcntl.flock` on `webmention-worker.lock` next to the database. Only the holder works the queues; the others try again each poll interval. The OS releases the lock if the holder dies, and the new holder resets rows stuck in `sending`. | Validates received webmentions; discovers endpoints and sends queued outgoing webmentions, with retries; saves missing response avatars every 10 minutes and removes unused ones weekly (v2.13.0); sweeps new responses into notifications and sets `webmentions.notified_at` (v2.14.0, `notifications.py`, ADR-074) |
|
||||
| WebSub worker (`websub_worker.py`) | `WEBSUB_ENABLED` and not testing | Same pattern with `websub-worker.lock` | Verifies subscription intents, delivers topic content (signed with `X-Hub-Signature` when the subscriber gave a secret), retries, expires leases; pings an external hub instead if `WEBSUB_HUB_URL` is set |
|
||||
| Syndication worker (`syndication.py`) | At least one crosspost target configured, and not testing | No file lock. Rows in `syndications` are claimed with a 5-minute `claimed_until` lease by an atomic `UPDATE`, so any process may work a row but only one at a time; a `version` column keeps edits made during a send. Threads token refreshes are serialised with a lock file next to `threads_token.json`. | Creates, updates or deletes the remote post for each (note, target) pair; up to 8 attempts. Then backfeed: checks copies for responses (v2.13.0, `backfeed.py`, ADR-073) |
|
||||
| Syndication worker (`syndication.py`) | At least one crosspost target configured, and not testing | No file lock. Rows in `syndications` are claimed with a 5-minute `claimed_until` lease by an atomic `UPDATE`, so any process may work a row but only one at a time; a `version` column keeps edits made during a send. Threads token refreshes are serialised with a lock file next to `threads_token.json`. | Creates, updates or deletes the remote post for each (note, target) pair; up to 8 attempts. Then, only when `BACKFEED_ENABLED`, backfeed: checks copies for responses, each claimed with a `backfeed_claimed_until` lease (v2.13.0, `backfeed.py`, ADR-073) |
|
||||
|
||||
`BACKGROUND_WORKERS_ENABLED=false` starts none of them; the MCP sidecar
|
||||
(below) sets it so the workers only run in the main container.
|
||||
|
||||
All workers run inside an app context, are daemon threads (they end with the
|
||||
process) and sleep for their poll interval when there is nothing to do. Under
|
||||
@@ -225,9 +245,12 @@ Content is kept in files and everything else in SQLite, both under
|
||||
- **Media**: `media/YYYY/MM/<uuid>.<ext>` plus `<uuid>_<variant>.<ext>`
|
||||
variants, staged in `media/.tmp/` while being processed.
|
||||
- **Database**: `starpunk.db` (WAL mode): note metadata, tags, media records,
|
||||
sessions, IndieAuth codes and tokens, webmentions and the outgoing queue,
|
||||
syndications, WebSub subscriptions and queues, caches (author h-card, reply
|
||||
sessions, IndieAuth codes and tokens, webmentions (including backfed silo
|
||||
responses, marked by `origin` and `remote_id`) and the outgoing queue,
|
||||
syndications (with backfeed state and silo-only counts), WebSub subscriptions and queues, caches (author h-card, reply
|
||||
contexts), the FTS5 index and `site_state`. See [database.md](database.md).
|
||||
- **Avatars**: `avatars/<sha256>.webp`, saved copies of response authors'
|
||||
avatars (v2.13.0); they can be re-fetched, so losing them is harmless.
|
||||
- **Other files**: `logs/starpunk.log` (rotating), worker lock files,
|
||||
`threads_token.json`, and `debug/` for failed uploads when
|
||||
`DEBUG_SAVE_FAILED_UPLOADS=true`.
|
||||
@@ -253,7 +276,14 @@ are in [simplified-auth-architecture.md](simplified-auth-architecture.md).
|
||||
OIDC) approves; the client exchanges the code at `/auth/token` (PKCE
|
||||
required). Codes and tokens are stored hashed. Tokens last
|
||||
`INDIEAUTH_TOKEN_LIFETIME_DAYS` and can be revoked at `/auth/revoke` or in
|
||||
`/admin/tokens`. Scopes: `create`, `update`, `delete`, `media`, `profile`.
|
||||
`/admin/tokens`. Scopes: `create`, `update`, `delete`, `media`, `draft`,
|
||||
`profile`.
|
||||
- **MCP (v2.15.0, ADR-075)**: AI clients use the same flow, identified by a
|
||||
client ID metadata document and asking for `resource=SITE_URL/mcp`. Their
|
||||
tokens are bound to that resource and checked by the MCP sidecar, a second
|
||||
container (uvicorn, official MCP SDK) that the proxy sends `/mcp` to. Its
|
||||
tools read, search and write notes through the Micropub handlers. See
|
||||
[mcp.md](mcp.md).
|
||||
- **Development**: `DEV_MODE=true` adds `/dev/login`, which logs in as
|
||||
`DEV_ADMIN_ME` without any checks. Never enabled in production; start-up
|
||||
logs a warning when it is on.
|
||||
@@ -279,20 +309,28 @@ their credentials are set. The full list with defaults is in
|
||||
- **Author h-card** (`author_profile`, 24 hours) and **reply contexts**
|
||||
(`reply_contexts`) are cached in the database.
|
||||
- The webmention worker caches endpoint discovery results in memory.
|
||||
- **Response avatars** are saved once as files named by the SHA-256 of the
|
||||
source URL and served from `/avatars/<name>` with
|
||||
`Cache-Control: public, max-age=604800` (one week).
|
||||
|
||||
## Security posture
|
||||
|
||||
- **Outbound requests (SSRF)**: fetches of URLs that come from outside
|
||||
(webmention sources and targets, endpoint discovery, reply contexts, WebSub
|
||||
callbacks, remote Micropub photos, IndieAuth client pages, crosspost link
|
||||
cards) are checked first: every address the host resolves to must be public
|
||||
(private, loopback, link-local, CGNAT, multicast and reserved ranges are
|
||||
refused). Every fetch of a user-supplied URL (webmentions, reply contexts,
|
||||
WebSub, remote Micropub photos, IndieAuth client pages and, since v2.11.0,
|
||||
crosspost link cards) uses the fetcher in `webmention_ssrf.py`: it follows
|
||||
redirects by hand and re-checks each hop, connects to the address it
|
||||
checked (no second DNS lookup) and limits response size (1 MB by default)
|
||||
and total time. `DEV_MODE` relaxes the checks for local testing.
|
||||
- **Outbound requests (SSRF)**: every fetch of a URL that comes from
|
||||
outside (webmention sources and targets, endpoint discovery, reply
|
||||
contexts, WebSub callbacks, remote Micropub photos, IndieAuth client pages,
|
||||
crosspost link cards since v2.11.0, response avatars since v2.13.0) goes
|
||||
through the fetcher in `webmention_ssrf.py`. Every address the host
|
||||
resolves to must be public (private, loopback, link-local, CGNAT,
|
||||
multicast and reserved ranges are refused); it follows redirects by hand
|
||||
and re-checks each hop, connects to the address it checked (no second DNS
|
||||
lookup) and limits response size (1 MB by default) and total time.
|
||||
`DEV_MODE` relaxes the checks for local testing. Exceptions: avatars on
|
||||
the site's own `GOTOSOCIAL_URL` host are fetched directly, as the
|
||||
crossposting client does, since behind the same proxy it may resolve to an
|
||||
internal address (v2.13.1); Bluesky CDN avatars are fetched from the
|
||||
account's PDS with `com.atproto.sync.getBlob`, itself through the safe
|
||||
fetcher. Apprise notifications go to the owner-configured `NOTIFY_URLS`,
|
||||
outside the safe fetcher.
|
||||
- **HTML sanitising**: rendered notes (Markdown or HTML sent by a Micropub
|
||||
client) and webmention content are cleaned with nh3 allow-lists; search
|
||||
highlighting escapes everything except `<mark>`.
|
||||
@@ -327,4 +365,4 @@ their credentials are set. The full list with defaults is in
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2026-11-03 (v2.12.0)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Authentication and Authorization Architecture
|
||||
|
||||
Current as of v2.10.1. Decision record: [ADR-064](../decisions/ADR-064-oidc-admin-login-and-builtin-indieauth-server.md),
|
||||
Current as of v2.14.0 (no auth changes since v2.11.0). Decision record: [ADR-064](../decisions/ADR-064-oidc-admin-login-and-builtin-indieauth-server.md),
|
||||
which supersedes the "no self-hosted IndieAuth" decisions
|
||||
([ADR-050](../decisions/ADR-050-remove-custom-indieauth-server.md),
|
||||
[ADR-056](../decisions/ADR-056-no-selfhosted-indieauth.md)) and the external
|
||||
@@ -137,8 +137,10 @@ form `{"error", "error_description"}`.
|
||||
"token_endpoint": "<SITE_URL>/auth/token",
|
||||
"revocation_endpoint": "<SITE_URL>/auth/revoke",
|
||||
"revocation_endpoint_auth_methods_supported": ["none"],
|
||||
"scopes_supported": ["create", "update", "delete", "media", "profile"],
|
||||
"scopes_supported": ["create", "update", "delete", "media", "draft", "profile"],
|
||||
"response_types_supported": ["code"],
|
||||
"token_endpoint_auth_methods_supported": ["none"],
|
||||
"client_id_metadata_document_supported": true,
|
||||
"grant_types_supported": ["authorization_code"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
"authorization_response_iss_parameter_supported": true
|
||||
@@ -192,7 +194,7 @@ requested and left checked, issues a code, and redirects with `code`,
|
||||
| Value | 32 random bytes, URL-safe | 32 random bytes, URL-safe |
|
||||
| Stored as | SHA-256 hash | SHA-256 hash |
|
||||
| Lifetime | 10 minutes | `INDIEAUTH_TOKEN_LIFETIME_DAYS` (default 90) |
|
||||
| Bound to | `client_id`, `redirect_uri`, `scope`, `code_challenge` | `client_id`, `scope` |
|
||||
| Bound to | `client_id`, `redirect_uri`, `scope`, `code_challenge`, `resource` | `client_id`, `scope`, `resource` |
|
||||
|
||||
`redeem_authorization_code` handles redemption for both `POST /auth/token`
|
||||
and `POST /auth/authorize`:
|
||||
@@ -213,11 +215,22 @@ refresh tokens: a client re-authorizes when its token expires.
|
||||
|
||||
Expired codes are deleted whenever a new code is issued.
|
||||
|
||||
**Resource indicators (v2.15.0, ADR-075).** An authorization request may
|
||||
include `resource` (RFC 8707). The only accepted value is `SITE_URL/mcp`
|
||||
(a trailing slash is ignored); anything else is `invalid_target`. With it,
|
||||
a request without `scope` is offered `create update delete media draft`, and
|
||||
the consent screen says the client is an AI assistant using MCP. The resource
|
||||
is stored on the code and then on the token. A token request that names a
|
||||
different resource gets `invalid_target`. Micropub clients send no resource
|
||||
and their tokens have none. The MCP endpoint only accepts tokens for its
|
||||
resource; see [mcp.md](mcp.md).
|
||||
|
||||
### Verification and revocation
|
||||
|
||||
- `verify_access_token(token)` hashes the token and accepts it if it is
|
||||
neither revoked nor expired, then updates `last_used_at`. It returns
|
||||
`{me: ADMIN_ME, client_id, scope}`.
|
||||
`{me: ADMIN_ME, client_id, scope, resource, expires_at}`. The legacy
|
||||
`GET /auth/token` still answers with only `me`, `client_id` and `scope`.
|
||||
- `check_scope(required, scope)` matches whole words in the space-separated
|
||||
scope string.
|
||||
- Revocation sets `revoked_at`. It can happen by token value, through
|
||||
@@ -308,8 +321,8 @@ enough. If it is another page, that page must advertise StarPunk's
|
||||
|---|---|---|
|
||||
| `sessions` | Admin browser sessions | `session_token_hash`, `me`, `expires_at`, `last_used_at`, `user_agent`, `ip_address` |
|
||||
| `oidc_login_state` | One pending OIDC login | `state` (PK), `nonce`, `code_verifier`, `next_url`, `expires_at` |
|
||||
| `indieauth_codes` | Authorization codes | `code_hash`, `client_id`, `redirect_uri`, `scope`, `code_challenge`, `expires_at`, `used_at` |
|
||||
| `indieauth_tokens` | Access tokens | `token_hash`, `client_id`, `scope`, `expires_at`, `last_used_at`, `revoked_at` |
|
||||
| `indieauth_codes` | Authorization codes | `code_hash`, `client_id`, `redirect_uri`, `scope`, `code_challenge`, `resource` (migration 022), `expires_at`, `used_at` |
|
||||
| `indieauth_tokens` | Access tokens | `token_hash`, `client_id`, `scope`, `resource` (migration 022), `expires_at`, `last_used_at`, `revoked_at` |
|
||||
|
||||
The legacy v1 tables `auth_state`, `tokens` and `authorization_codes` are
|
||||
not used (see the migration's header comment).
|
||||
@@ -338,7 +351,6 @@ connection pinned, a 5-second limit).
|
||||
|
||||
Known gaps:
|
||||
|
||||
- `scopes_supported` leaves out `draft`, although Micropub honours it and
|
||||
the consent screen grants it when requested. Unknown scopes are also shown
|
||||
and granted as requested; they just have no effect.
|
||||
- Unknown scopes are shown and granted as requested; they just have no
|
||||
effect. (`draft` has been listed in `scopes_supported` since v2.15.0.)
|
||||
- No token introspection endpoint and no refresh tokens.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Syndication (POSSE) Architecture
|
||||
|
||||
Current as of v2.10.1. Code: `starpunk/syndication.py`.
|
||||
Current as of v2.14.0. Code: `starpunk/syndication.py`, `starpunk/backfeed.py`.
|
||||
|
||||
StarPunk publishes on its own site first and then copies each note to other
|
||||
networks (POSSE: Publish on your Own Site, Syndicate Elsewhere). Later
|
||||
@@ -16,7 +16,9 @@ Decisions: [ADR-065](../decisions/ADR-065-direct-syndication-posse.md)
|
||||
(Bluesky), [ADR-068](../decisions/ADR-068-likes-and-reposts.md) (likes and
|
||||
reposts), [ADR-069](../decisions/ADR-069-threads-syndication.md) (Threads),
|
||||
[ADR-070](../decisions/ADR-070-crosspost-links-and-cards.md) (links and link
|
||||
cards), and the [v2.9.0 Micropub review](../design/v2.9.0/2026-11-03-micropub-review.md)
|
||||
cards), [ADR-073](../decisions/ADR-073-backfeed.md) (backfeed),
|
||||
[ADR-074](../decisions/ADR-074-notifications.md) (notifications, including
|
||||
crossposting problems), and the [v2.9.0 Micropub review](../design/v2.9.0/2026-11-03-micropub-review.md)
|
||||
(bookmarks, `mp-syndicate-to` default).
|
||||
|
||||
## Targets
|
||||
@@ -34,7 +36,10 @@ in the process.
|
||||
Display names come from `GOTOSOCIAL_NAME`, `BLUESKY_NAME` and
|
||||
`THREADS_NAME`. GoToSocial statuses use `GOTOSOCIAL_VISIBILITY` (default
|
||||
`public`). The GoToSocial token needs `write:statuses` and `write:media`,
|
||||
plus `read:search` and `write:favourites` for likes and boosts.
|
||||
plus `read:search` and `write:favourites` for likes and boosts, and
|
||||
`read:statuses` and `read:accounts` (or `read`) for backfeed. Backfeed on
|
||||
Threads needs `threads_read_replies` and `threads_manage_insights`. The
|
||||
Threads client uses the API host `graph.threads.com` (v2.13.0).
|
||||
|
||||
Bluesky and Threads can't edit posts through their APIs. Once a copy exists
|
||||
there, edits to the note don't change it, but unpublish and delete still
|
||||
@@ -59,6 +64,9 @@ is sent until the note is published.
|
||||
|
||||
## Data: the `syndications` table (migration 012)
|
||||
|
||||
Migration 020 adds the backfeed columns; see [Backfeed](#backfeed-v2130-adr-073)
|
||||
and [database.md](database.md#crossposting).
|
||||
|
||||
One row per (note, target), unique on `(note_id, target)`:
|
||||
|
||||
| Column | Meaning |
|
||||
@@ -83,6 +91,8 @@ delete and the worker can still remove the copy.
|
||||
| Micropub photo changes | `note_changed(id)` | Same |
|
||||
| `delete_note()` (soft or hard), `undelete_note()` | `note_changed(id)` | Same |
|
||||
| Retry button on the edit page | `retry(id)` | That row set to `pending` now, attempts reset |
|
||||
| Check now (`POST /admin/syndication/<id>/check`) | `backfeed.check_now(id)` | That copy's responses checked at the next worker pass |
|
||||
| Backfill responses (`POST /admin/backfeed/backfill`) | `backfeed.start_backfill()` | Every eligible copy flagged for one check |
|
||||
|
||||
## Worker
|
||||
|
||||
@@ -130,7 +140,8 @@ again with the new content. `_fail()` does the same.
|
||||
errors (codes 10, 190, 200).
|
||||
- Other errors retry after `min(30 s × 2^attempts, 6 h)`. After 8 attempts
|
||||
the row becomes `failed`. The error is shown on the edit page with a
|
||||
Retry button.
|
||||
Retry button. When a row finally fails, the owner also gets a `problems`
|
||||
notification (ADR-074).
|
||||
- `RemoteGone` (404, or Graph error 100/33) during an update means the copy
|
||||
was deleted remotely, so a new one is created. During a delete it counts as
|
||||
success.
|
||||
@@ -227,7 +238,7 @@ to itself (v2.8.0).
|
||||
|
||||
`starpunk/backfeed.py` brings responses to the copies back to the note.
|
||||
After each crosspost pass, the worker loop calls `backfeed.process_due()`,
|
||||
which checks up to three synced copies of published notes (not likes or
|
||||
which does nothing unless `BACKFEED_ENABLED`; otherwise it checks up to three synced copies of published notes (not likes or
|
||||
reposts) that are due, each under a lease (`backfeed_claimed_until`):
|
||||
|
||||
- **Reading.** Each client has `responses(remote_id, remote_url)`, which
|
||||
@@ -244,10 +255,14 @@ reposts) that are due, each under a lease (`backfeed_claimed_until`):
|
||||
`WEBMENTION_AUTO_APPROVE` default; an existing row keeps its moderation.
|
||||
A complete harvest marks that silo's rows for the note that weren't
|
||||
found `invalid` ("No longer on <silo>"). Authors with `#nobridge` or
|
||||
`#nobot` in their bio, or Bluesky's `!no-unauthenticated` label, are
|
||||
skipped and their rows deleted. If the note's shown responses changed,
|
||||
its webmentions are re-sent (spec 3.1.4). Threads counts go in
|
||||
`syndications.likes_count`, `reposts_count`, `quotes_count`.
|
||||
`#nobot` in their bio, or Bluesky's `!no-unauthenticated` label, are not
|
||||
stored and their rows are deleted; since v2.13.3 their likes, reposts and
|
||||
quotes are counted anonymously instead (`hidden_counts()`). If the note's
|
||||
shown responses changed, its webmentions are re-sent (spec 3.1.4).
|
||||
`syndications.likes_count`, `reposts_count` and `quotes_count` hold the
|
||||
silo-only counts: all of Threads; elsewhere people who opted out. New
|
||||
responses found by a backfill, or by a copy's first check on a note older
|
||||
than a day, are stored as already notified (v2.14.0).
|
||||
- **Schedule.** `backfeed_next_at` follows the note's age: 15 minutes (day
|
||||
1), 1 hour (week 1), 1 day (to 30 days), 1 week (to
|
||||
`BACKFEED_MAX_AGE_DAYS`), with up to 10% jitter; none after. Failures back
|
||||
@@ -259,7 +274,8 @@ reposts) that are due, each under a lease (`backfeed_claimed_until`):
|
||||
`site_state`.
|
||||
- **Refused credentials.** A 401/403 (or Graph auth error) puts the target
|
||||
in `backfeed.denied` until restart; the admin Webmentions page says which
|
||||
scopes are needed. Crossposting is unaffected.
|
||||
scopes are needed, and a `problems` notification is sent. Crossposting
|
||||
is unaffected.
|
||||
|
||||
Avatars of all responses (received and backfed) are saved by
|
||||
`starpunk/avatars.py` and served from `/avatars/<sha256>.webp`; the
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# StarPunk Technology Stack
|
||||
|
||||
**Version**: 2.10.1 (2026-11-03)
|
||||
**Version**: 2.14.0 (2026-11-10)
|
||||
**Status**: Current. The original v0.x stack write-up is kept as
|
||||
[technology-stack-legacy.md](technology-stack-legacy.md) for history.
|
||||
[technology-stack-legacy.md](../design/v0.x/technology-stack-legacy.md) for history.
|
||||
|
||||
StarPunk deliberately uses few dependencies: a WSGI web framework, SQLite
|
||||
from the standard library, plain files, server-rendered templates and a
|
||||
@@ -21,7 +21,7 @@ the pieces fit together.
|
||||
| Content storage | Markdown files on disk |
|
||||
| Background work | `threading` daemon threads; `fcntl.flock` file locks to pick one process |
|
||||
| Templates | Jinja2, server-side rendered |
|
||||
| Front end | One hand-written stylesheet; one small vanilla JS file for the editor's Markdown preview |
|
||||
| Front end | One hand-written stylesheet; small inline scripts on admin pages; no JavaScript on public pages |
|
||||
| Packaging | `uv` creates the virtual environment and installs requirements (locally and in the image) |
|
||||
| Container | Multi-stage `Containerfile` (Podman/Docker), non-root user |
|
||||
| Reverse proxy | Caddy in production (examples for Caddy and nginx in the repo) |
|
||||
@@ -46,8 +46,10 @@ vulnerabilities (`pip-audit`); check again before each release.
|
||||
| apprise | `2.2.*` | Notifications to the owner's services (`starpunk/notifications.py`, ADR-074); sends to the URLs the owner configures, outside the SSRF-safe fetcher |
|
||||
| PyJWT[crypto] | `2.15.*` | Verifying OIDC ID tokens (JWKS, RS/ES signatures via `cryptography`) |
|
||||
| python-dotenv | `1.2.*` | Loading `.env` |
|
||||
| Pillow | `13.0.*` | Image validation, resizing and variants |
|
||||
| Pillow | `13.0.*` | Image validation, resizing and variants; converting response avatars to 96 px WebP (`avatars.py`) |
|
||||
| pillow-heif | `1.8.*` | HEIC/HEIF uploads (iPhone photos) |
|
||||
| mcp | `2.3.*` | MCP server for AI clients (`starpunk/mcp_server/`, ADR-075); brings Starlette, pydantic and anyio. Only the sidecar imports it |
|
||||
| uvicorn | `0.54.*` | ASGI server for the MCP sidecar |
|
||||
|
||||
`markupsafe` comes with Flask/Jinja2.
|
||||
|
||||
@@ -69,10 +71,11 @@ front-end framework or bundler, no separate search server.
|
||||
|
||||
| Area | Standards |
|
||||
|------|-----------|
|
||||
| IndieWeb | Micropub (create, update, delete, undelete, queries, media endpoint), IndieAuth (authorization server with PKCE, metadata endpoint, token revocation), Webmention (send and receive), WebSub (publisher and built-in hub), microformats2 (h-entry, h-feed, h-card markup and parsing), rel=me |
|
||||
| IndieWeb | Micropub (create, update, delete, undelete, queries, media endpoint), IndieAuth (authorization server with PKCE, metadata endpoint, token revocation), Webmention (send and receive), WebSub (publisher and built-in hub), microformats2 (h-entry, h-feed, h-card markup and parsing), rel=me, web actions (`<indie-action>`), backfeed of responses from the silos |
|
||||
| Login | OpenID Connect authorization code flow with PKCE (provider: Pocket ID) |
|
||||
| Feeds | RSS 2.0, Atom 1.0, JSON Feed 1.1, OPML 2.0, HTTP content negotiation |
|
||||
| Crossposting | Mastodon client API (GoToSocial), AT Protocol (Bluesky XRPC), Threads Graph API |
|
||||
| AI clients | Model Context Protocol (Streamable HTTP, stateless), OAuth 2.0 Protected Resource Metadata (RFC 9728), Resource Indicators (RFC 8707), Client ID Metadata Documents |
|
||||
| Crossposting | Mastodon client API (GoToSocial), AT Protocol (Bluesky XRPC), Threads Graph API; the same APIs are read for backfeed |
|
||||
|
||||
Protocol details: [indieweb-protocols.md](indieweb-protocols.md),
|
||||
[simplified-auth-architecture.md](simplified-auth-architecture.md),
|
||||
@@ -80,7 +83,7 @@ Protocol details: [indieweb-protocols.md](indieweb-protocols.md),
|
||||
|
||||
## Testing
|
||||
|
||||
- **Framework**: pytest with pytest-mock; about 1,250 tests in `tests/`
|
||||
- **Framework**: pytest with pytest-mock; about 1,260 tests in `tests/`
|
||||
(`test_*.py` per module or feature, shared fixtures in `tests/conftest.py`,
|
||||
helpers in `tests/helpers/`).
|
||||
- **Isolation**: the `app` fixture calls `create_app()` with `TESTING=True`
|
||||
@@ -93,10 +96,12 @@ Protocol details: [indieweb-protocols.md](indieweb-protocols.md),
|
||||
- **Running locally**:
|
||||
|
||||
```bash
|
||||
uv venv && uv pip install -r requirements-dev.txt
|
||||
.venv/bin/python -m pytest
|
||||
uv venv --python 3.14 && uv pip install -r requirements-dev.txt
|
||||
SESSION_SECRET=test uv run pytest tests/test_<area>.py
|
||||
```
|
||||
|
||||
Locally, run the tests for the area you changed; CI runs the full suite.
|
||||
|
||||
- **In CI**: the `test` stage of the `Containerfile` installs the production
|
||||
requirements plus `requirements-test.txt` and runs the whole suite. The
|
||||
image is only built and pushed if it passes. Checklist:
|
||||
@@ -120,4 +125,4 @@ standards.
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Status
|
||||
|
||||
Accepted (v2.13.0, 2026-11-10)
|
||||
Accepted (v2.13.0, 2026-11-10; amended v2.13.2, v2.13.3)
|
||||
|
||||
Implementation notes (v2.13.0):
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# ADR-075: MCP server for AI clients
|
||||
|
||||
## Status
|
||||
|
||||
Accepted (v2.15.0, 2026-11-11)
|
||||
|
||||
## Context
|
||||
|
||||
The owner wants AI assistants (claude.ai custom connectors, Claude Code and
|
||||
other [Model Context Protocol](https://modelcontextprotocol.io/) clients) to
|
||||
read, search and write notes. Micropub already covers writing, but MCP
|
||||
clients don't speak Micropub: they discover tools over MCP and get tokens
|
||||
through OAuth 2.1 with protected resource metadata (RFC 9728), resource
|
||||
indicators (RFC 8707), and either dynamic client registration or a Client ID
|
||||
Metadata Document (CIMD).
|
||||
|
||||
StarPunk already runs an OAuth/IndieAuth authorization server (ADR-064) with
|
||||
PKCE, public clients only, and clients identified by a `client_id` URL whose
|
||||
JSON document lists `redirect_uris`. That is what MCP calls CIMD. Claude uses
|
||||
CIMD when the server's metadata says `client_id_metadata_document_supported:
|
||||
true` and lists `none` in `token_endpoint_auth_methods_supported`.
|
||||
|
||||
StarPunk is Flask on gunicorn sync workers (WSGI). The official MCP Python
|
||||
SDK is ASGI.
|
||||
|
||||
Options considered:
|
||||
|
||||
1. **Local stdio bridge** that calls `/micropub` with a stored token, like
|
||||
existing Micropub MCP servers. No server changes, but every client needs
|
||||
the bridge installed, claude.ai and mobile can't use it, and reading is
|
||||
limited to what Micropub queries expose.
|
||||
2. **Hand-written MCP route in Flask**, stateless JSON only. No new
|
||||
dependencies or processes, but StarPunk would own the protocol details
|
||||
(version negotiation, JSON-RPC, Origin checks, auth metadata) and track
|
||||
the spec itself.
|
||||
3. **Official SDK in a sidecar process** from the same image, behind the
|
||||
same reverse proxy, sharing the data volume.
|
||||
4. **Dynamic client registration** (RFC 7591) in the authorization server.
|
||||
Every connection would register a new client, and nothing needs it once
|
||||
CIMD works.
|
||||
|
||||
## Decision
|
||||
|
||||
### 1. A sidecar running the official SDK (option 3)
|
||||
|
||||
`starpunk/mcp_server/` builds an `mcp.server.MCPServer` (SDK 2.3) and serves
|
||||
it with uvicorn (`uvicorn starpunk.mcp_server.app:app --port 8001`), as a
|
||||
second container from the same image. The reverse proxy sends `/mcp*` and
|
||||
`/.well-known/oauth-protected-resource*` to it and everything else to
|
||||
gunicorn. The endpoint is `SITE_URL/mcp`.
|
||||
|
||||
The transport is stateless Streamable HTTP with plain JSON responses. No
|
||||
session lives in the process, so restarts and several workers are harmless.
|
||||
|
||||
The sidecar builds the Flask app with `BACKGROUND_WORKERS_ENABLED=false`, so
|
||||
only the main container runs the webmention, WebSub and syndication
|
||||
workers. Each tool runs in a worker thread inside a Flask request context
|
||||
for `SITE_URL`, and calls the same service functions as the web app.
|
||||
SQLite (WAL) handles the second process like another gunicorn worker.
|
||||
|
||||
### 2. StarPunk is the authorization server; the sidecar only checks tokens
|
||||
|
||||
- The authorization server metadata adds
|
||||
`client_id_metadata_document_supported: true` and
|
||||
`token_endpoint_auth_methods_supported: ["none"]`, and `scopes_supported`
|
||||
now includes `draft`.
|
||||
- An authorization request may carry `resource` (RFC 8707). The only resource
|
||||
StarPunk names is `SITE_URL/mcp`; anything else is `invalid_target`. The
|
||||
resource is stored on the code and the token (migration 022), shown on the
|
||||
consent screen, and must match if the token request repeats it.
|
||||
- An MCP request with no `scope` is offered `create update delete media
|
||||
draft`. The owner unticks what they don't want on the consent screen.
|
||||
(The SDK publishes the resource's `scopes_supported` from its
|
||||
required scopes, which StarPunk leaves empty so any token can connect.)
|
||||
- The sidecar's `TokenVerifier` looks tokens up with `verify_access_token`
|
||||
and reports their resource. With `validate_token_resource`, the SDK
|
||||
refuses tokens not issued for `/mcp`, so a Micropub app's token can't be
|
||||
replayed against MCP. MCP tokens still work at `/micropub`; both stay the
|
||||
owner's own clients, and the Connected Apps page marks MCP tokens.
|
||||
- DNS rebinding protection allows only the `SITE_URL` host and origin
|
||||
(plus localhost in `DEV_MODE`).
|
||||
|
||||
### 3. Tools: reading and writing notes, nothing else
|
||||
|
||||
| Tool | Scope |
|
||||
|---|---|
|
||||
| `search_notes`, `list_notes`, `get_note`, `get_site_config` | any token; drafts need `create`, `update`, `delete` or `draft` |
|
||||
| `list_tags` | `create`, `update`, `delete` or `draft` (as Micropub `q=category`) |
|
||||
| `create_note` | `create` or `draft` (draft-only tokens always make drafts) |
|
||||
| `update_note` | `update` |
|
||||
| `delete_note`, `undelete_note` | `delete` |
|
||||
| `upload_media` | `media` or `create` |
|
||||
|
||||
Writing tools build a Micropub JSON request and call `handle_create`,
|
||||
`handle_update` and `handle_delete`. Scope rules, validation, crossposting,
|
||||
webmentions and WebSub notifications are therefore identical to Micropub.
|
||||
`create_note` makes a draft unless told otherwise. Tool annotations mark
|
||||
reading tools read-only and update and delete as destructive.
|
||||
|
||||
Syndication management, webmention moderation and other admin functions are
|
||||
not exposed.
|
||||
|
||||
## Consequences
|
||||
|
||||
- AI clients connect with just the URL: claude.ai via Settings → Connectors,
|
||||
Claude Code via `claude mcp add --transport http starpunk SITE_URL/mcp`.
|
||||
The owner approves them on the usual consent screen, and they appear (and
|
||||
can be revoked) under Connected Apps.
|
||||
- New runtime dependencies: `mcp` (with Starlette, pydantic and anyio) and
|
||||
`uvicorn`. They are only imported by the sidecar.
|
||||
- Deployments run a second container and need two proxy routes. A site that
|
||||
doesn't run the sidecar just has no MCP; nothing else changes.
|
||||
- There are still no refresh tokens. MCP clients re-authorize after
|
||||
`INDIEAUTH_TOKEN_LIFETIME_DAYS`.
|
||||
- SDK upgrades need care: 3.0 is expected to change defaults (for example
|
||||
`validate_token_resource`, which StarPunk already sets).
|
||||
|
||||
## Alternatives
|
||||
|
||||
Options 1, 2 and 4 above. A stdio bridge could still be added later for
|
||||
clients that can't do OAuth; it would use a token from this flow.
|
||||
@@ -5,8 +5,8 @@ records one decision: its context, what was decided, and the consequences.
|
||||
Superseded ADRs are kept as history; their Status line names the ADR that
|
||||
replaced them.
|
||||
|
||||
**Total ADR files**: 70 (69 numbers: ADR-001 to ADR-044 and ADR-050 to
|
||||
ADR-074, with two files numbered ADR-012). See [Numbering](#numbering).
|
||||
**Total ADR files**: 71 (70 numbers: ADR-001 to ADR-044 and ADR-050 to
|
||||
ADR-075, with two files numbered ADR-012). See [Numbering](#numbering).
|
||||
|
||||
Status values: **Accepted** (in force), **Superseded** (replaced by a later
|
||||
ADR), **Deprecated** (withdrawn, nothing replaces it; none at present),
|
||||
@@ -85,8 +85,7 @@ See also [IndieWeb protocols](../architecture/indieweb-protocols.md).
|
||||
| [066](ADR-066-bluesky-syndication.md) | Crossposting to Bluesky | Accepted | Bluesky as a second crosspost target (v2.2.0). |
|
||||
| [069](ADR-069-threads-syndication.md) | Crossposting to Threads | Accepted | Threads as a third target, with automatic token refresh (v2.6.0). |
|
||||
| [070](ADR-070-crosspost-links-and-cards.md) | Links and link cards in crossposts | Accepted | Keep note links in crossposts and build link cards for the linked page (v2.6.3). |
|
||||
| [074](ADR-074-notifications.md) | Notifications through Apprise | Accepted | Notify the owner of new responses and crosspost/backfeed problems via the embedded Apprise library (v2.14.0). |
|
||||
| [073](ADR-073-backfeed.md) | Backfeed of responses to crossposts | Accepted | Poll GoToSocial, Bluesky and Threads for responses to crossposts and store them as webmentions; admin backfill (v2.13.0). |
|
||||
| [073](ADR-073-backfeed.md) | Backfeed of responses to crossposts | Accepted | Poll GoToSocial, Bluesky and Threads for responses to crossposts and store them as webmentions; admin backfill (v2.13.0, amended v2.13.2–v2.13.3). |
|
||||
|
||||
### Authentication (current)
|
||||
|
||||
@@ -96,6 +95,7 @@ See also [IndieWeb protocols](../architecture/indieweb-protocols.md).
|
||||
| [010](ADR-010-authentication-module-design.md) | Authentication Module Design | Accepted* | Single `auth.py` module and server-side sessions; the login flow is now ADR-064. |
|
||||
| [011](ADR-011-development-authentication-mechanism.md) | Development Authentication Mechanism | Accepted | `DEV_MODE` login bypass for local development only. |
|
||||
| [022](ADR-022-auth-route-prefix-fix.md) | Fix IndieAuth Callback Route Mismatch | Accepted | Auth routes live under `/auth` (v0.9.2). |
|
||||
| [075](ADR-075-mcp-server.md) | MCP server for AI clients | Accepted | `/mcp` served by the official MCP SDK in a sidecar; StarPunk's IndieAuth server issues resource-bound tokens via client ID metadata documents (v2.15.0). |
|
||||
|
||||
### Operations, errors and monitoring
|
||||
|
||||
@@ -106,6 +106,7 @@ See also [IndieWeb protocols](../architecture/indieweb-protocols.md).
|
||||
| [054](ADR-054-structured-logging-architecture.md) | Structured Logging Architecture | Accepted | Rotating log files with correlation IDs (v1.1.1). |
|
||||
| [055](ADR-055-error-handling-philosophy.md) | Error Handling Philosophy | Accepted | Layered handling: graceful degradation, clear user messages, detailed logs. |
|
||||
| [072](ADR-072-remove-metrics-dashboard.md) | Remove the metrics dashboard | Accepted | Drop the in-memory metrics system and dashboard; keep `/health`, `/admin/health` and logs (v2.12.0). |
|
||||
| [074](ADR-074-notifications.md) | Notifications through Apprise | Accepted | Notify the owner of new responses and crosspost/backfeed problems via the embedded Apprise library (v2.14.0). |
|
||||
|
||||
See also [deployment](../architecture/deployment.md).
|
||||
|
||||
@@ -169,7 +170,7 @@ was carried out and is not itself superseded.
|
||||
|
||||
## How to create a new ADR
|
||||
|
||||
1. Use the next number after the highest existing one (currently ADR-075).
|
||||
1. Use the next number after the highest existing one (currently ADR-076).
|
||||
2. Name it `ADR-NNN-brief-descriptive-title.md`.
|
||||
3. Follow the format of recent ADRs (e.g. ADR-070, ADR-071):
|
||||
|
||||
@@ -202,5 +203,5 @@ was carried out and is not itself superseded.
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2026-11-03
|
||||
**Total ADR files**: 67
|
||||
**Last Updated**: 2026-11-10
|
||||
**Total ADR files**: 70
|
||||
+26
-12
@@ -21,7 +21,13 @@ is in `../architecture/`; decisions are in `../decisions/` (ADRs).
|
||||
|
||||
## Contents
|
||||
|
||||
[v1.0.0](#v100) · [v1.1.1](#v111) · [v1.1.2](#v112) · [v1.2.0](#v120) · [v1.3.0](#v130) · [v1.3.1](#v131) · [v1.4.0](#v140) · [v1.4.1](#v141) · [v1.4.2](#v142) · [v1.5.0](#v150) · [v1.6.0](#v160) · [v2.0.0](#v200) · [v2.0.1](#v201) · [v2.0.2](#v202) · [v2.1.0](#v210) · [v2.2.0](#v220) · [v2.3.0](#v230) · [v2.3.1](#v231) · [v2.3.2](#v232) · [v2.3.3](#v233) · [v2.4.0](#v240) · [v2.5.0](#v250) · [v2.6.0](#v260) · [v2.6.1](#v261) · [v2.6.2](#v262) · [v2.6.3](#v263) · [v2.6.4](#v264) · [v2.6.5](#v265) · [v2.6.6](#v266) · [v2.6.7](#v267) · [v2.6.8](#v268) · [v2.6.9](#v269) · [v2.7.0](#v270) · [v2.7.1](#v271) · [v2.7.2](#v272) · [v2.8.0](#v280) · [v2.8.1](#v281) · [v2.9.0](#v290) · [v2.10.0](#v2100) · [v2.10.1](#v2101) · [v2.10.2](#v2102) · [v2.11.0](#v2110) · [v2.12.0](#v2120) · [v2.12.1](#v2121) · [v2.13.0](#v2130) · [v2.13.1](#v2131) · [v2.13.2](#v2132) · [v2.13.3](#v2133) · [v2.13.4](#v2134) · [v2.14.0](#v2140) · [hotfix](#hotfix)
|
||||
[v0.x](#v0x) · [v1.0.0](#v100) · [v1.1.1](#v111) · [v1.1.2](#v112) · [v1.2.0](#v120) · [v1.3.0](#v130) · [v1.3.1](#v131) · [v1.4.0](#v140) · [v1.4.1](#v141) · [v1.4.2](#v142) · [v1.5.0](#v150) · [v1.6.0](#v160) · [v2.0.0](#v200) · [v2.0.1](#v201) · [v2.0.2](#v202) · [v2.1.0](#v210) · [v2.2.0](#v220) · [v2.3.0](#v230) · [v2.3.1](#v231) · [v2.3.2](#v232) · [v2.3.3](#v233) · [v2.4.0](#v240) · [v2.5.0](#v250) · [v2.6.0](#v260) · [v2.6.1](#v261) · [v2.6.2](#v262) · [v2.6.3](#v263) · [v2.6.4](#v264) · [v2.6.5](#v265) · [v2.6.6](#v266) · [v2.6.7](#v267) · [v2.6.8](#v268) · [v2.6.9](#v269) · [v2.7.0](#v270) · [v2.7.1](#v271) · [v2.7.2](#v272) · [v2.8.0](#v280) · [v2.8.1](#v281) · [v2.9.0](#v290) · [v2.10.0](#v2100) · [v2.10.1](#v2101) · [v2.10.2](#v2102) · [v2.11.0](#v2110) · [v2.12.0](#v2120) · [v2.12.1](#v2121) · [v2.13.0](#v2130) · [v2.13.1](#v2131) · [v2.13.2](#v2132) · [v2.13.3](#v2133) · [v2.13.4](#v2134) · [v2.14.0](#v2140) · [v2.14.1](#v2141) · [v2.14.2](#v2142) · [hotfix](#hotfix)
|
||||
|
||||
## v0.x
|
||||
|
||||
Not a release folder: documents from before v1.0.0 kept for history.
|
||||
|
||||
- [technology-stack-legacy.md](v0.x/technology-stack-legacy.md) — StarPunk Technology Stack - Quick Reference
|
||||
|
||||
## v1.0.0
|
||||
|
||||
@@ -408,43 +414,51 @@ OIDC admin login and built-in IndieAuth server.
|
||||
|
||||
## v2.10.2
|
||||
|
||||
- [2026-11-03-reply-context-fetch.md](v2.10.2/2026-11-03-reply-context-fetch.md) - Reply contexts fetched again (fetch_source returns three values since v2.7.0)
|
||||
- [2026-11-03-reply-context-fetch.md](v2.10.2/2026-11-03-reply-context-fetch.md) — Reply context fetch
|
||||
|
||||
## v2.11.0
|
||||
|
||||
- [2026-11-03-maintenance-release.md](v2.11.0/2026-11-03-maintenance-release.md) - Dependency upgrades (Python 3.14), foreign keys, CSRF, fetchers, debug default, shared rate limits
|
||||
- [2026-11-03-maintenance-release.md](v2.11.0/2026-11-03-maintenance-release.md) — Maintenance release
|
||||
|
||||
## v2.12.0
|
||||
|
||||
- [2026-11-03-remove-metrics.md](v2.12.0/2026-11-03-remove-metrics.md) - Metrics dashboard and `starpunk/monitoring` removed (ADR-072)
|
||||
- [2026-11-03-remove-metrics.md](v2.12.0/2026-11-03-remove-metrics.md) — Remove the metrics dashboard
|
||||
|
||||
## v2.12.1
|
||||
|
||||
- [2026-11-10-category-unused-tags.md](v2.12.1/2026-11-10-category-unused-tags.md) - q=category lists only tags on posts that exist
|
||||
- [2026-11-10-category-unused-tags.md](v2.12.1/2026-11-10-category-unused-tags.md) — q=category lists only tags in use
|
||||
|
||||
## v2.13.0
|
||||
|
||||
- [2026-11-10-backfeed.md](v2.13.0/2026-11-10-backfeed.md) - Backfeed of responses to crossposts (ADR-073), avatar cache, delete tombstones
|
||||
- [2026-11-10-backfeed.md](v2.13.0/2026-11-10-backfeed.md) — Backfeed (implementation report)
|
||||
|
||||
## v2.13.1
|
||||
|
||||
- [2026-11-10-avatar-fetch.md](v2.13.1/2026-11-10-avatar-fetch.md) - Avatars from the own GoToSocial server and from Bluesky PDSes
|
||||
- [2026-11-10-avatar-fetch.md](v2.13.1/2026-11-10-avatar-fetch.md) — Avatar fetching in production
|
||||
|
||||
## v2.13.2
|
||||
|
||||
- [2026-11-10-reaction-counts.md](v2.13.2/2026-11-10-reaction-counts.md) - Likes/reposts as a counts line with hover lists; web actions
|
||||
- [2026-11-10-reaction-counts.md](v2.13.2/2026-11-10-reaction-counts.md) — Reaction counts and web actions
|
||||
|
||||
## v2.13.3
|
||||
|
||||
- [2026-11-10-count-opted-out.md](v2.13.3/2026-11-10-count-opted-out.md) - Opted-out people's likes and reposts counted without names
|
||||
- [2026-11-10-count-opted-out.md](v2.13.3/2026-11-10-count-opted-out.md) — Count opted-out people without naming them
|
||||
|
||||
## v2.13.4
|
||||
|
||||
- [2026-11-10-list-counts.md](v2.13.4/2026-11-10-list-counts.md) - Counts on lists of notes; whole reply card links to the reply; class clash fixed
|
||||
- [2026-11-10-list-counts.md](v2.13.4/2026-11-10-list-counts.md) — Counts on lists of notes, reply cards as links
|
||||
|
||||
## v2.14.0
|
||||
|
||||
- [2026-11-10-notifications.md](v2.14.0/2026-11-10-notifications.md) - Notifications through Apprise (ADR-074)
|
||||
- [2026-11-10-notifications.md](v2.14.0/2026-11-10-notifications.md) — Notifications (implementation report)
|
||||
|
||||
## v2.14.1
|
||||
|
||||
- [2026-11-10-tags-and-captions.md](v2.14.1/2026-11-10-tags-and-captions.md) — Clearing tags in the editor; captions escaped in feeds
|
||||
|
||||
## v2.14.2
|
||||
|
||||
- [2026-11-10-quotes-cleanup.md](v2.14.2/2026-11-10-quotes-cleanup.md) — Quote counts; dead files removed
|
||||
|
||||
## hotfix
|
||||
|
||||
@@ -465,4 +479,4 @@ IndieAuth PKCE endpoint discovery hotfix (2025-12-17, between v1.5.0 and v1.6.0;
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2026-11-03
|
||||
**Last Updated**: 2026-11-10
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
> **Historical document.** This describes StarPunk's original v0.x technology
|
||||
> choices (for example IndieLogin.com for admin login) and is kept for
|
||||
> context only. It does not describe the current system; see
|
||||
> [technology-stack.md](technology-stack.md) and [overview.md](overview.md).
|
||||
> [technology-stack.md](../../architecture/technology-stack.md) and [overview.md](../../architecture/overview.md).
|
||||
|
||||
## Project Understanding
|
||||
|
||||
@@ -1901,7 +1901,7 @@ class Webmention:
|
||||
## References
|
||||
|
||||
- [ADR-004: File-Based Note Storage](../../decisions/ADR-004-file-based-note-storage.md)
|
||||
- [Database Schema](../../../starpunk/monitoring/database.py)
|
||||
- [Database Schema](../../../starpunk/database/schema.py)
|
||||
- [Phase 1.1: Core Utilities](phase-1.1-core-utilities.md)
|
||||
- [Python Coding Standards](../../standards/python-coding-standards.md)
|
||||
- [Python Dataclasses Documentation](https://docs.python.org/3/library/dataclasses.html)
|
||||
|
||||
@@ -2061,7 +2061,7 @@ Phase 2.1 is complete when:
|
||||
- [ADR-007: Slug Generation Algorithm](../../decisions/ADR-007-slug-generation-algorithm.md)
|
||||
- [Phase 1.1: Core Utilities](phase-1.1-core-utilities.md)
|
||||
- [Phase 1.2: Data Models](phase-1.2-data-models.md)
|
||||
- [Database Schema](../../../starpunk/monitoring/database.py)
|
||||
- [Database Schema](../../../starpunk/database/schema.py)
|
||||
- [Python Coding Standards](../../standards/python-coding-standards.md)
|
||||
- [Architecture Overview](../../architecture/overview.md)
|
||||
- Security Architecture (`security.md`, not preserved)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# v2.14.1: Clearing tags in the editor; captions escaped in feeds
|
||||
|
||||
Two bugs from the backlog (High), confirmed against the code at v2.14.0.
|
||||
|
||||
## Clearing tags
|
||||
|
||||
`routes/admin.py` (edit POST) passed `tags=tags if tags else None`, and
|
||||
`notes.update_note` treats `None` as "unchanged", so an empty Tags field
|
||||
kept the old tags although the form says "Leave blank to remove all tags".
|
||||
It now passes the parsed list (possibly empty) whenever the form has a
|
||||
`tags` field, and `None` only when it doesn't.
|
||||
|
||||
## Captions in feed HTML
|
||||
|
||||
The media `<img>` built for item HTML put the caption into `alt="…"`
|
||||
unescaped in four places: `feeds/rss.py` (two), `feeds/atom.py` and
|
||||
`feeds/json_feed.py`. A caption with `"`, `<` or `&` broke the markup. The
|
||||
caption and the media URL are now `html.escape(..., quote=True)`d. The
|
||||
Atom enclosure's `title` attribute was already escaped with `_escape_xml`
|
||||
and is unchanged (escaping it again would double it).
|
||||
|
||||
## Verification
|
||||
|
||||
`tests/test_tags_and_captions.py` (4 tests, all failing before the fix):
|
||||
caption escaped once in RSS, Atom (and the enclosure title not doubled) and
|
||||
JSON Feed; the editor leaves tags alone without the field and clears them
|
||||
with an empty one. Feed, admin, tag, public-route and media tests pass.
|
||||
@@ -0,0 +1,31 @@
|
||||
# v2.14.2: Quote counts; dead files removed
|
||||
|
||||
The two remaining items from the v2.14.0 documentation review.
|
||||
|
||||
## Quote counts
|
||||
|
||||
Backfeed stored anonymous quote counts (`syndications.quotes_count`: all
|
||||
Threads quotes, and quotes by people who opted out elsewhere) that nothing
|
||||
displayed. The counts line (`partials/responses.html` `reactions`) now has a
|
||||
quote count after replies: named quotes plus those counts. Its card shows
|
||||
only the anonymous part ("2 on Threads"); named quotes stay listed under
|
||||
Responses. Quotes have no web action (there is no standard verb).
|
||||
`webmention_queries.response_counts` adds `quotes`, so lists of notes show
|
||||
them too.
|
||||
|
||||
## Removed
|
||||
|
||||
- `static/js/preview.js` (empty since the first commit) and the jsDelivr
|
||||
`marked` script the editor pages loaded with it.
|
||||
- `templates/feed.xml` (empty, never rendered) and `static/indielogin-test.html`
|
||||
(a v1 IndieLogin test page).
|
||||
- `syndication.get_targets()` read `THREADS_API` from the config, which
|
||||
`config.py` never loads; the client now always uses the `THREADS_API`
|
||||
constant.
|
||||
|
||||
## Verification
|
||||
|
||||
`tests/test_backfeed.py::test_quote_counts_include_anonymous_ones`; backfeed,
|
||||
syndication, admin, template, public-route, microformats, notification,
|
||||
webmention and feed tests pass. Rendered the counts line with the quote card
|
||||
open in headless Chromium.
|
||||
+13
-15
@@ -1,9 +1,9 @@
|
||||
# StarPunk Backlog
|
||||
|
||||
**Last Updated**: 2026-11-03 (current release: v2.11.0)
|
||||
**Last Updated**: 2026-11-10 (current release: v2.14.0)
|
||||
|
||||
These are the open features and bugs, sorted by priority. Each item was checked against the code
|
||||
at v2.11.0. Work that has shipped is listed per release in `vX.Y.Z/RELEASE.md` and in
|
||||
at v2.14.0. Work that has shipped is listed per release in `vX.Y.Z/RELEASE.md` and in
|
||||
`CHANGELOG.md`.
|
||||
|
||||
## Priority Levels
|
||||
@@ -29,16 +29,6 @@ None open.
|
||||
|
||||
## Medium
|
||||
|
||||
### Admin editor cannot clear all tags
|
||||
- **Description**: When a note is saved with an empty tag field, the route passes `tags=None`. `update_note` treats that as "unchanged", so the last tags can't be removed from the editor.
|
||||
- **Where**: `starpunk/routes/admin.py` (edit POST: `tags=tags if tags else None`), `starpunk/notes.py` (`update_note`)
|
||||
- **Source**: Old backlog (v1.3.0 follow-up); still present
|
||||
|
||||
### Media captions not escaped in RSS HTML
|
||||
- **Description**: The RSS description embeds `<img alt="{caption}">` without escaping the caption. A caption containing `"` or `<` breaks the item's HTML.
|
||||
- **Where**: `starpunk/feeds/rss.py` (two places, ~lines 136 and 277)
|
||||
- **Source**: Old backlog (Architect Review 2.2.10); still present
|
||||
|
||||
### No rate limiting on upload endpoints
|
||||
- **Description**: Media uploads (`/admin/new` and the Micropub media endpoint) have no rate limit. Both require authentication, so the risk comes from a leaked token or session.
|
||||
- **Where**: `starpunk/routes/admin.py`, `starpunk/routes/micropub.py`
|
||||
@@ -75,7 +65,7 @@ None open.
|
||||
- **Source**: Documentation refresh 2026-11-03
|
||||
|
||||
### Tag-filtered feeds
|
||||
- **Description**: Tag pages are h-feeds and WebSub topics, but there are no RSS, Atom or JSON feeds per tag (for example `/tag/python/feed.atom`). Tag pages also have no pagination, and the editor has no tag autocomplete.
|
||||
- **Description**: Tag pages are h-feeds and WebSub topics, but there are no RSS, Atom or JSON feeds per tag (for example `/tag/python/feed.atom`). Tag pages also have no pagination, and the editor has no tag autocomplete (Micropub `q=category`, v2.12.1, already gives the list a `<datalist>` could use).
|
||||
- **Where**: `starpunk/routes/public.py`, `starpunk/feeds/`, `templates/admin/`
|
||||
- **Source**: Old backlog (Tag enhancements)
|
||||
|
||||
@@ -154,7 +144,7 @@ None open.
|
||||
- **Source**: Old backlog (v1.5.0 scoping)
|
||||
|
||||
### Unused settings and legacy tables
|
||||
- **Description**: `NOTES_PATH` is read and its folder created, but notes are always written under `DATA_PATH/notes`. `SITE_AUTHOR` is required but shown nowhere. `INITIAL_SCHEMA_SQL` recreates the unused `tokens` and `authorization_codes` tables (dropped by migration 004) on every start, and `auth_state` is unused. Version fallbacks are stale (`author_discovery.py` "1.2.0", `base.html` "0.5.0").
|
||||
- **Description**: `NOTES_PATH` is read and its folder created, but notes are always written under `DATA_PATH/notes`. `SITE_AUTHOR` is checked as required but defaults to "Unknown" and is shown nowhere. `INITIAL_SCHEMA_SQL` recreates the unused `tokens` and `authorization_codes` tables (dropped by migration 004) on every start, and `auth_state` is unused. Version fallbacks are stale (`author_discovery.py` "1.2.0", `base.html` "0.5.0").
|
||||
- **Where**: `starpunk/config.py`, `starpunk/utils.py`, `starpunk/database/schema.py`, `starpunk/author_discovery.py`, `templates/base.html`
|
||||
- **Source**: Documentation refresh 2026-11-03 (docs/architecture/database.md, deployment.md)
|
||||
|
||||
@@ -171,10 +161,18 @@ None open.
|
||||
|
||||
---
|
||||
|
||||
## Done since the last update (2025-12-17)
|
||||
## Done (recent releases)
|
||||
|
||||
These items were removed from the backlog because they have shipped:
|
||||
|
||||
- v2.14.2: quote counts (with anonymous ones) shown; dead editor scripts, files and the `THREADS_API` read removed
|
||||
- v2.14.1: the editor can clear all tags; image captions escaped in RSS, Atom and JSON Feed HTML
|
||||
|
||||
- v2.14.0: notifications of new responses and crosspost/backfeed problems through Apprise (ADR-074)
|
||||
- v2.13.0–v2.13.4: backfeed of likes, reposts, quotes and replies from GoToSocial, Bluesky and Threads (ADR-073); counts line with web actions; counts on lists of notes; local avatar copies
|
||||
- v2.12.1: Micropub `q=category` lists only tags in use
|
||||
- v2.12.0: metrics dashboard and monitoring package removed (ADR-072)
|
||||
|
||||
- LICENSE: MIT, copyright Phil Skentelbery 2025-2026 (2026-11-03)
|
||||
|
||||
- v2.11.0: SQLite foreign keys enforced (orphans cleaned up by migration 018); CSRF tokens on admin, logout and consent forms; IndieAuth client and crosspost link-card fetches moved onto the SSRF-safe fetcher; `FLASK_DEBUG`/`FLASK_ENV` default to off/production; rate limits shared by all processes (and old windows pruned, so the webmention limiter no longer grows); dependencies upgraded (Python 3.14, no known vulnerabilities); stale `compose.yaml`, duplicate `dev_auth.py` and `test.ini` removed or fixed; `lxml`/`python-dateutil` pinned, `pytest` out of the runtime requirements
|
||||
|
||||
@@ -4,19 +4,19 @@ Future work and per-release plans. See `../DOCUMENTATION.md` (PROJECTPLAN).
|
||||
|
||||
## Backlog
|
||||
|
||||
- **[BACKLOG.md](BACKLOG.md)** - Open features and bugs by priority (updated for v2.11.0)
|
||||
- **[BACKLOG.md](BACKLOG.md)** - Open features and bugs by priority (updated for v2.14.0)
|
||||
|
||||
## Releases
|
||||
|
||||
- **[v1.0.0](v1.0.0/RELEASE.md)** (Released 2025-11-24)
|
||||
- **[v1.1.0](v1.1.0/RELEASE.md)** (Released 2025-11-25)
|
||||
- **[v1.1.1](v1.1.1/RELEASE.md)** (Released 2025-11-26)
|
||||
- **[v1.1.2](v1.1.2/RELEASE.md)** (Released 2025-11-27)
|
||||
- **[v1.1.1](v1.1.1/RELEASE.md)** (Released 2025-11-25)
|
||||
- **[v1.1.2](v1.1.2/RELEASE.md)** (Released 2025-11-28)
|
||||
- **[v1.2.0](v1.2.0/RELEASE.md)** (Released 2025-12-09)
|
||||
- **[v1.3.0](v1.3.0/RELEASE.md)** (Complete)
|
||||
- **[v1.3.1](v1.3.1/RELEASE.md)** - Feed Categories/Tags Support (Planning)
|
||||
- **[v1.4.0](v1.4.0/RELEASE.md)** - Micropub Media Endpoint, Large Image Support, Enhanced Feed Media (Planning)
|
||||
- **[v1.5.0](v1.5.0/RELEASE.md)** - Stability, Test Coverage, and Technical Debt Reduction (Approved)
|
||||
- **[v1.3.0](v1.3.0/RELEASE.md)** (Released 2025-12-10)
|
||||
- **[v1.3.1](v1.3.1/RELEASE.md)** - Feed Categories/Tags Support (Released 2025-12-10)
|
||||
- **[v1.4.0](v1.4.0/RELEASE.md)** - Micropub Media Endpoint, Large Image Support, Enhanced Feed Media (Released 2025-12-16 as 1.4.0rc1, then 1.4.1 and 1.4.2)
|
||||
- **[v1.5.0](v1.5.0/RELEASE.md)** - Stability, Test Coverage, and Technical Debt Reduction (Released 2025-12-17)
|
||||
- **[v2.0.0](v2.0.0/RELEASE.md)** - OIDC admin login and built-in IndieAuth server (Released 2026-10-31)
|
||||
- **[v2.0.1](v2.0.1/RELEASE.md)** - Absolute URLs behind HTTPS proxy (Released 2026-10-31)
|
||||
- **[v2.0.2](v2.0.2/RELEASE.md)** - CI registry login (Released 2026-10-31)
|
||||
@@ -49,3 +49,12 @@ Future work and per-release plans. See `../DOCUMENTATION.md` (PROJECTPLAN).
|
||||
- **[v2.10.2](v2.10.2/RELEASE.md)** - Reply context fetch fix (Released 2026-11-03)
|
||||
- **[v2.11.0](v2.11.0/RELEASE.md)** - Maintenance: dependency upgrades, High backlog items (Released 2026-11-03)
|
||||
- **[v2.12.0](v2.12.0/RELEASE.md)** - Metrics dashboard removed (Released 2026-11-03)
|
||||
- **[v2.12.1](v2.12.1/RELEASE.md)** - `q=category` lists only tags in use (Released 2026-11-10)
|
||||
- **[v2.13.0](v2.13.0/RELEASE.md)** - Backfeed of responses to crossposts (Released 2026-11-10)
|
||||
- **[v2.13.1](v2.13.1/RELEASE.md)** - Avatar fetching fixes (Released 2026-11-10)
|
||||
- **[v2.13.2](v2.13.2/RELEASE.md)** - Counts line and web actions (Released 2026-11-10)
|
||||
- **[v2.13.3](v2.13.3/RELEASE.md)** - Opted-out people counted without names (Released 2026-11-10)
|
||||
- **[v2.13.4](v2.13.4/RELEASE.md)** - Counts on lists of notes, reply cards link out (Released 2026-11-10)
|
||||
- **[v2.14.0](v2.14.0/RELEASE.md)** - Notifications through Apprise (Released 2026-11-10)
|
||||
- **[v2.14.1](v2.14.1/RELEASE.md)** - Clearing tags in the editor; captions escaped in feeds (Released 2026-11-10)
|
||||
- **[v2.14.2](v2.14.2/RELEASE.md)** - Quote counts; dead files removed (Released 2026-11-10)
|
||||
@@ -1,6 +1,6 @@
|
||||
# StarPunk v1.1.1 Release
|
||||
|
||||
**Status**: Released 2025-11-26
|
||||
**Status**: Released 2025-11-25
|
||||
|
||||
## Features
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# StarPunk v1.1.2 Release
|
||||
|
||||
**Status**: Released 2025-11-27
|
||||
**Status**: Released 2025-11-28
|
||||
**Codename**: Syndicate
|
||||
|
||||
## Features
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# StarPunk v1.3.0 Release
|
||||
|
||||
**Status**: Complete
|
||||
**Status**: Released 2025-12-10
|
||||
**Codename**: "Categories"
|
||||
**Branch**: `feature/v1.3.0-tags-microformats`
|
||||
**Approved**: 2025-12-10
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# StarPunk v1.3.1 Release
|
||||
|
||||
**Status**: Planning
|
||||
**Status**: Released 2025-12-10
|
||||
**Codename**: "Syndicate Tags"
|
||||
**Focus**: Feed Categories/Tags Support
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# StarPunk v1.4.0 Release
|
||||
|
||||
**Status**: Planning
|
||||
**Status**: Released 2025-12-16 (as 1.4.0rc1; then 1.4.1 and 1.4.2)
|
||||
**Codename**: "Media"
|
||||
**Focus**: Micropub Media Endpoint, Large Image Support, Enhanced Feed Media
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# StarPunk v1.5.0 Release Plan
|
||||
|
||||
**Status**: Approved
|
||||
**Status**: Released 2025-12-17
|
||||
**Codename**: "Trigger"
|
||||
**Focus**: Stability, Test Coverage, and Technical Debt Reduction
|
||||
**Last Updated**: 2025-12-17
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# v2.10.2
|
||||
|
||||
- **Date**: 2026-11-03
|
||||
- **Status**: Released
|
||||
- **Status**: Released 2026-11-03
|
||||
|
||||
## Bugs fixed
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# v2.11.0
|
||||
|
||||
- **Date**: 2026-11-03
|
||||
- **Status**: Released
|
||||
- **Status**: Released 2026-11-03
|
||||
- **Focus**: Maintenance: dependency upgrades and the High backlog items
|
||||
|
||||
## Security
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# v2.12.0
|
||||
|
||||
- **Date**: 2026-11-03
|
||||
- **Status**: Released
|
||||
- **Status**: Released 2026-11-03
|
||||
- **Focus**: Remove the metrics dashboard
|
||||
|
||||
## Removed
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# v2.12.1
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: Micropub `q=category` lists only tags in use
|
||||
|
||||
## Fixed
|
||||
|
||||
- `q=category` returns only tags on posts that exist (not ones an edit removed, nor ones only on deleted posts)
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [Design note](../../design/v2.12.1/2026-11-10-category-unused-tags.md)
|
||||
@@ -0,0 +1,25 @@
|
||||
# v2.13.0
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: Backfeed of responses to crossposts
|
||||
|
||||
## Added
|
||||
|
||||
- Likes, reposts, quotes and replies to GoToSocial and Bluesky crossposts, and replies on Threads, shown on the note
|
||||
- Age-based checking schedule up to `BACKFEED_MAX_AGE_DAYS` (90); admin backfill and per-crosspost Check now
|
||||
- Threads like/repost/quote counts; a Quotes group; origin filter and Deleted view in the admin
|
||||
- Settings `BACKFEED_ENABLED`, `BACKFEED_MAX_AGE_DAYS`; migration 020
|
||||
|
||||
## Changed
|
||||
|
||||
- Response avatars saved locally (`/avatars/`)
|
||||
- Admin delete keeps a tombstone
|
||||
- `#nobridge` / `#nobot` and Bluesky's logged-out label honoured; already backfed responses not shown twice from Bridgy
|
||||
- Threads client on `graph.threads.com`
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [ADR-073](../../decisions/ADR-073-backfeed.md)
|
||||
- [Design note](../../design/v2.13.0/2026-11-10-backfeed.md)
|
||||
@@ -0,0 +1,15 @@
|
||||
# v2.13.1
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: Avatar fetching in production
|
||||
|
||||
## Fixed
|
||||
|
||||
- Avatars from the site's own GoToSocial (resolves to an internal address) and from Bluesky (CDN refuses some server IPv4 addresses; fetched from the PDS instead)
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [ADR-073](../../decisions/ADR-073-backfeed.md)
|
||||
- [Design note](../../design/v2.13.1/2026-11-10-avatar-fetch.md)
|
||||
@@ -0,0 +1,20 @@
|
||||
# v2.13.2
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: Counts line for likes and reposts; web actions
|
||||
|
||||
## Changed
|
||||
|
||||
- Likes, reposts and bookmarks shown as one line of counts under the note, with who on hover; Threads counts folded in
|
||||
- `<indie-action>` web actions with links to the note's crossposts
|
||||
|
||||
## Fixed
|
||||
|
||||
- Avatars GoToSocial hasn't cached (redirects to the original server)
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [ADR-073](../../decisions/ADR-073-backfeed.md)
|
||||
- [Design note](../../design/v2.13.2/2026-11-10-reaction-counts.md)
|
||||
@@ -0,0 +1,15 @@
|
||||
# v2.13.3
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: Opted-out people counted without names
|
||||
|
||||
## Changed
|
||||
|
||||
- Likes and reposts by people who opted out of backfeed count in the totals, without name or avatar
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [ADR-073](../../decisions/ADR-073-backfeed.md)
|
||||
- [Design note](../../design/v2.13.3/2026-11-10-count-opted-out.md)
|
||||
@@ -0,0 +1,22 @@
|
||||
# v2.13.4
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: Counts on lists of notes; reply cards
|
||||
|
||||
## Added
|
||||
|
||||
- Like, repost and reply counts on the home, tag and Likes pages
|
||||
|
||||
## Changed
|
||||
|
||||
- A whole reply card opens the reply where it was posted
|
||||
|
||||
## Fixed
|
||||
|
||||
- The counts line's CSS clashed with the Liked / Reposted / In reply to lines (`.reaction`)
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [Design note](../../design/v2.13.4/2026-11-10-list-counts.md)
|
||||
@@ -0,0 +1,16 @@
|
||||
# v2.14.0
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: Notifications through Apprise
|
||||
|
||||
## Added
|
||||
|
||||
- Notifications of new responses and crosspost/backfeed problems via the embedded Apprise library
|
||||
- Settings `NOTIFY_URLS`, `NOTIFY_EVENTS`, `NOTIFY_PRIORITY`; admin status and Send test notification; migration 021
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [ADR-074](../../decisions/ADR-074-notifications.md)
|
||||
- [Design note](../../design/v2.14.0/2026-11-10-notifications.md)
|
||||
@@ -0,0 +1,15 @@
|
||||
# v2.14.1
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: The two High backlog bugs
|
||||
|
||||
## Fixed
|
||||
|
||||
- The editor can clear all of a note's tags
|
||||
- Image captions escaped in RSS, Atom and JSON Feed item HTML
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [Design note](../../design/v2.14.1/2026-11-10-tags-and-captions.md)
|
||||
@@ -0,0 +1,18 @@
|
||||
# v2.14.2
|
||||
|
||||
- **Date**: 2026-11-10
|
||||
- **Status**: Released
|
||||
- **Focus**: Quote counts; dead files removed
|
||||
|
||||
## Added
|
||||
|
||||
- Quote counts (with anonymous ones) in the counts line and on lists of notes
|
||||
|
||||
## Removed
|
||||
|
||||
- Unused editor scripts (`marked` from a CDN, empty `preview.js`), `templates/feed.xml`, `static/indielogin-test.html`, the `THREADS_API` config read
|
||||
|
||||
## Related
|
||||
|
||||
- [CHANGELOG](../../../CHANGELOG.md)
|
||||
- [Design note](../../design/v2.14.2/2026-11-10-quotes-cleanup.md)
|
||||
+4
-4
@@ -1,11 +1,11 @@
|
||||
# Utility Function Patterns
|
||||
|
||||
**Status**: Active
|
||||
**Last Updated**: 2026-11-03 (v2.10.1; reviewed, content from 2025-11-18)
|
||||
**Status**: Deprecated (2026-11-10). Superseded by [python-coding-standards.md](../python-coding-standards.md), which this document contradicts on type hints (`X | None`, built-in generics, hints on new and changed public functions).
|
||||
**Last Updated**: 2026-11-03 (v2.10.1; content from 2025-11-18)
|
||||
|
||||
## Purpose
|
||||
|
||||
This document establishes coding patterns and conventions specifically for utility functions in StarPunk (`starpunk/utils.py`, `starpunk/slug_utils.py`, `starpunk/mf2_utils.py` and helpers in other modules). These patterns ensure utilities are consistent, testable, and maintainable. General rules, including project-wide patterns for configuration, database access and outbound HTTP, are in [python-coding-standards.md](python-coding-standards.md); where the two differ, that document wins.
|
||||
This document establishes coding patterns and conventions specifically for utility functions in StarPunk (`starpunk/utils.py`, `starpunk/slug_utils.py`, `starpunk/mf2_utils.py` and helpers in other modules). These patterns ensure utilities are consistent, testable, and maintainable. General rules, including project-wide patterns for configuration, database access and outbound HTTP, are in [python-coding-standards.md](../python-coding-standards.md); where the two differ, that document wins.
|
||||
|
||||
The examples are illustrative. Several mirror real functions in `starpunk/utils.py` (`calculate_content_hash`, `write_note_file`, `validate_slug`, `generate_slug`, `validate_note_path`); others (`require_valid_slug`, `iter_note_files`) only show the pattern.
|
||||
|
||||
@@ -731,7 +731,7 @@ def generate_slug(content: str) -> str:
|
||||
|
||||
## References
|
||||
|
||||
- [Python Coding Standards](python-coding-standards.md)
|
||||
- [Python Coding Standards](../python-coding-standards.md)
|
||||
- [PEP 8 - Style Guide](https://peps.python.org/pep-0008/)
|
||||
- [PEP 257 - Docstring Conventions](https://peps.python.org/pep-0257/)
|
||||
- [PEP 484 - Type Hints](https://peps.python.org/pep-0484/)
|
||||
@@ -1,10 +1,10 @@
|
||||
# Standards Index
|
||||
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
|
||||
Standards for developing and releasing StarPunk. Folder rules are in
|
||||
[../DOCUMENTATION.md](../DOCUMENTATION.md). All standards below were checked
|
||||
against the code at v2.10.1.
|
||||
against the code at v2.14.0.
|
||||
|
||||
## Active standards
|
||||
|
||||
@@ -16,7 +16,6 @@ against the code at v2.10.1.
|
||||
| [versioning-strategy.md](versioning-strategy.md) | Choosing MAJOR / MINOR / PATCH |
|
||||
| [version-implementation-guide.md](version-implementation-guide.md) | Where the version lives, changelog entry and design note format |
|
||||
| [python-coding-standards.md](python-coding-standards.md) | Style, naming, and project patterns (config, database, outbound HTTP, errors, routes, workers) |
|
||||
| [utility-function-patterns.md](utility-function-patterns.md) | Patterns for small helper functions |
|
||||
| [cookie-naming-convention.md](cookie-naming-convention.md) | `starpunk_` cookie prefix and the cookies in use |
|
||||
| [documentation-organization.md](documentation-organization.md) | Templates and conventions for docs (folder rules: DOCUMENTATION.md) |
|
||||
|
||||
@@ -31,8 +30,8 @@ against the code at v2.10.1.
|
||||
## Key rules in brief
|
||||
|
||||
- `uv` for environments, `uv run` for every command.
|
||||
- Tests need `SESSION_SECRET`; the full suite takes about 6 minutes, 5 of
|
||||
them in `tests/test_migration_race_condition.py`.
|
||||
- Tests need `SESSION_SECRET`. Locally, run only the tests for the area you
|
||||
changed; CI runs the full suite (about 6 minutes) on every `vX.Y.Z` tag.
|
||||
- Every release: branch in a worktree, bump `__version__` and
|
||||
`__version_info__`, changelog entry, design note (or ADR amendment),
|
||||
`git merge --no-ff`, annotated `vX.Y.Z` tag; CI tests and publishes the
|
||||
@@ -43,8 +42,9 @@ against the code at v2.10.1.
|
||||
|
||||
## Deprecated standards
|
||||
|
||||
Standards that no longer apply move to `DEPRECATED/` (none at
|
||||
present). Earlier versions of the standards above are in git history.
|
||||
Standards that no longer apply move to `DEPRECATED/`:
|
||||
[utility-function-patterns.md](DEPRECATED/utility-function-patterns.md)
|
||||
(superseded by python-coding-standards.md, 2026-11-10). Earlier versions of the standards above are in git history.
|
||||
|
||||
## Related
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Status**: Active
|
||||
**Date**: 2025-11-18
|
||||
**Last Updated**: 2026-11-03 (v2.10.1; cookie list checked against the code)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0; cookie list checked against the code)
|
||||
**Version**: 1.1
|
||||
|
||||
## Purpose
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Development Setup
|
||||
|
||||
**Status**: Active
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
|
||||
How to set up a local StarPunk environment, run the app and run the tests.
|
||||
Each configuration variable is described in [`.env.example`](../../.env.example);
|
||||
@@ -17,8 +17,9 @@ deployment is in [architecture/deployment.md](../architecture/deployment.md).
|
||||
## Environment
|
||||
|
||||
The repository has no `pyproject.toml`; dependencies are in
|
||||
`requirements.txt` (runtime) and `requirements-dev.txt` (adds pytest-cov,
|
||||
pytest-mock, black, flake8, mypy).
|
||||
`requirements.txt` (runtime) and `requirements-dev.txt` (adds
|
||||
`requirements-test.txt` (pytest, pytest-mock), plus pytest-cov, black, flake8,
|
||||
mypy and pip-audit).
|
||||
|
||||
```bash
|
||||
git clone https://git.thesatelliteoflove.com/phil/StarPunk.git
|
||||
@@ -100,9 +101,9 @@ docker run --rm -p 8000:8000 --env-file .env -v ./container-data:/data starpunk:
|
||||
## Running the tests
|
||||
|
||||
```bash
|
||||
SESSION_SECRET=test uv run pytest # full suite
|
||||
SESSION_SECRET=test uv run pytest tests/test_websub.py # one file
|
||||
SESSION_SECRET=test uv run pytest tests/test_websub.py # the area you changed
|
||||
SESSION_SECRET=test uv run pytest tests/test_micropub.py -k delete -x
|
||||
SESSION_SECRET=test uv run pytest # full suite (CI runs this; rarely needed locally)
|
||||
```
|
||||
|
||||
- `SESSION_SECRET` must be set (in `.env` or the environment) because
|
||||
@@ -113,9 +114,9 @@ SESSION_SECRET=test uv run pytest tests/test_micropub.py -k delete -x
|
||||
`DATA_PATH` and database, so tests never touch `./data`. Under
|
||||
`TESTING=True` the background workers don't start and
|
||||
the production OIDC check is skipped.
|
||||
- `tests/test_migration_race_condition.py` is slow (about 5 minutes). While
|
||||
iterating, add `--ignore=tests/test_migration_race_condition.py`; run the
|
||||
full suite before releasing.
|
||||
- Locally, run the tests for the area you changed; the full suite, including
|
||||
the slow `tests/test_migration_race_condition.py` (about 5 minutes), runs in
|
||||
CI on the release tag.
|
||||
- Coverage: `SESSION_SECRET=test uv run pytest --cov=starpunk --cov-report=term-missing`.
|
||||
- The CI test stage can be reproduced exactly with
|
||||
`docker build --target test -f Containerfile .` (see
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Documentation Organization
|
||||
|
||||
**Status**: Active
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
|
||||
**[docs/DOCUMENTATION.md](../DOCUMENTATION.md) is authoritative** for what
|
||||
goes in which folder and supersedes this document. This standard only adds
|
||||
@@ -94,5 +94,5 @@ top saying what replaced it, and removed from the active list in
|
||||
|
||||
- Architecture documents describing a design that no longer exists are
|
||||
either rewritten or renamed with a `-legacy` suffix and a note at the top
|
||||
(e.g. `architecture/technology-stack-legacy.md`).
|
||||
(e.g. `design/v0.x/technology-stack-legacy.md`).
|
||||
- Design notes and ADRs are historical records and stay where they are.
|
||||
@@ -1,7 +1,7 @@
|
||||
# Git Branching and Release Process
|
||||
|
||||
**Status**: Active
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
|
||||
How changes reach `main`, how releases are cut, and what happens after a
|
||||
tag is pushed. This is the flow used for the v2 releases (see
|
||||
@@ -27,6 +27,7 @@ differ, this document describes current practice.
|
||||
| `feat/` | new behaviour (MINOR) | `feat/v2.10.0-websub` |
|
||||
| `fix/` | bug and security fixes (PATCH) | `fix/v2.10.1-websub-hardening` |
|
||||
| `ci/` | build and CI changes | `ci/v2.7.1-pytest` |
|
||||
| `chore/` | maintenance, removals, licensing | `chore/remove-metrics` |
|
||||
| `docs/` | documentation only, no release | `docs/refresh-v2.10.1` |
|
||||
|
||||
Release branches are named `<prefix>/vX.Y.Z-<short-description>`, so the
|
||||
@@ -83,8 +84,9 @@ Code, tests and docs together:
|
||||
- [ ] Add a design note `docs/design/vX.Y.Z/YYYY-MM-DD-<topic>.md` (what
|
||||
changed and why, how it was verified). Small releases fully covered by
|
||||
an ADR amendment and the changelog may skip it
|
||||
- [ ] Full test suite passes:
|
||||
`SESSION_SECRET=test uv run pytest`
|
||||
- [ ] Tests for the changed area pass locally, e.g.
|
||||
`SESSION_SECRET=test uv run pytest tests/test_notifications.py`;
|
||||
CI runs the full suite on the tag (step 4)
|
||||
|
||||
Commit (usually one commit):
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
# Python Coding Standards
|
||||
|
||||
**Status**: Active
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
|
||||
How Python code in StarPunk is written. The project rule comes first:
|
||||
"Every line of code must justify its existence. When in doubt, leave it
|
||||
out." Patterns specific to small helper functions are in
|
||||
[utility-function-patterns.md](utility-function-patterns.md).
|
||||
out."
|
||||
|
||||
## Base style
|
||||
|
||||
@@ -147,5 +146,4 @@ functions or `Test...` classes with descriptive names
|
||||
## References
|
||||
|
||||
- [PEP 8](https://peps.python.org/pep-0008/), [PEP 257](https://peps.python.org/pep-0257/), [PEP 484](https://peps.python.org/pep-0484/)
|
||||
- [utility-function-patterns.md](utility-function-patterns.md)
|
||||
- [ADR-055: Error handling philosophy](../decisions/ADR-055-error-handling-philosophy.md)
|
||||
@@ -1,7 +1,7 @@
|
||||
# Testing Checklist
|
||||
|
||||
**Status**: Active
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
|
||||
What to test, how to run the tests, and what CI does with them. Setup and
|
||||
the environment variables the tests need are in
|
||||
@@ -12,12 +12,14 @@ the environment variables the tests need are in
|
||||
**Locally**
|
||||
|
||||
```bash
|
||||
SESSION_SECRET=test uv run pytest # everything
|
||||
SESSION_SECRET=test uv run pytest --ignore=tests/test_migration_race_condition.py # fast loop
|
||||
SESSION_SECRET=test uv run pytest tests/test_websub.py tests/test_websub_hardening.py # the area you changed
|
||||
SESSION_SECRET=test uv run pytest # everything (CI does this)
|
||||
```
|
||||
|
||||
`tests/test_migration_race_condition.py` takes about 5 minutes; skip it
|
||||
while iterating, never before a release.
|
||||
Locally, run the tests for the area you changed. The full suite, including
|
||||
the 5-minute `tests/test_migration_race_condition.py`, runs in CI. For wide
|
||||
changes (migrations, `config.py`, `create_app`, `tests/conftest.py`) you can
|
||||
build the CI test stage first: `docker build --target test -f Containerfile .`
|
||||
|
||||
**In CI** (`.gitea/workflows/build-container.yml`), on every pushed
|
||||
`vX.Y.Z` tag (or a manual run):
|
||||
@@ -30,16 +32,17 @@ while iterating, never before a release.
|
||||
2. Only if that succeeds is the runtime image built and pushed as
|
||||
`:vX.Y.Z` and `:latest`.
|
||||
|
||||
So a failing test blocks the release image; it does not block the merge or
|
||||
the tag. Run the full suite before merging (see
|
||||
[git-branching-strategy.md](git-branching-strategy.md#release-process)).
|
||||
So a failing test blocks the release image, not the merge or the tag; CI is
|
||||
where the full suite runs. If it fails, fix it in the next PATCH (see
|
||||
[git-branching-strategy.md](git-branching-strategy.md#release-process),
|
||||
step 4).
|
||||
To reproduce CI locally: `docker build --target test -f Containerfile .`
|
||||
(pytest-cov is not installed in that stage, so don't depend on it in
|
||||
tests).
|
||||
|
||||
## Every change
|
||||
|
||||
- [ ] Full suite passes locally
|
||||
- [ ] Tests for the changed area pass locally (CI runs the full suite)
|
||||
- [ ] New behaviour has tests; a bug fix has a test that failed before the fix
|
||||
- [ ] Tests use the `app` / `client` fixtures from `tests/conftest.py`
|
||||
(temporary data directory, `TESTING=True`); nothing touches `./data`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Version Implementation Guide
|
||||
|
||||
**Status**: Active
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
|
||||
Where the version number lives and what to write for each release. Which
|
||||
number to pick: [versioning-strategy.md](versioning-strategy.md). Git steps:
|
||||
@@ -14,8 +14,8 @@ There is one source: `starpunk/__init__.py`, at the end of the file.
|
||||
```python
|
||||
# Package version (Semantic Versioning 2.0.0)
|
||||
# See docs/standards/versioning-strategy.md for details
|
||||
__version__ = "2.10.1"
|
||||
__version_info__ = (2, 10, 1)
|
||||
__version__ = "X.Y.Z"
|
||||
__version_info__ = (X, Y, Z)
|
||||
```
|
||||
|
||||
Update both lines. Nothing else holds the number: there is no
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Versioning Strategy
|
||||
|
||||
**Status**: Active
|
||||
**Last Updated**: 2026-11-03 (v2.10.1)
|
||||
**Last Updated**: 2026-11-10 (v2.14.0)
|
||||
|
||||
StarPunk uses [Semantic Versioning 2.0.0](https://semver.org/):
|
||||
`MAJOR.MINOR.PATCH`, currently **2.14.0**. Every release is a git tag
|
||||
`MAJOR.MINOR.PATCH` (the current version is in `starpunk/__init__.py`). Every release is a git tag
|
||||
`vX.Y.Z` and a `CHANGELOG.md` entry. Where the number is stored and how to
|
||||
write the changelog entry is in
|
||||
[version-implementation-guide.md](version-implementation-guide.md); the
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Migration 022: RFC 8707 resource indicators for IndieAuth codes and tokens
|
||||
-- Version: 2.15.0 (ADR-075)
|
||||
-- Tokens for the MCP endpoint are bound to it; Micropub tokens leave it NULL.
|
||||
|
||||
ALTER TABLE indieauth_codes ADD COLUMN resource TEXT;
|
||||
ALTER TABLE indieauth_tokens ADD COLUMN resource TEXT;
|
||||
+5
-1
@@ -1,4 +1,4 @@
|
||||
# StarPunk runtime dependencies (v2.11.0)
|
||||
# StarPunk runtime dependencies (v2.15.0)
|
||||
# Pinned to a minor series; see docs/architecture/technology-stack.md.
|
||||
|
||||
# Web framework and server
|
||||
@@ -25,3 +25,7 @@ apprise==2.2.*
|
||||
# Images
|
||||
Pillow==13.0.*
|
||||
pillow-heif==1.8.*
|
||||
|
||||
# MCP server sidecar (v2.15.0, ADR-075): official SDK, served by uvicorn
|
||||
mcp==2.3.*
|
||||
uvicorn==0.54.*
|
||||
@@ -325,9 +325,12 @@ def create_app(config=None):
|
||||
|
||||
register_error_handlers(app)
|
||||
|
||||
# Background workers, unless this process is the MCP sidecar (v2.15.0, ADR-075)
|
||||
workers = app.config.get("BACKGROUND_WORKERS_ENABLED", True)
|
||||
|
||||
# Start webmention worker thread (v1.6.0 Phase 2)
|
||||
# Per background-worker.md: Skip in test mode
|
||||
if app.config.get('WEBMENTION_WORKER_ENABLED', True) and not app.config.get('TESTING', False):
|
||||
if workers and app.config.get('WEBMENTION_WORKER_ENABLED', True) and not app.config.get('TESTING', False):
|
||||
from starpunk.webmention_worker import WebmentionWorker
|
||||
webmention_worker = WebmentionWorker(
|
||||
app,
|
||||
@@ -348,13 +351,13 @@ def create_app(config=None):
|
||||
|
||||
# Start WebSub worker (v2.10.0)
|
||||
from starpunk.websub_worker import start_worker
|
||||
app.websub_worker = start_worker(app)
|
||||
app.websub_worker = start_worker(app) if workers else None
|
||||
if app.websub_worker:
|
||||
app.logger.info("WebSub worker started")
|
||||
|
||||
# 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):
|
||||
if workers and targets_configured(app.config) and not app.config.get("TESTING", False):
|
||||
app.syndication_worker = SyndicationWorker(
|
||||
app, poll_interval=app.config["SYNDICATION_POLL_INTERVAL"]
|
||||
)
|
||||
@@ -465,5 +468,5 @@ def create_app(config=None):
|
||||
|
||||
# Package version (Semantic Versioning 2.0.0)
|
||||
# See docs/standards/versioning-strategy.md for details
|
||||
__version__ = "2.14.0"
|
||||
__version_info__ = (2, 14, 0)
|
||||
__version__ = "2.15.0"
|
||||
__version_info__ = (2, 15, 0)
|
||||
@@ -113,6 +113,8 @@ def load_config(app, config_override=None):
|
||||
app.config["WEBSUB_MAX_SUBSCRIPTIONS"] = int(os.getenv("WEBSUB_MAX_SUBSCRIPTIONS", "1000"))
|
||||
app.config["WEBSUB_MAX_PER_HOST"] = int(os.getenv("WEBSUB_MAX_PER_HOST", "25"))
|
||||
app.config["WEBSUB_POLL_INTERVAL"] = int(os.getenv("WEBSUB_POLL_INTERVAL", "5"))
|
||||
# Off in the MCP sidecar so it never runs a second set of workers (v2.15.0, ADR-075)
|
||||
app.config["BACKGROUND_WORKERS_ENABLED"] = os.getenv("BACKGROUND_WORKERS_ENABLED", "true").lower() == "true"
|
||||
app.config["WEBMENTION_WORKER_ENABLED"] = os.getenv("WEBMENTION_WORKER_ENABLED", "true").lower() == "true"
|
||||
app.config["WEBMENTION_POLL_INTERVAL"] = int(os.getenv("WEBMENTION_POLL_INTERVAL", "10"))
|
||||
app.config["WEBMENTION_ERROR_BACKOFF"] = int(os.getenv("WEBMENTION_ERROR_BACKOFF", "60"))
|
||||
|
||||
@@ -16,6 +16,7 @@ Standards:
|
||||
"""
|
||||
|
||||
# Standard library imports
|
||||
from html import escape
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
import xml.etree.ElementTree as ET
|
||||
@@ -199,8 +200,8 @@ def generate_atom_streaming(
|
||||
html_content += '<div class="media">'
|
||||
for item in note.media:
|
||||
media_url = f"{site_url}/media/{item['path']}"
|
||||
caption = item.get('caption', '')
|
||||
html_content += f'<img src="{media_url}" alt="{caption}" />'
|
||||
caption = escape(item.get('caption') or '', quote=True) # v2.14.1
|
||||
html_content += f'<img src="{escape(media_url, quote=True)}" alt="{caption}" />'
|
||||
html_content += '</div>'
|
||||
|
||||
# Add text content below media
|
||||
|
||||
@@ -16,6 +16,7 @@ Standards:
|
||||
"""
|
||||
|
||||
# Standard library imports
|
||||
from html import escape
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Dict, Any
|
||||
import json
|
||||
@@ -247,8 +248,8 @@ def _build_item_object(site_url: str, note: Note) -> Dict[str, Any]:
|
||||
content_html += '<div class="media">'
|
||||
for media_item in note.media:
|
||||
media_url = f"{site_url}/media/{media_item['path']}"
|
||||
caption = media_item.get('caption', '')
|
||||
content_html += f'<img src="{media_url}" alt="{caption}" />'
|
||||
caption = escape(media_item.get('caption') or '', quote=True) # v2.14.1
|
||||
content_html += f'<img src="{escape(media_url, quote=True)}" alt="{caption}" />'
|
||||
content_html += '</div>'
|
||||
|
||||
# Add text content below media
|
||||
|
||||
@@ -20,6 +20,7 @@ Standards:
|
||||
"""
|
||||
|
||||
# Standard library imports
|
||||
from html import escape
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
@@ -127,8 +128,8 @@ def generate_rss(
|
||||
html_content += '<div class="media">'
|
||||
for item in note.media:
|
||||
media_url = f"{site_url}/media/{item['path']}"
|
||||
caption = item.get('caption', '')
|
||||
html_content += f'<img src="{media_url}" alt="{caption}" />'
|
||||
caption = escape(item.get('caption') or '', quote=True) # v2.14.1
|
||||
html_content += f'<img src="{escape(media_url, quote=True)}" alt="{caption}" />'
|
||||
html_content += '</div>'
|
||||
|
||||
# Add text content below media
|
||||
@@ -254,8 +255,8 @@ def generate_rss_streaming(
|
||||
html_content += '<div class="media">'
|
||||
for item in note.media:
|
||||
media_url = f"{site_url}/media/{item['path']}"
|
||||
caption = item.get('caption', '')
|
||||
html_content += f'<img src="{media_url}" alt="{caption}" />'
|
||||
caption = escape(item.get('caption') or '', quote=True) # v2.14.1
|
||||
html_content += f'<img src="{escape(media_url, quote=True)}" alt="{caption}" />'
|
||||
html_content += '</div>'
|
||||
|
||||
# Add text content below media
|
||||
|
||||
+57
-17
@@ -25,7 +25,11 @@ from starpunk.database import get_db
|
||||
from starpunk.utils import absolute_url_for
|
||||
|
||||
CODE_LIFETIME_MINUTES = 10
|
||||
SUPPORTED_SCOPES = ["create", "update", "delete", "media", "profile"]
|
||||
SUPPORTED_SCOPES = ["create", "update", "delete", "media", "draft", "profile"]
|
||||
|
||||
# Scopes offered to an MCP client that asks for none (v2.15.0, ADR-075):
|
||||
# the owner unticks what they don't want on the consent screen
|
||||
MCP_DEFAULT_SCOPES = ["create", "update", "delete", "media", "draft"]
|
||||
|
||||
|
||||
class AuthorizationRequestError(Exception):
|
||||
@@ -56,6 +60,11 @@ def issuer() -> str:
|
||||
return current_app.config["SITE_URL"].rstrip("/") + "/"
|
||||
|
||||
|
||||
def mcp_resource() -> str:
|
||||
"""The MCP endpoint's resource identifier (RFC 8707, v2.15.0)"""
|
||||
return current_app.config["SITE_URL"].rstrip("/") + "/mcp"
|
||||
|
||||
|
||||
def admin_me() -> str:
|
||||
"""The single identity StarPunk issues tokens for"""
|
||||
return current_app.config["ADMIN_ME"]
|
||||
@@ -134,7 +143,7 @@ def validate_authorization_request(params: Dict[str, str]) -> Dict[str, Any]:
|
||||
|
||||
Returns:
|
||||
Normalized request: client_id, redirect_uri, state, scopes,
|
||||
code_challenge
|
||||
code_challenge, resource
|
||||
|
||||
Raises:
|
||||
AuthorizationRequestError
|
||||
@@ -176,17 +185,31 @@ def validate_authorization_request(params: Dict[str, str]) -> Dict[str, Any]:
|
||||
|
||||
scopes = [s for s in (params.get("scope") or "").split() if s]
|
||||
|
||||
# RFC 8707 resource indicator: only the MCP endpoint is a named resource
|
||||
# here (v2.15.0, ADR-075). Micropub clients don't send one.
|
||||
resource = (params.get("resource") or "").strip() or None
|
||||
if resource is not None:
|
||||
if resource.rstrip("/") != mcp_resource():
|
||||
raise AuthorizationRequestError(
|
||||
"invalid_target", "Unknown resource; this server only issues tokens for its MCP endpoint"
|
||||
)
|
||||
resource = mcp_resource()
|
||||
if not scopes:
|
||||
scopes = list(MCP_DEFAULT_SCOPES)
|
||||
|
||||
return {
|
||||
"client_id": client_id,
|
||||
"redirect_uri": redirect_uri,
|
||||
"state": params["state"],
|
||||
"scopes": scopes,
|
||||
"code_challenge": code_challenge,
|
||||
"resource": resource,
|
||||
}
|
||||
|
||||
|
||||
def create_authorization_code(
|
||||
client_id: str, redirect_uri: str, scope: str, code_challenge: str
|
||||
client_id: str, redirect_uri: str, scope: str, code_challenge: str,
|
||||
resource: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Issue a single-use authorization code (stored hashed)"""
|
||||
code = secrets.token_urlsafe(32)
|
||||
@@ -195,8 +218,8 @@ def create_authorization_code(
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO indieauth_codes
|
||||
(code_hash, client_id, redirect_uri, scope, code_challenge, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
(code_hash, client_id, redirect_uri, scope, code_challenge, expires_at, resource)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
_hash(code),
|
||||
@@ -205,6 +228,7 @@ def create_authorization_code(
|
||||
scope,
|
||||
code_challenge,
|
||||
datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=CODE_LIFETIME_MINUTES),
|
||||
resource,
|
||||
),
|
||||
)
|
||||
db.commit()
|
||||
@@ -218,7 +242,7 @@ def redeem_authorization_code(
|
||||
Redeem an authorization code exactly once
|
||||
|
||||
Returns:
|
||||
{"me": ..., "scope": ..., "client_id": ...}
|
||||
{"me": ..., "scope": ..., "client_id": ..., "resource": ...}
|
||||
|
||||
Raises:
|
||||
InvalidGrantError
|
||||
@@ -240,7 +264,7 @@ def redeem_authorization_code(
|
||||
raise InvalidGrantError("Authorization code is invalid, expired or already used")
|
||||
|
||||
row = db.execute(
|
||||
"SELECT client_id, redirect_uri, scope, code_challenge FROM indieauth_codes WHERE code_hash = ?",
|
||||
"SELECT client_id, redirect_uri, scope, code_challenge, resource FROM indieauth_codes WHERE code_hash = ?",
|
||||
(_hash(code),),
|
||||
).fetchone()
|
||||
|
||||
@@ -252,11 +276,20 @@ def redeem_authorization_code(
|
||||
if not secrets.compare_digest(challenge, row["code_challenge"]):
|
||||
raise InvalidGrantError("PKCE verification failed")
|
||||
|
||||
return {"me": admin_me(), "scope": row["scope"], "client_id": row["client_id"]}
|
||||
return {
|
||||
"me": admin_me(),
|
||||
"scope": row["scope"],
|
||||
"client_id": row["client_id"],
|
||||
"resource": row["resource"],
|
||||
}
|
||||
|
||||
|
||||
def create_access_token(client_id: str, scope: str) -> Dict[str, Any]:
|
||||
"""Issue an access token (stored hashed); returns the token response"""
|
||||
def create_access_token(client_id: str, scope: str, resource: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Issue an access token (stored hashed); returns the token response
|
||||
|
||||
resource is the RFC 8707 resource the token is for (the MCP endpoint),
|
||||
or None for Micropub tokens.
|
||||
"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
lifetime_days = current_app.config.get("INDIEAUTH_TOKEN_LIFETIME_DAYS", 90)
|
||||
expires_at = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=lifetime_days)
|
||||
@@ -264,10 +297,10 @@ def create_access_token(client_id: str, scope: str) -> Dict[str, Any]:
|
||||
db = get_db(current_app)
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO indieauth_tokens (token_hash, client_id, scope, expires_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
INSERT INTO indieauth_tokens (token_hash, client_id, scope, expires_at, resource)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(_hash(token), client_id, scope, expires_at),
|
||||
(_hash(token), client_id, scope, expires_at, resource),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
@@ -286,14 +319,15 @@ def verify_access_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
Check a bearer token issued by StarPunk
|
||||
|
||||
Returns:
|
||||
{"me", "client_id", "scope"} if active, otherwise None
|
||||
{"me", "client_id", "scope", "resource", "expires_at"} if active,
|
||||
otherwise None
|
||||
"""
|
||||
if not token:
|
||||
return None
|
||||
db = get_db(current_app)
|
||||
row = db.execute(
|
||||
"""
|
||||
SELECT id, client_id, scope FROM indieauth_tokens
|
||||
SELECT id, client_id, scope, resource, expires_at FROM indieauth_tokens
|
||||
WHERE token_hash = ? AND revoked_at IS NULL AND expires_at > datetime('now')
|
||||
""",
|
||||
(_hash(token),),
|
||||
@@ -306,7 +340,13 @@ def verify_access_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
(row["id"],),
|
||||
)
|
||||
db.commit()
|
||||
return {"me": admin_me(), "client_id": row["client_id"], "scope": row["scope"]}
|
||||
return {
|
||||
"me": admin_me(),
|
||||
"client_id": row["client_id"],
|
||||
"scope": row["scope"],
|
||||
"resource": row["resource"],
|
||||
"expires_at": row["expires_at"],
|
||||
}
|
||||
|
||||
|
||||
def revoke_access_token(token: str) -> None:
|
||||
@@ -334,7 +374,7 @@ def list_active_tokens() -> List[Dict[str, Any]]:
|
||||
db = get_db(current_app)
|
||||
rows = db.execute(
|
||||
"""
|
||||
SELECT id, client_id, scope, created_at, expires_at, last_used_at
|
||||
SELECT id, client_id, scope, resource, created_at, expires_at, last_used_at
|
||||
FROM indieauth_tokens
|
||||
WHERE revoked_at IS NULL AND expires_at > datetime('now')
|
||||
ORDER BY created_at DESC
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""
|
||||
MCP server for StarPunk (v2.15.0, ADR-075)
|
||||
|
||||
AI clients (claude.ai connectors, Claude Code, ...) read and write notes
|
||||
through the Model Context Protocol at SITE_URL/mcp. It runs as a sidecar
|
||||
process (uvicorn, the official MCP Python SDK) next to the Flask app and
|
||||
calls the same service functions. StarPunk's own IndieAuth server issues the
|
||||
tokens; this server only checks them (an OAuth resource server).
|
||||
"""
|
||||
|
||||
from starpunk.mcp_server.server import create_asgi_app, create_mcp_server
|
||||
|
||||
__all__ = ["create_asgi_app", "create_mcp_server"]
|
||||
@@ -0,0 +1,13 @@
|
||||
"""
|
||||
ASGI entry point for the MCP sidecar (v2.15.0, ADR-075)
|
||||
|
||||
uvicorn starpunk.mcp_server.app:app --host 0.0.0.0 --port 8001
|
||||
|
||||
Run it with BACKGROUND_WORKERS_ENABLED=false and the same environment and
|
||||
data volume as the main app. Route /mcp and
|
||||
/.well-known/oauth-protected-resource/mcp to it.
|
||||
"""
|
||||
|
||||
from starpunk.mcp_server.server import create_asgi_app
|
||||
|
||||
app = create_asgi_app()
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
Bearer token checks for the MCP endpoint (v2.15.0, ADR-075)
|
||||
|
||||
Tokens are StarPunk IndieAuth tokens bound to the MCP resource (RFC 8707).
|
||||
The SDK's bearer middleware turns a missing or rejected token into a 401
|
||||
that points the client at the protected resource metadata, and refuses
|
||||
tokens whose resource isn't this endpoint (validate_token_resource).
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import anyio.to_thread
|
||||
from flask import Flask
|
||||
from mcp.server.auth.provider import AccessToken
|
||||
|
||||
from starpunk.indieauth import verify_access_token
|
||||
|
||||
|
||||
def _epoch(value) -> Optional[int]:
|
||||
"""SQLite timestamp (datetime or 'YYYY-MM-DD HH:MM:SS' UTC) -> epoch seconds"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return int(value.timestamp())
|
||||
|
||||
|
||||
class StarPunkTokenVerifier:
|
||||
"""TokenVerifier backed by the indieauth_tokens table"""
|
||||
|
||||
def __init__(self, app: Flask):
|
||||
self.app = app
|
||||
|
||||
def _verify(self, token: str) -> Optional[AccessToken]:
|
||||
with self.app.app_context():
|
||||
info = verify_access_token(token)
|
||||
if not info:
|
||||
return None
|
||||
return AccessToken(
|
||||
token=token,
|
||||
client_id=info["client_id"],
|
||||
scopes=(info["scope"] or "").split(),
|
||||
expires_at=_epoch(info.get("expires_at")),
|
||||
resource=info.get("resource"),
|
||||
subject=info["me"],
|
||||
)
|
||||
|
||||
async def verify_token(self, token: str) -> Optional[AccessToken]:
|
||||
# Database work happens off the event loop
|
||||
return await anyio.to_thread.run_sync(self._verify, token)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
The MCP server and its ASGI app (v2.15.0, ADR-075)
|
||||
|
||||
Stateless Streamable HTTP with plain JSON responses: every request stands
|
||||
alone, so any number of uvicorn workers can serve it and nothing is lost on
|
||||
restart.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from flask import Flask
|
||||
from mcp.server import MCPServer
|
||||
from mcp.server.auth.settings import AuthSettings
|
||||
from mcp.server.transport_security import TransportSecuritySettings
|
||||
from pydantic import AnyHttpUrl
|
||||
from starlette.applications import Starlette
|
||||
|
||||
from starpunk.mcp_server.auth import StarPunkTokenVerifier
|
||||
from starpunk.mcp_server.tools import register_tools
|
||||
|
||||
INSTRUCTIONS = """\
|
||||
StarPunk is an IndieWeb site: a personal blog of short notes and longer
|
||||
articles, owned by one person. Notes are Markdown. A note whose first line
|
||||
is '# Heading' is an article with that title. Notes can be drafts
|
||||
(unpublished) or published; publishing may crosspost them to social
|
||||
networks chosen with syndicate_to (see get_site_config). Prefer drafts unless
|
||||
the owner asked to publish. Deleting is a soft delete that undelete_note
|
||||
reverses.
|
||||
"""
|
||||
|
||||
|
||||
def _site(app: Flask) -> str:
|
||||
return app.config["SITE_URL"].rstrip("/")
|
||||
|
||||
|
||||
def create_mcp_server(app: Flask) -> MCPServer:
|
||||
"""The MCP server, with StarPunk's tools and token checks"""
|
||||
site = _site(app)
|
||||
server = MCPServer(
|
||||
name="StarPunk",
|
||||
instructions=INSTRUCTIONS,
|
||||
website_url=site,
|
||||
version=app.config.get("VERSION", ""),
|
||||
token_verifier=StarPunkTokenVerifier(app),
|
||||
auth=AuthSettings(
|
||||
# Same string as the issuer in /.well-known/oauth-authorization-server
|
||||
issuer_url=AnyHttpUrl(site + "/"),
|
||||
resource_server_url=AnyHttpUrl(site + "/mcp"),
|
||||
# Tools check their own scopes; any StarPunk token may connect
|
||||
required_scopes=[],
|
||||
validate_token_resource=True,
|
||||
),
|
||||
)
|
||||
register_tools(server, app)
|
||||
return server
|
||||
|
||||
|
||||
def _transport_security(app: Flask) -> TransportSecuritySettings:
|
||||
"""Only requests for this site's host and from its origin (DNS rebinding)"""
|
||||
site = urlparse(_site(app))
|
||||
hosts = [site.netloc]
|
||||
origins = [f"{site.scheme}://{site.netloc}"]
|
||||
if app.config.get("DEV_MODE"):
|
||||
hosts += ["localhost:*", "127.0.0.1:*"]
|
||||
origins += ["http://localhost:*", "http://127.0.0.1:*"]
|
||||
return TransportSecuritySettings(
|
||||
enable_dns_rebinding_protection=True,
|
||||
allowed_hosts=hosts,
|
||||
allowed_origins=origins,
|
||||
)
|
||||
|
||||
|
||||
def create_asgi_app(app: Optional[Flask] = None) -> Starlette:
|
||||
"""
|
||||
ASGI app serving /mcp and its protected resource metadata
|
||||
|
||||
Args:
|
||||
app: The Flask app to call into. Built from the environment if not
|
||||
given, with background workers off (the main app runs those).
|
||||
"""
|
||||
if app is None:
|
||||
from starpunk import create_app
|
||||
|
||||
app = create_app({"BACKGROUND_WORKERS_ENABLED": False})
|
||||
|
||||
server = create_mcp_server(app)
|
||||
return server.streamable_http_app(
|
||||
streamable_http_path="/mcp",
|
||||
stateless_http=True,
|
||||
json_response=True,
|
||||
# Base64 photos for upload_media: 10 MB of image is ~14 MB encoded
|
||||
max_request_body_size=16 * 1024 * 1024,
|
||||
transport_security=_transport_security(app),
|
||||
)
|
||||
@@ -0,0 +1,362 @@
|
||||
"""
|
||||
MCP tools for StarPunk (v2.15.0, ADR-075)
|
||||
|
||||
Reading tools call the notes, tags and search services. Writing tools build
|
||||
a Micropub request and hand it to the Micropub handlers, so an MCP post goes
|
||||
through exactly the same checks and side effects (scopes, drafts-only
|
||||
tokens, crossposting, webmentions, WebSub) as one from any Micropub client.
|
||||
|
||||
Scopes are the Micropub ones: reading needs any StarPunk token; drafts and
|
||||
tags need create, update, delete or draft; writing needs create (or draft),
|
||||
update, delete or media.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import anyio.to_thread
|
||||
from flask import Flask
|
||||
from mcp.server import MCPServer
|
||||
from mcp.server.auth.middleware.auth_context import get_access_token
|
||||
from mcp.server.mcpserver.exceptions import ToolError
|
||||
from mcp.types import ToolAnnotations
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from starpunk.indieauth import check_scope
|
||||
from starpunk.micropub import MicropubError
|
||||
|
||||
DRAFT_SCOPES = ("create", "update", "delete", "draft")
|
||||
MAX_LIMIT = 100
|
||||
|
||||
|
||||
class Photo(BaseModel):
|
||||
"""A photo for a note"""
|
||||
|
||||
url: str = Field(description="URL from upload_media, or any public image URL")
|
||||
alt: str = Field(default="", description="Alt text describing the photo")
|
||||
|
||||
|
||||
def _token_info() -> dict:
|
||||
"""The caller's token as the Micropub handlers expect it"""
|
||||
token = get_access_token()
|
||||
if token is None:
|
||||
raise ToolError("Not authenticated")
|
||||
return {"me": token.subject, "client_id": token.client_id, "scope": " ".join(token.scopes)}
|
||||
|
||||
|
||||
def _require(info: dict, *scopes: str) -> None:
|
||||
if not any(check_scope(s, info["scope"]) for s in scopes):
|
||||
raise ToolError(f"This needs the {' or '.join(scopes)} scope; reconnect and grant it")
|
||||
|
||||
|
||||
def _sees_drafts(info: dict) -> bool:
|
||||
return any(check_scope(s, info["scope"]) for s in DRAFT_SCOPES)
|
||||
|
||||
|
||||
def _clamp(limit: int) -> int:
|
||||
return max(1, min(int(limit), MAX_LIMIT))
|
||||
|
||||
|
||||
def _note_url(slug: str) -> str:
|
||||
from starpunk.utils import absolute_url_for
|
||||
|
||||
return absolute_url_for("public.note", slug=slug)
|
||||
|
||||
|
||||
def _summary(note) -> dict:
|
||||
from starpunk.utils import iso_utc
|
||||
|
||||
return {
|
||||
"url": _note_url(note.slug),
|
||||
"slug": note.slug,
|
||||
"title": note.title,
|
||||
"kind": note.kind,
|
||||
"status": "published" if note.published else "draft",
|
||||
"published": iso_utc(note.created_at),
|
||||
"excerpt": note.excerpt,
|
||||
}
|
||||
|
||||
|
||||
def _find_note(url_or_slug: str):
|
||||
"""A note by its URL on this site or its slug"""
|
||||
from starpunk.micropub import _note_from_url
|
||||
from starpunk.notes import get_note
|
||||
|
||||
value = (url_or_slug or "").strip()
|
||||
if urlparse(value).scheme:
|
||||
return _note_from_url(value)
|
||||
note = get_note(slug=value.strip("/").split("/")[-1]) if value else None
|
||||
if note is None:
|
||||
raise ToolError("Note not found")
|
||||
return note
|
||||
|
||||
|
||||
def _status_after(url: str) -> dict:
|
||||
"""Summary of the note at url, as it is now"""
|
||||
return _summary(_find_note(url))
|
||||
|
||||
|
||||
def register_tools(server: MCPServer, app: Flask) -> None:
|
||||
"""Add StarPunk's tools to the MCP server"""
|
||||
site = app.config["SITE_URL"].rstrip("/")
|
||||
|
||||
async def run(fn: Callable[..., Any], *args, **kwargs) -> Any:
|
||||
"""Run fn in a worker thread inside a Flask request context for SITE_URL"""
|
||||
|
||||
def call():
|
||||
with app.test_request_context(base_url=site):
|
||||
try:
|
||||
return fn(*args, **kwargs)
|
||||
except MicropubError as e:
|
||||
raise ToolError(e.error_description or e.error) from e
|
||||
except ValueError as e:
|
||||
raise ToolError(str(e)) from e
|
||||
|
||||
return await anyio.to_thread.run_sync(call)
|
||||
|
||||
read_only = ToolAnnotations(read_only_hint=True, open_world_hint=False)
|
||||
|
||||
# Reading
|
||||
|
||||
@server.tool(annotations=read_only)
|
||||
async def search_notes(query: str, include_drafts: bool = False, limit: int = 20) -> dict:
|
||||
"""Full-text search of the site's notes. Returns matches with a snippet;
|
||||
use get_note for the whole note."""
|
||||
info = _token_info()
|
||||
if include_drafts:
|
||||
_require(info, *DRAFT_SCOPES)
|
||||
|
||||
def search():
|
||||
from starpunk.search import has_fts_table, search_notes as fts
|
||||
|
||||
db_path = Path(app.config["DATABASE_PATH"])
|
||||
if not has_fts_table(db_path):
|
||||
raise ToolError("Search is not available on this server")
|
||||
results = fts(query=query, db_path=db_path, published_only=not include_drafts, limit=_clamp(limit))
|
||||
return {
|
||||
"results": [
|
||||
{"url": _note_url(r["slug"]), "slug": r["slug"], "title": r.get("title"),
|
||||
"snippet": r.get("snippet")}
|
||||
for r in results
|
||||
]
|
||||
}
|
||||
|
||||
return await run(search)
|
||||
|
||||
@server.tool(annotations=read_only)
|
||||
async def list_notes(include_drafts: bool = False, limit: int = 20, offset: int = 0) -> dict:
|
||||
"""The site's notes, newest first. Drafts are left out unless
|
||||
include_drafts is true."""
|
||||
info = _token_info()
|
||||
if include_drafts:
|
||||
_require(info, *DRAFT_SCOPES)
|
||||
|
||||
def notes():
|
||||
from starpunk.notes import list_notes as list_all
|
||||
|
||||
found = list_all(published_only=not include_drafts, limit=_clamp(limit), offset=max(0, offset))
|
||||
return {"notes": [_summary(n) for n in found], "offset": max(0, offset)}
|
||||
|
||||
return await run(notes)
|
||||
|
||||
@server.tool(annotations=read_only)
|
||||
async def get_note(url_or_slug: str) -> dict:
|
||||
"""One note in full: Markdown content, title (name), tags (category),
|
||||
photos, status, reply/like/repost/bookmark target and crosspost links,
|
||||
as Microformats2 properties."""
|
||||
info = _token_info()
|
||||
|
||||
def one():
|
||||
from starpunk.micropub import note_to_mf2
|
||||
|
||||
note = _find_note(url_or_slug)
|
||||
if not note.published and not _sees_drafts(info):
|
||||
raise ToolError("Note not found")
|
||||
return {"url": _note_url(note.slug), "slug": note.slug,
|
||||
"properties": note_to_mf2(note)["properties"]}
|
||||
|
||||
return await run(one)
|
||||
|
||||
@server.tool(annotations=read_only)
|
||||
async def list_tags(filter: str = "") -> dict:
|
||||
"""Tags in use on the site, most used first, optionally only those
|
||||
containing filter."""
|
||||
info = _token_info()
|
||||
_require(info, *DRAFT_SCOPES)
|
||||
|
||||
def tags():
|
||||
from starpunk.micropub import _all_categories
|
||||
|
||||
return {"tags": _all_categories(filter)}
|
||||
|
||||
return await run(tags)
|
||||
|
||||
@server.tool(annotations=read_only)
|
||||
async def get_site_config() -> dict:
|
||||
"""What the site supports: post types and the crosspost targets
|
||||
(syndicate-to uids) that create_note's syndicate_to accepts."""
|
||||
info = _token_info()
|
||||
|
||||
def config():
|
||||
from starpunk.micropub import handle_query
|
||||
|
||||
response = handle_query({"q": "config"}, info)
|
||||
# Flask views may return (response, status[, headers])
|
||||
if isinstance(response, tuple):
|
||||
response = response[0]
|
||||
return response.get_json()
|
||||
|
||||
return await run(config)
|
||||
|
||||
# Writing
|
||||
|
||||
@server.tool(annotations=ToolAnnotations(destructive_hint=False, open_world_hint=True))
|
||||
async def create_note(
|
||||
content: str = "",
|
||||
title: Optional[str] = None,
|
||||
tags: Optional[list[str]] = None,
|
||||
draft: bool = True,
|
||||
photos: Optional[list[Photo]] = None,
|
||||
in_reply_to: Optional[str] = None,
|
||||
like_of: Optional[str] = None,
|
||||
repost_of: Optional[str] = None,
|
||||
bookmark_of: Optional[str] = None,
|
||||
syndicate_to: Optional[list[str]] = None,
|
||||
slug: Optional[str] = None,
|
||||
published_at: Optional[str] = None,
|
||||
) -> dict:
|
||||
"""Create a note (Markdown). It is a draft unless draft is false;
|
||||
publishing makes it public and crossposts it to the syndicate_to
|
||||
targets. A title makes it an article. At most one of like_of,
|
||||
repost_of and bookmark_of. published_at is an ISO 8601 date."""
|
||||
info = _token_info()
|
||||
_require(info, "create", "draft")
|
||||
|
||||
props: dict[str, list] = {"post-status": ["draft" if draft else "published"]}
|
||||
if content:
|
||||
props["content"] = [content]
|
||||
if title:
|
||||
props["name"] = [title]
|
||||
if tags:
|
||||
props["category"] = list(tags)
|
||||
if photos:
|
||||
props["photo"] = [{"value": p.url, "alt": p.alt} for p in photos]
|
||||
for name, value in (("in-reply-to", in_reply_to), ("like-of", like_of),
|
||||
("repost-of", repost_of), ("bookmark-of", bookmark_of),
|
||||
("published", published_at)):
|
||||
if value:
|
||||
props[name] = [value]
|
||||
data: dict[str, Any] = {"type": ["h-entry"], "properties": props}
|
||||
if syndicate_to:
|
||||
data["mp-syndicate-to"] = list(syndicate_to)
|
||||
if slug:
|
||||
data["mp-slug"] = slug
|
||||
|
||||
def create():
|
||||
from starpunk.micropub import handle_create
|
||||
|
||||
_, _, headers = handle_create(data, info)
|
||||
return _status_after(headers["Location"])
|
||||
|
||||
return await run(create)
|
||||
|
||||
@server.tool(annotations=ToolAnnotations(destructive_hint=True, idempotent_hint=True, open_world_hint=True))
|
||||
async def update_note(
|
||||
url: str,
|
||||
content: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
tags: Optional[list[str]] = None,
|
||||
add_tags: Optional[list[str]] = None,
|
||||
remove_tags: Optional[list[str]] = None,
|
||||
draft: Optional[bool] = None,
|
||||
photos: Optional[list[Photo]] = None,
|
||||
in_reply_to: Optional[str] = None,
|
||||
) -> dict:
|
||||
"""Change a note. Only the fields given change: content replaces the
|
||||
text, title replaces the title ("" removes it), tags replaces all
|
||||
tags, add_tags/remove_tags adjust them, photos replaces all photos,
|
||||
draft false publishes a draft (and crossposts it) and true unpublishes.
|
||||
Edits to published notes follow to their crossposts."""
|
||||
info = _token_info()
|
||||
_require(info, "update")
|
||||
|
||||
replace: dict[str, list] = {}
|
||||
if content is not None:
|
||||
replace["content"] = [content]
|
||||
if title is not None:
|
||||
replace["name"] = [title]
|
||||
if tags is not None:
|
||||
replace["category"] = list(tags)
|
||||
if draft is not None:
|
||||
replace["post-status"] = ["draft" if draft else "published"]
|
||||
if photos is not None:
|
||||
replace["photo"] = [{"value": p.url, "alt": p.alt} for p in photos]
|
||||
if in_reply_to is not None:
|
||||
replace["in-reply-to"] = [in_reply_to]
|
||||
data: dict[str, Any] = {"action": "update", "url": url, "replace": replace}
|
||||
if add_tags:
|
||||
data["add"] = {"category": list(add_tags)}
|
||||
if remove_tags:
|
||||
data["delete"] = {"category": list(remove_tags)}
|
||||
|
||||
def update():
|
||||
from starpunk.micropub import handle_update
|
||||
|
||||
note = _find_note(url)
|
||||
data["url"] = _note_url(note.slug)
|
||||
handle_update(data, info)
|
||||
return _status_after(data["url"])
|
||||
|
||||
return await run(update)
|
||||
|
||||
@server.tool(annotations=ToolAnnotations(destructive_hint=True, idempotent_hint=True, open_world_hint=False))
|
||||
async def delete_note(url: str) -> dict:
|
||||
"""Delete a note. It can be restored with undelete_note."""
|
||||
info = _token_info()
|
||||
_require(info, "delete")
|
||||
|
||||
def delete():
|
||||
from starpunk.micropub import handle_delete
|
||||
|
||||
note_url = _note_url(_find_note(url).slug)
|
||||
handle_delete({"url": note_url}, info)
|
||||
return {"url": note_url, "status": "deleted"}
|
||||
|
||||
return await run(delete)
|
||||
|
||||
@server.tool(annotations=ToolAnnotations(destructive_hint=False, idempotent_hint=True, open_world_hint=False))
|
||||
async def undelete_note(url: str) -> dict:
|
||||
"""Restore a deleted note."""
|
||||
info = _token_info()
|
||||
_require(info, "delete")
|
||||
note_url = url if urlparse(url).scheme else f"{site}/note/{url.strip('/')}"
|
||||
|
||||
def undelete():
|
||||
from starpunk.micropub import handle_delete
|
||||
|
||||
handle_delete({"url": note_url}, info, undelete=True)
|
||||
return _status_after(note_url)
|
||||
|
||||
return await run(undelete)
|
||||
|
||||
@server.tool(annotations=ToolAnnotations(destructive_hint=False, open_world_hint=False))
|
||||
async def upload_media(filename: str, data_base64: str) -> dict:
|
||||
"""Upload an image (JPEG, PNG, GIF, WebP or HEIC, base64-encoded) and
|
||||
get its URL, to use as a photo in create_note or update_note."""
|
||||
info = _token_info()
|
||||
_require(info, "media", "create")
|
||||
try:
|
||||
data = base64.b64decode(data_base64, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
raise ToolError("data_base64 is not valid base64")
|
||||
|
||||
def upload():
|
||||
from starpunk.media import save_media
|
||||
|
||||
media = save_media(data, filename)
|
||||
return {"url": f"{site}/media/{media['path']}"}
|
||||
|
||||
return await run(upload)
|
||||
@@ -309,7 +309,9 @@ def update_note_submit(note_id: int):
|
||||
id=note_id,
|
||||
content=content,
|
||||
published=published,
|
||||
tags=tags if tags else None
|
||||
# An empty Tags field removes all tags (v2.14.1); a form without
|
||||
# the field leaves them alone
|
||||
tags=tags if "tags" in request.form else None
|
||||
)
|
||||
if "syndication_form" in request.form:
|
||||
from starpunk.syndication import select_targets
|
||||
|
||||
@@ -51,6 +51,7 @@ _REQUEST_FIELDS = (
|
||||
"code_challenge",
|
||||
"code_challenge_method",
|
||||
"scope",
|
||||
"resource",
|
||||
)
|
||||
|
||||
|
||||
@@ -95,6 +96,11 @@ def metadata():
|
||||
"revocation_endpoint_auth_methods_supported": ["none"],
|
||||
"scopes_supported": SUPPORTED_SCOPES,
|
||||
"response_types_supported": ["code"],
|
||||
# Public clients only (PKCE); clients identify with a client_id
|
||||
# URL whose JSON metadata lists redirect_uris, which is what MCP
|
||||
# calls a Client ID Metadata Document (v2.15.0, ADR-075)
|
||||
"token_endpoint_auth_methods_supported": ["none"],
|
||||
"client_id_metadata_document_supported": True,
|
||||
"grant_types_supported": ["authorization_code"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
"authorization_response_iss_parameter_supported": True,
|
||||
@@ -158,6 +164,7 @@ def approve():
|
||||
auth_request["redirect_uri"],
|
||||
" ".join(granted),
|
||||
auth_request["code_challenge"],
|
||||
resource=auth_request["resource"],
|
||||
)
|
||||
current_app.logger.info(
|
||||
f"IndieAuth: approved {auth_request['client_id']} (scope: {' '.join(granted) or 'none'})"
|
||||
@@ -209,7 +216,12 @@ def token():
|
||||
# Spec: a code issued without scope cannot be used for an access token
|
||||
return _oauth_error("invalid_grant", "No scope was granted; use the authorization endpoint")
|
||||
|
||||
return _json(create_access_token(result["client_id"], result["scope"]))
|
||||
# RFC 8707: a resource named here must be the one the code was issued for
|
||||
requested = (request.form.get("resource") or "").strip().rstrip("/")
|
||||
if requested and requested != (result["resource"] or ""):
|
||||
return _oauth_error("invalid_target", "resource does not match the authorization request")
|
||||
|
||||
return _json(create_access_token(result["client_id"], result["scope"], resource=result["resource"]))
|
||||
|
||||
|
||||
@bp.route("/auth/token", methods=["GET"])
|
||||
@@ -222,7 +234,7 @@ def token_verify():
|
||||
info = verify_access_token(token)
|
||||
if not info:
|
||||
return _oauth_error("unauthorized", "Invalid or expired access token", 401)
|
||||
return _json(info)
|
||||
return _json({k: info[k] for k in ("me", "client_id", "scope")})
|
||||
|
||||
|
||||
@bp.route("/auth/revoke", methods=["POST"])
|
||||
|
||||
@@ -1074,8 +1074,7 @@ def get_targets() -> Dict[str, Target]:
|
||||
if token:
|
||||
client = _client_cache.get("threads")
|
||||
if client is None or client.config_token != token:
|
||||
client = ThreadsClient(token, Path(config["DATA_PATH"]) / "threads_token.json",
|
||||
api=config.get("THREADS_API") or THREADS_API)
|
||||
client = ThreadsClient(token, Path(config["DATA_PATH"]) / "threads_token.json")
|
||||
_client_cache["threads"] = client
|
||||
username = (config.get("THREADS_USERNAME") or "").lstrip("@")
|
||||
targets["threads"] = Target(
|
||||
|
||||
@@ -112,7 +112,8 @@ def get_webmentions_for_note(note_id: int) -> Dict[str, List[Dict[str, Any]]]:
|
||||
|
||||
def response_counts(note_ids: List[int]) -> Dict[int, Dict[str, int]]:
|
||||
"""
|
||||
Likes, reposts and replies per note, for lists of notes (v2.13.4).
|
||||
Likes, reposts, replies and quotes per note, for lists of notes
|
||||
(v2.13.4; quotes v2.14.2).
|
||||
|
||||
Shown responses (valid and approved) plus the counts silos give without
|
||||
names (Threads; people who opted out of backfeed) on synced crossposts.
|
||||
@@ -126,21 +127,22 @@ def response_counts(note_ids: List[int]) -> Dict[int, Dict[str, int]]:
|
||||
|
||||
def add(note_id, key, n):
|
||||
if n:
|
||||
counts.setdefault(note_id, {'likes': 0, 'reposts': 0, 'replies': 0})[key] += n
|
||||
counts.setdefault(note_id, {'likes': 0, 'reposts': 0, 'replies': 0, 'quotes': 0})[key] += n
|
||||
|
||||
for row in db.execute(
|
||||
f"""
|
||||
SELECT target_note_id, mention_type, COUNT(*) FROM webmentions
|
||||
WHERE target_note_id IN ({marks}) AND validation_status = 'valid'
|
||||
AND moderation_status = 'approved' AND mention_type IN ('like', 'repost', 'reply')
|
||||
AND moderation_status = 'approved' AND mention_type IN ('like', 'repost', 'reply', 'quote')
|
||||
GROUP BY target_note_id, mention_type
|
||||
""",
|
||||
note_ids,
|
||||
):
|
||||
add(row[0], {'like': 'likes', 'repost': 'reposts', 'reply': 'replies'}[row[1]], row[2])
|
||||
add(row[0], {'like': 'likes', 'repost': 'reposts', 'reply': 'replies', 'quote': 'quotes'}[row[1]], row[2])
|
||||
for row in db.execute(
|
||||
f"""
|
||||
SELECT note_id, SUM(COALESCE(likes_count, 0)), SUM(COALESCE(reposts_count, 0))
|
||||
SELECT note_id, SUM(COALESCE(likes_count, 0)), SUM(COALESCE(reposts_count, 0)),
|
||||
SUM(COALESCE(quotes_count, 0))
|
||||
FROM syndications WHERE note_id IN ({marks}) AND state = 'synced'
|
||||
GROUP BY note_id
|
||||
""",
|
||||
@@ -148,6 +150,7 @@ def response_counts(note_ids: List[int]) -> Dict[int, Dict[str, int]]:
|
||||
):
|
||||
add(row[0], 'likes', row[1])
|
||||
add(row[0], 'reposts', row[2])
|
||||
add(row[0], 'quotes', row[3])
|
||||
return counts
|
||||
|
||||
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>IndieLogin Test Form</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>IndieLogin Test Form</h1>
|
||||
<p>This is the exact form from IndieLogin.com API docs</p>
|
||||
|
||||
<form action="https://indielogin.com/authorize" method="get">
|
||||
<label for="url">Web Address:</label>
|
||||
<input id="url" type="text" name="me" placeholder="yourdomain.com" value="https://thesatelliteoflove.com" />
|
||||
<p><button type="submit">Sign In</button></p>
|
||||
<input type="hidden" name="client_id" value="https://starpunk.thesatelliteoflove.com/" />
|
||||
<input type="hidden" name="redirect_uri" value="https://starpunk.thesatelliteoflove.com/auth/callback" />
|
||||
<input type="hidden" name="state" value="TESTSTATE123456789" />
|
||||
<input type="hidden" name="code_challenge" value="E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" />
|
||||
<input type="hidden" name="code_challenge_method" value="S256" />
|
||||
</form>
|
||||
|
||||
<hr>
|
||||
<p><strong>Note:</strong> This uses a fixed code_challenge for testing. In production, this should be generated fresh each time.</p>
|
||||
<p><strong>Form will submit to:</strong> https://indielogin.com/authorize</p>
|
||||
</body>
|
||||
</html>
|
||||
Whitespace-only changes.
@@ -14,6 +14,11 @@
|
||||
<strong>{{ auth_request.client_id }}</strong> wants to sign in as
|
||||
<strong>{{ me }}</strong>.
|
||||
</p>
|
||||
{% if auth_request.resource %}
|
||||
<p>This is an AI assistant asking to use your site through MCP
|
||||
(<code>{{ auth_request.resource }}</code>). It can read your notes and drafts,
|
||||
and do whatever you allow below.</p>
|
||||
{% endif %}
|
||||
<p><small>After approval you will be sent to {{ auth_request.redirect_uri }}</small></p>
|
||||
|
||||
<form action="{{ url_for('indieauth.approve') }}" method="POST" class="login-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
|
||||
@@ -116,8 +116,3 @@
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block head %}
|
||||
{{ super() }}
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<script src="{{ url_for('static', filename='js/preview.js') }}"></script>
|
||||
{% endblock %}
|
||||
@@ -88,8 +88,6 @@
|
||||
|
||||
{% block head %}
|
||||
{{ super() }}
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<script src="{{ url_for('static', filename='js/preview.js') }}"></script>
|
||||
|
||||
<style>
|
||||
.media-preview {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
{% block admin_content %}
|
||||
<div class="tokens-admin">
|
||||
<h2>Connected Apps</h2>
|
||||
<p>Micropub apps you have approved. Revoke any you no longer use.</p>
|
||||
<p>Micropub apps and AI assistants (MCP) you have approved. Revoke any you no longer use.</p>
|
||||
|
||||
{% if tokens %}
|
||||
<div class="table-scroll">
|
||||
@@ -23,7 +23,7 @@
|
||||
<tbody>
|
||||
{% for t in tokens %}
|
||||
<tr>
|
||||
<td>{{ t.client_id }}</td>
|
||||
<td>{{ t.client_id }}{% if t.resource %} <small>(MCP)</small>{% endif %}</td>
|
||||
<td>{{ t.scope }}</td>
|
||||
<td>{{ t.created_at }}</td>
|
||||
<td>{{ t.last_used_at or "never" }}</td>
|
||||
|
||||
Whitespace-only changes.
+1
-1
@@ -79,7 +79,7 @@
|
||||
</footer>
|
||||
|
||||
<div id="responses"></div>
|
||||
{{ responses.reactions(likes, reposts, replies, bookmarks, syndications, absolute_url_for('public.note', slug=note.slug)) }}
|
||||
{{ responses.reactions(likes, reposts, replies, bookmarks, syndications, absolute_url_for('public.note', slug=note.slug), quotes) }}
|
||||
|
||||
<nav class="note-nav">
|
||||
<a href="/">← All notes</a>
|
||||
|
||||
@@ -64,6 +64,7 @@
|
||||
'like': '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>',
|
||||
'repost': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>',
|
||||
'reply': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 11.5a8.4 8.4 0 0 1-9 8.4 8.6 8.6 0 0 1-3.9-.9L3 21l1.9-5.1A8.4 8.4 0 0 1 12 3.1a8.4 8.4 0 0 1 9 8.4z"/></svg>',
|
||||
'quote': '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M7.2 5C4.3 6.4 3 8.9 3 12.3V19h7v-7H6.3c.1-2.2 1-3.7 2.9-4.6L7.2 5zm10 0c-2.9 1.4-4.2 3.9-4.2 7.3V19h7v-7h-3.7c.1-2.2 1-3.7 2.9-4.6L17.2 5z"/></svg>',
|
||||
'bookmark': '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M6 2h12a1 1 0 0 1 1 1v19l-7-4-7 4V3a1 1 0 0 1 1-1z"/></svg>',
|
||||
} %}
|
||||
{% set VERBS = {'like': 'Like', 'repost': 'Repost', 'reply': 'Reply'} %}
|
||||
@@ -95,19 +96,22 @@
|
||||
{% endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro reactions(likes, reposts, replies, bookmarks, syndications, permalink) %}
|
||||
{% set anon_likes, anon_reposts = [], [] %}
|
||||
{% macro reactions(likes, reposts, replies, bookmarks, syndications, permalink, quotes=[]) %}
|
||||
{% set anon_likes, anon_reposts, anon_quotes = [], [], [] %}
|
||||
{% for s in syndications or [] %}
|
||||
{% if s.likes_count %}{% set _ = anon_likes.append((s.name, s.likes_count)) %}{% endif %}
|
||||
{% if s.reposts_count %}{% set _ = anon_reposts.append((s.name, s.reposts_count)) %}{% endif %}
|
||||
{% if s.quotes_count %}{% set _ = anon_quotes.append((s.name, s.quotes_count)) %}{% endif %}
|
||||
{% endfor %}
|
||||
{% set copies = (syndications or [])|selectattr('remote_url')|list %}
|
||||
{% if copies or likes or reposts or replies or bookmarks or anon_likes or anon_reposts %}
|
||||
{% if copies or likes or reposts or replies or quotes or bookmarks or anon_likes or anon_reposts or anon_quotes %}
|
||||
<div class="response-counts">
|
||||
{{ reaction('like', likes or [], 'u-like', anon_likes, 'like', 'likes', copies, permalink) }}
|
||||
{{ reaction('repost', reposts or [], 'u-repost', anon_reposts, 'repost', 'reposts', copies, permalink) }}
|
||||
{# Replies are listed in full below; here just the count and where to reply #}
|
||||
{{ reaction('reply', replies or [], '', [], 'reply', 'replies', copies, permalink, people=False) }}
|
||||
{# Quotes: named ones are listed below; the card shows those without names (v2.14.2) #}
|
||||
{{ reaction('quote', quotes or [], '', anon_quotes, 'quote', 'quotes', people=False) }}
|
||||
{{ reaction('bookmark', bookmarks or [], 'u-bookmark', [], 'bookmark', 'bookmarks') }}
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -118,7 +122,7 @@
|
||||
{% macro list_counts(counts, permalink) %}
|
||||
{% if counts %}
|
||||
<a class="list-counts" href="{{ permalink }}#responses">
|
||||
{%- for key, kind, one, many in [('likes', 'like', 'like', 'likes'), ('reposts', 'repost', 'repost', 'reposts'), ('replies', 'reply', 'reply', 'replies')] if counts[key] -%}
|
||||
{%- for key, kind, one, many in [('likes', 'like', 'like', 'likes'), ('reposts', 'repost', 'repost', 'reposts'), ('replies', 'reply', 'reply', 'replies'), ('quotes', 'quote', 'quote', 'quotes')] if counts.get(key) -%}
|
||||
<span class="list-count list-count-{{ kind }}" title="{{ counts[key] }} {{ one if counts[key] == 1 else many }}">{{ ICONS[kind]|safe }}{{ counts[key] }}<span class="visually-hidden"> {{ one if counts[key] == 1 else many }}</span></span>
|
||||
{%- endfor -%}
|
||||
</a>
|
||||
|
||||
@@ -639,3 +639,21 @@ def test_home_page_shows_counts(app, client):
|
||||
assert 'title="3 likes"' in page and 'title="2 reposts"' in page and 'title="1 reply"' in page
|
||||
assert f"/note/{quiet.slug}#responses" not in page
|
||||
assert 'id="responses"' in app.test_client().get(f"/note/{note.slug}").get_data(as_text=True)
|
||||
|
||||
|
||||
def test_quote_counts_include_anonymous_ones(app, client):
|
||||
"""v2.14.2: quotes have a count, including those without names (Threads, opted out)"""
|
||||
note, sid = crossposted(app)
|
||||
client.harvest = Harvest([Response(kind="quote", source_url="https://bsky.app/profile/q/post/1",
|
||||
remote_id="at://q/1", author_name="Quoter",
|
||||
content_html="<p>Look</p>")])
|
||||
run(app)
|
||||
with app.app_context():
|
||||
get_db(app).execute("UPDATE syndications SET quotes_count = 2 WHERE id = ?", (sid,))
|
||||
get_db(app).commit()
|
||||
page = app.test_client().get(f"/note/{note.slug}").get_data(as_text=True)
|
||||
quote = page.split('response-count-quote')[1].split('</span>\n</span>')[0]
|
||||
assert '<span class="response-count-n">3</span>' in quote and "2 on GoToSocial" in quote
|
||||
assert "Quoter" in page, "the named quote is listed under Responses"
|
||||
home = app.test_client().get("/").get_data(as_text=True)
|
||||
assert 'title="3 quotes"' in home
|
||||
+79
-1
@@ -184,7 +184,9 @@ class TestCodesAndTokens:
|
||||
with app.test_request_context():
|
||||
code = create_authorization_code(CLIENT_ID, REDIRECT_URI, "create", challenge_for(verifier))
|
||||
result = redeem_authorization_code(code, CLIENT_ID, REDIRECT_URI, verifier)
|
||||
assert result == {"me": "https://example.com", "scope": "create", "client_id": CLIENT_ID}
|
||||
assert result == {
|
||||
"me": "https://example.com", "scope": "create", "client_id": CLIENT_ID, "resource": None,
|
||||
}
|
||||
|
||||
token = create_access_token(CLIENT_ID, "create")
|
||||
info = verify_access_token(token["access_token"])
|
||||
@@ -354,3 +356,79 @@ class TestEndpoints:
|
||||
admin_client.post(f"/admin/tokens/{token_id}/revoke")
|
||||
with app.test_request_context():
|
||||
assert verify_access_token(token) is None
|
||||
|
||||
|
||||
MCP_RESOURCE = "https://blog.example.com/mcp"
|
||||
|
||||
|
||||
class TestResourceIndicators:
|
||||
"""RFC 8707 resource binding for MCP clients (v2.15.0, ADR-075)"""
|
||||
|
||||
def test_metadata_advertises_cimd_and_draft(self, client):
|
||||
data = client.get("/.well-known/oauth-authorization-server").get_json()
|
||||
assert data["client_id_metadata_document_supported"] is True
|
||||
assert data["token_endpoint_auth_methods_supported"] == ["none"]
|
||||
assert "draft" in data["scopes_supported"]
|
||||
|
||||
def test_mcp_resource_accepted(self, app):
|
||||
with app.test_request_context():
|
||||
result = validate_authorization_request(auth_params(resource=MCP_RESOURCE + "/"))
|
||||
assert result["resource"] == MCP_RESOURCE
|
||||
|
||||
def test_no_resource_is_micropub(self, app):
|
||||
with app.test_request_context():
|
||||
assert validate_authorization_request(auth_params())["resource"] is None
|
||||
|
||||
def test_unknown_resource_rejected(self, app):
|
||||
with app.test_request_context():
|
||||
with pytest.raises(AuthorizationRequestError) as e:
|
||||
validate_authorization_request(auth_params(resource="https://other.example/mcp"))
|
||||
assert e.value.error == "invalid_target"
|
||||
assert e.value.redirectable
|
||||
|
||||
def test_mcp_client_without_scope_is_offered_defaults(self, app):
|
||||
with app.test_request_context():
|
||||
result = validate_authorization_request(auth_params(scope="", resource=MCP_RESOURCE))
|
||||
assert result["scopes"] == ["create", "update", "delete", "media", "draft"]
|
||||
|
||||
def test_consent_page_names_mcp(self, admin_client):
|
||||
response = admin_client.get("/auth/authorize?" + urlencode(auth_params(resource=MCP_RESOURCE)))
|
||||
assert response.status_code == 200
|
||||
assert b"MCP" in response.data
|
||||
assert b'name="resource" value="https://blog.example.com/mcp"' in response.data
|
||||
|
||||
def _token_form(self, query, **extra):
|
||||
return {
|
||||
"grant_type": "authorization_code",
|
||||
"code": query["code"][0],
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"code_verifier": "v" * 50,
|
||||
**extra,
|
||||
}
|
||||
|
||||
def test_resource_carried_to_token(self, app, admin_client, client):
|
||||
query = approve(admin_client, granted=["create"], resource=MCP_RESOURCE)
|
||||
body = client.post("/auth/token", data=self._token_form(query, resource=MCP_RESOURCE)).get_json()
|
||||
with app.test_request_context():
|
||||
info = verify_access_token(body["access_token"])
|
||||
assert info["resource"] == MCP_RESOURCE
|
||||
assert info["scope"] == "create"
|
||||
|
||||
def test_token_request_resource_must_match(self, admin_client, client):
|
||||
query = approve(admin_client, granted=["create"], resource=MCP_RESOURCE)
|
||||
response = client.post("/auth/token", data=self._token_form(query, resource="https://other.example/"))
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"] == "invalid_target"
|
||||
|
||||
def test_micropub_token_has_no_resource(self, app, admin_client, client):
|
||||
query = approve(admin_client, granted=["create"])
|
||||
body = client.post("/auth/token", data=self._token_form(query)).get_json()
|
||||
with app.test_request_context():
|
||||
assert verify_access_token(body["access_token"])["resource"] is None
|
||||
|
||||
def test_legacy_verification_shape_unchanged(self, app, client):
|
||||
with app.test_request_context():
|
||||
token = create_access_token(CLIENT_ID, "create", resource=MCP_RESOURCE)["access_token"]
|
||||
data = client.get("/auth/token", headers={"Authorization": f"Bearer {token}"}).get_json()
|
||||
assert data == {"me": "https://example.com", "client_id": CLIENT_ID, "scope": "create"}
|
||||
@@ -0,0 +1,259 @@
|
||||
"""
|
||||
Tests for the MCP server (starpunk/mcp_server, v2.15.0, ADR-075)
|
||||
|
||||
Requests go through the real ASGI app (Streamable HTTP, stateless JSON) with
|
||||
real StarPunk tokens, so the SDK's bearer checks, resource binding and DNS
|
||||
rebinding protection are exercised along with the tools.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
from starpunk.indieauth import create_access_token, revoke_access_token
|
||||
from starpunk.mcp_server import create_asgi_app
|
||||
|
||||
SITE = "https://blog.example.com"
|
||||
RESOURCE = SITE + "/mcp"
|
||||
ALL_SCOPES = "create update delete media draft"
|
||||
HEADERS = {
|
||||
"Accept": "application/json, text/event-stream",
|
||||
"Content-Type": "application/json",
|
||||
"MCP-Protocol-Version": "2025-11-25",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path):
|
||||
from starpunk import create_app
|
||||
|
||||
data = tmp_path / "data"
|
||||
return create_app(
|
||||
{
|
||||
"TESTING": True,
|
||||
"SITE_URL": SITE,
|
||||
"ADMIN_ME": "https://example.com",
|
||||
"SESSION_SECRET": "test-secret",
|
||||
"DATA_PATH": data,
|
||||
"NOTES_PATH": data / "notes",
|
||||
"DATABASE_PATH": data / "starpunk.db",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def http(app):
|
||||
with TestClient(create_asgi_app(app), base_url=SITE) as client:
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def token(app):
|
||||
"""Make a token bound to the MCP resource (or another) with given scopes"""
|
||||
|
||||
def make(scope=ALL_SCOPES, resource=RESOURCE):
|
||||
with app.app_context():
|
||||
return create_access_token("https://claude.ai/client.json", scope, resource=resource)["access_token"]
|
||||
|
||||
return make
|
||||
|
||||
|
||||
def rpc(http, token, method, params=None, headers=None):
|
||||
body = {"jsonrpc": "2.0", "id": 1, "method": method}
|
||||
if params is not None:
|
||||
body["params"] = params
|
||||
auth = {"Authorization": f"Bearer {token}"} if token else {}
|
||||
return http.post("/mcp", json=body, headers={**HEADERS, **auth, **(headers or {})})
|
||||
|
||||
|
||||
def call(http, token, name, **arguments):
|
||||
"""Call a tool; returns (is_error, parsed JSON result or error text)"""
|
||||
response = rpc(http, token, "tools/call", {"name": name, "arguments": arguments})
|
||||
assert response.status_code == 200, response.text
|
||||
result = response.json()["result"]
|
||||
text = result["content"][0]["text"]
|
||||
if result.get("isError"):
|
||||
return True, text
|
||||
return False, json.loads(text)
|
||||
|
||||
|
||||
def ok(http, token, name, **arguments):
|
||||
is_error, result = call(http, token, name, **arguments)
|
||||
assert not is_error, result
|
||||
return result
|
||||
|
||||
|
||||
class TestAuth:
|
||||
def test_no_token_points_to_resource_metadata(self, http):
|
||||
response = rpc(http, None, "tools/list")
|
||||
assert response.status_code == 401
|
||||
assert f'resource_metadata="{SITE}/.well-known/oauth-protected-resource/mcp"' in (
|
||||
response.headers["www-authenticate"]
|
||||
)
|
||||
|
||||
def test_protected_resource_metadata(self, http):
|
||||
data = http.get("/.well-known/oauth-protected-resource/mcp").json()
|
||||
assert data["resource"] == RESOURCE
|
||||
# Must equal the issuer in /.well-known/oauth-authorization-server
|
||||
assert data["authorization_servers"] == [SITE + "/"]
|
||||
|
||||
def test_micropub_token_refused(self, http, token):
|
||||
assert rpc(http, token(resource=None), "tools/list").status_code == 401
|
||||
|
||||
def test_other_resource_refused(self, http, token):
|
||||
assert rpc(http, token(resource="https://other.example/mcp"), "tools/list").status_code == 401
|
||||
|
||||
def test_revoked_token_refused(self, app, http, token):
|
||||
value = token()
|
||||
with app.app_context():
|
||||
revoke_access_token(value)
|
||||
assert rpc(http, value, "tools/list").status_code == 401
|
||||
|
||||
def test_unknown_host_refused(self, http, token):
|
||||
response = rpc(http, token(), "tools/list", headers={"Host": "evil.example"})
|
||||
assert response.status_code in (400, 403, 421)
|
||||
|
||||
def test_lists_tools(self, http, token):
|
||||
response = rpc(http, token(), "tools/list")
|
||||
names = {t["name"] for t in response.json()["result"]["tools"]}
|
||||
assert names == {
|
||||
"search_notes", "list_notes", "get_note", "list_tags", "get_site_config",
|
||||
"create_note", "update_note", "delete_note", "undelete_note", "upload_media",
|
||||
}
|
||||
|
||||
def test_read_tools_are_marked_read_only(self, http, token):
|
||||
tools = {t["name"]: t for t in rpc(http, token(), "tools/list").json()["result"]["tools"]}
|
||||
assert tools["list_notes"]["annotations"]["readOnlyHint"] is True
|
||||
assert tools["delete_note"]["annotations"]["destructiveHint"] is True
|
||||
|
||||
|
||||
class TestWriting:
|
||||
def test_create_defaults_to_draft(self, http, token):
|
||||
note = ok(http, token(), "create_note", content="Hello from MCP", tags=["ai"])
|
||||
assert note["status"] == "draft"
|
||||
assert note["url"].startswith(SITE + "/note/")
|
||||
|
||||
def test_create_published_article(self, http, token):
|
||||
tok = token()
|
||||
note = ok(http, tok, "create_note", content="Body", title="An article", draft=False)
|
||||
assert note["status"] == "published"
|
||||
props = ok(http, tok, "get_note", url_or_slug=note["url"])["properties"]
|
||||
assert props["name"] == ["An article"]
|
||||
assert props["post-status"] == ["published"]
|
||||
|
||||
def test_draft_only_token_cannot_publish(self, http, token):
|
||||
note = ok(http, token("draft"), "create_note", content="Sneaky", draft=False)
|
||||
assert note["status"] == "draft"
|
||||
|
||||
def test_create_needs_scope(self, http, token):
|
||||
is_error, message = call(http, token("update"), "create_note", content="x")
|
||||
assert is_error and "create or draft" in message
|
||||
|
||||
def test_update_tags_and_publish(self, http, token):
|
||||
tok = token()
|
||||
note = ok(http, tok, "create_note", content="Tagged", tags=["one", "two"])
|
||||
updated = ok(http, tok, "update_note", url=note["slug"], add_tags=["three"],
|
||||
remove_tags=["one"], draft=False)
|
||||
assert updated["status"] == "published"
|
||||
props = ok(http, tok, "get_note", url_or_slug=note["slug"])["properties"]
|
||||
assert props["category"] == ["two", "three"]
|
||||
|
||||
def test_update_content_and_remove_title(self, http, token):
|
||||
tok = token()
|
||||
note = ok(http, tok, "create_note", content="Old", title="Title")
|
||||
ok(http, tok, "update_note", url=note["url"], content="New", title="")
|
||||
props = ok(http, tok, "get_note", url_or_slug=note["url"])["properties"]
|
||||
assert props["content"] == ["New"]
|
||||
assert "name" not in props
|
||||
|
||||
def test_update_needs_scope(self, http, token):
|
||||
note = ok(http, token(), "create_note", content="x")
|
||||
is_error, _ = call(http, token("create"), "update_note", url=note["url"], content="y")
|
||||
assert is_error
|
||||
|
||||
def test_delete_and_undelete(self, http, token):
|
||||
tok = token()
|
||||
note = ok(http, tok, "create_note", content="Gone soon", draft=False)
|
||||
assert ok(http, tok, "delete_note", url=note["url"])["status"] == "deleted"
|
||||
assert call(http, tok, "get_note", url_or_slug=note["slug"])[0]
|
||||
assert ok(http, tok, "undelete_note", url=note["slug"])["status"] == "published"
|
||||
|
||||
def test_note_on_other_site_refused(self, http, token):
|
||||
is_error, message = call(http, token(), "delete_note", url="https://other.example/note/x")
|
||||
assert is_error and "not on this site" in message
|
||||
|
||||
def test_upload_media_then_attach(self, http, token):
|
||||
tok = token()
|
||||
buffer = io.BytesIO()
|
||||
Image.new("RGB", (40, 30), "red").save(buffer, format="PNG")
|
||||
media = ok(http, tok, "upload_media", filename="red.png",
|
||||
data_base64=base64.b64encode(buffer.getvalue()).decode())
|
||||
assert media["url"].startswith(SITE + "/media/")
|
||||
note = ok(http, tok, "create_note", photos=[{"url": media["url"], "alt": "A red square"}])
|
||||
props = ok(http, tok, "get_note", url_or_slug=note["slug"])["properties"]
|
||||
assert props["photo"][0]["alt"] == "A red square"
|
||||
|
||||
def test_upload_rejects_bad_base64(self, http, token):
|
||||
is_error, message = call(http, token(), "upload_media", filename="x.png", data_base64="!!!")
|
||||
assert is_error and "base64" in message
|
||||
|
||||
|
||||
class TestReading:
|
||||
def test_list_hides_drafts_by_default(self, http, token):
|
||||
tok = token()
|
||||
ok(http, tok, "create_note", content="Draft")
|
||||
ok(http, tok, "create_note", content="Public", draft=False)
|
||||
assert [n["excerpt"] for n in ok(http, tok, "list_notes")["notes"]] == ["Public"]
|
||||
assert len(ok(http, tok, "list_notes", include_drafts=True)["notes"]) == 2
|
||||
|
||||
def test_drafts_need_a_posting_scope(self, http, token):
|
||||
ok(http, token(), "create_note", content="Secret draft")
|
||||
reader = token("media")
|
||||
assert call(http, reader, "list_notes", include_drafts=True)[0]
|
||||
assert ok(http, reader, "list_notes")["notes"] == []
|
||||
|
||||
def test_draft_hidden_from_get_without_scope(self, http, token):
|
||||
note = ok(http, token(), "create_note", content="Secret draft")
|
||||
is_error, _ = call(http, token("media"), "get_note", url_or_slug=note["slug"])
|
||||
assert is_error
|
||||
|
||||
def test_search(self, http, token):
|
||||
tok = token()
|
||||
ok(http, tok, "create_note", content="Pancakes on Sunday", draft=False)
|
||||
ok(http, tok, "create_note", content="Waffles", draft=False)
|
||||
results = ok(http, tok, "search_notes", query="pancakes")["results"]
|
||||
assert len(results) == 1 and results[0]["url"].startswith(SITE + "/note/")
|
||||
|
||||
def test_tags(self, http, token):
|
||||
tok = token()
|
||||
ok(http, tok, "create_note", content="x", tags=["Cats", "dogs"])
|
||||
assert set(ok(http, tok, "list_tags")["tags"]) == {"Cats", "dogs"}
|
||||
assert ok(http, tok, "list_tags", filter="cat")["tags"] == ["Cats"]
|
||||
|
||||
def test_site_config(self, http, token):
|
||||
config = ok(http, token("media"), "get_site_config")
|
||||
assert config["media-endpoint"] == SITE + "/micropub/media"
|
||||
assert "syndicate-to" in config
|
||||
|
||||
|
||||
class TestSidecarApp:
|
||||
def test_workers_off_when_built_from_environment(self, monkeypatch, tmp_path):
|
||||
"""create_asgi_app() without an app never starts background workers"""
|
||||
import starpunk
|
||||
|
||||
seen = {}
|
||||
real = starpunk.create_app
|
||||
|
||||
def spy(config=None):
|
||||
seen.update(config or {})
|
||||
return real({**(config or {}), "TESTING": True, "SITE_URL": SITE,
|
||||
"SESSION_SECRET": "x", "ADMIN_ME": "https://example.com", "DATA_PATH": tmp_path,
|
||||
"NOTES_PATH": tmp_path / "notes", "DATABASE_PATH": tmp_path / "db.sqlite"})
|
||||
|
||||
monkeypatch.setattr(starpunk, "create_app", spy)
|
||||
create_asgi_app()
|
||||
assert seen["BACKGROUND_WORKERS_ENABLED"] is False
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
v2.14.1 fixes: clearing all tags in the editor, and media captions escaped
|
||||
in the HTML of RSS, Atom and JSON Feed items.
|
||||
"""
|
||||
|
||||
import io
|
||||
import json
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from starpunk import create_app
|
||||
from starpunk.media import attach_media_to_note, save_media
|
||||
from starpunk.notes import create_note
|
||||
from starpunk.tags import get_note_tags
|
||||
|
||||
CAPTION = 'Say "hi" <b>bold</b> & more'
|
||||
ESCAPED = 'alt="Say "hi" <b>bold</b> & more"'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path):
|
||||
data = tmp_path / "data"
|
||||
app = create_app({
|
||||
"TESTING": True, "DATABASE_PATH": data / "starpunk.db", "DATA_PATH": data,
|
||||
"NOTES_PATH": data / "notes", "SESSION_SECRET": "x", "ADMIN_ME": "https://example.com",
|
||||
"SITE_URL": "https://blog.example.com", "SITE_NAME": "Test", "CSRF_ENABLED": False,
|
||||
})
|
||||
yield app
|
||||
|
||||
|
||||
def png():
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (800, 600), "red").save(buf, "PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def captioned(app):
|
||||
with app.app_context():
|
||||
note = create_note(content="A photo", published=True)
|
||||
media = save_media(png(), "photo.png")
|
||||
attach_media_to_note(note.id, [media["id"]], [CAPTION])
|
||||
return note
|
||||
|
||||
|
||||
def test_rss_caption_escaped(app, captioned):
|
||||
body = app.test_client().get("/feed.rss").get_data(as_text=True)
|
||||
description = ET.fromstring(body).find("./channel/item/description").text
|
||||
assert ESCAPED in description
|
||||
assert "<b>bold</b>" not in description
|
||||
|
||||
|
||||
def test_atom_caption_escaped_once(app, captioned):
|
||||
body = app.test_client().get("/feed.atom").get_data(as_text=True)
|
||||
ns = {"a": "http://www.w3.org/2005/Atom"}
|
||||
entry = ET.fromstring(body).find("a:entry", ns)
|
||||
content = entry.find("a:content", ns).text
|
||||
assert ESCAPED in content and "<b>bold</b>" not in content
|
||||
# The enclosure's title attribute was already escaped; not twice
|
||||
enclosure = next(l for l in entry.findall("a:link", ns) if l.get("rel") == "enclosure")
|
||||
assert enclosure.get("title") == CAPTION
|
||||
|
||||
|
||||
def test_json_feed_caption_escaped(app, captioned):
|
||||
item = json.loads(app.test_client().get("/feed.json").get_data(as_text=True))["items"][0]
|
||||
assert ESCAPED in item["content_html"] and "<b>bold</b>" not in item["content_html"]
|
||||
|
||||
|
||||
def test_editor_can_clear_all_tags(app):
|
||||
from starpunk.auth import create_session
|
||||
|
||||
with app.app_context():
|
||||
note = create_note(content="Tagged", published=True, tags=["one", "two"])
|
||||
with app.test_request_context():
|
||||
token = create_session("https://example.com")
|
||||
client = app.test_client()
|
||||
client.set_cookie("starpunk_session", token)
|
||||
|
||||
# A form without the Tags field leaves the tags alone
|
||||
client.post(f"/admin/edit/{note.id}", data={"content": "Tagged", "published": "on"})
|
||||
with app.app_context():
|
||||
assert {t["name"] for t in get_note_tags(note.id)} == {"one", "two"}
|
||||
|
||||
# An empty Tags field removes them all
|
||||
client.post(f"/admin/edit/{note.id}", data={"content": "Tagged", "published": "on", "tags": ""})
|
||||
with app.app_context():
|
||||
assert get_note_tags(note.id) == []
|
||||
Reference in new issue
Block a user