Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

chore: file cleanup

Gabe Kangas4b09a1b11693
diff --git a/IMPLEMENTATION_CONTEXT.md b/IMPLEMENTATION_CONTEXT.md
deleted file mode 100644
index 20f3b51e02..0000000000
--- a/IMPLEMENTATION_CONTEXT.md
+++ /dev/null
@@ -1,216 +0,0 @@
-# Owncast Server Federation Phase 2 - Implementation Context
-
-## Overview
-This document provides complete context for the implementation of Server Federation Phase 2 in Owncast. This feature allows Owncast servers to follow other Owncast servers and receive ActivityPub "Arrive" and "Leave" activities to track their online/offline status and stream metadata.
-
-## Feature Requirements
-Based on `docs/features/server-federation-2.md`:
-- Accept ActivityPub "Arrive" activity when federated server comes online
-- Accept ActivityPub "Leave" activity when federated server goes offline
-- Store federated server information (name, logo, status, stream metadata)
-- Provide APIs for managing followed federated servers
-- Display federated servers in frontend
-
-## Implementation Status: ✅ COMPLETED
-
-All components have been successfully implemented and the application builds without errors.
-
-## Files Created/Modified
-
-### Database Layer
-1. **`db/schema.sql`** - Added `federated_servers` table:
- ```sql
- CREATE TABLE IF NOT EXISTS federated_servers (
- "id" INTEGER NOT NULL PRIMARY KEY,
- "iri" TEXT NOT NULL UNIQUE,
- "name" TEXT,
- "logo_url" TEXT,
- "is_online" BOOLEAN DEFAULT FALSE,
- "stream_title" TEXT,
- "stream_description" TEXT,
- "stream_tags" TEXT,
- "thumbnail_url" TEXT,
- "last_seen_online" TIMESTAMP,
- "last_status_update" TIMESTAMP,
- "added_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- "followed_at" TIMESTAMP
- );
- ```
-
-2. **`db/query.sql`** - Added SQLC queries:
- - GetFederatedServers
- - GetFederatedServer
- - AddFederatedServer
- - UpdateFederatedServerStatus
- - UpdateFederatedServerOnlineStatus
- - RemoveFederatedServer
-
-3. **`db/models.go` & `db/query.sql.go`** - Auto-generated via `sqlc generate`
-
-### Models Layer
-4. **`models/federatedserver.go`** - Created models:
- ```go
- type FederatedServer struct {
- ID int32 `json:"id"`
- IRI string `json:"iri"`
- Name *string `json:"name,omitempty"`
- LogoURL *string `json:"logoUrl,omitempty"`
- IsOnline bool `json:"isOnline"`
- StreamTitle *string `json:"streamTitle,omitempty"`
- StreamDescription *string `json:"streamDescription,omitempty"`
- Tags []string `json:"tags,omitempty"`
- ThumbnailURL *string `json:"thumbnailUrl,omitempty"`
- LastSeenOnline *time.Time `json:"lastSeenOnline,omitempty"`
- LastStatusUpdate *time.Time `json:"lastStatusUpdate,omitempty"`
- AddedAt time.Time `json:"addedAt"`
- FollowedAt *time.Time `json:"followedAt,omitempty"`
- }
-
- type FederatedStreamUpdate struct {
- Title *string `json:"title,omitempty"`
- Description *string `json:"description,omitempty"`
- Tags []string `json:"tags,omitempty"`
- ThumbnailURL *string `json:"thumbnailUrl,omitempty"`
- }
- ```
-
-### Repository Layer
-5. **`persistence/federatedserversrepository/federatedserversrepository.go`** - Interface definition
-6. **`persistence/federatedserversrepository/sqlfederatedserversrepository.go`** - SQL implementation using repository pattern
-
-### ActivityPub Handlers
-7. **`activitypub/inbox/arrive.go`** - Handles "Arrive" activities:
- - Extracts actor IRI and target
- - Validates federated server
- - Updates online status with stream metadata
-
-8. **`activitypub/inbox/leave.go`** - Handles "Leave" activities:
- - Extracts actor IRI and target
- - Updates offline status
-
-9. **`activitypub/inbox/worker.go`** - Modified to include new handlers:
- ```go
- resolvers.Resolve(context.Background(), request.Body,
- handleUpdateRequest, handleFollowInboxRequest, handleLikeRequest,
- handleAnnounceRequest, handleUndoInboxRequest, handleCreateRequest,
- handleArriveInboxRequest, handleLeaveInboxRequest)
- ```
-
-### API Layer
-10. **`openapi.yaml`** - Added endpoints:
- - `GET /api/federation/servers` (public)
- - `POST /admin/federation/servers` (admin, BasicAuth)
- - `DELETE /admin/federation/servers/{id}` (admin, BasicAuth)
- - Added `FederatedServer` schema
-
-11. **`webserver/handlers/generated/`** - Auto-generated API code via `oapi-codegen`
-
-12. **`webserver/handlers/admin/federatedservers.go`** - Handler implementations:
- - GetFederatedServers()
- - AddFederatedServer()
- - RemoveFederatedServer()
- - Options handlers for CORS
-
-13. **`webserver/handlers/handler.go`** - Added route bindings:
- ```go
- func (*ServerInterfaceImpl) GetFederatedServers(w http.ResponseWriter, r *http.Request) {
- admin.GetFederatedServers(w, r)
- }
- func (*ServerInterfaceImpl) AddFederatedServer(w http.ResponseWriter, r *http.Request) {
- middleware.RequireAdminAuth(admin.AddFederatedServer)(w, r)
- }
- // ... etc
- ```
-
-### Existing Files Modified (Build Fixes)
-14. **`persistence/userrepository/userrepository.go`** - Fixed int32 type conversion
-15. **`activitypub/persistence/followers.go`** - Fixed int32 type conversions
-16. **`activitypub/persistence/persistence.go`** - Fixed int32 type conversions
-
-## Key Implementation Details
-
-### ActivityPub Integration
-- **Arrive Activity**: Uses `GetActivityStreamsTarget()` to extract server URL
-- **Leave Activity**: Similar extraction, sets server offline
-- **Metadata Extraction**: Pulls stream title, description, image from activity properties
-- **Validation**: Ensures actor matches target host (servers announce themselves)
-
-### Repository Pattern
-- Follows existing Owncast patterns from `configrepository`
-- Interface-based design for testability
-- Global singleton via `Get()` function
-- Proper datastore integration
-
-### API Security
-- Public endpoint for listing servers (no auth)
-- Admin endpoints require HTTP Basic Auth via `middleware.RequireAdminAuth`
-- Proper CORS handling with OPTIONS methods
-- Input validation and error handling
-
-### Database Design
-- Uses SQLite with proper indexing
-- JSON storage for tags array
-- Timestamps for tracking activity
-- Nullable fields for optional metadata
-
-## Build Process
-1. Updated schema: `db/schema.sql`
-2. Updated queries: `db/query.sql`
-3. Generated models: `sqlc generate`
-4. Updated OpenAPI: `openapi.yaml`
-5. Generated API: `make api-generate` (both types and server)
-6. Fixed type conflicts: int → int32 conversions
-7. Final build: `go build -o owncast .` ✅
-
-## Frontend Integration
-The frontend components already partially exist:
-- `web/hooks/useFederatedServers.tsx` - React hook for API calls
-- `web/components/admin/FederatedServers/` - Admin components
-- `web/components/ui/StreamsTab/` - Public display components
-
-API endpoints match the expected interface in the frontend hook.
-
-## Testing Approach
-To test this implementation:
-
-1. **Start Owncast**: `go run main.go`
-2. **Admin Interface**: Navigate to `/admin` → Federation settings
-3. **Add Server**: POST to `/api/admin/federation/servers` with server URL
-4. **List Servers**: GET `/api/federation/servers`
-5. **ActivityPub Testing**: Send Arrive/Leave activities to `/inbox`
-
-## Troubleshooting Notes
-
-### Common Issues Fixed
-- **Type Conflicts**: `sqlc generate` changed int→int32, required casting
-- **ActivityStreams Methods**: Used `GetActivityStreamsTarget()` not `GetActivityStreamsObject()`
-- **Import Cleanup**: Removed unused imports causing build errors
-
-### Future Enhancements
-- Enhanced tag parsing from ActivityPub activities
-- Server discovery and automatic following
-- Push notifications for server status changes
-- Admin UI for federation management
-
-## Context for Resumption
-When resuming work on this implementation:
-
-1. **All core functionality is implemented and working**
-2. **The app builds successfully** - no outstanding errors
-3. **Next steps would be**: Frontend integration, testing, UI polish
-4. **Key files to reference**: This context file, the implementation plan at `docs/implementation-plan-server-federation-2.md`
-
-## Code Generation Commands Used
-```bash
-# Database models
-make sqlc
-
-# API code
-make api-generate
-
-# Cleanup
-go mod tidy
-make fmt
-```
-
-This implementation fully satisfies the requirements in `docs/features/server-federation-2.md` and is ready for production use.
\ No newline at end of file
diff --git a/docs/backend.md b/docs/backend.md
deleted file mode 100644
index 605f618fbb..0000000000
--- a/docs/backend.md
+++ /dev/null
@@ -1,188 +0,0 @@
-# Owncast Backend Architecture
-
-This is a work in progress document detailing the future backend architecture of Owncast. It should be seen as a living document until a refactor of the backend is complete.
-
-## Dependencies
-
-Dependencies are services that are required across the application. This can be things like the chat service or a data repository for config values or user data.
-
-Note: A better name that "dependencies" might be clearer. Perhaps "services" or "providers".
-
-TODO: Have a complete list of dependencies.
-
-### Data Repositories
-
-The repository pattern provides a layer of abstraction between the application and the data store, allowing the application to interact with the data store through a well-defined interface, rather than directly accessing the data store. This helps to decouple the application from the data store.
-
-TODO: List out the repositories and what they do.
-
-Learn more about the [repository pattern](https://techinscribed.com/different-approaches-to-pass-database-connection-into-controllers-in-golang/).
-
-### Application Controller
-
-The `AppController` has references to all the dependencies and serves as an arbiter between consumers of these services and the services themselves.
-
-A reference to the `AppController` is passed in to the all the core functionality in the application and each package would have its own interface that `AppController` implements. This can include getting access to dependency services like getting access to the chat service, getting access to the config repository values or knowing application state such as if a stream is live or how many viewers are watching via metrics.
-
-TODO: Show examples of how the application is passed in to packages and how to reference dependencies through it.
-
-## Diagram
-
-```mermaid
-%% Owncast backend architecture.
-%% See https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/
-%% for a cheat sheet on creating this diagram.
-%% Paste this document in https://mermaid.live as a quick way to edit.
-
-%% TODO: Add links between nodes and the actual code.
-
-%% This is a graph style diagram, Top Down.
-graph TD
-
-
-%% Define Nodes and Subgraphs
-
-subgraph VideoPipeline[Video Pipeline]
- VideoTranscoder(fa:fa-video Video Transcoder)
- RTMPService[fa:fa-video RTMP Service]
-end
-
-subgraph ChatService[fa:fa-comment Chat\nService]
-end
-
-subgraph Dependencies
-
- App{AppController}
- ChatService--->App
- Webhooks--->App
- ActivityPubOutboundHandlers[fa:fa-hashtag ActivityPub\nOutbound]--->App
-
- ConfigRepository(fa:fa-hard-drive Config\nRepository)--->App
- UserRepository(fa:fa-hard-drive User\nRepository)--->App
- NotificationsRepository(fa:fa-hard-drive Notifications\nRepository)--->App
- ChatRepository(fa:fa-hard-drive Chat\nRepository)
- APRepository(fa:fa-hard-drive ActivityPub\nRepository)
-
- Database(fa:fa-hard-drive Database)--->ConfigRepository
- Database--->UserRepository
- Database--->APRepository
- Database--->NotificationsRepository
-
- ChatRepository-->ChatService
-
- ApplicationState(fa:fa-list Application\nState)--->App
- GeoIP(fa:fa-globe GeoIP\nLookup)--->App
- Statistics(fa:fa-list Statistics)--->App
- OutboundWebhooks[Outbound\nWebhooks]--->App
-
-end
-
-subgraph VideoStorageProviders[Video Storage Providers]
- LocalStorage((fa:fa-hard-drive Local\nStorage))
- S3Storage((fa:fa-hard-drive S3\nStorage))
-end
-
-subgraph Authentication[Chat Authentication]
- IndieAuth[fa:fa-key IndieAuth]
- FediAuth[fa:fa-key FediAuth]
-end
-
-subgraph Notifications[External Notifications]
- DiscordNotifier[fa:fa-comment Discord]
- BrowserNotifier[fa:fa-browser Browser]
-end
-
-subgraph WebServer[Web Server]
- ActivityPubHandlers[fa:fa-file ActivityPub\nHandlers]
-
- subgraph WebAssets[Web Assets]
- EmbeddedStaticFiles((fa:fa-file Embedded\nStatic Assets))
- OnDiskStaticFiles((fa:fa-file On Disk\nStatic Assets))
- WebApplication[fa:fa-file Web\nApplication]
- PublicFiles[fa:fa-file Public\nDirectory]
- end
-
- subgraph HTTPHandlers[fa:fa-browser HTTP Handlers]
- AdminAPIs[Admin\nAPIs]
- ThirdPartyAPIs[3rd Party\nAPIs]
- WebSocket[WebSocket]
- subgraph ChatAPIs[Chat\nAPIs]
- ChatUserRegistration[Chat User\nRegistration]
- Emoji[Emojis]
- subgraph ChatAuthAPIs[Chat\nAuthentication]
- FediAuth
- IndieAuth
- end
- end
- subgraph VideoAPIs[fa:fa-video Video APIs]
- ViewerPing[Viewer\nPing]
- PlaybackMetrics[Playback\nHealth Metrics]
- end
- ActivityPubHandlers
- ApplicationConfig[Application\nConfig]
- ApplicationStatus[Application\nStatus]
- Directory[Directory\nAPI]
- Followers[Followers]
- end
-end
-
-subgraph Streamer
- BroadcastingSoftware>fa:fa-video Broadcasting\nSoftware]
-end
-
-%% All the services and packages require access
-%% to dependencies through a Application reference.
-App-.->HTTPHandlers
-App-.->VideoPipeline
-App-.->ActivityPub
-App-.->Authentication
-App-.->Notifications
-App-.->DirectoryNotifier[Owncast\nDirectory]
-
-LocalStorage--HLS-->OnDiskStaticFiles
-
-RTMPService>RTMP Ingest]--RTMP-->VideoTranscoder
-VideoTranscoder--HLS-->VideoStorageProviders
-
-%% Streamers
-BroadcastingSoftware--RTMP-->RTMPService
-
-%% Style the nodes
-
-%% Define reusable styles for node types
-classDef bigtext font-weight:bold,font-size:40px
-classDef repository fill:#4F625B,color:#fff
-classDef webservice fill:#6082B6,color:#fff
-classDef rtmp fill:#608200, color:#fff
-classDef inbound fill:#6544e9,stoke:#fff,color:#fff
-classDef outboundservice fill:#2386e2,stroke:green,color:#fff
-classDef storage fill:#42bea6,color:#fff
-
-%% Assign styles to nodes
-class App bigtext
-class UserRepository repository
-class ConfigRepository repository
-class APRepository repository
-class NotificationsRepository repository
-class ChatRepository repository
-
-class HTTPHandlers inbound
-class ActivityPubInboundHandlers inbound
-class InboundWebhooks inbound
-
-class ActivityPubOutboundHandlers outboundservice
-class DiscordNotifier outboundservice
-class BrowserNotifier outboundservice
-class OutboundWebhooks outboundservice
-class DirectoryNotifier outboundservice
-
-class BroadcastingSoftware rtmp
-class RTMPService rtmp
-
-class Database storage
-class LocalStorage storage
-class S3Storage storage
-
-%% Customize the theme styles
-%%{init: {'theme':'base', 'themeVariables': {'darkMode': true, 'lineColor': '#c3dafe', 'tertiaryTextColor': 'white', 'clusterBkg': '#2d3748', 'primaryTextColor': '#39373d', "edgeLabelBackground": "white", "fontFamily": "monospace", "fontSize": "30px"}}}%%
-```
diff --git a/docs/features/server-federation-1.md b/docs/features/server-federation-1.md
deleted file mode 100644
index 179c76edbe..0000000000
--- a/docs/features/server-federation-1.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# Following / Federating with Other Owncast Servers: Phase 1 UI
-
-This document outlines the specifications for implementing the user interface changes required to support server federation in Owncast. This feature will allow Owncast servers to follow and display the status of other Owncast servers.
-
-This allows visitors to an Owncast server to see a list of other Owncast servers that are being followed, along with their current status (online/offline) and stream information if they are online. This creates a network effect, allowing users to discover and navigate to other Owncast servers easily. It also gives somewhere for somebody to go if the server they are on is offline.
-
-The user interface should give the feel of browsing through Twitch or YouTube, with each followed server represented by a card that includes a thumbnail, server name, stream title, description, and tags.
-
-This document focuses solely on the user interface changes required to support server federation. The backend and API changes required to support this feature will be added separately.
-
-## Goal
-
-The goal of this feature is to allow an Owncast server to federate status with other Owncast servers. This allows a network of Owncast servers to share information about their status, such as whether they are online or offline, and to share information about their streams, such as the title and description of the stream.
-
-## Requirements
-
-### Web User Interface
-
-- The web user interface changes should be done using Ant Design v4 components, not Ant Design v5.
-- Styling should be done using CSS modules and follow the existing styling conventions in the Owncast codebase. This means using sass scss files.
-- Any new components should be added to Storybook for testing and prototyping.
-
-### Primary user-facing interface changes
-
-- Add a new tab to the main web interface called "Streams".
-- If the tab bar is currently hidden because there were previously no tabs to show, it should become visible when the "Streams" tab is added.
-- The "Streams" tab should display a list of all federated Owncast servers and their current status (online/offline).
-- Each Owncast server should be represented by a card in the style of Twitch or YouTube with a thumbnail on top and text information below.
-- For each online server, display the following information:
- - Server logo
- - Server name
- - Stream title
- - Stream description
- - Tags associated with the stream
- - A thumbnail image of the current stream (if available)
-- For each offline server, display the following information:
- - Server logo
- - Server name
- - Status: Offline
- - Tags
-- Allow users to click on a server card to navigate to the server's URL.
-
-### Admin Interface
-
-- Add a new admin section under "Social" for following servers.
-- The admin interface should allow administrators to add a federated servers.
-- Administrators should be able to remove federated servers from the list.
-- Validate the URL of the federated server when adding it to ensure it is a valid URL.
-- Display the current status of each federated server (online/offline) in the admin interface.
diff --git a/docs/features/server-federation-2.md b/docs/features/server-federation-2.md
deleted file mode 100644
index 28a5d47312..0000000000
--- a/docs/features/server-federation-2.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# Following / Federating with Other Owncast Servers: Phase 2 Accepting ActivityPub Status Updates
-
-This document outlines the specifications for implementing the backend and API changes required to support inbound server federation status updates in Owncast using ActivityPub. This feature will allow Owncast servers to follow and display the status of other Owncast servers.
-
-## Goal
-
-The goal of this feature is to allow an Owncast server to federate status with other Owncast servers. This allows a network of Owncast servers to share information about their status, such as whether they are online or offline, and to share information about their streams, such as the title and description of the stream.
-
-The specific goal of this change is
-
-### ActivityPub Support
-
-- Accept an ActivityPub "Arrive" activity from a federated Owncast server when its live stream comes online. https://www.w3.org/TR/activitystreams-vocabulary/#dfn-arrive
-- Accept an ActivityPub "Leave" activity from a federated Owncast server when its live stream goes offline. https://www.w3.org/TR/activitystreams-vocabulary/#dfn-leave
-- In both cases expect the actor to be the Owncast server itself.
-- In both cases expect the object to be the URL of the federated server.
-- Use the existing ActivityPub infrastructure in Owncast to handle the delivery and receipt of these activities via the inbox and worker queue.
-
-### Database Changes
-
-- Add a new table to store the list of federated Owncast servers that are being followed.
-- Add fields to store the current status of each federated server (online/offline) and stream information (title, description, tags, thumbnail URL).
-- Add timestamps for when the server was last seen online and when the last status update was received.
-- Update the table when an "Arrive" or "Leave" activity is received.
-
-## Requirements
-- For each federated server exchange the following information:
- - Server logo
- - Server name
- - Stream title
- - Stream description
- - Tags associated with the stream
- - A thumbnail image of the current stream (if available)
diff --git a/docs/features/server-federation-4-implementation-plan.md b/docs/features/server-federation-4-implementation-plan.md
deleted file mode 100644
index 910a700ee0..0000000000
--- a/docs/features/server-federation-4-implementation-plan.md
+++ /dev/null
@@ -1,205 +0,0 @@
-# Server Federation Phase 4 - Implementation Plan
-## ActivityPub Stream Ended Status Updates
-
-### Overview
-This implementation adds support for sending and receiving ActivityPub "Leave" activities when an Owncast server's live stream ends. This allows federated servers to update their status tracking of other servers in real-time.
-
-### Implementation Components
-
-## 1. ActivityPub Leave Activity Handling
-
-### 1.1 Outbound Leave Activity (When Local Stream Ends)
-**Location**: Same location where `GoLive` is called when stream starts
-
-- **Trigger Point**: When stream transitions from online to offline (parallel to GoLive but for offline)
-- **Tasks**:
- - Create ActivityPub "Leave" activity with:
- - Actor: Local Owncast server actor
- - Object: URL of the local server
- - Custom metadata using `SetOwncastMetadata`: Server logo, name, stream title, description, tags
- - Queue activity for delivery to all federated followers
- - Use existing ActivityPub outbox infrastructure
-
-### 1.2 Inbound Leave Activity Reception
-**Location**: `activitypub/inbox/worker.go` or similar inbox handler
-
-- **Trigger**: Receive "Leave" activity in inbox
-- **Tasks**:
- - Validate activity structure and signature
- - Extract server metadata using `ParseOwncastMetadata`
- - Update federated server status to offline
- - Update cached server metadata (logo, name, stream info, tags)
- - Trigger UI update notifications if needed
-
-## 2. ActivityPub Activity Structure
-
-### Leave Activity Format
-```json
-{
- "@context": "https://www.w3.org/ns/activitystreams",
- "type": "Leave",
- "id": "https://example.owncast.tv/activities/leave-123",
- "actor": "https://example.owncast.tv/federation/user/",
- "object": "https://example.owncast.tv",
- "published": "2024-01-01T00:00:00Z",
- "logo": "https://example.owncast.tv/logo.png",
- "name": "Example Server",
- "streamTitle": "My Stream",
- "streamDescription": "Stream description",
- "tags": ["gaming", "tech"]
-}
-```
-
-Note: Metadata fields are set at the root level using `SetOwncastMetadata` and parsed using `ParseOwncastMetadata`, following the existing pattern.
-
-## 3. Integration Points
-
-### 3.1 Stream Lifecycle Integration
-**Files to Modify**:
-- Same file where `GoLive` is implemented for stream start
-- Stream offline transition handler (parallel to GoLive)
-
-**Implementation**:
-- Create `GoOffline` function parallel to `GoLive`
-- Hook into existing stream offline event
-- Trigger Leave activity creation with metadata
-- Ensure activity is sent after stream fully offline
-
-### 3.2 ActivityPub Infrastructure Integration
-**Existing Components to Use**:
-- `activitypub/outbox/` - For sending activities
-- `activitypub/inbox/` - For receiving activities
-- `activitypub/persistence/` - For queue management
-- `activitypub/crypto/` - For signing activities
-
-### 3.3 Federation Server Status Management
-**Files to Modify**:
-- Federation server status tracker/cache
-- UI notification system for status updates
-
-## 4. Testing Strategy
-
-### 4.1 Unit Tests
-- **Leave Activity Creation**: Test proper activity structure
-- **Leave Activity Processing**: Test status update logic
-- **Metadata Extraction**: Test parsing of custom metadata
-
-### 4.2 Integration Tests
-**Location**: `test/automated/api/`
-- Test Leave activity endpoint reception
-- Test status update propagation
-- Test metadata update persistence
-
-### 4.3 End-to-End Testing
-- Set up two Owncast instances
-- Federate them together
-- Start/stop stream on one instance
-- Verify Leave activity received on other instance
-- Verify status updated correctly
-
-## 5. Implementation Steps
-
-### Phase 1: Leave Activity Sending (2-3 days)
-1. Identify where GoLive is called for stream start
-2. Create GoOffline function parallel to GoLive
-3. Create Leave activity builder function
-4. Use SetOwncastMetadata to add metadata to activity
-5. Integrate with existing outbox queue
-6. Test activity creation and queuing
-
-### Phase 2: Leave Activity Reception (2-3 days)
-1. Add Leave activity handler to inbox worker
-2. Use ParseOwncastMetadata for metadata extraction
-3. Update federated server status
-4. Persist metadata changes
-5. Test activity processing
-
-### Phase 3: Integration & Testing (2 days)
-1. Full integration testing
-2. Error handling and edge cases
-3. Performance testing with multiple federated servers
-4. Documentation updates
-
-### Phase 4: UI Updates (Optional - 1 day)
-1. Real-time status updates in UI
-2. Display updated metadata
-3. Visual indicators for offline servers
-
-## 6. Technical Considerations
-
-### Performance
-- Activity sending should be async/non-blocking
-- Batch updates if multiple servers go offline simultaneously
-- Cache server metadata to reduce database queries
-
-### Error Handling
-- Retry failed activity deliveries
-- Handle malformed activities gracefully
-- Log failures for debugging
-
-### Security
-- Verify activity signatures
-- Validate actor authorization
-- Sanitize metadata fields
-
-### Backwards Compatibility
-- Ensure compatibility with servers not supporting Leave activities
-- Graceful degradation if metadata missing
-- Version checking for activity format
-
-## 7. Dependencies
-
-### Existing Code to Review
-- `activitypub/` - ActivityPub implementation
-- `core/webhooks/` - Stream event handlers
-- `core/data/` - Database models
-- `models/` - Data structures
-
-### External Dependencies
-- No new external dependencies required
-- Uses existing ActivityPub libraries
-
-## 8. Success Criteria
-
-- [ ] Leave activity sent when stream goes offline
-- [ ] Leave activity received and processed correctly
-- [ ] Federated server status updated to offline
-- [ ] Server metadata updated with latest information
-- [ ] All tests passing
-- [ ] No performance regression
-- [ ] Error handling implemented
-- [ ] Documentation updated
-
-## 9. Risks & Mitigation
-
-### Risk 1: Activity Delivery Failures
-**Mitigation**: Implement retry mechanism with exponential backoff
-
-### Risk 2: Metadata Size
-**Mitigation**: Limit metadata fields, implement size validation
-
-### Risk 3: Race Conditions
-**Mitigation**: Use proper locking for status updates
-
-## 10. Future Enhancements
-
-- Support for other activity types (Join, Update)
-- Bulk status updates for efficiency
-- WebSocket notifications for real-time updates
-- Historical status tracking
-
-## Timeline Estimate
-
-**Total Duration**: 7-8 days
-
-- Days 1-3: Outbound Leave activity implementation
-- Days 4-6: Inbound Leave activity handling
-- Days 7-8: Integration testing and refinements
-
-## Notes for Implementation
-
-1. Follow existing ActivityPub patterns in codebase
-2. Use OpenAPI spec generation for any new endpoints
-3. Add comprehensive logging for debugging
-4. Consider rate limiting for activity processing
-5. Ensure all strings support localization
\ No newline at end of file
diff --git a/docs/features/server-federation-4.md b/docs/features/server-federation-4.md
deleted file mode 100644
index def26fe7b8..0000000000
--- a/docs/features/server-federation-4.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# Following / Federating with Other Owncast Servers: Phase 4 Sending ActivityPub stream ended status update
-
-This document outlines the specifications for implementing the backend and API changes required to support outbound server federation status updates in Owncast using ActivityPub. This feature will allow Owncast servers to follow and display the status of other Owncast servers.
-
-## Goal
-
-The goal of this feature is to allow an Owncast server to federate status with other Owncast servers. This allows a network of Owncast servers to share information about their status, such as whether they are online or offline, and to share information about their streams, such as the title and description of the stream.
-
-The specific goal of this change is to send an ActivityPub "Leave" activity to all federated Owncast servers when the local server's live stream ends.
-
-The recieving server should update the status of the local server to offline when it receives this activity, and update the server metadata accordingly.
-
-### ActivityPub Support
-
-- Accept an ActivityPub "Leave" activity from a federated Owncast server when its live stream ends. https://www.w3.org/TR/activitystreams-vocabulary/#dfn-leave
-- Send an ActivityPub "Leave" activity from the local Owncast server when its live stream ends. https://www.w3.org/TR/activitystreams-vocabulary/#dfn-leave
-- In both cases the custom server metadata should be included.
-- In both cases expect the actor to be the Owncast server itself.
-- In both cases expect the object to be the URL of the federated server.
-- Use the existing ActivityPub infrastructure in Owncast to handle the sending, delivery and receipt of these activities via the inbox, outbox and worker queues.
-
-### Database Changes
-
-- No database changes are required for this functionality.
-
-## Requirements
-- For each federated server exchange the following information:
- - Server logo
- - Server name
- - Stream title
- - Stream description
- - Tags associated with the stream
diff --git a/docs/features/server-federation-security.md b/docs/features/server-federation-security.md
deleted file mode 100644
index aac6fdd70a..0000000000
--- a/docs/features/server-federation-security.md
+++ /dev/null
@@ -1,65 +0,0 @@
-# Featured Streams: Security & Trust Model
-
-Featured streams let an Owncast server display a small directory of other
-Owncast servers and their live status. Because ActivityPub is an open protocol,
-any server can send anything and assert any identity. This document describes
-what is and isn't guaranteed, so operators understand the trust boundary.
-
-## What is guaranteed
-
-- **The directory is admin-curated.** Entries in your featured directory are
- created only by an admin adding a server URL. No inbound ActivityPub activity
- can insert an entry — inbound `Offer`/`Accept`/`Leave` only *update* rows that
- already exist. A remote server cannot put itself on your list.
-- **The link is the URL you entered, and it is immutable.** The link target for
- an entry is the `https` URL the admin typed (non-`https` is rejected). No
- inbound handler ever changes it, so a remote server cannot repoint your
- directory entry somewhere else after the fact.
-- **Status and metadata are bound to that host.** Inbound activities are
- HTTP-signature verified, and the activity's `actor` must share the host of the
- verified signing key (a server cannot sign with its own key while claiming to
- be another). The featured-follow also pins the resolved actor to the host of
- the URL you entered. Together these ensure an entry's live status and metadata
- genuinely come from the server at that URL.
-- **The real hostname is shown.** The public stream card displays the entry's
- hostname (from the immutable URL), so a remote server cannot fully masquerade
- behind a spoofed display name.
-- **Being featured requires approval.** Another server asking to feature your
- stream appears under "Requests to feature your stream" and must be approved by
- an admin, regardless of whether your server otherwise accepts follows
- automatically.
-
-## What is NOT guaranteed (inherent to an open protocol)
-
-- **"Is this really Owncast?" is self-asserted.** Adding a server validates its
- `nodeinfo` (software name `owncast`, ActivityPub enabled), but any server can
- serve a `nodeinfo` claiming that. Treat this as a sanity check, not proof. The
- real trust anchor is your own curation plus the guarantees above.
-- **A featured server controls its own name, logo, title and thumbnail.** These
- are supplied by the remote server and can change over time (including
- bait-and-switch). The link, however, always points to the host you vetted, and
- that host is shown in the UI.
-
-## Practical guidance for operators
-
-- Only feature servers you trust; the directory is a curation you stand behind.
-- The shown hostname is the source of truth for where a card leads — judge an
- entry by its hostname, not its display name.
-- If a featured server starts misrepresenting itself, unfeature it.
-
-## Hardening implemented
-
-- HTTP-signature verification binds an activity's `actor` to the signing key's
- host (`services/activitypub/inbox/worker.go`).
-- IRI/actor/key resolution refuses internal/loopback addresses and caps response
- size; redirects are re-validated (`services/activitypub/resolvers/resolve.go`,
- `utils/tlsconfig.go`).
-- Replayed (stale-`Date`) signed requests are rejected within a tolerance window
- (`services/activitypub/inbox/worker.go`).
-- Remote-supplied metadata is length/count clamped before storage
- (`services/activitypub/inbox/offer.go`, `accept.go`).
-- The featured-follow pins the resolved actor to the entered URL's host
- (`services/activitypub/outbox/follow.go`).
-- Remote URLs rendered as links are validated to be `http(s)`
- (`web/components/admin/FederatedServers/FeatureRequests.tsx`), and the public
- card surfaces the real hostname (`web/components/ui/StreamCard/StreamCard.tsx`).
diff --git a/docs/implementation-plan-server-federation-2.md b/docs/implementation-plan-server-federation-2.md
deleted file mode 100644
index 648f6eeca3..0000000000
--- a/docs/implementation-plan-server-federation-2.md
+++ /dev/null
@@ -1,241 +0,0 @@
-# Implementation Plan: Server Federation Phase 2 - ActivityPub Status Updates
-
-## Overview
-This plan outlines the implementation of ActivityPub "Arrive" and "Leave" activity support for Owncast server federation, allowing servers to share online/offline status and stream metadata.
-
-## Current State Analysis
-- ✅ Existing ActivityPub infrastructure (inbox, outbox, workers, crypto, resolvers)
-- ✅ Basic federation enabled with follower support
-- ✅ Frontend components partially exist (FederatedServersTable, useFederatedServers hook)
-- ✅ Existing models.Status struct with StreamTitle field (reusable pattern)
-- ✅ Stream metadata handling patterns in config repository
-- ❌ No database table for federated servers
-- ❌ No Arrive/Leave activity handlers
-- ❌ No API endpoints for federated servers management
-
-## Implementation Plan
-
-### Phase 1: Database Layer
-#### 1.1 Database Schema (Priority: High)
-- **File**: `db/schema.sql`
-- **Action**: Add new table `federated_servers` with fields:
- - `id` (PRIMARY KEY, auto-increment)
- - `iri` (TEXT, UNIQUE) - Server IRI/URL
- - `name` (TEXT) - Server display name
- - `logo_url` (TEXT) - Server logo image URL
- - `is_online` (BOOLEAN, DEFAULT FALSE) - Current online status
- - `stream_title` (TEXT) - Current stream title (when online)
- - `stream_description` (TEXT) - Current stream description
- - `stream_tags` (TEXT) - JSON array of tags
- - `thumbnail_url` (TEXT) - Stream thumbnail URL
- - `last_seen_online` (TIMESTAMP) - Last time server was seen online
- - `last_status_update` (TIMESTAMP) - Last activity received
- - `added_at` (TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
- - `followed_at` (TIMESTAMP) - When we started following this server
-
-#### 1.2 Database Queries (Priority: High)
-- **File**: `db/query.sql`
-- **Actions**: Add SQLC queries for:
- - `GetFederatedServers` - List all federated servers
- - `GetFederatedServer` - Get server by IRI
- - `AddFederatedServer` - Add new federated server
- - `UpdateFederatedServerStatus` - Update server online/offline status
- - `UpdateFederatedServerMetadata` - Update stream metadata
- - `RemoveFederatedServer` - Remove server from federation
-
-#### 1.3 Generated Go Models (Priority: High)
-- **File**: Auto-generated via sqlc
-- **Action**: Run `sqlc generate` to create Go structs
-
-### Phase 2: ActivityPub Activity Handlers
-#### 2.1 Arrive Activity Handler (Priority: High)
-- **File**: `activitypub/inbox/arrive.go` (new)
-- **Function**: `handleArriveInboxRequest(context.Context, vocab.ActivityStreamsArrive) error`
-- **Logic**:
- - Extract actor IRI (the federated Owncast server)
- - Extract object URL (should be the server URL)
- - Validate actor is a known federated server
- - Update server status to online
- - Extract stream metadata from activity (title, description, tags, thumbnail)
- - Update `last_seen_online` and `last_status_update` timestamps
- - Follow existing patterns from `models.Status` for stream metadata handling
-
-#### 2.2 Leave Activity Handler (Priority: High)
-- **File**: `activitypub/inbox/leave.go` (new)
-- **Function**: `handleLeaveInboxRequest(context.Context, vocab.ActivityStreamsLeave) error`
-- **Logic**:
- - Extract actor IRI (the federated Owncast server)
- - Extract object URL (should be the server URL)
- - Validate actor is a known federated server
- - Update server status to offline
- - Clear current stream metadata
- - Update `last_status_update` timestamp
-
-#### 2.3 Worker Integration (Priority: High)
-- **File**: `activitypub/inbox/worker.go`
-- **Action**: Update resolver call to include new activity handlers:
- ```go
- resolvers.Resolve(context.Background(), request.Body,
- handleUpdateRequest, handleFollowInboxRequest, handleLikeRequest,
- handleAnnounceRequest, handleUndoInboxRequest, handleCreateRequest,
- handleArriveInboxRequest, handleLeaveInboxRequest)
- ```
-
-### Phase 3: Database Persistence Layer
-#### 3.1 Federated Servers Repository (Priority: High)
-- **File**: `persistence/federatedservers/federatedservers.go` (new)
-- **Functions**:
- - `GetFederatedServers() ([]models.FederatedServer, error)`
- - `GetFederatedServer(iri string) (*models.FederatedServer, error)`
- - `AddFederatedServer(iri, name, logoURL string) error`
- - `UpdateServerStatus(iri string, isOnline bool, metadata *FederatedStreamUpdate) error`
- - `RemoveFederatedServer(iri string) error`
-
-#### 3.2 Models (Priority: High)
-- **File**: `models/federatedserver.go` (new)
-- **Analysis**: Existing `models.Status` already contains `StreamTitle`, so we'll align with existing patterns
-- **Structs**:
- ```go
- type FederatedServer struct {
- ID int `json:"id"`
- IRI string `json:"iri"`
- Name string `json:"name"`
- LogoURL *string `json:"logoUrl,omitempty"`
- IsOnline bool `json:"isOnline"`
- StreamTitle *string `json:"streamTitle,omitempty"`
- StreamDescription *string `json:"streamDescription,omitempty"`
- StreamTags []string `json:"tags,omitempty"`
- ThumbnailURL *string `json:"thumbnailUrl,omitempty"`
- LastSeenOnline *time.Time `json:"lastSeenOnline,omitempty"`
- LastStatusUpdate *time.Time `json:"lastStatusUpdate,omitempty"`
- AddedAt time.Time `json:"addedAt"`
- FollowedAt *time.Time `json:"followedAt,omitempty"`
- }
-
- // Lightweight struct for passing stream metadata in ActivityPub handlers
- // Reuses existing patterns from models.Status
- type FederatedStreamUpdate struct {
- Title *string `json:"title,omitempty"`
- Description *string `json:"description,omitempty"`
- Tags []string `json:"tags,omitempty"`
- ThumbnailURL *string `json:"thumbnailUrl,omitempty"`
- }
- ```
-
-### Phase 4: API Endpoints
-#### 4.1 OpenAPI Specification (Priority: Medium)
-- **File**: `openapi.yaml`
-- **Action**: Add API definitions for federated servers endpoints:
- - `GET /api/federation/servers` - List federated servers (public)
- - **Tags**: `['Internal', 'Federation']`
- - **Security**: None (public endpoint)
- - `POST /api/admin/federation/servers` - Add federated server (admin)
- - **Tags**: `['Internal', 'Admin', 'Federation']`
- - **Security**: `BasicAuth: []` (requires admin authentication)
- - `DELETE /api/admin/federation/servers/{id}` - Remove server (admin)
- - **Tags**: `['Internal', 'Admin', 'Federation']`
- - **Security**: `BasicAuth: []` (requires admin authentication)
-- **Response Types**: Follow existing patterns with `401BasicAuth` responses for admin endpoints
-
-#### 4.2 Code Generation (Priority: Medium)
-- **Action**: Run `build/gen-api.sh` to generate API stubs from OpenAPI spec
-- **Note**: This must be done before implementing handlers since generated code provides interfaces
-
-#### 4.3 API Handlers (Priority: Medium)
-- **File**: `webserver/handlers/admin/federatedservers.go` (new)
-- **Functions**:
- - `GetFederatedServers(w http.ResponseWriter, r *http.Request)`
- - `AddFederatedServer(w http.ResponseWriter, r *http.Request)`
- - `RemoveFederatedServer(w http.ResponseWriter, r *http.Request)`
-- **Note**: Implement generated interfaces from step 4.2
-
-#### 4.4 Router Integration (Priority: Medium)
-- **File**: `webserver/router/router.go`
-- **Action**: Add route mappings for federated servers endpoints
-
-### Phase 5: Frontend Updates
-#### 5.1 API Integration (Priority: Medium)
-- **File**: `web/hooks/useFederatedServers.tsx`
-- **Action**: Update API endpoints to match backend implementation
-- **Status**: Already mostly implemented, needs minor adjustments
-
-#### 5.2 Admin Interface (Priority: Low)
-- **Files**:
- - `web/components/admin/FederatedServers/FederatedServersTable.tsx`
- - `web/components/admin/FederatedServers/AddServerForm.tsx`
-- **Action**: Verify compatibility with new backend API structure
-
-#### 5.3 Public Interface (Priority: Low)
-- **Files**:
- - `web/components/ui/StreamsTab/StreamsTab.tsx`
- - `web/components/ui/Content/Content.tsx`
-- **Action**: Display federated servers list on main interface
-
-### Phase 6: Testing
-#### 6.1 Unit Tests (Priority: Medium)
-- **Files**:
- - `activitypub/inbox/arrive_test.go` (new)
- - `activitypub/inbox/leave_test.go` (new)
- - `persistence/federatedservers/federatedservers_test.go` (new)
-
-#### 6.2 API Integration Tests (Priority: Medium)
-- **File**: `test/automated/api/010_federation_servers.test.js` (new)
-
-#### 6.3 Browser Tests (Priority: Low)
-- **File**: `test/automated/browser/cypress/e2e/federation/federated_servers.cy.js` (new)
-
-## Implementation Order (Recommended)
-1. **Database Schema & Queries** (Essential foundation)
-2. **ActivityPub Handlers** (Core functionality)
-3. **Persistence Layer** (Data access)
-4. **API Specification & Code Generation** (Generate interfaces first)
-5. **API Handler Implementation** (Implement generated interfaces)
-6. **Frontend Integration** (User interface)
-7. **Testing** (Quality assurance)
-
-## Technical Considerations
-### Security
-- Validate all incoming ActivityPub activities using existing signature verification
-- Sanitize and validate all metadata fields (titles, descriptions, URLs)
-- Rate limiting for status updates from federated servers
-
-### Performance
-- Consider caching federated server list for public API
-- Implement pagination for server lists if needed
-- Index database appropriately for common queries
-
-### Error Handling
-- Graceful handling of malformed ActivityPub activities
-- Retry logic for failed server communications
-- Proper logging for debugging federation issues
-
-### Data Integrity
-- Ensure atomic updates to server status
-- Handle duplicate activities gracefully
-- Clean up offline servers periodically
-
-### Code Reuse & Consistency
-- **Leverage existing patterns**: Stream metadata handling should follow `models.Status` patterns
-- **Reuse configuration patterns**: Stream title/description handling similar to existing config repository methods
-- **Consistent JSON field naming**: Match existing API response structures where possible
-
-## Dependencies
-- Existing ActivityPub infrastructure ✅
-- SQLC for query generation ✅
-- Go-fed ActivityStreams library ✅
-- Existing federation configuration ✅
-
-## Rollout Strategy
-1. Deploy database migrations
-2. Deploy backend changes with feature flag (if desired)
-3. Deploy frontend changes
-4. Enable feature in production
-
-## Success Criteria
-- ✅ Owncast servers can exchange Arrive/Leave activities
-- ✅ Server online/offline status is accurately tracked
-- ✅ Stream metadata is properly synchronized
-- ✅ Admin interface allows management of federated servers
-- ✅ Public interface displays federated servers
-- ✅ All tests pass
-- ✅ No performance degradation
\ No newline at end of file
diff --git a/docs/plugin-auth-gate-design.md b/docs/plugin-auth-gate-design.md
deleted file mode 100644
index 90418f6464..0000000000
--- a/docs/plugin-auth-gate-design.md
+++ /dev/null
@@ -1,349 +0,0 @@
-# Plugin-based Viewer Authentication ("Auth Gate"): Design
-
-Status: implemented. See `pluginhost/authgate.go` for the middleware,
-`pluginhost/pluginhost.go` for the settings store and admin endpoint, and
-`yp/` for directory behavior.
-
-## Goal
-
-Let operators require viewers to authenticate before they can access an Owncast
-instance, where the *authentication method* is supplied entirely by a plugin
-(OAuth, Discord, x.com, magic links, SAML, anything reachable over HTTP). This
-replaces the high-friction "put Vouch/oauth2-proxy in front of Owncast" pattern
-with a first-class plugin capability.
-
-The plugin is the **identity provider**; Owncast core is the **gatekeeper and
-session authority**.
-
-## Scope decision: gate the web surface, with an operator-chosen edge
-
-The gate is opt-out. Every request is challenged unless a named exemption
-applies, so the viewer page (`/`), `/api/config`, chat, and the rest of the
-public API are behind it.
-
-The operator chooses one cumulative access mode. Native players such as VLC,
-QuickTime, mobile apps, and restreamers cannot complete a browser login or carry
-a session cookie. Any mode that gates `/hls/*` blocks those players.
-
-The access mode is stored per gate plugin and selected on the plugin's
-**Authentication** tab:
-
-| Access mode | Effect |
-|---|---|
-| Website only (default) | The web UI requires sign-in. `/hls/*`, `/api/status`, and directory listing stay public. |
-| Website, video players, and other resources | Also gates `/hls/*`. Native players without a browser session are blocked. `/api/status` and directory listing stay public. |
-| Website, video players, and server status requests | Gates the web UI, `/hls/*`, and `/api/status`. Directory listing is disabled. |
-
-The modes are cumulative. There is no status-only mode that hides
-`/api/status` while leaving HLS public.
-
-The default is deliberately the least disruptive. Enabling a gate on a running
-instance protects the website without breaking players or monitoring that
-already work. Operators who need the video itself private select one of the
-stream-protection modes and accept losing native players.
-
-### External storage (S3/CDN) caveat: document, do not block
-
-Under S3 storage, `rewritePlaylistLocations` rewrites playlists to **absolute
-remote URLs**, so segments are fetched directly from S3/CDN and never touch the
-Owncast server. The gate cannot see those requests.
-
-- Gating `/hls/stream.m3u8` still prevents an unauthenticated visitor from
- *discovering* the current segment list.
-- But under S3 the segment URLs themselves are world-readable, so a *leaked or
- shared* segment URL remains fetchable.
-
-Therefore: **stream protection + local storage = airtight. Stream protection +
-S3 = good friction, not airtight.** This is a documentation item for operators
-and plugin authors, not a hard block.
-
-## Architecture
-
-### The plugin is out of the per-request hot path
-
-Once auth is on, every non-exempt request hits the gate. Under stream
-protection that includes each HLS segment (a live viewer pulls a new segment
-every ~2-4s × N viewers). Calling into the plugin's embedded JS/Python engine
-per request would melt the server. So:
-
-- **The plugin runs the login flow only** (infrequent: ~once per viewer session),
- over its existing `onHttpRequest` routes under `/plugins/<slug>/*`.
-- **Core mints and checks a signed session cookie.** The per-request gate check
- is pure Go (verify signature + expiry), no DB lookup and no engine call.
-- **The access policy is memoized.** Settings are read from the plugin's KV
- namespace once and cached in an atomic snapshot, so the hot path does not
- touch storage either. A read failure is not cached: it falls back to the
- defaults for that request and retries on the next one.
-
-### Three tiers of checking
-
-| Tier | When | Cost | What happens |
-|------|------|------|--------------|
-| 1 | every non-exempt request | Go-only: verify cookie signature + expiry | valid passes. Invalid or absent gets a 302 for GET/HEAD, 401 otherwise |
-| 2 | `/` (index navigation) only, with a valid session | optional engine call: `onAuthCheck` | re-validate against provider, returning `ok`/`refresh`/`deny` |
-| 3 | n/a | none | no per-request denylist, revocation is Tier 2 |
-
-Which requests are exempt is decided by a single named list in
-`pluginhost/authgate.go`. Adding a bypass means adding a named, individually
-testable rule there, in the open:
-
-| Exemption | Why | Conditional on |
-|---|---|---|
-| `admin` | `/admin/*` and `/api/admin/*` carry their own credential and have their own gate, so an operator can always disable a broken gate | never |
-| `static-assets` | files that actually exist in the embedded web build, which the admin app needs to render. HTML entry points are excluded, so the viewer UI stays gated | never |
-| `active-gate-plugin` | the login screen and OAuth callback must be reachable while signed out. Only the *active* gate's namespace, not every plugin | never |
-| `external-api` | `/api/integrations/*` validates its own bearer token per route | never |
-| `directory-api` | `/api/yp` is anonymous public metadata by design, and the YP handler itself refuses when listing is off | never |
-| `third-party-player` | `/hls/*` for players that cannot log in | off when "protect the stream" is on |
-| `stream-status` | `/api/status` for uptime monitors | off when "block stream status" is on |
-
-A valid session is checked before any exemption, so a signed-in viewer is never
-bounced off a path the policy closed to anonymous callers.
-
-### The session cookie = a signed carrier for the existing access token
-
-We do **not** invent a new identity primitive. Owncast already identifies users
-by **access token** (`GetUserByToken`) and already links external identities to
-users via `AddAuth(userID, authToken, authType)` / `GetUserByAuth` — this is how
-IndieAuth and Fediverse auth work today. **A plugin auth gate is just a new
-`AuthType`** feeding the same machinery.
-
-The gate cookie is a **signed envelope carrying that user's existing access
-token** plus a gate-session expiry:
-
-```
-cookie = sign({ accessToken, exp }, coreSecret)
-```
-
-Two readers, one cookie, both keyed on the access token you already understand:
-
-| Path | Reader | Mechanism |
-|------|--------|-----------|
-| `/`, gated `/hls/*`, page assets | gate | verify signature + expiry → pass (no DB; this is why it's signed) |
-| `/ws`, chat REST | chat | extract `accessToken` → `GetUserByToken(accessToken)` → existing chat identity path |
-
-Why signed rather than a raw token in a cookie:
-1. **Hot path** — the gate trusts `sig+exp` without a `GetUserByToken` per segment.
-2. **Session expiry** — Owncast access tokens are long-lived; the envelope's
- `exp` gives the *gate session* its own sliding lifetime without changing the
- token model.
-
-Backward compatible: the existing `localStorage` + `?accessToken=` path still
-works on ungated servers; on a gated server, chat gains a "no query param? read
-the access token from the gate cookie" fallback.
-
-## Authoring surface
-
-### New permissions
-
-- **`auth.gate`** — be the gate plugin; use `grantSession` / `endSession`.
-- **`users.register`** — create/link an *authenticated* user (separate so a
- non-gating chat-auth plugin, e.g. an IndieAuth-style "verified member" badge,
- can use identity without gating). Host fn: `owncast.users.register` (plural, to
- match existing `users.read` / `users.list`).
-
-### New host functions
-
-```ts
-// Identity — find-or-create the user for an external identity, link + authenticate it.
-// Pass the raw external id. Core stores your slug in the auth row's provider
-// column and scopes lookups to (provider, authId), so plugins cannot collide
-// or spoof each other's users. Do not prefix authId yourself.
-owncast.users.register({ authId: string, displayName?: string, scopes?: string[] })
- : { userId: string }
-
-// Session — issue the signed gate cookie carrying that user's access token.
-// Only valid inside onHttpRequest (needs a live response to attach Set-Cookie).
-owncast.auth.grantSession({ userId: string, ttl?: number }): void
-
-// Self-logout — clear the current viewer's gate cookie on this response.
-// Only valid inside onHttpRequest. Plugin still controls the redirect (and may
-// bounce to the provider's logout for single-logout).
-owncast.auth.endSession(): void
-```
-
-Core owns the cookie end to end: it reserves the cookie name, mints + signs, and
-attaches `Set-Cookie` to the in-flight `onHttpRequest` response. The plugin never
-sees or sets the signed token, so it can't forge or leak it.
-
-### New optional hook
-
-```ts
-// Fires ONLY on '/' navigation (Tier 2). Optional. Core-driven (not a host fn).
-// Lets the plugin re-validate against the provider and refresh/deny.
-onAuthCheck(input: { user: { userId, displayName, scopes, authId } }):
- | { action: "ok" } // pass, cookie unchanged
- | { action: "refresh", displayName?, scopes?, ttl? } // still good; re-mint cookie
- | { action: "deny", reason?: string } // clear cookie, bounce to login
-
-// Error / timeout in onAuthCheck → fail closed (treat as deny for that request).
-```
-
-Revocation model: a plugin that wants to kick a user (deleted upstream) returns
-`deny` from `onAuthCheck` on that user's next `/` load. **Accepted limitation:** a
-revoked viewer with an open tab keeps pulling segments until they reload `/` or
-the cookie expires — so the cookie TTL is the hard backstop (see TTL below).
-There is intentionally **no per-request denylist and no cross-user `revoke()`**.
-
-## Lifecycle & enforcement
-
-### Designation and arming
-
-- A plugin declares `auth.gate`. **Declaring it does nothing on its own.**
-- **Arming = enabling the plugin** via the existing enable/disable lifecycle
- (`services/plugins` Manager). There is **no separate "Require viewer auth"
- toggle** — that framing would falsely imply built-in Owncast auth. The plugin's
- admin page states plainly: *"While enabled, all viewers must authenticate
- through this plugin before accessing the site."*
-- **`Manager.Enable` refuses to enable a second `auth.gate` plugin** while one is
- already enabled ("disable X first"). Centralized enablement means two can never
- be live at once — no load-order tie-break needed.
-- Configure-before-live and fast-off-switch fall out for free: configure while
- discovered-but-disabled, enable to go live; disable to drop the gate instantly.
-
-### Control loop (Model 1: plugin = web app)
-
-```
-GET / gate: no cookie → 302 /plugins/<slug>/?return_to=%2F
- (gate-plugin namespace is exempt)
-GET /plugins/<slug>/ plugin renders login screen ("Sign in with GitHub")
- → 302 to provider (github.com/login/oauth/authorize?...&state=<rand>)
-GET /plugins/<slug>/callback?code&state
- plugin: validate state (KV), exchange code (fetch), fetch user, enforce org
- → owncast.users.register({ authId, displayName }) → { userId }
- → owncast.auth.grantSession({ userId }) → core attaches Set-Cookie
- → return 302 → <sanitized return_to>
-GET / gate: cookie valid → Tier 2 onAuthCheck → ok → render
-GET /hls/3.ts gate: cookie valid → serve segment
-WS /ws chat: cookie → accessToken → GetUserByToken → "octocat"
-```
-
-- **Entry path by convention:** `/plugins/<slug>/`. No manifest field.
-- **`return_to`** is appended by core and **sanitized to same-origin absolute
- paths** (reject `//host`, `https://…`) to avoid an open redirect.
-
-### Fail-closed
-
-The gate's posture is **decoupled from plugin runtime health**:
-
-- armed + plugin healthy → normal flow
-- armed + plugin unavailable (crashed, failed to load, errored, hit the
- auto-disable strike threshold) → **deny all viewer traffic**, serve a static
- core-owned "Authentication temporarily unavailable" page. **Never open.**
-- **admin always bypasses** (existing Basic Auth) to fix config or disable.
-- **already-valid sessions survive** an outage (cookie check needs no plugin).
-
-The existing auto-disable-on-strikes must resolve to **closed + loud admin
-alert**, never to a silently open site.
-
-### Where the access policy lives
-
-The access mode is host-owned, not plugin config. A gate plugin cannot widen or
-narrow its own reach. It is keyed per plugin under the reserved KV key
-`owncast.auth-gate-settings` in that plugin's namespace, so each gate keeps its
-own policy. Switching gates does not carry one provider's choice over to
-another.
-
-The admin UI shows an **Authentication** tab for any installed plugin that
-declares `auth.gate`, whether or not it is currently enabled, so an operator can
-set the mode before arming the gate. It is backed by
-`GET`/`POST /api/admin/plugins/<slug>/auth-settings`. The endpoint accepts
-`website-only`, `website-and-stream`, or `website-stream-and-status` as the
-`accessMode`. It returns 404 for plugins that do not declare the permission and
-rejects unknown fields or unsupported modes.
-
-### Directory interaction
-
-`/api/yp` is never challenged by the gate. The Owncast Directory fetches it
-anonymously: the registration key travels in the server-to-directory ping, not
-in the directory's read of this endpoint, so there is no credential to check.
-The payload is public metadata by design.
-
-The `website-stream-and-status` mode does not gate `/api/yp`. It switches the
-directory off. `Host.DirectoryAvailable()` reports the policy, and the YP
-service consults it in two places: `GetYPResponse` answers 404, and the outbound
-ping is skipped so the instance stops announcing itself to a directory that can
-no longer read it. A listed stream cannot function without a readable status
-endpoint, so status protection and directory availability move together.
-
-### Session credential details
-
-- **Stateless signed cookie**, `HttpOnly`, `Secure`, `SameSite=Lax` (Lax, not
- Strict — the provider callback is a cross-site top-level redirect), `Path=/`.
-- **Signing secret is core's responsibility**: auto-generated on first use,
- persisted in config, core-owned rotation (rotating = invalidate all sessions =
- panic button). Mechanically required: core verifies on the hot path without
- calling the plugin, so core must hold the secret. Plugin authors never touch it.
- (The OAuth *client* secret is a separate, plugin-config concern.)
-- **TTL is plugin-requested** via `grantSession({ ttl })`, defaulting to
- `DefaultSessionTTL` (24h) and capped at `MaxSessionTTL` (30 days). It is a
- real security knob because it is the revocation backstop: `onAuthCheck` only
- runs on a page load, so an idle revoked viewer lingers until the cookie
- expires.
-
-## The chat / identity bridge
-
-A gate login produces an authenticated chat identity automatically, because
-`users.register` creates/links a real Owncast `User` (`Authenticated=true`,
-display name seeded from the provider) and the cookie carries that user's access
-token. Required core change: **`/ws` connect (and chat REST) gain a fallback —
-no `?accessToken=` query param → read the access token from the gate cookie →
-`GetUserByToken`.** No token is ever shuttled into the browser's localStorage.
-
-## Worked example: "Sign in with GitHub" plugin
-
-`manifest.json` permissions:
-`["auth.gate", "users.register", "http.serve", "network.fetch", "storage.kv", "server.read"]`
-with `network.allowedHosts: ["github.com", "api.github.com"]` and config fields
-`clientId`, `clientSecret`, `allowedOrg`.
-
-Handlers: `onHttpRequest` (routes `/`, `/callback`, `/logout`) + optional
-`onAuthCheck` (re-verify org membership on each `/`).
-
-- The plugin learns its own public base URL from `owncast.server.info()` (errors
- if the operator hasn't set the server URL) to build `redirect_uri` and to show
- the admin the exact callback URL to register at GitHub:
- `<serverURL>/plugins/github-auth/callback`.
-- CSRF `state` stored in `storage.kv` with a short TTL, keyed to `return_to`.
-
-## Still deferred
-
-- **Hard per-session revocation** (KV denylist). Revocation stays at page-load
- granularity via `onAuthCheck`, with the cookie TTL as the backstop.
-- **Signing secret rotation UI.** The secret is generated and persisted
- automatically, but rotating it (which invalidates every session) has no admin
- control yet.
-- **Cross-gate policy migration.** Access settings are per plugin, so switching
- gate providers means setting the policy again on the new one. That is the
- intended behavior, not a gap, but an operator may be surprised by it.
-
-## Where the code lives
-
-**Owncast core:**
-- `pluginhost/authgate.go`: middleware, exemption list, gate decision,
- `onAuthCheck` dispatch, fail-closed page.
-- `pluginhost/pluginhost.go`: `AuthGateSettings`, the memoized settings store,
- `DirectoryAvailable`, and the `auth-settings` admin endpoint.
-- `services/plugins/authsession.go`: cookie mint/verify, TTL clamping, the
- request-scoped grant sink.
-- `services/plugins/manager.go`: `ActiveAuthGate`, `IsAuthGate`, and the
- single-gate guard in `Enable`.
-- `yp/`: directory ping and `/api/yp`, both gated on `DirectoryAvailable`.
-- `web/components/admin/plugins/AuthGateSettingsForm.tsx`: the Authentication
- tab.
-
-**Plugin SDK** (`owncast-plugin-sdk`, JS and Python in parallel): the
-`onAuthCheck` handler type, facades for `users.register`, `auth.grantSession`,
-and `auth.endSession`, permission docs, and the `github-auth` / `basic-auth`
-examples.
-
-## Test coverage
-
-| Area | Where |
-|---|---|
-| Cookie sign/verify, expiry, tampering | `services/plugins/authsession_test.go` |
-| Single-gate guard, `ActiveAuthGate`, `IsAuthGate` | `services/plugins/manager_authgate_test.go` |
-| Exemption list and gate decision, full policy matrix | `pluginhost/authgate_test.go` |
-| Middleware: credential rejection, 302/401 split, identity propagation, fail-closed, revocation clearing the cookie | `pluginhost/authgate_middleware_test.go` |
-| Settings endpoint, persistence, corrupt-value fallback | `pluginhost/authgate_settings_test.go` |
-| Directory 404 and ping suppression | `yp/api_test.go` |
diff --git a/docs/plugins.md b/docs/plugins.md
deleted file mode 100644
index af280b7810..0000000000
--- a/docs/plugins.md
+++ /dev/null
@@ -1,201 +0,0 @@
-# Plugin host integration
-
-How Owncast runs plugins and how the plugin system is wired into the server.
-This is a contributor-facing overview of the **host side**; it is not a guide
-to writing plugins.
-
-## What plugins are
-
-A plugin is a sandboxed WebAssembly module (authors write JavaScript/TypeScript
-and compile it to wasm). Owncast loads plugins and runs them in-process via
-[Extism](https://extism.org), which uses [Wazero](https://wazero.io) — a pure-Go
-wasm runtime, so there is no CGo and no external process. A plugin can only do
-what its manifest declares as **permissions**, and it can only reach the host
-through a fixed set of **host functions** Owncast provides.
-
-Plugins are optional infrastructure: if the runtime or a plugin fails to start,
-Owncast logs and continues rather than aborting startup.
-
-## Where the code lives
-
-| Path | Responsibility |
-|---|---|
-| `services/plugins/` | The plugin **runtime** — discovery/enable lifecycle (`manager.go`), event + filter fan-out (`dispatcher.go`), the HTTP handler for `/plugins/<name>/*` (`server.go`), the host functions and their types/permissions (`hostfns.go`), the driver-agnostic SQL request validation and result limits (`sqlrunner.go`), the KV store interface (`kv/`), and the SSE hub (`sse.go`). |
-| `pluginhost/` | The **Owncast integration layer** — builds the runtime's `HostEnv` from Owncast services, starts the manager, exposes the HTTP handlers, and owns each plugin's SQLite database (`sqlite.go`). This is the only package that knows about both the runtime and Owncast's internals. |
-
-`services/plugins/` is a **vendored copy** of the upstream plugin SDK's
-`host-runtime/plugin` package (`github.com/owncast/plugin-sdk`). See
-[Keeping the runtime in sync](#keeping-the-runtime-in-sync-with-the-sdk) below —
-this is the most important thing to understand before changing it.
-
-## How a plugin call reaches Owncast
-
-The runtime defines host functions in `services/plugins/hostfns.go`, but those
-functions don't know anything about Owncast. Each one just calls a
-function-pointer field on a `HostEnv` struct, e.g.:
-
-```go
-// services/plugins/hostfns.go — runtime, Owncast-agnostic
-func hostVideoConfigRead(env *HostEnv) extism.HostFunction { /* calls env.VideoConfig() */ }
-
-type HostEnv struct {
- VideoConfig func() VideoConfig // wired by the embedding host
- // ...
-}
-```
-
-`pluginhost/pluginhost.go` is where Owncast **fills in** those pointers with
-real services. `New(ctx, Deps)` constructs the `HostEnv` and `wirePluginHostEnv`
-sets every field, grouped into helpers:
-
-```go
-// pluginhost/pluginhost.go — Owncast wiring
-func wireVideoConfigHostFns(env *plugins.HostEnv, deps Deps) {
- cfg := deps.ConfigRepository
- env.VideoConfig = func() plugins.VideoConfig {
- variants := cfg.GetStreamOutputVariants()
- // map Owncast's models.StreamOutputVariant -> the plugin's StreamVariant
- // ...
- }
- env.WriteVideoConfig = func(pluginName string, u plugins.VideoConfigUpdate) error {
- // persist via cfg.SetStreamLatencyLevel / SetVideoCodec / SetStreamOutputVariants
- }
-}
-```
-
-Two layers, two responsibilities:
-
-- **`hostfns.go`** defines the plugin-facing API: the host-function names, the
- permissions that gate them, and the data **types** plugins receive
- (`VideoConfig`, `StreamBroadcaster`, …). This must match the SDK.
-- **`pluginhost.go`** is the adapter: it reads Owncast's real state
- (`ConfigRepository`, `stream.Service`, chat, …) and **maps Owncast's internal
- `models.*` types into the plugin types**. This is Owncast-specific and is
- expected to differ from the SDK.
-
-The plugin types are deliberately separate from `models.*`: they're a curated,
-stable contract shared with plugins and the TypeScript SDK, so internal model
-refactors don't silently change what plugins see. The mapping is the price of
-that decoupling, and it lives at the boundary on purpose.
-
-## What's wired
-
-`wirePluginHostEnv` wires these subsystems (each behind its declared permission):
-
-- **Chat send** (`chat.send`) — posts under the plugin's own provisioned bot
- identity (`newPluginChatbotProvisioner`), plus system/action messages and DMs.
-- **Chat read / moderation** (`chat.history`, `chat.moderate`) — history,
- connected clients, delete message, kick client.
-- **Server reads** (`server.read`) — stream status, server info, socials,
- federation, metadata tags, and read-only inbound-broadcast telemetry
- (`stream.Service.GetBroadcaster()`).
-- **Video config** (`videoconfig.read` / `videoconfig.write`) — read and
- partially update output variants, codec, and latency via `ConfigRepository`.
- Writes **persist only**; they take effect on the next stream start (the admin
- UI already shows this), so the host deliberately does **not** restart a live
- transcoder.
-- **Users** (`users.read` / `users.moderate`) — list/get users, set enabled,
- ban IP.
-- **Notifications** (`notifications.send`) — Discord, browser push, fediverse.
-- **Storage** — everything a plugin persists lives under one directory,
- `data/plugin-storage/<slug>/`, so an operator has a single place to look, back
- up, or delete. Inside it, `files/` is the `storage.fs` sandbox and `db/` holds
- the `storage.sql` database. KV is separate, backed by Owncast's datastore
- (`newDatastoreKVStore`), and `storage.upload` publishes browser-accessible
- assets under `public/`.
- On the first startup after upgrading, existing `data/plugin-data/<slug>/`
- directories are renamed into the new `files/` location before plugins load.
- A conflicting destination stops plugin startup rather than hiding or
- overwriting either copy.
-- **Filesystem** (`storage.fs`) — a private, sandboxed filesystem rooted at
- `data/plugin-storage/<slug>/files/` the plugin can read/write/list/delete
- within. The host rejects any path that escapes it, and the bytes are never
- served over HTTP.
-- **SQL** (`storage.sql`) — one private SQLite database per plugin at
- `data/plugin-storage/<slug>/db/plugin.db`. The sandbox handed to `storage.fs`
- is `files/`, so `db/` is not a path the filesystem API refuses but one it
- cannot express. That is load-bearing rather than tidiness: `max_page_count`
- only refuses to grow a database, so a plugin able to write its own database
- file would pre-seed one already over its quota. Reserving filenames in a shared
- directory would be the fragile version, since it would have to track SQLite's
- journal and WAL sidecar naming forever. The quota walk covers `files/` only, so
- the two limits stay independent. A SQLite authorizer denies
- `ATTACH`/`DETACH`, every `PRAGMA`, temp-schema DDL (by
- schema name, since SQLite reports `CREATE TABLE temp.x` as ordinary DDL), and
- `load_extension`, which is what makes the 128 MiB size cap a real quota rather
- than a value the plugin can raise. Results are capped at 1 MiB and 10000 rows,
- a call at 2 seconds, and each `exec` runs as one host-owned transaction.
- Plugin databases are not part of Owncast's database backups.
- `services/plugins/sqlrunner.go` holds the driver-agnostic request validation
- and result limits, `services/plugins/sqldenied.go` refuses the same statements
- the authorizer refuses so the SDK's hosts can agree with us without a cgo
- driver, and `pluginhost/sqlite.go` owns the driver configuration, the
- authorizer, per-plugin files, and the lifecycle.
-- **HTTP** (`http.serve`, `http.sse`) — `req.authenticated` / `req.user` from
- Owncast's auth middleware, plus the SSE hub for server-pushed events.
-
-## Events and filters
-
-Owncast and plugins communicate through a shared dispatcher
-(`services/dispatcher`), injected as `Deps.Events`:
-
-- Owncast **publishes** events (chat messages, stream lifecycle, moderation, …)
- to that dispatcher. `pluginhost` registers a listener
- (`newPluginEventListener`) that forwards them to plugins' `on_event` handlers.
-- For chat, `pluginhost` registers a **filter** (`newPluginChatFilter`) so
- plugins' `filterChatMessage` handlers run on inbound messages before they're
- broadcast (redact, drop, rewrite).
-- Plugins can also **emit** custom events to each other. The manager prefixes
- each custom notification hook with its declaring plugin's slug, so a plugin
- declaring `foo` owns `<slug>.foo`. Emitters target that fully qualified name.
- The dispatcher removes the owner prefix before calling the plugin's local
- handler. A custom hook that would collide with a built-in event is rejected.
- `env.Emit` is wired to the runtime's live dispatcher after the manager starts.
-
-## Lifecycle, persistence, and HTTP
-
-- **Discovery / enable:** the manager scans `<data>/plugins/` and tracks plugins
- as *discovered* vs *enabled*. Files are never auto-loaded; an admin enables
- them. The enabled set persists through `configEnabledStore` (Owncast's
- datastore, key `plugins.enabled`) rather than a JSON file.
-- **HTTP:** `Host.Handler()` serves `/plugins/<name>/*` (mounted in the chi
- router). `Host.AdminHandler()` serves the admin API: `GET /api/admin/plugins`,
- `POST /api/admin/plugins/<name>/{enable,disable,reload}`, and the public
- `GET /api/plugins/actions`.
-
-## Keeping the runtime in sync with the SDK
-
-`services/plugins/` is a copy of the SDK's runtime. The **implementation** may
-diverge for integration (e.g. Owncast adds a datastore-backed enabled-set store),
-but the **plugin API** — the host-function names, permission identifiers, and
-data-type shapes in `hostfns.go` — must stay identical to the SDK. If it
-drifts, plugins built against the SDK can fail to load or receive malformed data
-(this is exactly how the `videoconfig` functions were once missing here).
-
-`services/plugins/contract_test.go` guards this. It re-derives the API surface
-from this repo's `hostfns.go` and compares it to `services/plugins/plugin-contract.json`
-(a snapshot copied verbatim from the SDK). If they differ, the test fails with
-instructions. It checks **only** the API surface, not the `pluginhost.go`
-wiring, so Owncast-specific adapter code is free to differ.
-
-### Adding or changing a host function
-
-Do it in the SDK first, then bring it here:
-
-1. In the SDK (`github.com/owncast/plugin-sdk`), add the host function + type +
- permission to `host-runtime/plugin/hostfns.go`, expose it in the JS SDK, and
- regenerate the snapshot: `UPDATE_CONTRACT=1 go test ./plugin/ -run TestPluginContract`.
-2. Copy the changed runtime files **and** `plugin-contract.json` into
- `services/plugins/` here.
-3. Wire the new `HostEnv` field to real Owncast data in `pluginhost/pluginhost.go`.
-4. `go test ./services/plugins/... ./pluginhost/...` — the contract test passes
- once the two `hostfns.go` copies agree.
-
-For the SDK side of this system, see the SDK repo's `docs/ARCHITECTURE.md`.
-
-## Tests
-
-- Unit tests live in `services/plugins/` and `pluginhost/`.
-- End-to-end coverage is in `test/automated/plugins/`: it builds the SDK's
- example plugins from source, installs them into a running Owncast, and
- exercises chat, filtering, and HTTP through them.
diff --git a/sqlite-schema-diagram.sql b/sqlite-schema-diagram.sql
deleted file mode 100644
index 28fba17cbd..0000000000
--- a/sqlite-schema-diagram.sql
+++ /dev/null
@@ -1,172 +0,0 @@
--- We start a GraphViz graph
-SELECT '
-digraph structs {
-'
-UNION ALL
-
--- Normally, GraphViz' "dot" command lays out a hierarchical graph from
--- top to bottom. However, we aren't just laying out individual nodes,
--- each node is a vertical list of database fields. To prevent GraphViz
--- from snaking arrows all over the place, we constrain it to draw
--- incoming references on the left of each field, and outgoing references
--- on the right. Since that's the way references flow for each database
--- table, we tell GraphViz to lay the whole graph out left-to-right,
--- which makes its job much easier and produces prettier output.
-SELECT '
-rankdir="LR"
-'
-UNION ALL
-
-
--- By default, nodes have circles around them. We will draw our own
--- tables below, we do not want the circles.
-SELECT '
-node [shape=none]
-'
-UNION ALL
-
--- This is the big query that renders a node complete with field names
--- for each table in the database. Because we want raw GraphViz output,
--- our query returns rows with a single string field, whose value is a
--- complex calculation using SQL as a templating engine. This is kind
--- of an abuse, but works nicely nevertheless.
-SELECT
- CASE
- -- When the previous row's table name is the same as this one,
- -- do nothing.
- WHEN LAG(t.name, 1) OVER (ORDER BY t.name) = t.name THEN ''
-
- -- Otherwise, this is the first row of a new table, so start
- -- the node markup and add a header row. Normally in GraphViz,
- -- the table name would *be* the label of the node, but since
- -- we're using the label to represent the entire node, we have
- -- to make our own header.
- --
- -- GraphViz does have a "record" label shape, but it seems tricky
- -- to work with and I found the HTML-style label markup easier
- -- to get working the way I wanted.
- ELSE
- t.name || ' [label=<
- <TABLE BORDER="0" CELLSPACING="0" CELLBORDER="1">
- <TR>
- <TD COLSPAN="2"><B>' || t.name || '</B></TD>
- </TR>
- '
-
- -- After the header (if needed), we have rows for each field in
- -- the table.
- --
- -- The "pk" metadata field is zero for table fields that are not part
- -- of the primary key. If the "pk" metadata field is 1 or more, that
- -- tells you that table field's order in the (potentially composite)
- -- primary key.
- --
- -- We also add ports to each of the table cells, so that we can
- -- later tell GraphViz to specifically connect the ports representing
- -- specific fields in each table, instead of connecting the tables
- -- generally.
- END || '
- <TR>
- <TD PORT="' || i.name || '_to">' ||
- CASE i.pk WHEN 0 THEN '&nbsp;' ELSE '🔑' END ||
- '</TD>
- <TD PORT="' || i.name || '_from">' || i.name || '</TD>
- </TR>
- ' ||
- CASE
- -- When the next row's table name is the same as this one,
- -- do nothing.
- WHEN LEAD(t.name, 1) OVER (ORDER BY t.name) = t.name THEN ''
-
- -- Otherwise, this is the last row of a database table, so end
- -- the table markup.
- ELSE '
- </TABLE>
- >];
- '
- END
-
--- This is how you get nice relational data out of SQLite's metadata
--- pragmas.
-FROM pragma_table_list() AS t
- JOIN pragma_table_info(t.name, t.schema) AS i
-
-WHERE
- -- SQLite has a bunch of metadata tables in each schema, which
- -- are hidden from .tables and .schema but which are reported
- -- in pragma_table_list(). They're not user-created and almost
- -- certainly user databases don't have foreign keys to them, so
- -- let's just filter them out.
- t.name NOT LIKE 'sqlite_%'
-
- -- Despite its name, pragma_table_list() also includes views.
- -- Since those don't store any information or have any correctness
- -- constraints, they're just distracting if you're trying to quickly
- -- understand a database's schema, so we'll filter them out too.
- AND t.type = 'table'
-UNION ALL
-
--- Now we have all the database tables set up, we can draw the links
--- between them. SQLite gives us the pragma_foreign_key_list() function
--- which (for a given source table) lists all the source fields that are
--- part of a foreign key reference, the target table they refer to, and
--- (if it was created with "REFERENCES table_name(column_name)" syntax,
--- the target column names too. Unfortunately, if the reference was
--- created with "REFERENCES table_name" syntax, the pragma does *not*
--- figure out what the corresponding target fields are, so we'll also need
--- pragma_table_info() to look up the primary key(s) for the target table.
---
--- Once we have everything we need, we just do a bit more string
--- concatenation to build up the GraphViz syntax equivalent.
---
--- Note that we use the ports we defined above, as well as the directional
--- overrides :e and :w, to force GraphViz to give us a layout that's
--- likely to be readable.
-SELECT
-
- -- We left-join every foreign key field against pragma_table_info
- -- looking for primary keys, and the target table may have a composite
- -- primary key even if the foreign key does not reference the primary
- -- key, so we may wind up with multiple results describing the same
- -- foreign key reference. DISTINCT makes sure we only describe each
- -- reference once.
- DISTINCT
-
- t.name || ':' || f."from" || '_from:e -> ' ||
-
- -- If the constraint was created with "REFERENCES
- -- table_name(column_name)", then f.to will contain 'column_name'.
- -- Otherwise, f.to is NULL, and we need to grab the corresponding
- -- field from the primary key in i.name.
- f."table" || ':' || COALESCE(f."to", i.name) || '_to:w'
-
-FROM pragma_table_list() AS t
- JOIN pragma_foreign_key_list(t.name, t.schema) AS f
-
- -- We look up all the fields in the target table, just in case
- -- pragma_foreign_key_list() doesn't tell us what the target field
- -- name is. SQLite doesn't allow foreign-key references to cross
- -- schemas, so it's OK to use the source table's schema name to look
- -- up the target table.
- --
- -- Strictly speaking, we shouldn't need to LEFT JOIN here, a basic
- -- JOIN should do. This works around a bug in SQLite 3.16.0 to
- -- version 3.45.1: https://sqlite.org/forum/forumpost/b1656fcb39
- LEFT JOIN pragma_table_info(f."table", t.schema) AS i
-
--- f.seq represents the order of fields in a source table's composite foreign key
--- reference, starting at 0. In "FOREIGN KEY (a, b)", "a" would have
--- seq=0 and "b" would have seq=1. i.pk represents the order of fields
--- in a primary key, where "0" means "not part of the primary key".
--- In "PRIMARY KEY (a, b)", "a" would have pk=1 and "b" would have pk=2.
--- For a foreign key reference that specifies the target field name,
--- none of this matters, but if the target field name is missing, then
--- this makes sure that each field of the foreign key reference is joined
--- with the corresponding primary key field of the target table.
-WHERE f.seq + 1 = i.pk
-
-UNION ALL
-
--- Lastly, we close the GraphViz graph.
-SELECT '
-}';