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

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

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

No files matched your search

+29 -71
View File
@@ -1,82 +1,40 @@
# Architecture Documentation Index
This directory contains architectural documentation, system design overviews, component diagrams, and architectural patterns for StarPunk CMS.
This directory describes the **current** design of StarPunk (v2.10.1). 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/).
## Core Architecture
## Documents
### System Overview
- **[overview.md](overview.md)** - Complete system architecture and design principles
- **[technology-stack.md](technology-stack.md)** - Current technology stack and dependencies
- **[technology-stack-legacy.md](technology-stack-legacy.md)** - Historical technology decisions
| Document | Description |
|----------|-------------|
| [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–017, 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 |
### Feature-Specific Architecture
## Where to start
#### IndieAuth & Authentication
- **[indieauth-assessment.md](indieauth-assessment.md)** - Assessment of IndieAuth implementation
- **[indieauth-client-diagnosis.md](indieauth-client-diagnosis.md)** - IndieAuth client diagnostic analysis
- **[indieauth-endpoint-discovery.md](indieauth-endpoint-discovery.md)** - Endpoint discovery architecture
- **[indieauth-identity-page.md](indieauth-identity-page.md)** - Identity page architecture
- **[indieauth-questions-answered.md](indieauth-questions-answered.md)** - Architectural Q&A for IndieAuth
- **[indieauth-removal-architectural-review.md](indieauth-removal-architectural-review.md)** - Review of custom IndieAuth removal
- **[indieauth-removal-implementation-guide.md](indieauth-removal-implementation-guide.md)** - Implementation guide for removal
- **[indieauth-removal-phases.md](indieauth-removal-phases.md)** - Phased removal approach
- **[indieauth-removal-plan.md](indieauth-removal-plan.md)** - Overall removal plan
- **[indieauth-token-verification-diagnosis.md](indieauth-token-verification-diagnosis.md)** - Token verification diagnostic analysis
- **[simplified-auth-architecture.md](simplified-auth-architecture.md)** - Simplified authentication architecture
- **[endpoint-discovery-answers.md](endpoint-discovery-answers.md)** - Endpoint discovery implementation Q&A
- **New to the code**: overview.md, then technology-stack.md.
- **Changing the schema**: database.md (migrations must be safe inside one
transaction).
- **Releasing or operating the site**: deployment.md.
- **Working on auth, Micropub, Webmention or WebSub**:
simplified-auth-architecture.md and indieweb-protocols.md, plus the ADRs
they link to.
#### Database & Migrations
- **[database-migration-architecture.md](database-migration-architecture.md)** - Database migration system architecture
- **[migration-fix-quick-reference.md](migration-fix-quick-reference.md)** - Quick reference for migration fixes
- **[migration-race-condition-answers.md](migration-race-condition-answers.md)** - Race condition resolution Q&A
## Related documentation
#### Syndication
- **[syndication-architecture.md](syndication-architecture.md)** - RSS feed and syndication architecture
## Version-Specific Architecture
### v1.0.0
- **[v1.0.0-release-validation.md](v1.0.0-release-validation.md)** - Release validation architecture
### v1.1.0
- **[v1.1.0-feature-architecture.md](v1.1.0-feature-architecture.md)** - Feature architecture for v1.1.0
- **[v1.1.0-implementation-decisions.md](v1.1.0-implementation-decisions.md)** - Implementation decisions
- **[v1.1.0-search-ui-validation.md](v1.1.0-search-ui-validation.md)** - Search UI validation
- **[v1.1.0-validation-report.md](v1.1.0-validation-report.md)** - Overall validation report
### v1.1.1
- **[v1.1.1-architecture-overview.md](v1.1.1-architecture-overview.md)** - Architecture overview for v1.1.1
## Phase Documentation
- **[phase1-completion-guide.md](phase1-completion-guide.md)** - Phase 1 completion guide
- **[phase-5-validation-report.md](phase-5-validation-report.md)** - Phase 5 validation report
## Review Documentation
- **[review-v1.0.0-rc.5.md](review-v1.0.0-rc.5.md)** - Architectural review of v1.0.0-rc.5
## How to Use This Documentation
### For New Developers
1. Start with **overview.md** to understand the system
2. Review **technology-stack.md** for current technologies
3. Read feature-specific architecture docs relevant to your work
### For Architects
1. Review version-specific architecture for historical context
2. Consult feature-specific docs when making changes
3. Update relevant docs when architecture changes
### For Contributors
1. Read **overview.md** for system understanding
2. Consult specific architecture docs for areas you're working on
3. Follow patterns documented in architecture files
## Related Documentation
- **[../decisions/](../decisions/)** - Architectural Decision Records (ADRs)
- **[../design/](../design/)** - Detailed design documents
- **[../standards/](../standards/)** - Coding standards and conventions
- [../decisions/](../decisions/): Architectural Decision Records (ADRs)
- [../design/](../design/): designs, questions and reports per version
- [../standards/](../standards/): coding, testing and versioning standards
- [../projectplan/](../projectplan/): backlog and release plans
---
**Last Updated**: 2025-11-25
**Maintained By**: Documentation Manager Agent
**Last Updated**: 2026-11-03 (v2.10.1)
+235
View File
@@ -0,0 +1,235 @@
# Database Architecture
**Version**: 2.10.1 (2026-11-03)
**Status**: Current. Verified against a database created by `create_app()`
with migrations 001–017.
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
in Markdown files (`notes/YYYY/MM/<slug>.md`) and the `notes` table points to
them. See [overview.md](overview.md) for how the rest of the system uses it.
## How the schema is built
On every start, `init_db()` (`starpunk/database/init.py`) does two things:
1. Runs `INITIAL_SCHEMA_SQL` (`starpunk/database/schema.py`). This is the
frozen v1.0.0 baseline, written with `CREATE … IF NOT EXISTS`: `notes`,
`sessions`, `tokens`, `authorization_codes`, `auth_state` and their
indexes. It must not be changed; every later change is a migration.
2. Runs `run_migrations()` (`starpunk/migrations.py`) over the SQL files in
`migrations/`, in file-name order.
### Migration runner
- Applied migrations are recorded in `schema_migrations`
(`migration_name`, `applied_at`).
- **Locking**: all four gunicorn processes run `create_app()` at the same
time. Each opens a direct (unpooled) connection with a 30-second busy
timeout and runs `BEGIN IMMEDIATE`, which takes SQLite's write lock. The
whole run (creating `schema_migrations`, checking what is pending, applying
every pending migration and recording it) happens in that one transaction
and is committed at the end, so a migration is applied once and atomically.
Statements are executed one by one with `conn.execute()` (split with
`sqlite3.complete_statement`, so trigger bodies stay whole), never with
`executescript()`, which would commit and drop the lock part-way (the cause
of the v2.8.0 deploy failure fixed in v2.8.1).
- A process that finds the database locked retries with exponential backoff
(up to 10 attempts, 120 seconds in total), then finds everything already
applied and returns.
- A failing migration rolls the whole run back and raises `MigrationError`,
which stops the app from starting.
- **Fresh databases**: when `schema_migrations` is empty, the runner checks
each of the early migrations (001–003) against the actual schema and only
records those whose effect is already present; migration 002 is reduced to
creating its indexes. All later migrations run normally.
Background: [ADR-031](../decisions/ADR-031-database-migration-system-redesign.md),
[ADR-032](../decisions/ADR-032-initial-schema-sql-implementation.md),
[ADR-033](../decisions/ADR-033-database-migration-redesign.md),
[ADR-037](../decisions/ADR-037-migration-race-condition-fix.md),
[ADR-041](../decisions/ADR-041-database-migration-conflict-resolution.md).
### Migrations
| File | Version | Change |
|------|---------|--------|
| `001_add_code_verifier_to_auth_state.sql` | 0.8 | `auth_state.code_verifier` (removed again by 003) |
| `002_secure_tokens_and_authorization_codes.sql` | 1.0.0-rc | Hashed `tokens` and `authorization_codes` (dropped by 004) |
| `003_remove_code_verifier_from_auth_state.sql` | 1.0 | Drops `auth_state.code_verifier` |
| `004_drop_token_tables.sql` | 1.0 | Drops `tokens` and `authorization_codes` |
| `005_add_fts5_search.sql` | 1.1 | `notes_fts` (FTS5) and the `notes_fts_delete` trigger |
| `006_add_author_profile.sql` | 1.2 | `author_profile` (h-card cache) |
| `007_add_media_support.sql` | 1.2 | `media`, `note_media` |
| `008_add_tags.sql` | 1.3 | `tags`, `note_tags` |
| `009_add_media_variants.sql` | 1.4 | `media_variants` |
| `010_add_webmentions.sql` | 1.6 | `notes.in_reply_to`, `webmentions`, `webmention_queue`, `reply_contexts` |
| `011_oidc_login_and_indieauth_server.sql` | 2.0 | `oidc_login_state`, `indieauth_codes`, `indieauth_tokens` |
| `012_add_syndications.sql` | 2.1 | `syndications` |
| `013_add_likes_reposts.sql` | 2.5 | `notes.like_of`, `notes.repost_of` |
| `014_webmention_source_details.sql` | 2.8 | `webmentions.source_post_url`, `webmentions.source_published` |
| `015_bookmarks_and_content_format.sql` | 2.9 | `notes.bookmark_of`, `notes.content_format` |
| `016_websub.sql` | 2.10.0 | `websub_subscriptions`, `websub_intents`, `websub_deliveries`, `site_state` |
| `017_websub_hardening.sql` | 2.10.1 | `websub_intents.request_id`, `requested_topic`, `callback_ip`; `websub_subscriptions.callback_ip` |
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.
## Tables
### Content
**`notes`**: one row per note; the content is in the file at `file_path`.
| Column | Purpose |
|--------|---------|
| `id`, `slug` (unique), `file_path` (unique) | Identity and location of the Markdown file (relative to `DATA_PATH`) |
| `published` | 0 = draft, 1 = public |
| `created_at`, `updated_at` | Timestamps (UTC) |
| `deleted_at` | Set on soft delete (file moved to `.trash/`); cleared by undelete |
| `content_hash` | SHA-256 of the file content |
| `in_reply_to`, `like_of`, `repost_of`, `bookmark_of` | URL the note responds to; set for replies, likes, reposts, bookmarks |
| `content_format` | `'html'` when a Micropub client sent HTML (so `q=source` returns HTML); NULL means Markdown |
Indexes on `created_at DESC`, `published`, `slug`, `deleted_at`, `like_of`.
**`notes_fts`**: FTS5 virtual table (`slug` unindexed, `title`, `content`;
`porter unicode61` tokenizer), with its shadow tables `notes_fts_config`,
`_content`, `_data`, `_docsize`, `_idx`. Rows use the note `id` as `rowid`.
Inserts and updates are done by `starpunk/search.py` (the database cannot
read note files); the trigger `notes_fts_delete` removes the row when a note
row is deleted. The index is rebuilt at start-up if it is empty.
**`tags`** (`name` normalised and unique, `display_name` as written) and
**`note_tags`** (`note_id`, `tag_id`, unique pair, cascading deletes).
**`media`**: an uploaded image: original `filename`, `stored_filename`
(UUID), `path` (`YYYY/MM/<uuid>.<ext>` under `media/`), `mime_type`, `size`,
`width`, `height`, `uploaded_at`.
**`media_variants`**: resized copies per image (`variant_type` one of
`thumb`, `small`, `medium`, `large`, `original`; `path`, dimensions, size);
unique per (`media_id`, `variant_type`), deleted with the image.
**`note_media`**: attaches media to notes with `display_order` and
`caption` (alt text); unique per (`note_id`, `media_id`).
### Authentication
**`sessions`**: admin sessions. `session_token_hash` (SHA-256 of the cookie
value), `me`, `created_at`, `expires_at`, `last_used_at`, `user_agent`,
`ip_address`.
**`oidc_login_state`**: one row per OIDC login in progress: `state`
(primary key), `nonce`, `code_verifier` (PKCE), `next_url`, `expires_at`.
Consumed once on callback.
**`indieauth_codes`**: authorization codes issued to Micropub clients:
`code_hash`, `client_id`, `redirect_uri`, `scope`, `code_challenge`,
`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
in `/admin/tokens`.
**Legacy tables, unused**: `auth_state` (v1 IndieLogin login state), `tokens`
and `authorization_codes` (v1 token tables). No code reads or writes them.
Migration 004 drops `tokens` and `authorization_codes`, but
`INITIAL_SCHEMA_SQL` recreates them (empty) on the next start, so a running
database normally contains them. They are harmless; v2 auth uses the tables
above.
### IndieWeb interactions
**`webmentions`**: received webmentions, 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` |
| `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`) |
| `validation_error`, `validated_at`, `received_at`, `updated_at` | Bookkeeping |
**`webmention_queue`**: outgoing webmentions, one per (`source_url`,
`target_url`): `source_note_id`, discovered `endpoint_url`, `status`
(`pending`, `sending`, `sent`, `failed`, `no_endpoint`), `retry_count`,
`next_retry_at`, `last_error`, `started_at`, `sent_at`.
**`reply_contexts`**: cache of the posts that replies (and other responses)
point to: `url` (unique), `title`, `content_snippet`, `published_at`, author
fields, `site_name`, `fetch_status` (`pending`, `fetched`, `error`),
`fetch_error`, `fetched_at`.
**`author_profile`**: cache of the owner's h-card discovered from `ADMIN_ME`:
`me`, `name`, `photo`, `url`, `note`, `rel_me_links` (JSON), `discovered_at`,
`cached_until` (24 hours).
### Crossposting
**`syndications`**: one row per (`note_id`, `target`), where `target` is a
configured target id (GoToSocial, Bluesky, Threads). `enabled` says whether
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
[syndication-architecture.md](syndication-architecture.md).
### WebSub
**`websub_subscriptions`**: verified subscriptions to this site's topics:
`topic`, `callback` (unique pair), `secret`, `lease_seconds`, `expires_at`,
`verified_at`, `last_success_at`, `last_error`, `callback_ip` (the address
the callback resolved to, for per-address limits).
**`websub_intents`**: subscribe and unsubscribe requests waiting for
verification of intent: `topic`, `callback` (unique pair), `mode`, `secret`,
`lease_seconds`, `attempts`, `next_attempt_at`, `request_id` (so verifying an
older request cannot consume a newer one), `requested_topic` (the topic as
sent, echoed in verification), `callback_ip`.
**`websub_deliveries`**: content waiting to be pushed: one row per
subscription (built-in hub) or one per topic with `subscription_id` NULL (a
publish ping to an external hub); partial unique indexes keep at most one
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.
### Bookkeeping
**`schema_migrations`**: applied migrations (see above).
## Connections
- **Request connections**: `starpunk/database/pool.py`. `init_pool()` creates
one `ConnectionPool` per process (up to 5 idle connections, 10-second busy
timeout; `DB_POOL_SIZE` and `DB_TIMEOUT` can be set only through the
`create_app()` config dict). Connections use `sqlite3.Row` rows,
`check_same_thread=False` and `PRAGMA journal_mode=WAL`, and are wrapped
in `MonitoredConnection` for query timing when metrics are on. `get_db()`
stores one connection in `flask.g` per request or app context; on teardown
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
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
contention is low.
## Backups
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).
---
**Last Updated**: 2026-11-03 (v2.10.1)
+269
View File
@@ -0,0 +1,269 @@
# Deployment Architecture
**Version**: 2.10.1 (2026-11-03)
**Status**: Current
How StarPunk is built, configured and run in production. The production site
is a single container behind Caddy on one host, managed with Ansible. This
document stays generic: hostnames, credentials and inventory live in the
deployment repository, not here.
## Overview
```
git tag vX.Y.Z ──► Gitea Actions ──► test stage (pytest) ──► runtime image
│ push :vX.Y.Z, :latest
▼
Gitea container registry
│ pull (tag set in Ansible)
▼
Internet ──► Caddy (TLS, headers, X-Forwarded-For) ──► container :8000 (gunicorn × 4)
│
/data volume (host)
```
## Container image (`Containerfile`)
A multi-stage build on `python:3.11-slim`; it works with Podman and Docker.
| Stage | Purpose |
|-------|---------|
| `builder` | Copies `uv` from `ghcr.io/astral-sh/uv`, creates `/opt/venv` and installs `requirements.txt` into it |
| `test` | Copies the venv, adds `pytest` and `pytest-mock`, copies the source and runs `python -m pytest -q -p no:cacheprovider tests` with test values for `SESSION_SECRET`, `SITE_URL` and `ADMIN_ME`. The stage only builds if the tests pass. |
| runtime (last, the default target) | Creates user `starpunk` (UID/GID 1000) and `/data/notes`, copies the venv and the application to `/app`, sets `DATA_PATH=/data`, `NOTES_PATH=/data/notes`, `DATABASE_PATH=/data/starpunk.db`, runs as `starpunk`, exposes port 8000 |
The runtime image's command is gunicorn:
```
gunicorn --bind 0.0.0.0:8000 --workers 4 --worker-class sync
--worker-tmp-dir /dev/shm --max-requests 1000 --max-requests-jitter 50
--timeout 30 --graceful-timeout 30
--access-logfile - --error-logfile - --log-level info app:app
```
Each of the four worker processes builds its own Flask app, so each runs
migrations (only one applies them, see [database.md](database.md)) and starts
its own background threads (see [overview.md](overview.md#background-workers)).
Workers are recycled after about 1000 requests; a recycled process starts
new threads, and the file locks pass to another process if the holder exits.
**Health check**: the image's `HEALTHCHECK` runs every 30 seconds (3-second
timeout, 10-second start period, 3 retries) and calls
`http://localhost:8000/health` with httpx. `/health` returns
`{"status": "ok", "version": …}` plus webmention-worker statistics, without
authentication.
## CI/CD (`.gitea/workflows/build-container.yml`)
- **Triggers**: pushing a tag matching `vX.Y.Z`, or a manual run.
- **Runner**: a Gitea Actions runner with no Docker daemon. Images are built
by a rootless BuildKit daemon reached over its socket
(`docker buildx create --driver remote`).
- **Steps**:
1. Log in to the Gitea container registry with the repository secret
`REGISTRY_TOKEN` (a token with only the `write:package` scope; the
automatic Actions token is refused by the registry).
2. `docker buildx build --target test`: runs the test suite. A failure
stops the workflow before anything is pushed.
3. Build the runtime image and push it tagged with the git tag
(e.g. `v2.10.1`) and `latest`. The image name is the repository path in
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)).
## 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.
Rolling back means deploying the previous tag. Migrations are not reversed
automatically, so a release with a migration needs a database backup first
if a rollback might be needed.
## Runtime layout
### Data volume (`/data`)
A host directory is mounted at `/data`, owned by UID 1000. Everything
persistent is there; the image itself holds no state.
| Path | Contents |
|------|----------|
| `starpunk.db` (+ `-wal`, `-shm`) | SQLite database in WAL mode |
| `notes/YYYY/MM/<slug>.md` | Note content |
| `.trash/YYYY/MM/` | Soft-deleted note files (restorable with Micropub undelete) |
| `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 |
| `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` |
The application does not make backups. A backup must include the database
(copied with SQLite's online backup because of WAL), `notes/` and `media/`.
Backups are handled by the deployment, outside the container.
### Reverse proxy
Caddy terminates TLS and proxies to the container's port 8000. Publish that
port only where the proxy can reach it (for example on the host's loopback
interface, as `compose.yaml` does), never publicly. Caddy adds security headers
(HSTS, CSP, X-Frame-Options, Referrer-Policy and so on; see
`Caddyfile.example`, and `nginx.conf.example` for nginx) and sets
`X-Forwarded-For`.
Set `TRUSTED_PROXY=true` behind the proxy. With it, StarPunk takes the client
address from the first entry of `X-Forwarded-For`, which the webmention and
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.
`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`.
## Configuration
Configuration is read from environment variables (and a `.env` file if
present) by `starpunk/config.py` at start-up. In production the variables
come from the Ansible-managed environment, with secrets from its vault.
`.env.example` documents them for local use. Booleans are `true`/`false`
unless noted.
### Required
| Variable | Default | Notes |
|----------|---------|-------|
| `SESSION_SECRET` | none | Required always. Signs sessions; also Flask's `SECRET_KEY` unless `FLASK_SECRET_KEY` is set |
| `SITE_URL` | `http://localhost:5000` | Public URL; a trailing `/` is added |
| `ADMIN_ME` | none | Owner's identity URL (h-card, Micropub `me`). Required unless `DEV_MODE` |
| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, `OIDC_ADMIN_SUB` | empty | Admin login via OIDC. Required unless `DEV_MODE` (or testing) |
### Site and authentication
| Variable | Default | Notes |
|----------|---------|-------|
| `SITE_NAME` | `StarPunk` | |
| `SITE_AUTHOR` | `Unknown` | |
| `SITE_DESCRIPTION` | `A minimal IndieWeb CMS` | |
| `SESSION_LIFETIME` | `30` | Days |
| `FLASK_SECRET_KEY` | `SESSION_SECRET` | |
| `OIDC_PROVIDER_NAME` | `single sign-on` | Label on the login button |
| `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` |
`TOKEN_ENDPOINT` and `INDIELOGIN_URL` are v1 settings; if present they are
ignored with a warning.
### Paths, runtime and logging
| Variable | Default | Notes |
|----------|---------|-------|
| `DATA_PATH` | `./data` (image: `/data`) | Root of all stored data |
| `DATABASE_PATH` | `./data/starpunk.db` (image: `/data/starpunk.db`) | |
| `NOTES_PATH` | `./data/notes` (image: `/data/notes`) | Created at start-up, but note files are always written to `DATA_PATH/notes` |
| `FLASK_ENV` | `development` | Set `production` in production |
| `FLASK_DEBUG` | `1` | Set `0` in production (the image does not set it) |
| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` |
| `VERSION` | package `__version__` | Overrides the reported version; normally unset |
### Feeds
| Variable | Default | Notes |
|----------|---------|-------|
| `FEED_MAX_ITEMS` | `50` | Notes per feed |
| `FEED_CACHE_SECONDS` | `300` | Cache TTL and `Cache-Control: max-age` |
| `FEED_CACHE_ENABLED` | `true` | |
| `FEED_CACHE_MAX_SIZE` | `50` | Cached feed documents per process |
### Webmention
| Variable | Default | Notes |
|----------|---------|-------|
| `WEBMENTION_ENABLED` | `true` | Endpoint, `Link` header and sending |
| `WEBMENTION_WORKER_ENABLED` | `true` | |
| `WEBMENTION_POLL_INTERVAL` | `10` | Seconds |
| `WEBMENTION_ERROR_BACKOFF` | `60` | Seconds after a worker error |
| `WEBMENTION_BATCH_SIZE` | `5` | Items per pass |
| `WEBMENTION_AUTO_APPROVE` | `true` | Valid webmentions are shown without moderation |
| `WEBMENTION_RATE_LIMIT_ENABLED` | `true` | |
| `WEBMENTION_RATE_LIMIT_IP` | `60` | Requests per window per client IP |
| `WEBMENTION_RATE_LIMIT_DOMAIN` | `10` | Requests per window per source domain |
| `WEBMENTION_RATE_LIMIT_WINDOW` | `60` | Seconds |
| `TRUSTED_PROXY` | `false` | Use `X-Forwarded-For` for the client IP (see above) |
### WebSub
| Variable | Default | Notes |
|----------|---------|-------|
| `WEBSUB_ENABLED` | `true` | Discovery links, hub and worker |
| `WEBSUB_HUB_URL` | empty | Use an external hub (StarPunk then sends publish pings) instead of the built-in one |
| `WEBSUB_MAX_SUBSCRIPTIONS` | `1000` | Total subscriptions |
| `WEBSUB_MAX_PER_HOST` | `25` | Subscriptions per callback host |
| `WEBSUB_POLL_INTERVAL` | `5` | Seconds |
### Crossposting (POSSE)
A target is enabled when its credentials are set; the syndication worker
starts only if at least one is.
| Variable | Default | Notes |
|----------|---------|-------|
| `GOTOSOCIAL_URL`, `GOTOSOCIAL_ACCESS_TOKEN` | empty | GoToSocial or any Mastodon-API server |
| `GOTOSOCIAL_NAME` | `GoToSocial` | Label in the UI and `syndicate-to` |
| `GOTOSOCIAL_VISIBILITY` | `public` | |
| `GOTOSOCIAL_MAX_CHARS` | `5000` | |
| `GOTOSOCIAL_MAX_MEDIA` | `4` | |
| `BLUESKY_HANDLE`, `BLUESKY_APP_PASSWORD` | empty | |
| `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_USERNAME` | empty | |
| `THREADS_NAME` | `Threads` | |
| `THREADS_MAX_CHARS` | `500` | |
| `THREADS_MAX_MEDIA` | `4` | |
| `SYNDICATION_POLL_INTERVAL` | `10` | Seconds |
### Metrics and debugging
| Variable | Default | Notes |
|----------|---------|-------|
| `METRICS_ENABLED` | `true` | HTTP/database metrics and the memory monitor |
| `METRICS_SLOW_QUERY_THRESHOLD` | `1.0` | Seconds |
| `METRICS_SAMPLING_RATE` | `1.0` | |
| `METRICS_BUFFER_SIZE` | `1000` | |
| `METRICS_MEMORY_INTERVAL` | `30` | Seconds |
| `DEBUG_SAVE_FAILED_UPLOADS` | `false` | Keep failed uploads in `debug/` |
| `DEBUG_FILE_MAX_AGE_DAYS` | `7` | |
| `DEBUG_FILE_MAX_SIZE_MB` | `100` | |
Fixed values: the maximum request body is 50 MB (`MAX_CONTENT_LENGTH`). The
connection pool size and timeout (`DB_POOL_SIZE`, `DB_TIMEOUT`) are not read
from the environment.
## Running locally
```bash
uv venv && 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
```
`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 .`.
---
**Last Updated**: 2026-11-03 (v2.10.1)
+524
View File
@@ -0,0 +1,524 @@
# IndieWeb and W3C Protocols
How StarPunk implements each protocol it speaks, as of v2.10.1, with its
compliance status and the gaps that remain. Each section links to the
decision records and review documents behind it.
| Protocol | Role | Status | Main code |
|---|---|---|---|
| [Micropub](#micropub) | Server (posts and media) | Reviewed against the Recommendation in v2.9.0; deliberate deviations listed | `starpunk/micropub.py`, `starpunk/routes/micropub.py` |
| [IndieAuth](#indieauth) | Authorization server for Micropub clients | Authorization code + PKCE, metadata, revocation | `starpunk/indieauth.py`, `starpunk/routes/indieauth.py` |
| [Webmention](#webmention) | Sender and receiver | Every MUST and SHOULD checked in v2.7.0 and v2.7.2; known limits listed | `starpunk/webmention_*.py`, `starpunk/routes/webmention.py` |
| [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` |
Crossposting to other networks (POSSE) is covered in
[syndication-architecture.md](syndication-architecture.md).
## 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
`starpunk/webmention_ssrf.py`:
- `validate_url_for_fetch()`: http(s) only. Every address from
`getaddrinfo` must be public. Private, loopback, link-local, multicast,
reserved, unspecified, CGNAT (`100.64.0.0/10`), `0.0.0.0/8` and
IPv4-mapped forms are blocked. It returns the checked address, preferring
IPv4. `DEV_MODE` allows localhost.
- **DNS pinning** (v2.7.2): each request connects to the checked IP, with
the original host in the `Host` header and as the TLS SNI name. The
certificate is still verified against the real hostname, so a rebinding
DNS server can't send the second lookup elsewhere.
- `safe_get()` follows up to 10 redirects by hand and checks each hop. The
response is capped at 1 MB by default.
- `safe_post()` doesn't follow redirects.
- **Hard deadlines** (v2.10.1): the whole exchange, not each read, is
limited to 10 s. When the deadline passes, the client is closed, so a
server trickling bytes can't hold a worker.
- DNS resolution failures raise `ResolutionError` (a `ValueError`), which
callers can treat as temporary.
- User-Agent: `StarPunk/<version> Webmention (+<SITE_URL>)`.
Workers that drain queues (Webmention, WebSub) run as one daemon thread per
gunicorn process. Each takes a non-blocking `flock` on a lock file in the
data directory, so only one process works the queue at a time and another
takes over if it dies.
---
## Micropub
Spec: https://www.w3.org/TR/micropub/. Decisions:
[ADR-028](../decisions/ADR-028-micropub-implementation.md),
[ADR-029](../decisions/ADR-029-micropub-indieauth-integration.md),
[ADR-057](../decisions/ADR-057-media-attachment-model.md) (photos),
[ADR-067](../decisions/ADR-067-micropub-update-delete.md) (update/delete),
[ADR-068](../decisions/ADR-068-likes-and-reposts.md) (likes/reposts).
Review: [v2.9.0 Micropub review](../design/v2.9.0/2026-11-03-micropub-review.md).
### Endpoints and discovery
| Endpoint | Purpose |
|---|---|
| `GET /micropub?q=...` | Queries |
| `POST /micropub` | Create, update, delete, undelete |
| `POST /micropub/media` (and legacy `POST /media`) | Media endpoint |
Every page has `<link rel="micropub">` plus the IndieAuth discovery links
(see [IndieAuth](#indieauth)). Authentication, token placement, scopes and
error codes are described in
[simplified-auth-architecture.md §3](simplified-auth-architecture.md#3-token-use-at-the-micropub-and-media-endpoints).
### Create
Accepts form-encoded, multipart (with photo files) and JSON bodies. Only
`h=entry` / `type: ["h-entry"]` is accepted; other types get 400. Success is
**201** with `Location` set to the permalink `/note/<slug>`.
| Property / command | Handling |
|---|---|
| `content` | String, or `{"html": ...}` / `{"text": ...}`. Text is preferred. HTML-only content is stored with `content_format = 'html'` (migration 015) and rendered through `render_markdown()` (Markdown, then nh3 allowlist sanitization) |
| `summary` | Used as the text when there is no `content` |
| `name` | Stored as a `# name` heading on the first line (StarPunk has no title column) |
| `category` | Tags (strings only; person tags as h-card objects are ignored) |
| `in-reply-to`, `like-of`, `repost-of`, `bookmark-of` | URL or h-cite. At most one of like/repost/bookmark. Content is optional for these |
| `photo` | URLs, `{"value", "alt"}` objects, or uploaded files; at most 4 (ADR-057), duplicates collapsed. Own `/media/` URLs are looked up; other URLs are downloaded through `safe_get` (20 MB cap). Any photo that can't be resolved means 400 and nothing is created |
| `published` | ISO 8601; converted to naive UTC; invalid gets 400 |
| `post-status` | `published` (default) or `draft`; others get 400 |
| `visibility` | `public`; `private` and `unlisted` are saved as drafts (StarPunk has no private posts); others get 400 |
| `video`, `audio` | 400 (not supported) |
| `location`, `checkin`, others | Ignored (allowed by 3.3.5) |
| `mp-slug` | Custom slug |
| `mp-syndicate-to` | Crosspost targets. **Absent means none** (v2.9.0). See [syndication-architecture.md](syndication-architecture.md#choosing-targets) |
`mp-*` keys are read as commands from the top level or from inside JSON
`properties`, and are never stored. JSON property values must be arrays; a
bare scalar is wrapped on create. If anything fails after the note is
created, the note is removed and 500 is returned, so the client never
believes a half-made post failed.
Post types advertised in `q=config`: note, article, photo, reply, like,
repost, bookmark.
### Update, delete, undelete
- **Update** (JSON only, `update` scope) targets a `/note/<slug>` URL on
this site.
- `replace` works on `content`, `name`, `category`, `in-reply-to`,
`post-status` and `photo`.
- `add` works on `category` and `photo` only.
- `delete` takes a list of property names, or values to remove for
`category` and `photo`.
- Values must be arrays. An update without any operation gets 400.
Unsupported properties get 400.
- Photos are resolved before anything changes. Success is **204**.
- Edits follow crossposts and are re-announced to Webmention targets and
WebSub subscribers.
- **Delete** (`delete` scope) is soft: the note is moved to the trash, its
page returns 410, and `undelete` restores it. Both return **204**.
### Queries
| Query | Scope | Result |
|---|---|---|
| `q=config` | any token | `media-endpoint`, `syndicate-to`, `q` list, `post-types` |
| `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 |
Unknown or missing `q` gets 400.
### Media endpoint
`POST /micropub/media`, multipart with one part named `file`, `media` or
`create` scope. It returns **201** with `Location: <SITE_URL>/media/<path>`.
Images are JPEG, PNG, GIF, WebP or HEIC, up to 50 MB in. They are optimized
and get responsive variants (`starpunk/media.py`,
[ADR-058](../decisions/ADR-058-image-optimization-strategy.md)). Validation
failures get 400.
### Known deviations and gaps
- **403 for `insufficient_scope`** (RFC 6750) where the Micropub error table
says 401. Kept on purpose.
- `add` is only supported for `category` and `photo`. `published`,
`syndication` and `location` can't be updated. `mp-syndicate-to` is only
read on create.
- `location` / `checkin` are ignored, and person tags are dropped.
- `video` and `audio` are refused.
- The `access_token` query parameter is still accepted on GET.
- Only notes (`/note/<slug>`) can be the target of update/delete/source.
---
## IndieAuth
StarPunk is its own IndieAuth authorization server for Micropub clients,
issuing tokens for the single identity `ADMIN_ME`. The admin approves
clients on a consent screen protected by OIDC login. Supported: the
authorization code flow with mandatory PKCE S256, `iss` in responses (RFC
9207), the metadata endpoint, a profile-only flow, a token endpoint, RFC
7009 revocation, and legacy token verification (`GET /auth/token`). Client
`redirect_uri`s must be same-origin or published by the client (JSON
metadata or `rel=redirect_uri`).
Full description, scopes and gaps:
[simplified-auth-architecture.md](simplified-auth-architecture.md).
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.
---
## Webmention
Spec: https://www.w3.org/TR/webmention/ (Recommendation, 12 January 2017).
Decision: [ADR-063](../decisions/ADR-063-webmention-implementation.md).
Reviews: [v2.6.9 fixes](../design/v2.6.9/2026-11-03-webmention-processing-fixes.md),
[v2.7.0 compliance](../design/v2.7.0/2026-11-03-webmention-spec-compliance.md),
[v2.7.2 remaining SHOULDs](../design/v2.7.2/2026-11-03-webmention-shoulds.md).
### Endpoint discovery (advertising)
With `WEBMENTION_ENABLED` (default true), every HTML response carries
`Link: </webmention>; rel="webmention"`, and `base.html` has
`<link rel="webmention" href="/webmention">`. When it is off, the receiving
route isn't registered at all.
### Receiving
`POST /webmention` (`routes/webmention.py`):
1. Rate limits: 60 requests per minute per client IP and 10 per minute per
source domain (`WEBMENTION_RATE_LIMIT_*`). Over the limit gets 429 with
`Retry-After`. The limiter is in memory, per process. The client IP
comes from `X-Forwarded-For` only when `TRUSTED_PROXY=true`.
2. Form-encoded (JSON also accepted). `source` and `target` are required,
http(s), at most 2048 characters, and different from each other.
Otherwise 400.
3. The target's host and port must be this site's. The fragment is stripped
before storing. The target must be a **published note**: anything else,
including the home page, gets 400 `invalid_target`.
4. The row is upserted into `webmentions` (unique on source + target) as
`pending`, and **202** is returned. A repeat from the same source resets
it to `pending` (an update, 3.2.4).
Verification is asynchronous (`WebmentionWorker`, poll
`WEBMENTION_POLL_INTERVAL` 10 s, batch of 5):
- **Fetch** the source with `safe_get` (redirects followed and checked,
1 MB, 10 s), with an `Accept` header preferring HTML.
- **Exact-match verification** (3.2.2), per media type:
- HTML: every link-bearing attribute (`lxml iterlinks`: `a`/`link` href,
`img`/`video`/`audio` src, ...), resolved against the final URL.
- JSON: any string value.
- Other `text/*`: substring match.
- Any other type: no match.
- Fragments are ignored on both sides.
- **Parse mf2** (HTML only) with mf2py:
- `mf2_utils.responding_entry()` picks the h-entry that responds to the
target.
- `response_type()` classifies it as reply, like, repost, bookmark or
mention.
- `entry_author()` follows the authorship algorithm without extra
fetches: author property, then the parent h-feed's author, then
`rel=author`, then the representative h-card.
- Also stored: a content snippet (e-content or p-summary, sanitized with
nh3, at most 500 characters), the source's `u-url` and `dt-published`
(migration 014).
- The author URL and photo are kept only if they are absolute http(s)
URLs (XSS, 4.1).
- **Outcomes**:
- 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.
- 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).
- **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).
### Sending
Queued by `webmention_sender.queue_webmentions_for_note()` from `notes.py`.
Sending isn't gated by `WEBMENTION_ENABLED`; it runs whenever the worker
does (`WEBMENTION_WORKER_ENABLED`).
| Event | Targets |
|---|---|
| Publish | Reply / like / repost / bookmark target first, then `<a href>` links from the rendered HTML in document order (not inside `<pre>`/`<code>`), absolute http(s) only, de-duplicated, at most 10 |
| Edit (published) | The same, plus every target notified before and links the edit removed (not capped) (3.1.4) |
| Delete | Every previously notified target is re-queued (3.1.5); for a hard delete the queue rows are detached first so the cascade doesn't remove them |
| Undelete | Re-queued again |
| Displayed responses change | Re-queued (see above) |
Re-queuing resets the cached endpoint, so discovery runs again (3.1.4).
**Endpoint discovery** (3.1.2): GET the target with `safe_get` (redirects
checked). The first `Link` header with a `rel` token `webmention` wins. The
header is parsed per RFC 8288: several links per header, several headers,
rel token lists, case-insensitive. Otherwise the first `<link>` or `<a>`
with `rel~=webmention` and an `href`, in document order. Relative URLs
resolve against the final URL, an empty `href` means the target itself, and
the query string is kept.
**Send** (3.1.3): a form-encoded POST through `safe_post`, pinned and with
no redirects followed (a 301/302 would turn the POST into a GET).
| Result | Outcome |
|---|---|
| Any 2xx | `sent` |
| 429, 5xx, network error | Retried after 1 h, 6 h, 24 h; `failed` after the 4th attempt |
| Other 3xx/4xx, SSRF-blocked endpoint | `failed` |
| No endpoint | `no_endpoint` |
**Deleted posts**: `/note/<slug>` returns **410 Gone** with a tombstone page
for soft-deleted notes, and for hard-deleted notes that had sent
webmentions (3.1.5).
### Security (section 4)
- XSS: author URL and photo must be http(s). Snippets are sanitized with
nh3 (and re-sanitized after truncation). The mentions list uses
`striptags`.
- SSRF: all fetches and POSTs go through the pinned fetcher described
above, so the endpoint URL is checked before POSTing.
- DoS: rate limits on receiving, a 1 MB / 10 s cap on fetches, and
asynchronous processing.
### Known limits
From the v2.7.0 review, still current:
- Home-page mentions (and mentions of anything that isn't a published note)
are refused rather than stored.
- Discovery ignores HTTP cache headers (5.3). Targets are fetched only when
a note is created, edited or deleted.
- The 410 page is a generic tombstone without microformats.
- `error` rows (transient failures of a new mention, or unexpected errors)
are not retried automatically. They are re-checked only when the sender
re-sends.
- The 202 response has no `Location` status URL.
---
## Microformats2
Specs: microformats2 parsing, h-entry, h-card, h-feed, h-cite,
representative h-card, authorship, Post Type Discovery. Decisions:
[ADR-040](../decisions/ADR-040-microformats2-compliance.md),
[ADR-061](../decisions/ADR-061-author-discovery.md). Review:
[v2.8.0 microformats2 review](../design/v2.8.0/2026-11-03-microformats2-review.md).
### What pages publish
| Page | Markup |
|---|---|
| `/` (home) | `h-feed` with `p-name`, hidden `u-url`, hidden `p-author h-card` (photo, name, URL, note), feed `u-photo`; each note an `h-entry` preview with `u-uid` |
| `/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 |
| `/likes`, `/tag/<tag>` | `h-feed` with `p-name`, `u-url`, `p-author h-card` |
Post Type Discovery gives note, article, reply, like, repost, bookmark and
photo correctly.
### Identity links
`base.html` always emits `rel=me` and `rel=author` pointing at the author's
home page (`author.url`, else `author.me`, else `ADMIN_ME`), even on a fresh
install (v2.8.0). Further `rel=me` links come from the discovered profile.
Because the `p-author h-card`'s `u-url` matches the `rel=me` URL, parsers
treat it as the page's representative h-card. Without a discovered profile
there is no h-card, only the `rel` links.
### Consuming
- **Author profile** (`author_discovery.py`, ADR-061): on login, StarPunk
fetches `ADMIN_ME`, picks its representative h-card with
`mf2_utils.representative_hcard()` (uid and url match the page, then
url matches a `rel=me`, then a single h-card whose url is the page),
parsed with the URL after redirects. It stores name, photo, URL, note and
rel-me links, cached for 24 hours. If discovery fails, the stale cache is
used.
- **Webmention sources**: `responding_entry`, `response_type` and
`entry_author` (see [Webmention](#webmention)).
- **Reply context** (`reply_context.py`): title, snippet, author and site
name of the post being replied to, liked, reposted or bookmarked, cached
in `reply_contexts`.
### Known gaps
From the v2.8.0 review, "Not done":
- The reply-context `h-cite` doesn't carry the cached author h-card, name or
published time.
- Photo alt text falls back to "Image" when a photo-only post has no
caption.
- Person tags (`p-category h-card`) aren't supported.
- Webmentions received before v2.8.0 keep NULL source details until they
are re-validated.
---
## WebSub
Spec: https://www.w3.org/TR/websub/. Decision:
[ADR-071](../decisions/ADR-071-websub.md), including its v2.10.1
amendments, which replace the original text where they differ.
### Topics
All absolute URLs under `SITE_URL`:
| Topic | Content type | Updated when |
|---|---|---|
| `/` | text/html | A public non-like note changes |
| `/feed.atom`, `/feed.rss`, `/feed.json` | feed types | A public non-like note changes |
| `/likes` | text/html | A public like changes |
| `/tag/<name>` | text/html | A note with that tag (before or after the change) changes |
`/feed.xml` (legacy) advertises `/feed.rss` as its `rel=self`. The
negotiated `/feed` advertises the topic of the format it served.
### Discovery
Topic responses (200/304) carry `Link: <hub>; rel="hub"` and
`Link: <topic>; rel="self"`. The same links are embedded: `<link rel="hub">`
and `<link rel="self">` in HTML heads, a hub `<link>` in Atom, an
`<atom:link rel="hub">` in RSS, and `"hubs"` in JSON Feed. All of this
happens only while `WEBSUB_ENABLED` (default true).
### On change
`websub.note_changed()` runs on create, edit, publish/unpublish, delete and
undelete, and once photos are attached. If the note is or was public, it:
1. bumps `content_version`, which is in the feed cache key and the ETag, so
every process serves fresh feeds at once;
2. queues one delivery per active subscription for each affected topic.
Only the latest content is sent: a newer delivery replaces a waiting one.
Drafts that stay drafts change nothing.
### Hub
`POST /websub`, form-encoded only (case-insensitive check):
- `hub.mode` is `subscribe` or `unsubscribe`.
- `hub.topic` must be one of the topics above, after decoding unreserved
percent-encodings and comparing scheme and host case-insensitively. Tag
topics must name an existing tag.
- `hub.callback` must:
- be printable, at most 2,048 characters, and absolute http(s);
- not be on this site;
- use port 80, 443 or 1024 and up;
- pass the SSRF check.
It is stored with an IDNA host.
- `hub.secret` must be non-empty and under 200 bytes. `hub.lease_seconds`
is clamped to 1 to 30 days (default 10). Both are ignored for
unsubscriptions.
- The hub answers **202**, then verifies later. Errors are 4xx with a
plain-text reason.
Limits (429 when hit):
- 30 requests per minute per client IP (per process; needs
`TRUSTED_PROXY=true` behind a proxy);
- at most 200 pending verifications;
- `WEBSUB_MAX_SUBSCRIPTIONS` (1000) in total;
- `WEBSUB_MAX_PER_HOST` (25) per callback IP address.
The limits count pending requests too. Renewals are always allowed.
`WebSubWorker` (file lock, poll `WEBSUB_POLL_INTERVAL` 5 s) handles each
queued item on its own, so one bad item can't stop it:
- **Verification of intent** (5.3): `GET` the callback (existing query
kept) with `hub.mode`, the topic exactly as requested, `hub.challenge`
and `hub.lease_seconds`. Success is a 2xx whose body equals the challenge.
Replies over 4 KB and redirects fail. Network/DNS errors and 5xx are
retried after 1, 5 and 15 minutes. A request id per intent (migration
017) stops an older verification from consuming a newer request. A
subscription row exists only once verified.
- **Distribution** (7): the topic is rendered inside the app, once per pass,
and POSTed with its `Content-Type`, `Link` rel=hub/self, and
`X-Hub-Signature: sha256=<HMAC>` when there is a secret.
- 2xx: success.
- 410: removes the subscription.
- Other failures: retried after 1 min, 5 min, 30 min, 2 h and 6 h, then
that delivery is dropped. The subscription stays until its lease ends.
- A topic that renders 404/410 ends its subscriptions with a
`hub.mode=denied` notice.
- Expired subscriptions are pruned hourly.
Outbound requests use `safe_get` / `safe_post`: pinned, no redirects,
10 s hard deadline.
**External hub**: with `WEBSUB_HUB_URL` set, StarPunk advertises that hub
and sends it a `hub.mode=publish` ping per changed topic. Its own `/websub`
refuses new subscriptions but still accepts unsubscriptions.
The admin dashboard shows subscribers per topic and deliveries being
retried.
### Known limits
- The hub serves only this site's topics, by design. websub.rocks' hub
tests use their own topics, so they can't be run against it.
- Rate limiting is per process and in memory.
- Deliveries always carry the full topic content (no diffs). Fat pings
aren't sent to external hubs.
---
## Feeds
Decisions: [ADR-014](../decisions/ADR-014-rss-feed-implementation.md),
[ADR-038](../decisions/ADR-038-syndication-formats.md),
[ADR-059](../decisions/ADR-059-full-feed-media-standardization.md).
| URL | Format |
|---|---|
| `/feed.rss` | RSS 2.0 (with `atom:link rel=self` and Media RSS) |
| `/feed.xml` | Legacy alias of `/feed.rss` |
| `/feed.atom` | Atom 1.0 |
| `/feed.json` | JSON Feed 1.1 |
| `/feed` | Content negotiation on `Accept` (RSS default; 406 with `X-Available-Formats` if nothing fits; `Vary: Accept`) |
| `/opml.xml` | OPML 2.0 listing the three feeds |
- Feeds contain the newest `FEED_MAX_ITEMS` (50) published notes, with full
HTML content and media. Likes are excluded, as on the home page.
Reposts and bookmarks start with a "🔁 Reposted" / "🔖 Bookmarked" line.
- Feeds are cached for `FEED_CACHE_SECONDS` (300). The cache key and ETag
include `content_version`, so any change to a public note invalidates
them in every process. `If-None-Match` gets 304.
- `base.html` advertises the negotiated `/feed` (as RSS) and the OPML file
with `rel=alternate`. Atom and JSON Feed are listed in the OPML but have
no `<link rel=alternate>` of their own.
- WebSub hub links are embedded in each feed (see above).
Gaps: there are no per-tag feeds (tag pages are h-feeds and WebSub topics,
but have no RSS/Atom/JSON equivalent). The `/likes` page has no feed.
File diff suppressed because it is too large. Load diff
+295 -381
View File
@@ -1,428 +1,342 @@
# StarPunk Simplified Authentication Architecture
# 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),
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
token verification of ADR-030 / ADR-036.
> The filename is historical: it described the v1.x "external provider only"
> design. Other documents link to it, so it is kept.
## Overview
After removing the custom IndieAuth authorization server, StarPunk becomes a pure Micropub server that relies on external providers for all authentication and authorization.
StarPunk is a single-user site with two kinds of client and two auth
mechanisms:
## Architecture Diagrams
| Who | Mechanism | Credential | Code |
|---|---|---|---|
| The site owner in a browser (admin UI, consent screen) | OpenID Connect login against an external provider (e.g. Pocket ID) | `starpunk_session` cookie, backed by a hashed row in `sessions` | `starpunk/auth.py`, `starpunk/routes/auth.py` |
| Micropub apps (Quill, Indigenous, ...) | StarPunk's own IndieAuth authorization server | Bearer access token, backed by a hashed row in `indieauth_tokens` | `starpunk/indieauth.py`, `starpunk/routes/indieauth.py` |
The two are chained: a Micropub app is approved on a consent screen that
requires an admin session, so every token ultimately rests on the OIDC
login. StarPunk stores no passwords.
### Before: Complex Mixed-Mode Architecture
```
┌──────────────────────────────────────────────────────────────┐
│ StarPunk Instance │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Web Interface │ │
│ │ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Admin Login │ │ Authorization │ │ Token Issuer │ │ │
│ │ └─────────────┘ └──────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Auth Module │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Sessions │ │ PKCE │ │ Tokens │ │ Codes │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Database │ │
│ │ ┌────────┐ ┌──────────────────┐ ┌─────────────────┐ │ │
│ │ │ Users │ │ authorization_codes│ │ tokens │ │ │
│ │ └────────┘ └──────────────────┘ └─────────────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
Browser (owner) StarPunk OIDC provider
─────────────── ──────── ─────────────
POST /auth/login ─────────────▶ initiate_login() ── redirect ──▶ authorize (PKCE, nonce)
owner authenticates
GET /auth/callback?code&state ◀────────────────────── redirect ───┘
handle_callback(): code exchange, ID token checks,
sub == OIDC_ADMIN_SUB → create_session(ADMIN_ME)
◀── Set-Cookie: starpunk_session
Problems:
- 500+ lines of security-critical code
- Dual role: authorization server AND resource server
- Complex token lifecycle management
- Database bloat with token storage
- Maintenance burden for security updates
Micropub app StarPunk
──────────── ────────
discovers indieauth-metadata / authorization_endpoint / token_endpoint
GET /auth/authorize?... ────────▶ validate request → (OIDC login if no session) → consent page
owner approves ─────────────────▶ POST /auth/authorize/approve → redirect: code, state, iss
POST /auth/token (code, verifier) ▶ access token (hash stored in indieauth_tokens)
POST /micropub, /micropub/media ─▶ verify_access_token() + scope check
```
### After: Clean Separation of Concerns
```
┌──────────────────────────────────────────────────────────────┐
│ StarPunk Instance │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Web Interface │ │
│ │ ┌─────────────┐ ┌──────────────┐ │ │
│ │ │ Admin Login │ │ Micropub │ │ │
│ │ └─────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Auth Module │ │
│ │ ┌──────────────┐ ┌──────────────────────┐ │ │
│ │ │ Sessions │ │ Token Verification │ │ │
│ │ │ (Admin Only) │ │ (External Provider) │ │ │
│ │ └──────────────┘ └──────────────────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Database │ │
│ │ ┌────────┐ ┌──────────┐ ┌─────────┐ │ │
│ │ │ Users │ │auth_state│ │ posts │ (No token tables)│ │
│ │ └────────┘ └──────────┘ └─────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
│
│ API Calls
▼
┌──────────────────────────────────────────────────────────────┐
│ External IndieAuth Providers │
│ ┌─────────────────────┐ ┌─────────────────────────┐ │
│ │ indieauth.com │ │ tokens.indieauth.com │ │
│ │ (Authorization) │ │ (Token Verification) │ │
│ └─────────────────────┘ └─────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
## 1. Admin login (OIDC)
Benefits:
- 500+ lines of code removed
- Clear single responsibility
- No security burden
- Minimal database footprint
- Zero maintenance for auth code
```
### Flow
## Authentication Flows
1. `GET /auth/login` shows `templates/admin/login.html`, or redirects to the
dashboard if the session cookie is already valid.
2. `POST /auth/login` calls `auth.initiate_login(next)`:
- Fetches `{OIDC_ISSUER}/.well-known/openid-configuration` (cached for an
hour per process). The document's `issuer` must equal `OIDC_ISSUER`, and
it must name `authorization_endpoint`, `token_endpoint` and `jwks_uri`.
- Generates `state`, `nonce` and a PKCE `code_verifier`, and stores them in
`oidc_login_state` with the sanitized `next` URL (same site only) and a
10-minute expiry.
- Redirects to the provider with `response_type=code`, `scope=openid` and
`code_challenge_method=S256`.
3. `GET /auth/callback`:
- A provider `error` parameter, or a missing `code`/`state`, flashes an
error and returns to the login page.
- The `state` row is fetched and deleted in one step: it is single use and
must not have expired.
- If the provider sent `iss` (RFC 9207), it must match the issuer.
- The code is exchanged at the token endpoint along with the
`code_verifier`. StarPunk authenticates as a confidential client (HTTP
Basic, `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET`).
- The ID token is verified with PyJWT against the provider's JWKS. The
checks are: the signature (algorithms from the provider metadata, never
`none`), `iss`, `aud` equal to the client id, `exp`, required `iat` and
`sub`, a 60 s leeway, and a `nonce` equal to the stored one.
- `sub` must equal `OIDC_ADMIN_SUB` (constant-time comparison). Any other
account gets "Not authorized as admin".
- A session is created for `ADMIN_ME`, the owner's identity URL. It is also
the `me` of every issued token. The author h-card is refreshed from
`ADMIN_ME` on a best-effort basis that never blocks login (see
[ADR-061](../decisions/ADR-061-author-discovery.md)).
### Flow 1: Admin Authentication (Unchanged)
```
Admin User StarPunk IndieLogin.com
│ │ │
├──── GET /admin/login ───→ │ │
│ │ │
│ ←── Login Form ─────────── │ │
│ │ │
├──── POST /auth/login ───→ │ │
│ (me=admin.com) │ │
│ ├──── Redirect ──────────────→ │
│ │ (client_id=starpunk.com) │
│ ←──────────── Authorization Request ───────────────────── │
│ │ │
├───────────── Authenticate with IndieLogin ──────────────→ │
│ │ │
│ │ ←── Callback ────────────────│
│ │ (me=admin.com) │
│ │ │
│ ←── Session Cookie ─────── │ │
│ │ │
│ Admin Access │ │
```
### Sessions
### Flow 2: Micropub Client Authentication (Simplified)
```
Micropub Client StarPunk External Token Endpoint
│ │ │
├─── POST /micropub ───→ │ │
│ Bearer: token123 │ │
│ ├──── GET /token ─────────→ │
│ │ Bearer: token123 │
│ │ │
│ │ ←── Token Info ──────────│
│ │ {me, scope, client_id} │
│ │ │
│ │ [Validate me==ADMIN_ME] │
│ │ [Check scope includes │
│ │ "create"] │
│ │ │
│ ←── 201 Created ────────│ │
│ Location: /post/123 │ │
```
- `create_session(me)` makes a random 32-byte URL-safe token. Only its
SHA-256 hash is stored in `sessions`, with `me`, `expires_at`
(`SESSION_LIFETIME` days, default 30), the user agent and the IP. Expired
sessions and login states are cleaned up each time a session is created.
- Cookie `starpunk_session`: `HttpOnly`, `SameSite=Lax`, `Secure` when
`SITE_URL` is https, `max-age` equal to the session lifetime.
- `verify_session(token)` looks up the hash, checks expiry and updates
`last_used_at`.
- `@require_auth` protects `/admin/*`. Without a valid session it remembers
the URL and redirects to `/auth/login`. It sets `g.user` and `g.me`.
- A `before_request` hook also resolves the session on public pages that
carry the cookie, so the header can show "Admin" instead of "Log in".
- `POST /auth/logout` deletes the session row and the cookie.
## Component Responsibilities
### Configuration
### StarPunk Components
Outside `DEV_MODE`, `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`,
`OIDC_ADMIN_SUB` and `ADMIN_ME` are required, and startup fails without them.
The provider must have `{SITE_URL}/auth/callback` registered as a redirect
URI.
#### 1. Admin Authentication (`/auth/*`)
**Responsibility**: Manage admin sessions via IndieLogin.com
**Does**:
- Initiate OAuth flow with IndieLogin.com
- Validate callback and create session
- Manage session lifecycle
### Development mode
**Does NOT**:
- Issue tokens
- Store passwords
- Manage user identities
With `DEV_MODE=true` (and `DEV_ADMIN_ME`), `/dev/login` creates a session
without OIDC. The blueprint is registered only in dev mode, and its
`before_request` guard returns 404 if `DEV_MODE` is off. Every page shows a
warning banner while it is on. Never enable it in production.
#### 2. Micropub Endpoint (`/micropub`)
**Responsibility**: Accept and process Micropub requests
**Does**:
- Extract Bearer tokens from requests
- Verify tokens with external endpoint
- Create/update/delete posts
- Return proper Micropub responses
## 2. Built-in IndieAuth authorization server
**Does NOT**:
- Issue tokens
- Manage authorization codes
- Store token data
StarPunk issues tokens for exactly one identity, `ADMIN_ME`. It implements
the authorization code flow of the current IndieAuth spec
(https://indieauth.spec.indieweb.org/), with PKCE required.
#### 3. Token Verification Module
**Responsibility**: Validate tokens with external providers
**Does**:
- Call external token endpoint
- Cache valid tokens (5 min TTL)
- Validate scope and identity
### Endpoints
**Does NOT**:
- Generate tokens
- Store tokens permanently
- Manage token lifecycle
| Method | Path | Purpose |
|---|---|---|
| GET | `/.well-known/oauth-authorization-server` | Server metadata (the target of `rel=indieauth-metadata`) |
| GET | `/auth/authorize` | Validate the request; show the consent screen (admin session required) |
| POST | `/auth/authorize/approve` | Consent decision from the screen |
| POST | `/auth/authorize` | Profile-only code redemption, returns `{"me": ...}` |
| POST | `/auth/token` | Exchange a code for an access token; also legacy `action=revoke` |
| GET | `/auth/token` | Legacy token verification (Bearer token → `me`, `client_id`, `scope`) |
| POST | `/auth/revoke` | RFC 7009 revocation (always 200) |
### External Provider Responsibilities
All JSON responses carry `Cache-Control: no-store`. Errors use the OAuth
form `{"error", "error_description"}`.
#### indieauth.com
- User authentication
- Authorization consent
- Authorization code generation
- Profile discovery
### Metadata
#### tokens.indieauth.com
- Token issuance
- Token verification
- Token revocation
- Scope management
## Configuration
### Required Settings
```ini
# Identity of the admin user
ADMIN_ME=https://your-domain.com
# External token endpoint for verification
TOKEN_ENDPOINT=https://tokens.indieauth.com/token
# Admin session secret (existing)
SECRET_KEY=your-secret-key
```
### HTML Discovery
```html
<!-- Added to all pages -->
<link rel="authorization_endpoint" href="https://indieauth.com/auth">
<link rel="token_endpoint" href="https://tokens.indieauth.com/token">
<link rel="micropub" href="https://starpunk.example.com/micropub">
```
## Security Model
### Trust Boundaries
```
┌─────────────────────────────────────────────────────────────┐
│ Trusted Zone │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ StarPunk Application │ │
│ │ - Session management │ │
│ │ - Post creation/management │ │
│ │ - Admin interface │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
Token Verification API
│
┌─────────────────────────────────────────────────────────────┐
│ Semi-Trusted Zone │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ External IndieAuth Providers │ │
│ │ - Token validation │ │
│ │ - Identity verification │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
User Authentication
│
┌─────────────────────────────────────────────────────────────┐
│ Untrusted Zone │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Micropub Clients │ │
│ │ - Must provide valid Bearer tokens │ │
│ │ - Tokens verified on every request │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
### Security Benefits of Simplified Architecture
1. **Reduced Attack Surface**
- No token generation = no cryptographic mistakes
- No token storage = no database leaks
- No PKCE = no implementation errors
2. **Specialized Security**
- Auth providers focus solely on security
- Regular updates from specialized teams
- Community-vetted implementations
3. **Clear Boundaries**
- StarPunk only verifies, never issues
- Single source of truth (external provider)
- No confused deputy problems
## Performance Characteristics
### Token Verification Performance
```
Without Cache:
┌──────────┐ 200-500ms ┌─────────────┐
│ Micropub ├───────────────────→│Token Endpoint│
└──────────┘ └─────────────┘
With Cache (95% hit rate):
┌──────────┐ <1ms ┌─────────────┐
│ Micropub ├───────────────────→│ Memory Cache │
└──────────┘ └─────────────┘
```
### Cache Strategy
```python
Cache Key: SHA256(token)
Cache Value: {
'me': 'https://user.com',
'client_id': 'https://client.com',
'scope': 'create update delete',
'expires_at': timestamp + 300 # 5 minutes
```json
{
"issuer": "<SITE_URL>/",
"authorization_endpoint": "<SITE_URL>/auth/authorize",
"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"],
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code"],
"code_challenge_methods_supported": ["S256"],
"authorization_response_iss_parameter_supported": true
}
```
### Expected Latencies
- First request: 200-500ms (external API)
- Cached request: <1ms
- Admin login: 1-2s (OAuth flow)
- Post creation: <50ms (after auth)
StarPunk has no introspection or userinfo endpoint. Only StarPunk itself
checks its tokens.
## Migration Impact
### Authorization request validation (`validate_authorization_request`)
### Breaking Changes
1. **All existing tokens invalid**
- Users must re-authenticate
- No migration path for tokens
- `client_id` must be an http(s) URL without a fragment.
- `redirect_uri` must be present and have no fragment. It must either share
the `client_id`'s scheme, host and port, or be published by the client. To
check the second case, StarPunk fetches the `client_id` URL (5 s timeout,
with an SSRF check on the URL unless `DEV_MODE` is on). It reads
`redirect_uris` from a JSON client metadata document, or
`rel="redirect_uri"` from the `Link` header and from `<link>`/`<a>`
elements.
- Problems with `client_id` or `redirect_uri` are shown to the user on an
error page (HTTP 400). They are never redirected, because the redirect
target can't be trusted.
- Other problems are redirected to the client with `error`,
`error_description`, `state` and `iss`. These are: a `response_type` other
than `code` (`unsupported_response_type`), a missing `state`, a missing
`code_challenge`, or a `code_challenge_method` other than `S256`.
- `scope` is split on spaces. Requested scopes are not filtered against
`scopes_supported`.
2. **Endpoint removal**
- `/auth/authorization` → 404
- `/auth/token` → 404
### Consent screen
3. **Configuration required**
- Must set `ADMIN_ME`
- Must configure domain with IndieAuth links
If `GET /auth/authorize` gets a valid request but there is no admin session,
StarPunk stores the request URL and redirects to the OIDC login, which
returns to that URL afterwards. With a session, it renders
`templates/admin/authorize.html`. The page shows the client id, the identity
the client will act as, the redirect URI, and one checkbox per requested
scope (all checked). A request without scopes is described as "only wants to
confirm your identity".
### Non-Breaking Preserved Functionality
1. **Admin login unchanged**
- Same URL (`/admin/login`)
- Same provider (IndieLogin.com)
- Sessions preserved
`POST /auth/authorize/approve` checks the session again and re-validates the
request from hidden form fields. "Deny" redirects with
`error=access_denied`. "Approve" grants only the scopes that were both
requested and left checked, issues a code, and redirects with `code`,
`state` and `iss`.
2. **Micropub API unchanged**
- Same endpoint (`/micropub`)
- Same request format
- Same response format
### Codes and tokens
## Comparison with Other Systems
| | Authorization code | Access token |
|---|---|---|
| Table | `indieauth_codes` | `indieauth_tokens` |
| 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` |
### WordPress + IndieAuth Plugin
- **Similarity**: External provider for auth
- **Difference**: WP has user management, we don't
`redeem_authorization_code` handles redemption for both `POST /auth/token`
and `POST /auth/authorize`:
### Known IndieWeb Sites
- **micro.blog**: Custom auth server (complex)
- **Indigenous**: Client only, uses external auth
- **StarPunk**: Micropub server only (simple)
1. `code` and `code_verifier` are required.
2. An atomic `UPDATE ... SET used_at = now WHERE code_hash = ? AND used_at IS
NULL AND expires_at > now` makes the code single-use, even across
gunicorn workers.
3. `client_id` and `redirect_uri` must match the code exactly.
4. `BASE64URL(SHA256(code_verifier))` must equal the stored challenge
(constant-time comparison).
### Architecture Philosophy
```
"Do one thing well"
│
├── StarPunk: Publish notes
├── IndieAuth.com: Authenticate users
└── Tokens.indieauth.com: Manage tokens
The token endpoint accepts only `grant_type=authorization_code`. It refuses
a code issued with no scope (`invalid_grant`), because such codes are for
the profile-only flow at the authorization endpoint. The response is
`{access_token, token_type: "Bearer", scope, me, expires_in}`. There are no
refresh tokens: a client re-authorizes when its token expires.
Expired codes are deleted whenever a new code is issued.
### 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}`.
- `check_scope(required, scope)` matches whole words in the space-separated
scope string.
- Revocation sets `revoked_at`. It can happen by token value, through
`POST /auth/revoke` or the legacy `POST /auth/token` with `action=revoke`
(unknown tokens are ignored, per RFC 7009). It can also happen by id, from
the admin page.
- `/admin/tokens` ("Connected Apps") lists active tokens with their client,
scope, dates and last use. Each has a Revoke button.
### Scopes
| Scope | Allows |
|---|---|
| `create` | Micropub create (published or draft), media upload, `q=source`, `q=category` |
| `draft` | Micropub create, always saved as a draft (v2.9.0); `q=source`, `q=category` |
| `update` | Micropub update; `q=source`, `q=category` |
| `delete` | Micropub delete and undelete; `q=source`, `q=category` |
| `media` | Media endpoint uploads |
| `profile` | Nothing beyond identity (there is no profile or userinfo endpoint) |
`q=config` and `q=syndicate-to` work with any valid token.
## 3. Token use at the Micropub and media endpoints
`routes/micropub.py` handles `GET/POST /micropub` and
`POST /micropub/media`. The old `POST /media` path is kept for existing
clients.
### Extracting the token (`micropub.extract_bearer_token`)
- The token comes from `Authorization: Bearer <token>`, with the scheme
matched case-insensitively (RFC 7235).
- Or it comes from `access_token` in the form body (POST) or the query
string (GET).
- A token in both places gets **400 `invalid_request`** (RFC 6750 §2,
v2.9.0).
- No token gets **401 `unauthorized`**, "No access token provided".
- An unknown, expired or revoked token gets **401 `unauthorized`**,
"Invalid or expired access token".
Every 401 carries `WWW-Authenticate: Bearer realm="micropub"`. When a token
was sent but isn't valid, `error="invalid_token"` is added (RFC 6750 §3,
v2.9.0).
### Scope rules
| Operation | Required scope | Notes |
|---|---|---|
| create | `create` or `draft` | With only `draft`, the post is saved unpublished whatever `post-status` says |
| update | `update` | |
| delete / undelete | `delete` | |
| `q=source`, `q=category` | any of `create`, `update`, `delete`, `draft` | These show drafts and tags (v2.9.0) |
| `q=config`, `q=syndicate-to` | any valid token | |
| media upload | `media` or `create` | `create` is accepted for older clients |
A missing scope gets **403 `insufficient_scope`** (RFC 6750). The Micropub
Recommendation's error table lists 401 for this case. StarPunk keeps 403 on
purpose (see the [v2.9.0 review](../design/v2.9.0/2026-11-03-micropub-review.md),
"Kept as is").
Micropub request handling itself is described in
[indieweb-protocols.md](indieweb-protocols.md#micropub).
## 4. Discovery
`templates/base.html` puts these links on every page, whether or not
`WEBMENTION_ENABLED` is set (v2.8.0):
```html
<link rel="micropub" href="<SITE_URL>/micropub">
<link rel="indieauth-metadata" href="<SITE_URL>/.well-known/oauth-authorization-server">
<link rel="authorization_endpoint" href="<SITE_URL>/auth/authorize">
<link rel="token_endpoint" href="<SITE_URL>/auth/token">
<link rel="me" href="<author home>">
<link rel="author" href="<author home>">
```
## Future Considerations
Micropub clients start from the URL the user types, which is normally
`ADMIN_ME`. If `ADMIN_ME` is the StarPunk site itself, the links above are
enough. If it is another page, that page must advertise StarPunk's
`indieauth-metadata` (or `authorization_endpoint` and `token_endpoint`) and
`micropub` links. Otherwise clients won't find StarPunk
([ADR-064](../decisions/ADR-064-oidc-admin-login-and-builtin-indieauth-server.md) §3).
### Potential V2 Enhancements (NOT for V1)
1. **Multi-user support**
- Would require user management
- Still use external auth
## 5. Data (migration 011)
2. **Multiple token endpoints**
- Support different providers per user
- Endpoint discovery from user domain
| Table | Purpose | Key columns |
|---|---|---|
| `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` |
3. **Token caching layer**
- Redis for distributed caching
- Longer TTL with refresh
The legacy v1 tables `auth_state`, `tokens` and `authorization_codes` are
not used (see the migration's header comment).
### Explicitly NOT Implementing
1. **Custom authorization server**
- Violates simplicity principle
- Maintenance burden
## 6. Security properties and known gaps
2. **Password authentication**
- Not IndieWeb compliant
- Security burden
In place:
3. **JWT validation**
- Not part of IndieAuth spec
- Unnecessary complexity
- No secrets at rest: session tokens, codes and access tokens are stored only
as SHA-256 hashes.
- OIDC: PKCE S256, a nonce, single-use expiring state, issuer checks (in the
metadata and the RFC 9207 `iss`), full ID-token validation, and a single
allowed `sub`.
- IndieAuth: PKCE S256 required, single-use 10-minute codes bound to the
client and redirect URI, `iss` in every authorization response, and
untrusted redirect URIs never followed.
- Post-login redirects are limited to this site.
## Testing Strategy
Known gaps:
### Unit Tests
```python
# Test external verification
@patch('httpx.get')
def test_token_verification(mock_get):
# Mock successful response
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {
'me': 'https://example.com',
'scope': 'create'
}
result = verify_token('test-token')
assert result is not None
```
### Integration Tests
```python
# Test with real endpoint (in CI)
def test_real_token_verification():
# Use test token from tokens.indieauth.com
token = get_test_token()
result = verify_token(token)
assert result['me'] == TEST_USER
```
### Manual Testing
1. Configure domain with IndieAuth links
2. Use Quill or Indigenous
3. Create test post
4. Verify token caching
## Metrics for Success
### Quantitative Metrics
- **Code removed**: >500 lines
- **Database tables removed**: 2
- **Complexity reduction**: ~40%
- **Test coverage maintained**: >90%
- **Performance**: <500ms token verification
### Qualitative Metrics
- **Clarity**: Clear separation of concerns
- **Maintainability**: No auth code to maintain
- **Security**: Specialized providers
- **Flexibility**: User choice of providers
- **Simplicity**: Focus on core functionality
---
**Document Version**: 1.0
**Created**: 2025-11-24
**Author**: StarPunk Architecture Team
**Purpose**: Document simplified authentication architecture after IndieAuth server removal
- Admin forms and the consent form have no CSRF token. They rely on the
`SameSite=Lax` session cookie, which cross-site POSTs don't carry.
- The client metadata fetch checks the `client_id` URL against private
addresses, but then makes a plain `httpx.get` that follows redirects.
Redirect hops are not re-checked and the connection is not pinned, unlike
`webmention_ssrf.safe_get`.
- `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.
- No token introspection endpoint and no refresh tokens.
+212 -190
View File
@@ -1,233 +1,255 @@
# Syndication Architecture
# Syndication (POSSE) Architecture
## Overview
StarPunk's syndication architecture provides multiple feed formats for content distribution, ensuring broad compatibility with feed readers and IndieWeb tools while maintaining simplicity.
Current as of v2.10.1. Code: `starpunk/syndication.py`.
## Current State (v1.1.0)
```
┌─────────────┐
│ Database │
│ (Notes) │
└──────┬──────┘
│
┌──────▼──────┐
│ feed.py │
│ (RSS 2.0) │
└──────┬──────┘
│
┌──────▼──────┐
│ /feed.xml │
│ endpoint │
└─────────────┘
```
StarPunk publishes on its own site first and then copies each note to other
networks (POSSE: Publish on your Own Site, Syndicate Elsewhere). Later
edits, unpublishing and deletes follow the copies.
## Target Architecture (v1.1.2+)
```
┌─────────────┐
│ Database │
│ (Notes) │
└──────┬──────┘
│
┌──────▼──────────────────┐
│ Feed Generation Layer │
├──────────┬───────────────┤
│ feed.py │ json_feed.py │
│ RSS/ATOM│ JSON │
└──────────┴───────────────┘
│
┌──────▼──────────────────┐
│ Feed Endpoints │
├─────────┬───────────────┤
│/feed.xml│ /feed.atom │
│ (RSS) │ (ATOM) │
├─────────┼───────────────┤
│ /feed.json │
│ (JSON Feed) │
└─────────────────────────┘
```
> Feeds (RSS, Atom, JSON Feed, OPML) and WebSub are pull and push
> distribution of the site itself, not crossposting. They are described in
> [indieweb-protocols.md](indieweb-protocols.md#feeds). This document
> covered feeds before v2.1.0.
## Design Principles
Decisions: [ADR-065](../decisions/ADR-065-direct-syndication-posse.md)
(GoToSocial, queue model), [ADR-066](../decisions/ADR-066-bluesky-syndication.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)
(bookmarks, `mp-syndicate-to` default).
### 1. Format Independence
Each syndication format operates independently:
- No shared state between formats
- Failures in one don't affect others
- Can be enabled/disabled individually
## Targets
### 2. Shared Data Access
All formats read from the same data source:
- Single query pattern for notes
- Consistent ordering (newest first)
- Same publication status filtering
A target exists when its credentials are configured. `get_targets()` builds
the list from config on each call and caches one client object per target
in the process.
### 3. Library Leverage
Maximize use of existing libraries:
- `feedgen` for RSS and ATOM
- Native Python `json` for JSON Feed
- No custom XML generation
| Target id | Client | Enabled by | Micropub `uid` | Text limit | Images | Edits follow? |
|---|---|---|---|---|---|---|
| `gotosocial` | `MastodonClient` (any Mastodon-API server) | `GOTOSOCIAL_URL` + `GOTOSOCIAL_ACCESS_TOKEN` | `GOTOSOCIAL_URL/` | `GOTOSOCIAL_MAX_CHARS` (5000) | `GOTOSOCIAL_MAX_MEDIA` (4) | Yes |
| `bluesky` | `BlueskyClient` (AT Protocol, app password) | `BLUESKY_HANDLE` + `BLUESKY_APP_PASSWORD` (`BLUESKY_SERVICE`, default `https://bsky.social`) | `https://bsky.app/profile/<handle>` | `BLUESKY_MAX_CHARS` (300) | 4 | No |
| `threads` | `ThreadsClient` (Meta Graph API) | `THREADS_ACCESS_TOKEN` (`THREADS_USERNAME` for links) | `https://www.threads.com/@<username>` | `THREADS_MAX_CHARS` (500) | `THREADS_MAX_MEDIA` (4) | No |
## Component Design
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.
### Feed Generation Module (`feed.py`)
**Current Responsibility**: RSS 2.0 generation
**Future Enhancement**: Add ATOM generation function
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
remove it.
```python
# Pseudocode structure
def generate_rss_feed(notes, config) -> str
def generate_atom_feed(notes, config) -> str # New
```
## Choosing targets
### JSON Feed Module (`json_feed.py`)
**New Component**: Dedicated JSON Feed generation
`select_targets(note_id, target_ids)` records which targets a note goes to.
Every configured target not in the list is disabled; if it already has a
copy, that copy is deleted. Targets the note never went to get no row.
```python
# Pseudocode structure
def generate_json_feed(notes, config) -> str
def format_json_item(note) -> dict
```
| Origin | Targets |
|---|---|
| Admin editor, new note | One checkbox per target, all checked by default |
| Admin editor, edit | Checkboxes reflect the targets currently enabled; saving applies the selection |
| Micropub create | Only the targets in `mp-syndicate-to` (form field, `mp-syndicate-to[]`, or inside JSON `properties`). Values may be a target's `uid` (trailing slash ignored) or its id. **No `mp-syndicate-to` means no crossposting** (v2.9.0; before, all targets) |
| Micropub update / delete | Target selection is unchanged; the change follows existing copies |
### Route Handlers
Simple pass-through to generation functions:
```python
@app.route('/feed.xml') # Existing
@app.route('/feed.atom') # New
@app.route('/feed.json') # New
```
Micropub clients learn the targets from `q=syndicate-to` and `q=config`
(`[{"uid", "name"}]`). Selecting targets for a draft records them; nothing
is sent until the note is published.
## Data Flow
## Data: the `syndications` table (migration 012)
1. **Request**: Client requests feed at endpoint
2. **Query**: Fetch published notes from database
3. **Transform**: Convert notes to format-specific structure
4. **Serialize**: Generate final output (XML/JSON)
5. **Response**: Return with appropriate Content-Type
One row per (note, target), unique on `(note_id, target)`:
## Microformats2 Architecture
| Column | Meaning |
|---|---|
| `enabled` | Whether the note should have a copy on this target |
| `remote_id`, `remote_url` | The copy: status id, `at://` URI, Threads media id, or a `favourite:<id>` / `reblog:<id>` marker for native likes and boosts |
| `state` | `pending`, `synced` or `failed` |
| `version` | Incremented on every change that needs a reconcile |
| `attempts`, `last_error`, `next_attempt_at` | Retry bookkeeping |
| `claimed_until` | Lease held by the worker processing the row |
### Template Layer Enhancement
Microformats2 operates at the HTML template layer:
`note_id` deliberately has no foreign key, so the row outlives a hard
delete and the worker can still remove the copy.
## Change hooks
| Event | Call | Effect |
|---|---|---|
| Admin create/edit | `select_targets()` | Rows set to `pending`, version bumped |
| Micropub create | `select_targets(resolve_targets(mp-syndicate-to))` | After photos are attached |
| `update_note()` (admin or Micropub, including publish/unpublish) | `note_changed(id)` | Every row of the note set to `pending`, version bumped, attempts reset |
| 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 |
## Worker
`SyndicationWorker` is a daemon thread started in every gunicorn process
when at least one target is configured (not under `TESTING`). It runs
`process_due()` every `SYNDICATION_POLL_INTERVAL` seconds (default 10), and
loops again immediately while there is work.
`process_due()`:
1. Calls each client's `maintain()` (the Threads token refresh).
2. Selects up to 5 rows that are `pending`, due, and not claimed.
3. Claims each row with an atomic
`UPDATE ... SET claimed_until = now + 5 min WHERE state = 'pending' AND
(claimed_until IS NULL OR claimed_until < now)`. The other processes skip
it. Unlike the Webmention and WebSub workers, there is no file lock: the
row claim is the only coordination.
4. Reconciles the row (below), then records the result.
### Reconcile
```
┌──────────────┐
│ Data Model │
│ (Notes) │
└──────┬───────┘
│
┌──────▼───────┐
│ Templates │
│ + mf2 markup│
└──────┬───────┘
│
┌──────▼───────┐
│ HTML Output │
│ (Semantic) │
└──────────────┘
note published and row enabled?
no → remote copy exists? delete it → (None, None)
yes → copy exists and target can't edit? → keep it as is
copy exists → update (if it's gone remotely: create again)
no copy → create
```
### Markup Strategy
- **Progressive Enhancement**: Add classes without changing structure
- **CSS Independence**: Use mf2-specific classes, not styling classes
- **Validation First**: Test with parsers during development
Deleted notes are not found by `get_note()`, so they count as "not
published".
## Configuration Requirements
### Versions
### New Configuration Variables
```ini
# Author information for h-card
AUTHOR_NAME = "Site Author"
AUTHOR_URL = "https://example.com"
AUTHOR_PHOTO = "/static/avatar.jpg" # Optional
The row's `version` is read when the row is picked up. `_finish()` sets
`state = 'synced'` only if the version is unchanged. If the note was edited
while the send was in flight, the row stays `pending` and is reconciled
again with the new content. `_fail()` does the same.
# Feed settings
FEED_LIMIT = 50
FEED_FORMATS = "rss,atom,json" # Comma-separated
```
### Retries and idempotency
## Performance Considerations
- `SyndicationError(permanent=True)` fails the row immediately. This covers
HTTP 4xx other than 429, a missing target, images too large for Bluesky,
a Threads container in `ERROR`/`EXPIRED`, and Graph API auth/permission
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.
- `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.
- Duplicate posts after a lost response are prevented as follows:
- GoToSocial: an `Idempotency-Key: starpunk-<row id>-<version>` header.
- Bluesky and Threads: on a retry (`attempts > 0`), the last 25 posts are
searched for one containing the permalink (for Threads reposts, the
reposted URL). A match is adopted instead of posting again.
- Threads' publish step sometimes fails transiently ("Fatal"); it is
retried unless the error is an auth error.
### Caching Strategy
- Feed generation is read-heavy, write-light
- Consider caching generated feeds (5-minute TTL)
- Invalidate cache on note creation/update
## Composing posts
### Resource Usage
- RSS/ATOM: ~O(n) memory for n notes
- JSON Feed: Similar memory profile
- Microformats2: No additional server resources
`Post` carries the note, permalink, tags, the target's character limit,
media files, and for likes, reposts and bookmarks, the URL they point at and
its fetched title (from the reply-context cache).
## Security Considerations
### Text
### Content Sanitization
- HTML in feeds must be properly escaped
- CDATA wrapping for RSS/ATOM
- JSON string encoding for JSON Feed
- No script injection vectors
`compose_text()` builds: body, a blank line, the permalink, a blank line,
the hashtags. If that is too long, the body is cut at a word boundary with
"…"; the permalink always survives. Hashtags (`#` plus the tag's display
name without non-word characters) may take at most a third of the limit. A
bookmark's body starts with `🔖 <bookmarked URL>` (v2.9.0). A photo-only
note starts with the permalink.
### Rate Limiting
- Apply same limits as HTML endpoints
- Consider aggressive caching for feeds
- Monitor for feed polling abuse
| Target | Body format | Links | Hashtags |
|---|---|---|---|
| GoToSocial | The note's Markdown, sent with `content_type: text/markdown`; embedded images removed from the text (sent as attachments) | As written | In the text |
| Bluesky | Plain text from the rendered Markdown | Markdown link text becomes a clickable link facet; bare URLs and `#tags` get link/tag facets (UTF-8 byte offsets) | In the text, as tag facets |
| Threads | Plain text | Markdown links are written `text (url)`, up to 4 different URLs plus the permalink (Threads allows 5); the length counts non-ASCII characters as UTF-8 bytes | None in the text; the first usable tag becomes the post's `topic_tag` |
## Testing Architecture
### Link cards (ADR-070)
### Unit Tests
```
tests/
├── test_feed.py # Enhanced for ATOM
├── test_json_feed.py # New test module
└── test_microformats.py # Template parsing tests
```
- **Bluesky**: if the note has images, they are the embed. Otherwise, if
the note links somewhere, StarPunk builds an `app.bsky.embed.external`
card for the first link. `page_card()` fetches the page (at most 512 KB,
every redirect hop checked against private addresses, 10 s per request,
5 redirects) and reads the Open Graph, Twitter or HTML title, description
and image. The image (at most 5 MB) is shrunk under 1 MB and uploaded as
the thumbnail. If the page can't be fetched, the card has just the URL.
A note without links gets a card for its own permalink, built from the
note without fetching anything.
- **Threads**: no explicit `link_attachment` (Meta rejects one for a page
it hasn't crawled yet). Threads previews the first link in the text by
itself.
- **GoToSocial**: the server makes its own previews.
### Integration Tests
- Validate against external validators
- Test feed reader compatibility
- Verify IndieWeb tool parsing
### Media
## Backwards Compatibility
`_media_files()` collects the note's attached photos first, then images
embedded in the note text that are in this site's media library (some
Micropub clients put uploaded photos in the content). It stops at the
target's image limit. The `large` variant is used when one exists. Alt text
comes from the caption, or from the embedded image's alt.
### URL Structure
- `/feed.xml` remains RSS 2.0 (no breaking change)
- New endpoints are additive only
- Auto-discovery links updated in templates
| Target | Handling |
|---|---|
| GoToSocial | Uploaded via `POST /api/v2/media` with description; re-uploaded on each edit |
| Bluesky | `uploadBlob`; images over 1,000,000 bytes are re-encoded as JPEG at decreasing size and quality, and fail permanently if they still don't fit. Aspect ratio is sent |
| Threads | Meta fetches each image from its public `/media/` URL. Only JPEG and PNG up to 8 MB are used; others are left off. 1 image → `IMAGE` container, 2 or more → `CAROUSEL` of child containers. Alt text up to 1000 characters |
### Database
- No schema changes required
- All features use existing Note model
- No migration needed
Only notes of kind `note` carry media; likes, reposts and bookmarks don't.
## Future Extensibility
### Likes, reposts and bookmarks
### Potential Enhancements
1. Content negotiation on `/feed`
2. WebSub (PubSubHubbub) support
3. Custom feed filtering (by tag, date)
4. Feed pagination for large sites
| Kind | GoToSocial | Bluesky | Threads |
|---|---|---|---|
| Like of a post on that network | Native favourite (`favourite:<id>`) | Native `app.bsky.feed.like` | Not crossposted (the API can't like) |
| Like of anything else | Not crossposted | Not crossposted | Not crossposted |
| Repost without comment, of a post on that network | Native boost (`reblog:<id>`) | Native `app.bsky.feed.repost` | Not native: posts `🔁 title` + URL |
| Repost with comment, of a post on that network | Status: comment, `🔁 title`, URL | Quote post (`app.bsky.embed.record`) | Comment, `🔁 title`, URL |
| Repost of another page | Status: (comment,) `🔁 title`, URL | Post with an external card for the URL | (Comment,) `🔁 title`, URL |
| Bookmark | Ordinary status starting `🔖 <url>` | Ordinary post starting `🔖 <url>` | Ordinary post starting `🔖 <url>` |
### Format Support Matrix
| Format | v1.1.0 | v1.1.2 | v1.2.0 |
|--------|--------|--------|--------|
| RSS 2.0 | ✅ | ✅ | ✅ |
| ATOM | ❌ | ✅ | ✅ |
| JSON Feed | ❌ | ✅ | ✅ |
| Microformats2 | Partial | Partial | ✅ |
"On that network" is decided by the client. GoToSocial resolves the URL
through `/api/v2/search?resolve=true`. Bluesky matches
`https://bsky.app/profile/<actor>/post/<rkey>` and resolves it to a URI and
CID. Native likes and boosts have no URL of their own and nothing to edit.
Deleting the note undoes them (`unfavourite` / `unreblog`, or deleting the
like or repost record). A like that isn't crossposted is recorded as synced
with no remote copy.
## Decision Rationale
## u-syndication
### Why Multiple Formats?
1. **No Universal Standard**: Different ecosystems prefer different formats
2. **Low Maintenance**: Feed formats are stable, rarely change
3. **User Choice**: Let users pick their preferred format
4. **IndieWeb Philosophy**: Embrace plurality and interoperability
`templates/note.html` lists every row that has a `remote_url` as "Also on
<name>", using `<a class="u-syndication" rel="syndication">`. Micropub
`q=source` returns the same URLs as the `syndication` property. The
Webmention worker rejects a webmention whose source is one of the note's
own copies (e.g. backfed by Bridgy), so a copy is never shown as a response
to itself (v2.8.0).
### Why This Architecture?
1. **Simplicity**: Each component has single responsibility
2. **Testability**: Isolated components are easier to test
3. **Maintainability**: Changes to one format don't affect others
4. **Performance**: Can optimize each format independently
## Client sessions and tokens
## References
- [RSS 2.0 Specification](https://www.rssboard.org/rss-specification)
- [ATOM RFC 4287](https://tools.ietf.org/html/rfc4287)
- [JSON Feed Specification](https://www.jsonfeed.org/)
- [Microformats2](https://microformats.org/wiki/microformats2)
- **Bluesky**: `createSession` with the app password, then
`refreshSession` when the access JWT expires (a 401 or `ExpiredToken`
triggers one re-login and retry). The PDS endpoint is taken from the DID
document. Calls are serialized per client with a lock.
- **Threads**: long-lived tokens expire after 60 days. `maintain()` tries a
refresh (`refresh_access_token`, `th_refresh_token`) at most once a day.
The current token is kept in `DATA_PATH/threads_token.json` (mode 0600,
written atomically), together with a SHA-256 "seed" of the configured
token. A different `THREADS_ACCESS_TOKEN` in the config therefore
replaces the saved one. An exclusive `flock` on `threads_token.lock` makes
one gunicorn process refresh while the others pick up its result. A failed
refresh is retried an hour later (network error) or the next day (HTTP
error, e.g. a token less than a day old). The httpx logger is raised to
WARNING because Threads takes the token in the URL, and errors never echo
the URL.
- **GoToSocial**: a static bearer token.
## Known limits
- Bluesky and Threads copies don't follow edits (platform limitation).
Unticking and re-ticking a target makes a new copy.
- Link-card and Threads image fetches check every redirect hop against
private addresses but don't pin DNS, and use a per-request rather than an
overall time limit. Webmention and WebSub fetching use the stricter
`webmention_ssrf` fetcher.
- No per-target choice for Micropub updates: `mp-syndicate-to` is read only
on create.
- Likes of ordinary web pages, and all likes on Threads, stay on the site.
@@ -1,5 +1,10 @@
# StarPunk Technology Stack - Quick Reference
> **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).
## Project Understanding
StarPunk is a **minimal, single-user IndieWeb CMS** for publishing notes with RSS syndication. The core philosophy is radical simplicity: "Every line of code must justify its existence."
File diff suppressed because it is too large. Load diff