From f3bcd95242997dbfe483857fe94ba9eeb4aa916e Mon Sep 17 00:00:00 2001 From: Viktor Barzin Date: Mon, 23 Feb 2026 22:47:06 +0000 Subject: [PATCH] [ci skip] f1-stream: replace Go service with Python/FastAPI skeleton Replaces the existing Go-based f1-stream service with a new Python/FastAPI backend as the foundation for the rebuilt F1 streaming aggregation service. - New FastAPI backend with health and root endpoints - Python 3.13 slim Dockerfile (replaces Go multi-stage build) - Updated Terraform deployment (port 8000, reduced resources) - Buildx-based redeploy.sh with --platform linux/amd64 - Added Woodpecker CI pipeline for automated builds - Removed all old Go source, node_modules, static assets --- .woodpecker/f1-stream.yml | 30 + stacks/f1-stream/files/.planning/PROJECT.md | 78 - .../f1-stream/files/.planning/REQUIREMENTS.md | 115 -- stacks/f1-stream/files/.planning/ROADMAP.md | 106 -- stacks/f1-stream/files/.planning/STATE.md | 93 -- .../files/.planning/codebase/ARCHITECTURE.md | 191 --- .../files/.planning/codebase/CONCERNS.md | 232 --- .../files/.planning/codebase/CONVENTIONS.md | 159 -- .../files/.planning/codebase/INTEGRATIONS.md | 121 -- .../files/.planning/codebase/STACK.md | 109 -- .../files/.planning/codebase/STRUCTURE.md | 202 --- .../files/.planning/codebase/TESTING.md | 256 --- stacks/f1-stream/files/.planning/config.json | 12 - .../01-scraper-validation/01-01-PLAN.md | 237 --- .../01-scraper-validation/01-01-SUMMARY.md | 107 -- .../01-scraper-validation/01-RESEARCH.md | 599 ------- .../01-scraper-validation/01-VERIFICATION.md | 200 --- .../02-01-PLAN.md | 225 --- .../02-01-SUMMARY.md | 106 -- .../02-02-PLAN.md | 197 --- .../02-02-SUMMARY.md | 101 -- .../02-RESEARCH.md | 801 --------- .../02-VERIFICATION.md | 123 -- .../03-auto-publish-pipeline/03-01-PLAN.md | 186 --- .../03-auto-publish-pipeline/03-01-SUMMARY.md | 105 -- .../03-VERIFICATION.md | 115 -- .../04-01-PLAN.md | 183 --- .../04-01-SUMMARY.md | 114 -- .../04-02-PLAN.md | 218 --- .../04-02-SUMMARY.md | 107 -- .../04-VERIFICATION.md | 108 -- .../05-sandbox-proxy-hardening/05-01-PLAN.md | 147 -- .../05-01-SUMMARY.md | 108 -- .../05-sandbox-proxy-hardening/05-02-PLAN.md | 240 --- .../05-02-SUMMARY.md | 102 -- .../05-VERIFICATION.md | 170 -- stacks/f1-stream/files/Dockerfile | 31 +- stacks/f1-stream/files/backend/main.py | 19 + .../f1-stream/files/backend/requirements.txt | 2 + stacks/f1-stream/files/go.mod | 45 - stacks/f1-stream/files/go.sum | 89 - stacks/f1-stream/files/index.html | 293 ---- stacks/f1-stream/files/internal/auth/auth.go | 359 ---- .../f1-stream/files/internal/auth/context.go | 20 - .../files/internal/extractor/browser.go | 38 - .../files/internal/extractor/capture.go | 167 -- .../files/internal/extractor/session.go | 383 ----- .../files/internal/extractor/webrtc.go | 248 --- .../files/internal/healthcheck/healthcheck.go | 188 --- .../files/internal/hlsproxy/hlsproxy.go | 209 --- .../f1-stream/files/internal/models/models.go | 53 - .../internal/playerconfig/playerconfig.go | 512 ------ .../f1-stream/files/internal/proxy/proxy.go | 473 ------ .../files/internal/scraper/reddit.go | 327 ---- .../files/internal/scraper/scraper.go | 105 -- .../files/internal/scraper/validate.go | 142 -- .../files/internal/scraper/validate_test.go | 124 -- .../files/internal/server/middleware.go | 93 -- .../f1-stream/files/internal/server/server.go | 338 ---- .../f1-stream/files/internal/store/health.go | 37 - .../f1-stream/files/internal/store/scraped.go | 63 - .../files/internal/store/sessions.go | 98 -- .../f1-stream/files/internal/store/store.go | 53 - .../f1-stream/files/internal/store/streams.go | 176 -- .../f1-stream/files/internal/store/users.go | 91 -- stacks/f1-stream/files/main.go | 163 -- .../files/node_modules/.package-lock.json | 6 - stacks/f1-stream/files/package-lock.json | 6 - stacks/f1-stream/files/package.json | 1 - stacks/f1-stream/files/redeploy.sh | 5 +- stacks/f1-stream/files/static/css/custom.css | 1455 ----------------- .../f1-stream/files/static/css/pico.min.css | 4 - stacks/f1-stream/files/static/index.html | 205 --- stacks/f1-stream/files/static/js/app.js | 121 -- stacks/f1-stream/files/static/js/auth.js | 219 --- stacks/f1-stream/files/static/js/player.js | 216 --- stacks/f1-stream/files/static/js/streams.js | 419 ----- stacks/f1-stream/files/static/js/utils.js | 9 - stacks/f1-stream/main.tf | 42 +- stacks/f1-stream/tiers.tf | 10 + 80 files changed, 81 insertions(+), 13879 deletions(-) create mode 100644 .woodpecker/f1-stream.yml delete mode 100644 stacks/f1-stream/files/.planning/PROJECT.md delete mode 100644 stacks/f1-stream/files/.planning/REQUIREMENTS.md delete mode 100644 stacks/f1-stream/files/.planning/ROADMAP.md delete mode 100644 stacks/f1-stream/files/.planning/STATE.md delete mode 100644 stacks/f1-stream/files/.planning/codebase/ARCHITECTURE.md delete mode 100644 stacks/f1-stream/files/.planning/codebase/CONCERNS.md delete mode 100644 stacks/f1-stream/files/.planning/codebase/CONVENTIONS.md delete mode 100644 stacks/f1-stream/files/.planning/codebase/INTEGRATIONS.md delete mode 100644 stacks/f1-stream/files/.planning/codebase/STACK.md delete mode 100644 stacks/f1-stream/files/.planning/codebase/STRUCTURE.md delete mode 100644 stacks/f1-stream/files/.planning/codebase/TESTING.md delete mode 100644 stacks/f1-stream/files/.planning/config.json delete mode 100644 stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-01-PLAN.md delete mode 100644 stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-01-SUMMARY.md delete mode 100644 stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-RESEARCH.md delete mode 100644 stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-VERIFICATION.md delete mode 100644 stacks/f1-stream/files/.planning/phases/02-health-check-infrastructure/02-01-PLAN.md delete mode 100644 stacks/f1-stream/files/.planning/phases/02-health-check-infrastructure/02-01-SUMMARY.md delete mode 100644 stacks/f1-stream/files/.planning/phases/02-health-check-infrastructure/02-02-PLAN.md delete mode 100644 stacks/f1-stream/files/.planning/phases/02-health-check-infrastructure/02-02-SUMMARY.md delete mode 100644 stacks/f1-stream/files/.planning/phases/02-health-check-infrastructure/02-RESEARCH.md delete mode 100644 stacks/f1-stream/files/.planning/phases/02-health-check-infrastructure/02-VERIFICATION.md delete mode 100644 stacks/f1-stream/files/.planning/phases/03-auto-publish-pipeline/03-01-PLAN.md delete mode 100644 stacks/f1-stream/files/.planning/phases/03-auto-publish-pipeline/03-01-SUMMARY.md delete mode 100644 stacks/f1-stream/files/.planning/phases/03-auto-publish-pipeline/03-VERIFICATION.md delete mode 100644 stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-01-PLAN.md delete mode 100644 stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-01-SUMMARY.md delete mode 100644 stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-02-PLAN.md delete mode 100644 stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-02-SUMMARY.md delete mode 100644 stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-VERIFICATION.md delete mode 100644 stacks/f1-stream/files/.planning/phases/05-sandbox-proxy-hardening/05-01-PLAN.md delete mode 100644 stacks/f1-stream/files/.planning/phases/05-sandbox-proxy-hardening/05-01-SUMMARY.md delete mode 100644 stacks/f1-stream/files/.planning/phases/05-sandbox-proxy-hardening/05-02-PLAN.md delete mode 100644 stacks/f1-stream/files/.planning/phases/05-sandbox-proxy-hardening/05-02-SUMMARY.md delete mode 100644 stacks/f1-stream/files/.planning/phases/05-sandbox-proxy-hardening/05-VERIFICATION.md create mode 100644 stacks/f1-stream/files/backend/main.py create mode 100644 stacks/f1-stream/files/backend/requirements.txt delete mode 100644 stacks/f1-stream/files/go.mod delete mode 100644 stacks/f1-stream/files/go.sum delete mode 100644 stacks/f1-stream/files/index.html delete mode 100644 stacks/f1-stream/files/internal/auth/auth.go delete mode 100644 stacks/f1-stream/files/internal/auth/context.go delete mode 100644 stacks/f1-stream/files/internal/extractor/browser.go delete mode 100644 stacks/f1-stream/files/internal/extractor/capture.go delete mode 100644 stacks/f1-stream/files/internal/extractor/session.go delete mode 100644 stacks/f1-stream/files/internal/extractor/webrtc.go delete mode 100644 stacks/f1-stream/files/internal/healthcheck/healthcheck.go delete mode 100644 stacks/f1-stream/files/internal/hlsproxy/hlsproxy.go delete mode 100644 stacks/f1-stream/files/internal/models/models.go delete mode 100644 stacks/f1-stream/files/internal/playerconfig/playerconfig.go delete mode 100644 stacks/f1-stream/files/internal/proxy/proxy.go delete mode 100644 stacks/f1-stream/files/internal/scraper/reddit.go delete mode 100644 stacks/f1-stream/files/internal/scraper/scraper.go delete mode 100644 stacks/f1-stream/files/internal/scraper/validate.go delete mode 100644 stacks/f1-stream/files/internal/scraper/validate_test.go delete mode 100644 stacks/f1-stream/files/internal/server/middleware.go delete mode 100644 stacks/f1-stream/files/internal/server/server.go delete mode 100644 stacks/f1-stream/files/internal/store/health.go delete mode 100644 stacks/f1-stream/files/internal/store/scraped.go delete mode 100644 stacks/f1-stream/files/internal/store/sessions.go delete mode 100644 stacks/f1-stream/files/internal/store/store.go delete mode 100644 stacks/f1-stream/files/internal/store/streams.go delete mode 100644 stacks/f1-stream/files/internal/store/users.go delete mode 100644 stacks/f1-stream/files/main.go delete mode 100644 stacks/f1-stream/files/node_modules/.package-lock.json delete mode 100644 stacks/f1-stream/files/package-lock.json delete mode 100644 stacks/f1-stream/files/package.json delete mode 100644 stacks/f1-stream/files/static/css/custom.css delete mode 100644 stacks/f1-stream/files/static/css/pico.min.css delete mode 100644 stacks/f1-stream/files/static/index.html delete mode 100644 stacks/f1-stream/files/static/js/app.js delete mode 100644 stacks/f1-stream/files/static/js/auth.js delete mode 100644 stacks/f1-stream/files/static/js/player.js delete mode 100644 stacks/f1-stream/files/static/js/streams.js delete mode 100644 stacks/f1-stream/files/static/js/utils.js create mode 100644 stacks/f1-stream/tiers.tf diff --git a/.woodpecker/f1-stream.yml b/.woodpecker/f1-stream.yml new file mode 100644 index 00000000..22afccf0 --- /dev/null +++ b/.woodpecker/f1-stream.yml @@ -0,0 +1,30 @@ +when: + event: push + path: "stacks/f1-stream/files/**" + +clone: + git: + image: woodpeckerci/plugin-git + settings: + attempts: 5 + backoff: 10s + +steps: + - name: build-image + image: woodpeckerci/plugin-docker-buildx + settings: + username: "viktorbarzin" + password: + from_secret: dockerhub-pat + repo: viktorbarzin/f1-stream + dockerfile: stacks/f1-stream/files/Dockerfile + context: stacks/f1-stream/files + platforms: linux/amd64 + provenance: false + auto_tag: true + + - name: deploy + image: bitnami/kubectl + commands: + - kubectl -n f1-stream rollout restart deployment f1-stream + - kubectl -n f1-stream rollout status deployment f1-stream --timeout=120s diff --git a/stacks/f1-stream/files/.planning/PROJECT.md b/stacks/f1-stream/files/.planning/PROJECT.md deleted file mode 100644 index 0c102123..00000000 --- a/stacks/f1-stream/files/.planning/PROJECT.md +++ /dev/null @@ -1,78 +0,0 @@ -# F1 Stream - -## What This Is - -A self-hosted web app that aggregates live Formula 1 streaming links from Reddit and user submissions, presenting them in a clean UI with embedded iframes. It scrapes r/motorsportsstreams2, allows users to submit their own stream URLs, and provides admin controls for content moderation. Built in Go with vanilla JS frontend, deployed on Kubernetes. - -## Core Value - -Users can find working F1 streams quickly — the app automatically discovers, validates, and surfaces healthy streams while removing dead ones. - -## Requirements - -### Validated - - - -- ✓ Reddit scraper polls r/motorsportsstreams2 for F1-related posts — existing -- ✓ URL extraction from post bodies and comment trees — existing -- ✓ F1 keyword filtering with negative keyword exclusion — existing -- ✓ Domain filtering (reddit, imgur, youtube, twitter excluded) — existing -- ✓ Deduplication via normalized URLs — existing -- ✓ User stream submission (anonymous + authenticated) — existing -- ✓ WebAuthn passwordless authentication — existing -- ✓ Admin approval workflow for user-submitted streams — existing -- ✓ HTTP proxy with rate limiting, private IP blocking, CSP stripping — existing -- ✓ Static frontend with iframe-based stream viewing — existing -- ✓ Default seed streams on first run — existing -- ✓ Stale link cleanup (24h) — existing -- ✓ Client-side health sort (reorder by reachability) — existing - -### Active - - - -- [ ] Scraper validates extracted URLs look like actual streams (video/player content), not random links -- [ ] Server-side health checker runs every 5 minutes against all known streams -- [ ] Health check: HTTP reachability check first, then proxy-fetch to detect video/player markers -- [ ] Configurable health check timeout -- [ ] Streams marked unhealthy after 5 consecutive check failures get hidden from public page -- [ ] Unhealthy streams retried on each check cycle — restored if they recover -- [ ] Scraped streams that pass health checks auto-published to main streams page -- [ ] Dead streams dynamically removed from the page without manual intervention -- [ ] Health status persisted (failure count, last check time, healthy/unhealthy state) - -### Out of Scope - -- Database migration (SQLite/PostgreSQL) — file-based storage is fine for this scope -- Multiple subreddit sources — stick with r/motorsportsstreams2 for now -- Real-time WebSocket push of stream status — polling is sufficient -- Mobile app — web-only -- OAuth/social login — WebAuthn is sufficient - -## Context - -- The app runs on a personal Kubernetes cluster, deployed via Terraform -- Single-user / small-group usage — performance at scale is not a concern -- The existing client-side `sortStreamsByHealth` does a basic `no-cors` fetch but can't inspect content; server-side checks via the proxy can do deeper validation -- Reddit's public JSON API requires no auth but rate-limits aggressively; the scraper already handles 429s with backoff -- Stream sites frequently go down, change URLs, or get taken down — health checking is essential for a good UX - -## Constraints - -- **Tech stack**: Go backend, vanilla JS frontend — no new frameworks or dependencies unless strictly necessary -- **Storage**: File-based JSON — no database -- **Deployment**: Docker container on Kubernetes, single replica -- **Reddit API**: Public JSON endpoints, must respect rate limits (1 req/sec delay already in place) - -## Key Decisions - -| Decision | Rationale | Outcome | -|----------|-----------|---------| -| Server-side health checks over client-side only | Client can't inspect response content (CORS); server proxy can detect video markers | — Pending | -| 5 consecutive failures before hiding | Avoids flapping — streams that are temporarily down aren't immediately removed | — Pending | -| Auto-publish scraped streams that pass health | Reduces manual admin work; the health check is the quality gate | — Pending | -| Health check every 5 minutes | Balances freshness vs. load — streams don't change status that frequently | — Pending | - ---- -*Last updated: 2026-02-17 after initialization* diff --git a/stacks/f1-stream/files/.planning/REQUIREMENTS.md b/stacks/f1-stream/files/.planning/REQUIREMENTS.md deleted file mode 100644 index c50a1f71..00000000 --- a/stacks/f1-stream/files/.planning/REQUIREMENTS.md +++ /dev/null @@ -1,115 +0,0 @@ -# Requirements: F1 Stream - -**Defined:** 2026-02-17 -**Core Value:** Users can find working F1 streams quickly — the app automatically discovers, validates, and surfaces healthy streams while removing dead ones. - -## v1 Requirements - -Requirements for initial release. Each maps to roadmap phases. - -### Scraper Validation - -- [ ] **SCRP-01**: Scraper filters Reddit posts by F1 keywords before extracting URLs (existing behavior, preserve) -- [ ] **SCRP-02**: Scraper validates each extracted URL by proxy-fetching it and checking for video/player content markers (video tags, HLS/DASH manifests, common player libraries) -- [ ] **SCRP-03**: URLs that don't look like streams (no video markers detected) are discarded before saving -- [ ] **SCRP-04**: Validation has a configurable timeout (default 10s) to avoid blocking on slow sites - -### Health Checking - -- [ ] **HLTH-01**: Background health checker service runs every 5 minutes against all known streams (scraped + user-submitted) -- [ ] **HLTH-02**: Health check performs HTTP reachability check first (does the URL respond with 2xx?) -- [ ] **HLTH-03**: If HTTP check passes, health checker proxy-fetches the page and checks for video/player content markers -- [ ] **HLTH-04**: Health check has a configurable timeout per check (default 10s) -- [ ] **HLTH-05**: Each stream tracks consecutive failure count, last check time, and healthy/unhealthy status in persisted state -- [ ] **HLTH-06**: Stream marked unhealthy after 5 consecutive health check failures -- [ ] **HLTH-07**: Unhealthy streams hidden from public streams page (`GET /api/streams/public`) -- [ ] **HLTH-08**: Unhealthy streams continue to be checked — restored to healthy if they recover (failure count resets) -- [ ] **HLTH-09**: Health check interval configurable via `HEALTH_CHECK_INTERVAL` env var (default 5m) - -### Auto-publish Pipeline - -- [ ] **AUTO-01**: Scraped streams that pass both scraper validation and initial health check are auto-published to the main streams page -- [ ] **AUTO-02**: Dead streams (unhealthy after 5 failures) are dynamically removed from the public page without admin intervention -- [ ] **AUTO-03**: Auto-published streams are distinguishable from user-submitted streams in the data model (source field) - -### Secure Embedding - -- [ ] **EMBED-01**: Proxy fetches stream page and attempts to extract direct video source URL (HLS .m3u8, DASH .mpd, direct MP4/WebM, or embedded video player source) -- [ ] **EMBED-02**: When direct video source is found, render it in a minimal HTML5 video player on the app's own page (no third-party page loaded) -- [ ] **EMBED-03**: When direct extraction fails, fall back to rendering the full proxied page in a shadow DOM sandbox -- [ ] **EMBED-04**: Shadow DOM sandbox blocks `window.open`, `window.top` navigation, popup creation, and `alert`/`confirm`/`prompt` -- [ ] **EMBED-05**: Shadow DOM sandbox prevents access to parent page cookies and localStorage -- [ ] **EMBED-06**: Proxy strips known ad/tracker scripts and domains from proxied content before serving -- [ ] **EMBED-07**: Proxy rewrites relative URLs in proxied content to route through the proxy (so sub-resources load correctly) -- [ ] **EMBED-08**: All proxied content served with strict CSP headers scoped to the sandbox context - -## v2 Requirements - -Deferred to future release. Tracked but not in current roadmap. - -### Enhanced Sources - -- **SRC-01**: Support scraping from additional subreddits or Discord channels -- **SRC-02**: User-reported stream quality ratings - -### UI Enhancements - -- **UI-01**: Real-time WebSocket push of stream health status changes -- **UI-02**: Stream quality indicator (resolution, bitrate if detectable) -- **UI-03**: Stream viewer count or popularity metric - -### Security Hardening - -- **SEC-01**: Ad-blocker filter list integration (uBlock Origin lists) -- **SEC-02**: JavaScript AST analysis for malicious patterns before allowing execution - -## Out of Scope - -| Feature | Reason | -|---------|--------| -| Database migration (SQLite/PostgreSQL) | File-based storage is sufficient for current scale | -| Multiple replica deployment | Single-user/small-group usage, single replica is fine | -| Mobile app | Web-only, responsive design sufficient | -| OAuth/social login | WebAuthn already works | -| Full browser automation (Puppeteer/Playwright) | Too heavy for stream validation; HTTP-based checks are sufficient | -| Video transcoding/re-streaming | Out of scope — we link to or proxy existing streams | - -## Traceability - -Which phases cover which requirements. Updated during roadmap creation. - -| Requirement | Phase | Status | -|-------------|-------|--------| -| SCRP-01 | Phase 1 | Pending | -| SCRP-02 | Phase 1 | Pending | -| SCRP-03 | Phase 1 | Pending | -| SCRP-04 | Phase 1 | Pending | -| HLTH-01 | Phase 2 | Pending | -| HLTH-02 | Phase 2 | Pending | -| HLTH-03 | Phase 2 | Pending | -| HLTH-04 | Phase 2 | Pending | -| HLTH-05 | Phase 2 | Pending | -| HLTH-06 | Phase 2 | Pending | -| HLTH-07 | Phase 2 | Pending | -| HLTH-08 | Phase 2 | Pending | -| HLTH-09 | Phase 2 | Pending | -| AUTO-01 | Phase 3 | Pending | -| AUTO-02 | Phase 3 | Pending | -| AUTO-03 | Phase 3 | Pending | -| EMBED-01 | Phase 4 | Pending | -| EMBED-02 | Phase 4 | Pending | -| EMBED-03 | Phase 5 | Pending | -| EMBED-04 | Phase 5 | Pending | -| EMBED-05 | Phase 5 | Pending | -| EMBED-06 | Phase 5 | Pending | -| EMBED-07 | Phase 5 | Pending | -| EMBED-08 | Phase 5 | Pending | - -**Coverage:** -- v1 requirements: 24 total -- Mapped to phases: 24 -- Unmapped: 0 - ---- -*Requirements defined: 2026-02-17* -*Last updated: 2026-02-17 after roadmap creation* diff --git a/stacks/f1-stream/files/.planning/ROADMAP.md b/stacks/f1-stream/files/.planning/ROADMAP.md deleted file mode 100644 index d79f7d42..00000000 --- a/stacks/f1-stream/files/.planning/ROADMAP.md +++ /dev/null @@ -1,106 +0,0 @@ -# Roadmap: F1 Stream - -## Overview - -This roadmap delivers server-side stream quality assurance and secure viewing. First, the scraper learns to validate that extracted URLs actually contain video content. Then a background health checker continuously monitors all streams. These combine into an auto-publish pipeline that surfaces good streams and hides dead ones without admin intervention. Finally, secure embedding replaces raw iframes with native video playback where possible and a hardened sandbox fallback for everything else. - -## Phases - -**Phase Numbering:** -- Integer phases (1, 2, 3): Planned milestone work -- Decimal phases (2.1, 2.2): Urgent insertions (marked with INSERTED) - -Decimal phases appear between their surrounding integers in numeric order. - -- [ ] **Phase 1: Scraper Validation** - Scraper validates extracted URLs contain video/player content before saving -- [ ] **Phase 2: Health Check Infrastructure** - Background service continuously monitors stream health and persists status -- [ ] **Phase 3: Auto-publish Pipeline** - Healthy scraped streams auto-publish; dead streams auto-hide -- [ ] **Phase 4: Video Extraction and Native Playback** - Extract direct video sources and play them in a native HTML5 player -- [ ] **Phase 5: Sandbox and Proxy Hardening** - Fallback rendering in a sandboxed shadow DOM with ad stripping and strict CSP - -## Phase Details - -### Phase 1: Scraper Validation -**Goal**: Scraped URLs are verified to contain actual video/player content before being stored, eliminating junk links at the source -**Depends on**: Nothing (extends existing scraper) -**Requirements**: SCRP-01, SCRP-02, SCRP-03, SCRP-04 -**Success Criteria** (what must be TRUE): - 1. Scraper still discovers F1-related posts from Reddit using keyword filtering (existing behavior preserved) - 2. Each extracted URL is proxy-fetched and inspected for video/player content markers (video tags, HLS/DASH manifests, player libraries) - 3. URLs without video content markers are discarded and do not appear in scraped.json - 4. Validation respects a configurable timeout so slow sites do not block the scrape cycle -**Plans**: 1 plan - -Plans: -- [ ] 01-01-PLAN.md — Add URL validation with video marker detection to scraper pipeline - -### Phase 2: Health Check Infrastructure -**Goal**: All known streams are continuously monitored for health, with status persisted and unhealthy streams hidden from users -**Depends on**: Phase 1 (reuses content validation logic from scraper validation) -**Requirements**: HLTH-01, HLTH-02, HLTH-03, HLTH-04, HLTH-05, HLTH-06, HLTH-07, HLTH-08, HLTH-09 -**Success Criteria** (what must be TRUE): - 1. A background service checks every known stream (scraped and user-submitted) on a regular interval that defaults to 5 minutes and is configurable via environment variable - 2. Each check performs HTTP reachability first, then proxy-fetches the page to verify video/player content markers - 3. Each stream's health state (consecutive failure count, last check time, healthy/unhealthy flag) is persisted across restarts - 4. A stream is hidden from the public streams page after 5 consecutive check failures, and restored if it later passes a check - 5. Health check timeout per stream is configurable -**Plans**: 2 plans - -Plans: -- [ ] 02-01-PLAN.md — HealthState model, store persistence, export HasVideoContent, create HealthChecker service -- [ ] 02-02-PLAN.md — Wire health checker in main.go, filter unhealthy streams from public API - -### Phase 3: Auto-publish Pipeline -**Goal**: Scraped streams that pass validation and health checks appear on the public page automatically; dead streams disappear without admin action -**Depends on**: Phase 1, Phase 2 -**Requirements**: AUTO-01, AUTO-02, AUTO-03 -**Success Criteria** (what must be TRUE): - 1. A scraped stream that passes scraper validation and its first health check is visible on the public streams page without any admin approval - 2. A stream marked unhealthy (5 consecutive failures) is no longer visible on the public page, with no admin intervention required - 3. Auto-published streams are distinguishable from user-submitted streams in the data model (source field tracks origin) -**Plans**: 1 plan - -Plans: -- [ ] 03-01-PLAN.md — Add Source field to Stream model, create PublishScrapedStream, wire scraper auto-publish - -### Phase 4: Video Extraction and Native Playback -**Goal**: When a stream URL contains an extractable video source, users watch it in a clean native HTML5 player instead of loading the third-party page -**Depends on**: Nothing (independent of phases 1-3; can be built in parallel but ordered here for delivery focus) -**Requirements**: EMBED-01, EMBED-02 -**Success Criteria** (what must be TRUE): - 1. The proxy can extract direct video source URLs (HLS .m3u8, DASH .mpd, direct MP4/WebM, or embedded player source attributes) from a stream page - 2. When a direct video source is found, the user sees a minimal HTML5 video player on the app's own page playing the stream without loading the original third-party page -**Plans**: 2 plans - -Plans: -- [ ] 04-01-PLAN.md — Backend video source extractor package and API endpoint -- [ ] 04-02-PLAN.md — Frontend native HTML5 video player with HLS.js and iframe fallback - -### Phase 5: Sandbox and Proxy Hardening -**Goal**: When direct video extraction fails, the proxied page is rendered safely in a sandbox that blocks popups, ads, and access to the parent page -**Depends on**: Phase 4 (this is the fallback path when extraction fails) -**Requirements**: EMBED-03, EMBED-04, EMBED-05, EMBED-06, EMBED-07, EMBED-08 -**Success Criteria** (what must be TRUE): - 1. When direct video extraction fails, the full proxied page renders inside a shadow DOM sandbox on the app's page - 2. The sandbox blocks window.open, top-frame navigation, popup creation, and alert/confirm/prompt dialogs - 3. The sandbox prevents the proxied content from accessing parent page cookies and localStorage - 4. Known ad/tracker scripts and domains are stripped from proxied content before serving, and relative URLs are rewritten to route through the proxy - 5. All proxied content is served with strict CSP headers scoped to the sandbox context -**Plans**: 2 plans - -Plans: -- [ ] 05-01-PLAN.md — Backend proxy hardening: HTML sanitizer with ad/tracker stripping, URL rewriting, and CSP headers -- [ ] 05-02-PLAN.md — Frontend shadow DOM sandbox replacing iframe fallback with API overrides - -## Progress - -**Execution Order:** -Phases execute in numeric order: 1 -> 2 -> 3 -> 4 -> 5 - -| Phase | Plans Complete | Status | Completed | -|-------|----------------|--------|-----------| -| 1. Scraper Validation | 0/1 | Planned | - | -| 2. Health Check Infrastructure | 0/2 | Planned | - | -| 3. Auto-publish Pipeline | 0/1 | Planned | - | -| 4. Video Extraction and Native Playback | 0/2 | Planned | - | -| 5. Sandbox and Proxy Hardening | 0/2 | Not started | - | diff --git a/stacks/f1-stream/files/.planning/STATE.md b/stacks/f1-stream/files/.planning/STATE.md deleted file mode 100644 index 043af6e1..00000000 --- a/stacks/f1-stream/files/.planning/STATE.md +++ /dev/null @@ -1,93 +0,0 @@ -# Project State - -## Project Reference - -See: .planning/PROJECT.md (updated 2026-02-17) - -**Core value:** Users can find working F1 streams quickly -- the app automatically discovers, validates, and surfaces healthy streams while removing dead ones. -**Current focus:** Phase 5: Sandbox Proxy Hardening (complete) - -## Current Position - -Phase: 5 of 5 (Sandbox Proxy Hardening) -Plan: 2 of 2 in current phase (complete) -Status: ALL PHASES COMPLETE -- project finished -Last activity: 2026-02-17 -- Completed 05-02 frontend shadow DOM sandbox - -Progress: [██████████] 100% - -## Performance Metrics - -**Velocity:** -- Total plans completed: 8 -- Average duration: 2.1min -- Total execution time: 0.28 hours - -**By Phase:** - -| Phase | Plans | Total | Avg/Plan | -|-------|-------|-------|----------| -| 01-scraper-validation | 1 | 3min | 3min | -| 02-health-check-infrastructure | 2 | 4min | 2min | -| 03-auto-publish-pipeline | 1 | 2min | 2min | -| 04-video-extraction-native-playback | 2 | 5min | 2.5min | -| 05-sandbox-proxy-hardening | 2 | 3min | 1.5min | - -**Recent Trend:** -- Last 5 plans: 2min, 3min, 2min, 2min, 1min -- Trend: Stable - -*Updated after each plan completion* - -## Accumulated Context - -### Decisions - -Decisions are logged in PROJECT.md Key Decisions table. -Recent decisions affecting current work: - -- Server-side health checks chosen over client-only (client can't inspect CORS responses) -- 5 consecutive failures threshold to avoid flapping -- Auto-publish for scraped streams that pass health check (health check is the quality gate) -- 5-minute health check interval (freshness vs load balance) -- String matching over DOM parsing for video detection (DOM reserved for Phase 4) -- 2MB body limit for HTML inspection to prevent memory issues -- 3 redirect limit to avoid infinite redirect chains on stream sites -- HealthMap reads file without lock to avoid deadlock from cross-lock scenarios -- Single HasVideoContent call covers both reachability and content checks -- Orphaned health state entries pruned each cycle to prevent unbounded file growth -- URLs not in health map assumed healthy to prevent new streams disappearing before first check -- HealthMap called within streamsMu/scrapedMu read locks safely via lock-free file read -- Source field uses string values (user/system/scraped) for readability over int enum -- PublishScrapedStream deduplicates by exact URL match; normalized matching stays in scraper layer -- Auto-publish iterates all validated links each cycle; deduplication makes repeat calls no-ops -- DOM parsing with golang.org/x/net/html for structured video source extraction (Phase 4) -- Dual extraction strategy: DOM walking + regex script parsing for maximum video URL coverage -- Priority ordering HLS > DASH > MP4 > WebM for frontend source selection -- 5-minute cache on extract endpoint to reduce upstream load -- Empty sources array (not error) when no video found to distinguish from fetch failures -- HLS.js loaded from jsDelivr CDN to avoid bundling complexity -- Extraction runs async after card render -- progressive enhancement with shadow DOM sandbox fallback -- DASH sources fall back to shadow DOM sandbox (dash.js too heavy for current scope) -- Silent console.log on extraction failure -- no user-facing errors for extraction issues -- 50+ ad/tracker domains in blocklist with parent-domain walk-up matching -- Inline scripts kept for video players; blocked scripts removed by domain -- CSP allows img/media/connect broadly since video sources come from arbitrary origins -- Non-HTML sub-resources proxied as-is with CSP headers -- Closed shadow DOM mode prevents external JS from accessing shadow root -- Script element created via createElement for execution in shadow DOM (innerHTML scripts don't execute) -- Direct link fallback when sandbox proxy fetch fails rather than broken state - -### Pending Todos - -None yet. - -### Blockers/Concerns - -None yet. - -## Session Continuity - -Last session: 2026-02-17 -Stopped at: Completed 05-02-PLAN.md (frontend shadow DOM sandbox) -- ALL PHASES COMPLETE -Resume file: None diff --git a/stacks/f1-stream/files/.planning/codebase/ARCHITECTURE.md b/stacks/f1-stream/files/.planning/codebase/ARCHITECTURE.md deleted file mode 100644 index 76ebca6b..00000000 --- a/stacks/f1-stream/files/.planning/codebase/ARCHITECTURE.md +++ /dev/null @@ -1,191 +0,0 @@ -# Architecture - -**Analysis Date:** 2026-02-17 - -## Pattern Overview - -**Overall:** Layered monolithic service with clear separation between HTTP API layer, business logic, and persistent storage layer. - -**Key Characteristics:** -- Single Go binary serving both API and static frontend -- File-based JSON persistence (no database) -- Modular internal packages for distinct concerns -- WebAuthn-based passwordless authentication -- Background scraper for content aggregation -- Rate-limited proxy service - -## Layers - -**HTTP Handler Layer:** -- Purpose: Accept and route HTTP requests, apply middleware, respond to clients -- Location: `internal/server/` -- Contains: Route registration, handler functions, middleware chains -- Depends on: Auth, Store, Proxy, Scraper packages -- Used by: HTTP clients (browser, mobile) - -**Authentication & Authorization Layer:** -- Purpose: Manage user registration, login, sessions, and permission checks -- Location: `internal/auth/` -- Contains: WebAuthn ceremony implementations, session management, context helpers -- Depends on: Store, go-webauthn library -- Used by: Server middleware and handlers - -**Business Logic Layer:** -- Purpose: Core domain operations (stream management, scraping, proxying) -- Location: `internal/scraper/`, `internal/proxy/` -- Contains: Scraper service (Reddit polling), Proxy service (content fetching with rate limiting) -- Depends on: Store for persistence -- Used by: Server, main entry point for orchestration - -**Data Model Layer:** -- Purpose: Define domain types and interfaces -- Location: `internal/models/models.go` -- Contains: `User`, `Stream`, `ScrapedLink`, `Session` types -- Depends on: External WebAuthn library for credential types -- Used by: All layers - -**Persistence Layer:** -- Purpose: Provide file-based storage abstraction -- Location: `internal/store/` -- Contains: JSON read/write helpers, file-based storage per entity type (streams, users, sessions, scraped links) -- Depends on: Models, filesystem -- Used by: All business logic layers - -## Data Flow - -**Stream Submission Flow:** - -1. Client submits stream URL and title via `POST /api/streams` -2. Server handler validates URL format and length -3. Optional: If authenticated user, stream marked as unpublished; if anonymous, marked as published -4. Stream stored via `Store.AddStream()` which reads current `streams.json`, appends new stream, writes atomically -5. Response returned with stream metadata - -**Authentication Flow (WebAuthn):** - -1. User initiates registration with `POST /api/auth/register/begin` sending username -2. Server validates username format, checks uniqueness, creates temporary user -3. Server generates WebAuthn registration options via go-webauthn library -4. Server stores session data in memory with 5-minute expiry -5. Client performs attestation ceremony, sends credential via `POST /api/auth/register/finish?username=...` -6. Server retrieves in-memory session, validates with go-webauthn -7. Credential appended to user in `users.json` -8. Session token created in `sessions.json`, set as HttpOnly cookie - -**Scraper Flow:** - -1. Scraper runs on timer (default 15 minutes) or on manual trigger -2. Calls `scrapeReddit()` to poll r/motorsportsstreams2 new posts -3. Extracts URLs using regex, filters by F1-related keywords -4. Merges with existing `scraped.json`, deduplicating by normalized URL -5. Writes updated list atomically -6. Stale entries cleaned up, active ones returned via `GET /api/scraped` - -**Proxy Flow:** - -1. Client requests `GET /proxy?url=https://...` -2. Server validates URL scheme (must be HTTPS), length, and target is not private IP -3. Applies rate limiting via token bucket per client IP -4. Fetches URL with timeout, limits response body to 5MB -5. Injects `` tag into HTML response for relative URL resolution -6. Strips X-Frame-Options and CSP headers to allow iframe embedding -7. Returns modified content - -**Admin Approval Flow:** - -1. Anonymous streams created with `Published: false` -2. Admin views all streams via `GET /api/admin/streams` -3. Admin toggles publication status via `PUT /api/streams/{id}/publish` -4. Published streams visible in `GET /api/streams/public` - -**State Management:** - -- **User Sessions:** In-memory WebAuthn ceremony sessions (5-minute TTL), persistent sessions in `sessions.json` with configurable TTL -- **Streams:** Fully loaded into memory from `streams.json` on each read/write, entire file rewritten atomically -- **Scraped Links:** Similar full-file pattern, deduplicated during scrape merge -- **Users:** Fully loaded per query, updated atomically per write -- **Cleanup:** Hourly cleanup of expired sessions via background goroutine - -## Key Abstractions - -**Store Interface (implicit):** -- Purpose: Encapsulate all file-based persistence operations -- Examples: `store.AddStream()`, `store.GetUserByName()`, `store.CreateSession()` -- Pattern: Each entity type has dedicated file; reads are lock-protected; writes are atomic (temp-file-then-rename) - -**Auth Middleware Chain:** -- Purpose: Extract and validate user from session cookie, inject into request context -- Examples: `AuthMiddleware()`, `RequireAuth()`, `RequireAdmin()` -- Pattern: Composable handler functions that wrap next handler - -**Scraper Service:** -- Purpose: Periodically fetch and aggregate content from external sources -- Examples: Background goroutine running on interval, triggered scrape -- Pattern: Mutex-protected scrape operations to prevent concurrent executions - -**Proxy Handler:** -- Purpose: Fetch external content safely with rate limiting and framing bypass -- Examples: URL validation, private IP blocking, rate limiting per IP, HTML base tag injection -- Pattern: Implements `http.Handler` interface, maintains per-IP token bucket state - -## Entry Points - -**HTTP Server (`main.go`):** -- Location: `main.go` -- Triggers: Process start -- Responsibilities: Initialize all services, configure routes, handle graceful shutdown on SIGTERM/SIGINT - -**Handler Routes (`internal/server/server.go`):** -- Location: `internal/server/server.go:registerRoutes()` -- Pattern: All routes defined in single function, middleware applied uniformly -- Public endpoints: Health, public streams, public scraped links -- Authenticated endpoints: Personal streams, submit stream, delete stream -- Admin endpoints: All streams, toggle publish, trigger scrape - -**Background Services:** -- Scraper: Started in goroutine at startup via `scraper.Run(ctx)` -- Session cleanup: Goroutine with hourly ticker -- Proxy rate-limit cleanup: Goroutine with 10-minute ticker - -## Error Handling - -**Strategy:** Error strings returned in JSON responses with appropriate HTTP status codes. Panics caught and logged by recovery middleware. - -**Patterns:** -- Validation errors: `400 Bad Request` -- Authentication failures: `401 Unauthorized` -- Permission denied: `403 Forbidden` -- Resource not found: `404 Not Found` -- Duplicate entries: `409 Conflict` -- Server errors: `500 Internal Server Error` -- Rate limit exceeded: `429 Too Many Requests` - -Errors include descriptive messages: `{"error":"username must be 3-30 chars, alphanumeric or underscore"}` - -## Cross-Cutting Concerns - -**Logging:** stdlib log package -- Request logging: Method, path, remote address via `LoggingMiddleware` -- Scraper logging: Intervals, timing, link counts -- Proxy logging: Fetch errors -- All goes to stdout - -**Validation:** -- Username: 3-30 chars, alphanumeric + underscore -- URLs: Must be HTTP(S), max 2048 chars, proxy-only supports HTTPS -- HTML escaping on stream titles to prevent injection - -**Authentication:** -- WebAuthn for registration/login (passwordless) -- Session tokens as HttpOnly, Secure, SameSite=Strict cookies -- Configurable session TTL (default 720 hours) -- First registered user becomes admin unless ADMIN_USERNAME env var set - -**CORS/Origin Check:** -- Origin header validated on mutation requests (POST, PUT, DELETE) -- Allowed origins configurable via WEBAUTHN_ORIGIN env var (comma-separated) -- CSRF protection via origin validation - ---- - -*Architecture analysis: 2026-02-17* diff --git a/stacks/f1-stream/files/.planning/codebase/CONCERNS.md b/stacks/f1-stream/files/.planning/codebase/CONCERNS.md deleted file mode 100644 index d295032e..00000000 --- a/stacks/f1-stream/files/.planning/codebase/CONCERNS.md +++ /dev/null @@ -1,232 +0,0 @@ -# Codebase Concerns - -**Analysis Date:** 2026-02-17 - -## Tech Debt - -**File-based JSON storage as primary data persistence:** -- Issue: All data (users, streams, sessions, scraped links) are stored as JSON files on disk with file-level locking. This is a fundamental scalability constraint. -- Files: `internal/store/store.go`, `internal/store/streams.go`, `internal/store/sessions.go`, `internal/store/users.go`, `internal/store/scraped.go` -- Impact: - - Non-atomic multi-file operations (e.g., DeleteStream reads all streams, filters, writes back). Race conditions possible if two deletes happen simultaneously. - - Entire file loaded into memory for any operation, even reads. With thousands of streams/sessions, this becomes slow and memory-inefficient. - - Sessions file grows unbounded until manual cleanup (CleanExpiredSessions runs hourly). Could cause memory/disk pressure. - - No transaction support, no rollback capability on failure. -- Fix approach: Migrate to a proper database (SQLite for simplicity, PostgreSQL for production). Keep JSON file for backup/export purposes only. - -**In-memory WebAuthn ceremony session storage with no cleanup guarantee:** -- Issue: Registration and login ceremony session data stored in `Auth.regSessions` and `Auth.loginSessions` maps. Cleanup relies on goroutines that may not execute if server crashes. -- Files: `internal/auth/auth.go` (lines 27-29, 107-117, 230-239) -- Impact: - - Memory leak on server restarts: orphaned sessions never cleaned up. - - No recovery mechanism if goroutine misses cleanup window. - - Session hijacking if an attacker can predict/guess the cleanup timing. -- Fix approach: Either move ceremony sessions to persistent store or use a time.AfterFunc with guaranteed cleanup (still risky). Better: use signed JWTs for ceremony state instead of server-side storage. - -**Scraper loads entire scraped links list into memory on every scrape:** -- Issue: `Scraper.scrape()` loads all existing links, filters and deduplicates them, then rewrites entire file. -- Files: `internal/scraper/scraper.go` (lines 46-92) -- Impact: With thousands of links, each 15-minute scrape cycle causes a large memory spike and full file rewrite. Inefficient deduplication logic (O(n) map lookups on every new link). -- Fix approach: With database migration, use INSERT OR IGNORE / upsert patterns. For now, batch process links in chunks and use database indexes for deduplication. - -**No input validation on URL lengths beyond basic checks:** -- Issue: URL length limited to 2048 chars in two places (`internal/server/server.go` line 153, `internal/proxy/proxy.go` line 72), but no validation of URL structure beyond "starts with http/https" and HTTPS-only in proxy. -- Files: `internal/server/server.go` (lines 146-160), `internal/proxy/proxy.go` (lines 54-80) -- Impact: Malformed URLs could bypass checks and cause unexpected behavior in downstream systems. User submission streams could contain typos/malware links. -- Fix approach: Use a proper URL parsing library with validation. Whitelist domains for stream submissions. Consider regex validation for known stream site patterns. - -**Hardcoded default streams in main.go:** -- Issue: Default stream URLs are hardcoded and point to external streaming sites that may become unavailable, redirect, or change terms of service. -- Files: `main.go` (lines 100-123) -- Impact: If any of these URLs break, users get broken default content. Sites could shut down or get legal takedown notices. Application appears to endorse/support these sites. -- Fix approach: Move to configuration file. Make seeding optional. Add stream validation/health checks before serving. Consider removing entirely if this is a liability concern. - -**Proxy strips CSP headers without replacement:** -- Issue: `internal/proxy/proxy.go` deliberately strips `X-Frame-Options` and CSP headers (line 123) to allow iframe-based proxying. No security headers added back. -- Files: `internal/proxy/proxy.go` (lines 121-125) -- Impact: Proxied content loses all origin security protections. Could allow downstream attacks to run XSS, clickjacking, etc. in the proxy context. Injected `` tag doesn't prevent all attacks. -- Fix approach: Add back a strict CSP policy scoped to the proxy origin. Implement iframe sandbox attributes. Add additional security headers (X-Content-Type-Options: nosniff, etc.). - -## Security Considerations - -**Authentication ceremony session fixation vulnerability:** -- Risk: Username used as session key for WebAuthn ceremonies (`Auth.BeginRegistration`, `Auth.BeginLogin`). Attacker could start ceremony for victim's account, then victim continues from attacker's session state. -- Files: `internal/auth/auth.go` (lines 107-108, 230-231) -- Current mitigation: None. Ceremony session stored in-memory and deleted after 5 minutes, but no CSRF token or state validation. -- Recommendations: Use cryptographically random state tokens for ceremony sessions instead of username. Store state in secure HTTP-only cookies or database. Validate state on finish. - -**Rate limiting per-IP but no account lockout for failed authentication:** -- Risk: Brute force attacks on specific usernames are possible. Attacker can try many passwords (using different IPs) against a single account without consequence. -- Files: `internal/proxy/proxy.go` implements rate limiting (per-IP token bucket), but no equivalent exists for auth endpoints (`internal/auth/auth.go`). -- Current mitigation: WebAuthn makes guessing harder (passkeys), but early attack surface (BeginLogin endpoint) has no protection. Leaked user list could enable targeted attacks. -- Recommendations: Add per-username failure tracking. Lock account after N failed attempts. Add exponential backoff. Require captcha after threshold. - -**CORS Origin validation incomplete:** -- Risk: `OriginCheck` middleware in `internal/server/middleware.go` (lines 71-93) only checks on non-GET requests. GET requests can still trigger state-changing operations (e.g., visiting a crafted link that proxies through the app). -- Files: `internal/server/middleware.go` (lines 74) -- Current mitigation: Proxy request uses query param, but no SameSite cookie attribute on proxy endpoint (only on session cookie). -- Recommendations: Require Origin header on all mutation requests. Consider using POST for scrape trigger. Add X-CSRF-Token validation. - -**Admin user initialization has race condition:** -- Risk: First user to register becomes admin if `ADMIN_USERNAME` not set. Two concurrent registration requests could both see 0 users and both become admin. -- Files: `internal/auth/auth.go` (lines 83-91) -- Current mitigation: Relies on file-level locking in store operations, but store operations are done after the check (line 121), not atomic. -- Recommendations: Move first-user-is-admin logic into CreateUser transaction, or seed admin during initialization phase before accepting requests. - -**Session token stored in http-only cookie but not marked Secure in non-HTTPS:** -- Risk: Cookie marked `Secure: r.TLS != nil` (line 187, 300). In development or non-HTTPS deployments, session token sent over plaintext HTTP. -- Files: `internal/auth/auth.go` (lines 187, 300) -- Current mitigation: None for non-HTTPS. Relies on deployment to enforce HTTPS. -- Recommendations: Always set Secure=true. Force HTTPS in production via HSTS header. Log warning if TLS is nil. - -**Proxy does not validate Content-Type before injecting `` tag:** -- Risk: Non-HTML responses (PDFs, images, binaries) could be corrupted by injecting `` tag. Base64 encoded binary data could break. -- Files: `internal/proxy/proxy.go` (lines 104-119) -- Current mitigation: 5MB body size limit, but no content-type validation. -- Recommendations: Check Content-Type header before modification. Skip injection for non-HTML types. Use proper HTML parsing (e.g., golang.org/x/net/html) instead of string manipulation. - -## Performance Bottlenecks - -**Scraper Reddit parsing with inefficient comment recursion:** -- Problem: `walkComments` in `internal/scraper/reddit.go` (lines 245-260) recursively walks comment trees using JSON unmarshaling in each recursion level. Could cause O(n^2) behavior on deep comment threads. -- Files: `internal/scraper/reddit.go` (lines 245-260, 132-142) -- Cause: Each comment reply is unmarshaled separately. For a thread with 1000 nested replies, this could create 1000 unmarshaling operations. -- Improvement path: Pre-flatten comment tree or use iterative traversal instead of recursion. Cache unmarshaled comments during initial fetch. - -**O(n) lookups on every store operation:** -- Problem: All store methods (GetUserByName, GetUserByID, FindStream by ID) iterate through entire in-memory list. -- Files: `internal/store/users.go` (lines 21-49), `internal/store/streams.go` (lines 12-52) -- Cause: File-based storage forces full-file loads. Even with caching, no indexing. -- Improvement path: With database migration, use indexed lookups. For now, maintain in-process cache with invalidation on updates. - -**Rate limiter token bucket not garbage collected properly:** -- Problem: Buckets for old IPs are deleted every 10 minutes (bucketCleanup), but inactive users' buckets accumulate until cleanup cycle. -- Files: `internal/proxy/proxy.go` (lines 170-181) -- Cause: Cleanup is reactive, not triggered on write. High-traffic scenarios could have thousands of stale buckets in memory. -- Improvement path: Use sync.Map for lock-free reads. Implement heap-based cleanup timer per bucket instead of global interval. - -**Entire streams/sessions list rewritten on every add/delete:** -- Problem: Adding one stream requires reading all streams, appending, and rewriting entire file. Deleting a session does the same. -- Files: `internal/store/streams.go` (lines 54-78, 80-103), `internal/store/sessions.go` (lines 22-44, 61-81) -- Cause: Atomic write pattern (writeJSON uses temp-file-then-rename), but forces full serialization. -- Improvement path: Migrate to database with transaction support. Implement write-ahead logging if staying with files. - -## Fragile Areas - -**Proxy string-based HTML manipulation is fragile:** -- Files: `internal/proxy/proxy.go` (lines 107-119) -- Why fragile: Uses string.Index to find `` and `` tags with string.ToLower comparisons. Cases like `` would be missed. Malformed HTML (missing closing tags, nested structures) could place `` tag in wrong location. -- Safe modification: Use golang.org/x/net/html parser. Insert `` into head node properly. Handle edge cases (no head, multiple heads, xhtml). -- Test coverage: No tests for proxy HTML injection logic. Edge cases untested. - -**Auth ceremony cleanup relies on goroutines:** -- Files: `internal/auth/auth.go` (lines 112-117, 234-239) -- Why fragile: If goroutine is blocked or delayed, cleanup doesn't happen. No guarantee cleanup runs at correct time. Server crash loses all in-flight ceremonies. -- Safe modification: Use context deadlines instead of sleep timers. Implement cleanup on FinishRegistration/FinishLogin regardless of goroutine. Store ceremonies in database with TTL. -- Test coverage: No tests for ceremony timeout behavior. Hard to test goroutine cleanup timing. - -**DeleteStream and related operations use string.Contains for error classification:** -- Files: `internal/server/server.go` (lines 196-203) -- Why fragile: Error messages must contain specific strings ("not authorized", "not found") for proper HTTP status mapping. Changing error text breaks error handling. -- Safe modification: Use error types (custom errors or error wrapping with errors.Is/As). Map error types to status codes centrally. -- Test coverage: No tests for error status code mapping. - -**Scraper is single-threaded with mutex but TriggerScrape starts new goroutine:** -- Files: `internal/scraper/scraper.go` (lines 42-44, 46-92) -- Why fragile: Calling TriggerScrape while scrape() is running (locked) will queue a second scrape. If scrapes take >15 minutes, queue grows. No bounds on concurrent scrapes. -- Safe modification: Use atomic flag to prevent concurrent scrapes. Queue only one pending scrape. Timeout long-running scrapes. -- Test coverage: No tests for concurrent scrape behavior or queue limits. - -**Admin check depends on user count atomicity:** -- Files: `internal/auth/auth.go` (lines 83-91) -- Why fragile: Check user count, then create user are separate operations. Two concurrent registrations both see count=0, both get admin. Later operation fails due to username uniqueness check, but by then both claimed to be admin. -- Safe modification: Move atomicity into CreateUser. Use database transaction. -- Test coverage: No concurrency tests for admin initialization. - -## Scaling Limits - -**All data files live on single filesystem:** -- Current capacity: Depends on disk size. Assuming 1GB available, JSON files with generous spacing could hold ~100k streams, users, or sessions before performance degrades. -- Limit: At 10k active users with 5 sessions each (50k sessions), sessions.json alone is >50MB uncompressed. Each read loads entire file. -- Scaling path: Migrate to database. Use SQLite for single-node, PostgreSQL for distributed. Implement sharding for sessions by user_id. - -**In-memory rate limit buckets per IP:** -- Current capacity: ~100k unique IPs can be tracked before memory pressure (each bucket ~48 bytes). -- Limit: Behind a proxy/load balancer, all traffic appears from proxy IP, making per-IP limiting useless. Map grows indefinitely per proxy. -- Scaling path: Move rate limiting to reverse proxy/load balancer layer (nginx, Envoy). Or, extract real IP from X-Forwarded-For more carefully (currently does this, but assumes trust). - -**Scraper single-threaded, only hits one subreddit:** -- Current capacity: 25 posts per run * 15-min interval = 100 posts/hour. Each post processes comments once. Total throughput ~1000-5000 URLs/hour depending on post depth. -- Limit: If stream demand increases or multiple subreddits need scraping, single scraper becomes bottleneck. No parallelism. -- Scaling path: Implement scraper pool. Scrape multiple subreddits in parallel. Move scraper to separate service. Implement distributed job queue. - -**WebAuthn session storage grows unbounded until server restart:** -- Current capacity: Each ceremony session is ~1KB. 1000 concurrent registrations = 1MB. 100k in-flight = 100MB. -- Limit: Memory exhaustion if registrations are started but not finished (or attacker starts many ceremonies). -- Scaling path: Use database for ceremony sessions. Implement hard timeout (e.g., 5 min) enforced by scheduled cleanup task. Set max concurrent ceremonies. - -## Dependencies at Risk - -**go-webauthn/webauthn v0.15.0:** -- Risk: Security library. May have vulnerabilities. Check for updates regularly. -- Impact: Passkey authentication could be compromised if library has bugs. -- Migration plan: Keep updated. Monitor GitHub releases. Test updates before deploying. - -**Hardcoded subreddit URL (reddit.com API):** -- Risk: Reddit API could change, add authentication requirements, or shut down /r/motorsportsstreams2 community. -- Impact: Scraper stops working entirely. No fallback stream sources. -- Migration plan: Implement abstraction for stream sources. Support multiple scraper backends (Reddit, Discord, Twitter, etc.). Add health checks for scraper endpoints. - -## Test Coverage Gaps - -**No tests for HTTP error handling:** -- What's not tested: Error status code mapping, error response formatting, error logging. -- Files: `internal/server/server.go` (all handlers), `internal/auth/auth.go` (all endpoints) -- Risk: Error responses could be inconsistent or leaky (exposing internal details). Status codes could be wrong. -- Priority: High - -**No tests for concurrent store operations:** -- What's not tested: Race conditions in add/delete/update. Concurrent reads while write in progress. -- Files: `internal/store/streams.go`, `internal/store/sessions.go`, `internal/store/users.go` -- Risk: Data corruption or loss under load. Auth bypass if race condition allows duplicate users. -- Priority: High - -**No tests for WebAuthn ceremony timeouts:** -- What's not tested: Behavior when ceremony session expires. Cleanup of orphaned sessions. -- Files: `internal/auth/auth.go` (BeginRegistration, FinishRegistration, BeginLogin, FinishLogin) -- Risk: Session fixation, orphaned memory, unexpected behavior on retry. -- Priority: Medium - -**No tests for proxy HTML injection:** -- What's not tested: Edge cases (malformed HTML, no head tag, nested structures). Security implications (XSS prevention, CSP). -- Files: `internal/proxy/proxy.go` (ServeHTTP) -- Risk: Injected tags could be placed incorrectly. Proxied content could break. Security headers could be ineffective. -- Priority: Medium - -**No tests for rate limiter token bucket algorithm:** -- What's not tested: Burst capacity behavior, refill rate, edge cases (high request volume, time skew). -- Files: `internal/proxy/proxy.go` (allowRequest, cleanBuckets) -- Risk: Rate limiting could be too strict or too lenient. Cleanup could fail to run. -- Priority: Medium - -**No tests for admin initialization logic:** -- What's not tested: First user gets admin flag. Edge cases with concurrent registrations. Behavior when ADMIN_USERNAME is set. -- Files: `internal/auth/auth.go` (BeginRegistration, lines 83-91) -- Risk: Non-admin user gets admin flag (privilege escalation). Two admins created unexpectedly. -- Priority: High - -**No integration tests for full auth flow:** -- What's not tested: Complete registration + login + logout cycle. Error recovery. Session expiration. -- Files: All of `internal/auth/auth.go` and `internal/server/server.go` auth endpoints. -- Risk: Subtle bugs in ceremony sequencing. Auth logic could break without being detected. -- Priority: High - -**No tests for scraper Reddit parsing:** -- What's not tested: Comment tree recursion. URL extraction. F1 keyword matching. Deduplication logic. -- Files: `internal/scraper/reddit.go` -- Risk: Scraper could miss streams, extract bad URLs, or fail on unexpected Reddit response format. -- Priority: Medium - ---- - -*Concerns audit: 2026-02-17* diff --git a/stacks/f1-stream/files/.planning/codebase/CONVENTIONS.md b/stacks/f1-stream/files/.planning/codebase/CONVENTIONS.md deleted file mode 100644 index 3a4f4e04..00000000 --- a/stacks/f1-stream/files/.planning/codebase/CONVENTIONS.md +++ /dev/null @@ -1,159 +0,0 @@ -# Coding Conventions - -**Analysis Date:** 2026-02-17 - -## Naming Patterns - -**Files:** -- Go packages: lowercase, single word when possible (e.g., `auth`, `store`, `proxy`) -- Go files: lowercase with descriptive names (e.g., `server.go`, `middleware.go`, `reddit.go`) -- JSON files: snake_case (e.g., `users.json`, `sessions.json`, `scraped_links.json`) -- JavaScript files: camelCase (e.g., `app.js`, `auth.js`, `streams.js`) - -**Functions and Methods:** -- Go: PascalCase for exported functions (e.g., `New`, `BeginRegistration`, `ServeHTTP`) -- Go: camelCase for unexported functions (e.g., `randomID`, `isF1Post`, `normalizeURL`) -- JavaScript: camelCase for all functions (e.g., `showToast`, `switchTab`, `doRegister`) - -**Variables and Fields:** -- Go: camelCase for local variables (e.g., `streams`, `userID`, `sessionTTL`) -- Go: PascalCase for exported struct fields (e.g., `ID`, `Username`, `IsAdmin`) -- Go: prefixed mutex pattern: `resourceMu` for mutex protecting resource (e.g., `streamsMu`, `usersMu`, `sessionsMu`) -- JavaScript: camelCase for all variables (e.g., `currentUser`, `beginResp`, `container`) - -**Types and Constants:** -- Go: PascalCase for exported types (e.g., `Server`, `Auth`, `Store`, `User`) -- Go: camelCase for unexported types (e.g., `contextKey`, `bucket`, `redditListing`) -- Go: SCREAMING_SNAKE_CASE for constants (e.g., `maxBodySize`, `rateLimit`, `bucketCleanup`) - -**Interfaces:** -- Go context keys use private types with exported constants (e.g., `type contextKey string; const userKey contextKey = "user"`) - -## Code Style - -**Formatting:** -- Language: Go (no automated formatter config detected, using standard gofmt conventions) -- Import organization: Standard library → local packages (separated by blank line) -- File layout: Package declaration → Imports → Constants/Variables → Types → Functions - -**Linting:** -- No eslint or golangci-yml configuration found -- Go code follows idiomatic Go conventions: error checking, defer cleanup, interface composition - -## Import Organization - -**Go Order:** -1. Standard library imports (context, encoding/json, fmt, log, etc.) -2. Blank line -3. Local f1-stream packages (internal/auth, internal/models, etc.) -4. Blank line -5. External third-party packages (github.com/...) - -**Example from `internal/auth/auth.go`:** -```go -import ( - "crypto/rand" - "encoding/json" - "fmt" - "log" - "net/http" - "regexp" - "sync" - "time" - - "f1-stream/internal/models" - "f1-stream/internal/store" - - "github.com/go-webauthn/webauthn/webauthn" -) -``` - -**JavaScript:** -- No explicit import organization (vanilla JavaScript, no modules) -- HTML file loads scripts in order: utils → app → auth/streams - -## Error Handling - -**Patterns:** -- Go: Explicit error return as second value (e.g., `err := operation(); if err != nil { return err }`) -- Go: Wrapping errors with context: `fmt.Errorf("operation failed: %w", err)` -- Go: String matching on error messages for classification (see `internal/server/server.go` line 196-205) -- Go: Logging errors with `log.Printf()` for non-critical failures, `log.Fatalf()` for startup errors -- Go: HTTP errors returned via `http.Error(w, message, statusCode)` for API endpoints -- JavaScript: Try-catch blocks for async operations, error fields in UI (e.g., `errEl.textContent = err.error || 'Operation failed'`) - -**HTTP Error Responses:** -- Standard JSON format: `{"error":"description"}` -- Success responses vary by endpoint (JSON arrays, `{"ok":true}`, encoded objects via `json.NewEncoder`) - -## Logging - -**Framework:** `log` package (standard library) - -**Patterns:** -- Informational: `log.Printf("message with %v context", value)` -- Errors: `log.Printf("operation failed: %v", err)` -- Startup: `log.Fatalf("critical: %v", err)` for initialization failures -- Component prefixes: `log.Printf("scraper: action description")` - -**Example from `internal/scraper/scraper.go`:** -```go -log.Printf("scraper: starting scrape") -log.Printf("scraper: error after %v: %v", time.Since(start).Round(time.Millisecond), err) -log.Printf("scraper: done in %v, added %d new links (total: %d)", time.Since(start).Round(time.Millisecond), added, len(existing)) -``` - -## Comments - -**When to Comment:** -- Explain WHY, not WHAT (code shows what, comments explain reasoning) -- Used for non-obvious logic or security concerns -- Example from `internal/proxy/proxy.go` line 123: `// Explicitly do NOT copy X-Frame-Options or CSP` -- Example from `internal/auth/auth.go` line 120: `// Store user temporarily - will be committed on finish` - -**Patterns:** -- Short inline comments before complex sections -- Package-level comments before exported types explaining purpose -- Security/business logic gets explained - -## Function Design - -**Size:** Functions keep complexity low, typically 20-50 lines; larger operations split across helpers - -**Parameters:** -- Receiver methods use pointer receivers: `func (s *Store) GetSession(token string) ...` -- Constructor pattern returns initialized type and error: `func New(...) (*Type, error)` -- HTTP handlers follow signature: `func(w http.ResponseWriter, r *http.Request)` - -**Return Values:** -- Errors always returned as last value: `(result, error)` -- Multiple return values when needed: `(*Type, error)` or `([]Type, error)` -- HTTP handlers write directly to ResponseWriter, return via `http.Error()` or direct writes -- Query methods return nil for "not found" rather than error (see `internal/store/users.go` line 33) - -## Module Design - -**Exports:** -- Exported names start with capital letter (e.g., `New`, `User`, `Server`) -- Unexported helpers start with lowercase -- Types exported when they're part of public API -- Helper functions (e.g., `isF1Post`, `normalizeURL`) kept unexported - -**Barrel Files:** Not used; single concerns per file - -**Package Organization:** -- `internal/auth/`: Authentication and WebAuthn implementation -- `internal/store/`: Data persistence (users.go, streams.go, sessions.go, scraped.go, store.go) -- `internal/server/`: HTTP routing and middleware -- `internal/scraper/`: Reddit scraping logic -- `internal/proxy/`: HTTP proxy with rate limiting -- `internal/models/`: Type definitions only - -**Struct Composition:** -- `Server` struct holds dependencies injected at construction (line 15-21 in `internal/server/server.go`) -- Methods extend functionality through receiver pattern -- No inheritance, composition via embedded types used sparingly - ---- - -*Convention analysis: 2026-02-17* diff --git a/stacks/f1-stream/files/.planning/codebase/INTEGRATIONS.md b/stacks/f1-stream/files/.planning/codebase/INTEGRATIONS.md deleted file mode 100644 index 23ba1d1f..00000000 --- a/stacks/f1-stream/files/.planning/codebase/INTEGRATIONS.md +++ /dev/null @@ -1,121 +0,0 @@ -# External Integrations - -**Analysis Date:** 2026-02-17 - -## APIs & External Services - -**Reddit API:** -- Service: Reddit public JSON API (no authentication required) -- What it's used for: Scraping F1 stream links from r/motorsportsstreams2 subreddit - - Fetches 25 most recent posts: `https://www.reddit.com/r/motorsportsstreams2/new.json?limit=25` - - Extracts URLs from post titles and comment bodies - - Filters by F1-related keywords - - Runs on configurable interval (default 15 minutes) -- Implementation: `internal/scraper/reddit.go` -- Authentication: None - public API endpoint - -**HTTP Proxy Service:** -- Service: Internal HTTP proxy for accessing external streams -- What it's used for: Fetching and proxying external stream pages while enforcing security policies - - Rate limiting: 30 requests/minute per IP with 5-request burst capacity - - URL validation: Only HTTPS URLs allowed, 2048-character limit - - Private IP blocking: Blocks requests to loopback, private, and link-local addresses - - Content transformation: Injects `` tag for relative URL resolution - - Strips X-Frame-Options and CSP headers to allow iframe embedding -- Implementation: `internal/proxy/proxy.go` -- Endpoint: `GET /proxy?url=[url]` - -## Data Storage - -**File Storage:** -- Type: Local filesystem (JSON files) -- Location: Configurable via `DATA_DIR` environment variable (default: `/data`) -- Persistence mechanism: - - Atomic writes using temp-file-then-rename pattern - - No database server required - - Files stored in flat structure: - - `streams.json` - User-submitted and scraped stream links - - `users.json` - User accounts with WebAuthn credentials - - `sessions.json` - Active user sessions - - `scraped.json` - Reddit-scraped links -- Client: Go `encoding/json` standard library with sync.RWMutex for thread-safe access - -**Caching:** -- Type: None - file-based storage only -- Session cleanup: Automatic garbage collection every 1 hour - -## Authentication & Identity - -**Auth Provider:** -- Type: Custom WebAuthn/FIDO2 implementation -- Library: github.com/go-webauthn/webauthn v0.15.0 -- Implementation details: - - Passwordless authentication using WebAuthn standard - - Registration ceremony: `POST /api/auth/register/begin` → `POST /api/auth/register/finish` - - Login ceremony: `POST /api/auth/login/begin` → `POST /api/auth/login/finish` - - Session tokens stored in HTTP-only, SameSite-strict cookies - - In-memory ceremony data storage with 5-minute expiration - - Manual admin assignment via `ADMIN_USERNAME` env var - - First user automatically becomes admin if no `ADMIN_USERNAME` set -- Files: `internal/auth/auth.go`, `internal/auth/context.go` - -## Monitoring & Observability - -**Error Tracking:** -- Type: None - no external error tracking service -- Implementation: Standard Go logging with `log` package - -**Logs:** -- Format: Standard Go log output (stdout) -- Level: Info and error messages -- No centralized logging, no external integration - -## CI/CD & Deployment - -**Hosting:** -- Platform: Kubernetes (Terraform module at `infra/modules/kubernetes/f1-stream/`) -- Deployment method: Container image - -**CI Pipeline:** -- Type: Not detected in this codebase -- Build method: Dockerfile multi-stage build - - Builder: golang:1.23-alpine with `go mod download` - - Runtime: alpine:3.20 with minimal dependencies - -## Environment Configuration - -**Required env vars (with defaults):** -- `LISTEN_ADDR` - Server listen address (default: `:8080`) -- `DATA_DIR` - Data storage directory (default: `/data`) -- `SCRAPE_INTERVAL` - Reddit scraper frequency (default: 15m) -- `SESSION_TTL` - Session expiration (default: 720h) -- `PROXY_TIMEOUT` - Proxy request timeout (default: 10s) -- `WEBAUTHN_RPID` - Relying party ID (default: `localhost`) -- `WEBAUTHN_ORIGIN` - Origin URL list, comma-separated (default: `http://localhost:8080`) -- `WEBAUTHN_DISPLAY_NAME` - UI display name (default: `F1 Stream`) -- `ADMIN_USERNAME` - Optional: pre-set admin username (no default) - -**Secrets location:** -- No secrets required - uses WebAuthn credentials stored locally -- CORS origin validation via `WEBAUTHN_ORIGIN` env var - -## Webhooks & Callbacks - -**Incoming:** -- None detected - -**Outgoing:** -- None detected - -## Stream Link Sources - -**Default Stream URLs (hardcoded in main.go):** -1. `https://wearechecking.live/streams-pages/motorsports` - WeAreChecking Motorsports -2. `https://vipleague.im/formula-1-schedule-streaming-links` - VIPLeague F1 -3. `https://www.vipbox.lc/` - VIPBox -4. `https://f1box.me/` - F1Box -5. `https://1stream.vip/formula-1-streams/` - 1Stream F1 - ---- - -*Integration audit: 2026-02-17* diff --git a/stacks/f1-stream/files/.planning/codebase/STACK.md b/stacks/f1-stream/files/.planning/codebase/STACK.md deleted file mode 100644 index cc9a0371..00000000 --- a/stacks/f1-stream/files/.planning/codebase/STACK.md +++ /dev/null @@ -1,109 +0,0 @@ -# Technology Stack - -**Analysis Date:** 2026-02-17 - -## Languages - -**Primary:** -- Go 1.24.1 - Backend application and main server logic - -**Secondary:** -- HTML/CSS/JavaScript - Frontend UI - -## Runtime - -**Environment:** -- Go runtime (compiled binary) - -**Container Runtime:** -- Docker/Alpine Linux (3.20) - Production deployment target -- Multi-stage Dockerfile with golang:1.23-alpine builder - -**Package Manager:** -- Go modules (go.mod/go.sum) - -## Frameworks - -**Core:** -- Standard Go `net/http` - HTTP server and routing - - Native http.ServeMux for route handling (Go 1.22+ pattern routing) - - Native http.FileServer for static file serving - - Native http.Handler interface for middleware - -**Authentication:** -- github.com/go-webauthn/webauthn v0.15.0 - WebAuthn/FIDO2 authentication - - Handles registration and login ceremonies - - Supports multiple credential types - -**Frontend:** -- HTML5 - Markup -- CSS - Styling (Pico CSS framework for minimal styling) -- Vanilla JavaScript - Client-side interactivity (no framework detected) - -## Key Dependencies - -**Critical:** -- github.com/go-webauthn/webauthn v0.15.0 - Passwordless authentication via WebAuthn - - Includes transitive dependencies: - - github.com/go-webauthn/x v0.1.26 - WebAuthn extension support - - github.com/golang-jwt/jwt/v5 v5.3.0 - JWT token handling - - github.com/google/go-tpm v0.9.6 - TPM support for credentials - - github.com/fxamacker/cbor/v2 v2.9.0 - CBOR encoding/decoding - - github.com/go-viper/mapstructure/v2 v2.4.0 - Configuration mapping - - github.com/google/uuid v1.6.0 - UUID generation - - golang.org/x/crypto v0.43.0 - Cryptographic primitives - - golang.org/x/sys v0.37.0 - System-level primitives - -**Infrastructure:** -- None detected (no external databases, queues, or third-party services in go.mod) -- File-based storage only - -## Configuration - -**Environment Variables:** -- `LISTEN_ADDR` - Server listen address (default: `:8080`) -- `DATA_DIR` - Data storage directory (default: `/data`) -- `SCRAPE_INTERVAL` - Reddit scraper interval (default: 15 minutes) -- `ADMIN_USERNAME` - Admin account username (optional) -- `SESSION_TTL` - Session expiration time (default: 720 hours) -- `PROXY_TIMEOUT` - HTTP proxy request timeout (default: 10 seconds) -- `WEBAUTHN_RPID` - WebAuthn relying party ID (default: `localhost`) -- `WEBAUTHN_ORIGIN` - WebAuthn origin URL (default: `http://localhost:8080`) -- `WEBAUTHN_DISPLAY_NAME` - WebAuthn display name (default: `F1 Stream`) - -**Build:** -- `Dockerfile` - Multi-stage Docker build - - Builder stage: golang:1.23-alpine with CGO_ENABLED=0 - - Runtime stage: alpine:3.20 with ca-certificates - - Exposes port 8080 - -## Platform Requirements - -**Development:** -- Go 1.24.1 or compatible -- Unix-like shell (bash/zsh) for build scripts -- Optional: Docker for containerized development - -**Production:** -- Kubernetes cluster (Terraform module structure suggests K8s deployment) -- Persistent volume for `/data` directory -- Port 8080 exposed for HTTP traffic -- ca-certificates for HTTPS proxying - -## Storage - -**Data Persistence:** -- File-based JSON storage in `DATA_DIR` -- Files: `streams.json`, `users.json`, `sessions.json`, `scraped.json` -- Atomic writes using temp-file-then-rename pattern (`writeJSON` function in `internal/store/store.go`) - -## External Data Sources - -**Reddit API:** -- URL: `https://www.reddit.com/r/motorsportsstreams2/new.json?limit=25` -- No authentication required (public subreddit) -- Used for scraping F1 stream links - ---- - -*Stack analysis: 2026-02-17* diff --git a/stacks/f1-stream/files/.planning/codebase/STRUCTURE.md b/stacks/f1-stream/files/.planning/codebase/STRUCTURE.md deleted file mode 100644 index db27252e..00000000 --- a/stacks/f1-stream/files/.planning/codebase/STRUCTURE.md +++ /dev/null @@ -1,202 +0,0 @@ -# Codebase Structure - -**Analysis Date:** 2026-02-17 - -## Directory Layout - -``` -f1-stream/ -├── main.go # Entry point, service initialization, signal handling -├── go.mod # Go module definition -├── go.sum # Dependency lock file -├── Dockerfile # Container image definition -├── redeploy.sh # Kubernetes redeployment script -├── index.html # HTML template served at root -├── internal/ # Private Go packages -│ ├── auth/ # WebAuthn authentication and session management -│ ├── models/ # Domain data types -│ ├── server/ # HTTP handlers, routes, middleware -│ ├── store/ # File-based persistence layer -│ ├── scraper/ # Reddit content scraper -│ └── proxy/ # HTTP proxy with rate limiting -├── static/ # Frontend assets served to clients -│ ├── index.html # Main SPA template -│ ├── css/ # Stylesheets -│ └── js/ # Client-side JavaScript modules -└── .planning/ # Planning/documentation directory - └── codebase/ # Architecture analysis documents -``` - -## Directory Purposes - -**Root Level:** -- Purpose: Service configuration and entry point -- Contains: Go module, main executable, Docker configuration, shell scripts -- Key files: `main.go` (service bootstrap), `go.mod` (dependencies) - -**`internal/`:** -- Purpose: Private packages (not importable by external code) -- Contains: All business logic, separated by concern -- Key pattern: Each subdirectory is a distinct Go package with clear responsibility - -**`internal/auth/`:** -- Purpose: User authentication, session management, context helpers -- Contains: WebAuthn ceremony handlers, session token management, user-in-context utilities -- Key files: - - `auth.go`: Registration/login handlers, ceremony session storage, credential validation - - `context.go`: Request context helpers for passing user data between middleware and handlers - -**`internal/models/`:** -- Purpose: Domain model definitions -- Contains: User, Stream, ScrapedLink, Session type definitions -- Key files: `models.go` (all types, includes WebAuthn interface implementations) - -**`internal/server/`:** -- Purpose: HTTP API and routing layer -- Contains: Handler functions, route registration, middleware implementations -- Key files: - - `server.go`: Server struct, route registration, API handlers (streams, admin, public endpoints) - - `middleware.go`: LoggingMiddleware, RecoveryMiddleware, AuthMiddleware, RequireAuth, RequireAdmin, OriginCheck - -**`internal/store/`:** -- Purpose: Persistent storage abstraction over file system -- Contains: JSON file operations, per-entity storage methods, atomic write patterns -- Key files: - - `store.go`: Store struct, directory initialization, JSON helper functions (readJSON, writeJSON) - - `streams.go`: Stream CRUD operations, publish toggle, seeding - - `users.go`: User lookup, credential updates, admin count - - `sessions.go`: Session creation, validation, expiry cleanup - - `scraped.go`: Scraped link persistence, active link filtering - -**`internal/scraper/`:** -- Purpose: Background content aggregation -- Contains: Interval-based scraper, Reddit-specific scraper logic -- Key files: - - `scraper.go`: Scraper service, interval-based run loop, manual trigger mechanism, deduplication logic - - `reddit.go`: Reddit API polling, F1 keyword filtering, URL extraction (not included in sample reads but referenced) - -**`internal/proxy/`:** -- Purpose: HTTP content fetching with security controls and rate limiting -- Contains: Rate limiter, private IP validation, response modification -- Key files: `proxy.go` (implements http.Handler, rate limiting, content fetching, base tag injection) - -**`static/`:** -- Purpose: Frontend assets served to browser -- Contains: HTML template and client-side code -- Key files: - - `index.html`: SPA HTML template (includes script tags loading js/) - - `js/app.js`: Toast notifications, dialog system, tab switching, initialization - - `js/auth.js`: Registration/login UI, WebAuthn client ceremony - - `js/streams.js`: Stream display, filtering, admin operations - - `js/utils.js`: Shared utilities (HTML escaping) - - `css/`: Stylesheets for app UI - -## Key File Locations - -**Entry Points:** -- `main.go`: Service initialization, dependency injection, signal handling, goroutine startup - -**Configuration:** -- Environment variables read in `main.go` (LISTEN_ADDR, DATA_DIR, SCRAPE_INTERVAL, etc.) -- WebAuthn config passed to `auth.New()` -- `.env` files not tracked (see .gitignore) - -**Core Logic:** -- Request routing: `internal/server/server.go:registerRoutes()` -- Auth logic: `internal/auth/auth.go` -- Data storage: `internal/store/store.go` and per-entity files -- Scraping: `internal/scraper/scraper.go` -- Proxying: `internal/proxy/proxy.go` - -**Testing:** -- No test files present in codebase (see TESTING.md concerns section) - -## Naming Conventions - -**Files:** -- Go source files: lowercase with underscores (e.g., `auth.go`, `middleware.go`) -- JavaScript files: lowercase with hyphens or underscores (e.g., `app.js`, `auth.js`) -- JSON data files: lowercase (e.g., `streams.json`, `users.json`, `sessions.json`) - -**Directories:** -- Go packages: lowercase, single word preferred (e.g., `auth`, `store`, `models`) -- Frontend assets: plural nouns (e.g., `static`, `css`, `js`) - -**Functions:** -- Go: CamelCase (exported), camelCase (unexported) -- JavaScript: camelCase throughout (e.g., `loadPublicStreams()`, `showToast()`) - -**Types:** -- Go structs: CamelCase (e.g., `User`, `Stream`, `Store`, `Auth`) -- Methods: CamelCase (e.g., `BeginLogin()`, `AddStream()`) - -**Variables:** -- Go: camelCase (e.g., `listenAddr`, `dataDir`, `adminUsername`) -- JavaScript: camelCase (e.g., `container`, `userID`, `sessionToken`) - -## Where to Add New Code - -**New Feature (e.g., new stream filter):** -- Primary code: Add handler in `internal/server/server.go`, register route in `registerRoutes()` -- Store operations: Add method to appropriate file in `internal/store/` (likely `streams.go`) -- Frontend: Add UI in `static/` and API call in `static/js/streams.js` or new module -- Models: Extend types in `internal/models/models.go` if new fields needed - -**New Authentication Method:** -- Core implementation: New file in `internal/auth/` (e.g., `oauth.go`) -- Handlers: Add methods following WebAuthn pattern (BeginXxx, FinishXxx) -- Routes: Register in `registerRoutes()` -- Frontend: Add form/button in `static/js/auth.js` - -**New Background Service (e.g., content validator):** -- Implementation: New file in `internal/` or new package `internal/validator/` -- Integration: Initialize in `main()` alongside `scraper.New()` -- Lifecycle: Use context pattern from scraper's `Run(ctx)` method -- Storage: Use existing `Store` instance - -**Utilities/Helpers:** -- Shared by Go packages: Add to package where most useful, or create new `internal/util/` package -- Shared by frontend: Add to `static/js/utils.js` or create new module -- Shared helpers pattern: Functions not tied to single package, used across multiple - -## Special Directories - -**`internal/`:** -- Purpose: Enforce package privacy (cannot be imported by external code) -- Generated: No -- Committed: Yes - -**`static/`:** -- Purpose: Served directly to clients via `http.FileServer` -- Generated: No (hand-written frontend) -- Committed: Yes - -**`.planning/codebase/`:** -- Purpose: Architecture documentation for development guidance -- Generated: No (manually created by mapping process) -- Committed: Yes - -**Data Directory (runtime):** -- Purpose: Persistent JSON files (streams.json, users.json, sessions.json, scraped.json) -- Location: Specified by DATA_DIR env var (default `/data`) -- Generated: Yes (created on first run) -- Committed: No (varies per deployment environment) - -## Import Patterns - -**Go Package Imports:** -- Standard library first: `import ("context" "fmt" "log")` -- Internal packages second: `import ("f1-stream/internal/auth" "f1-stream/internal/store")` -- External third-party last: `import ("github.com/go-webauthn/webauthn/webauthn")` - -**Cross-Package Dependencies:** -- Server depends on: Auth, Store, Proxy, Scraper, Models -- Auth depends on: Store, Models -- Scraper depends on: Store, Models -- Proxy depends on: none (standalone service) -- Store depends on: Models -- Models depends on: external WebAuthn library only - ---- - -*Structure analysis: 2026-02-17* diff --git a/stacks/f1-stream/files/.planning/codebase/TESTING.md b/stacks/f1-stream/files/.planning/codebase/TESTING.md deleted file mode 100644 index 8e381269..00000000 --- a/stacks/f1-stream/files/.planning/codebase/TESTING.md +++ /dev/null @@ -1,256 +0,0 @@ -# Testing Patterns - -**Analysis Date:** 2026-02-17 - -## Test Framework - -**Status:** No testing infrastructure present - -**Runner:** Not detected - -**Assertion Library:** Not applicable - -**Run Commands:** Not applicable - -## Test File Organization - -**Current State:** Zero test files found - -After scanning the codebase: -- No `*_test.go` files in `internal/` packages -- No `*.test.js` or `*.spec.js` files in static assets -- No test configuration files (jest.config.js, vitest.config.ts, etc.) -- No test runners in go.mod dependencies - -## Test Coverage - -**Requirements:** Not enforced; no test infrastructure - -**Current Coverage:** 0% - no tests exist - -## Test Types Present in Codebase - -### Unit Test Candidates (Not Currently Tested) - -**`internal/models/models.go`:** -- User and Stream model struct definitions -- WebAuthn interface implementations (lines 18-21) - -**`internal/auth/auth.go`:** -- Username validation via regex `usernameRe` (line 19) -- Registration/login ceremony steps -- Session creation and token generation -- Admin user detection logic (lines 83-91) - -**`internal/store/*.go` (all files):** -- JSON read/write operations with file locking -- User lookup and stream operations -- Session creation, validation, and cleanup -- Scraped link filtering and deduplication - -**`internal/scraper/reddit.go`:** -- F1 post detection: `isF1Post()` function (line 272-285) -- URL normalization: `normalizeURL()` function (line 262-270) -- URL extraction: `extractURLs()` function (line 210-243) -- Comment walking: `walkComments()` function (line 245-260) -- Keyword matching logic (lines 29-45) -- Retry logic with backoff (lines 183-208) - -**`internal/proxy/proxy.go`:** -- Rate limiting with token bucket algorithm (lines 145-168) -- Private host detection: `isPrivateHost()` function (line 128-143) -- Client IP extraction: `clientAddr()` function (line 184-191) -- Bucket cleanup mechanism (lines 170-182) - -**`internal/server/middleware.go`:** -- Auth middleware context injection -- Authorization checks (RequireAuth, RequireAdmin) -- Origin validation for CSRF protection -- Panic recovery middleware - -### Integration Test Candidates (Not Currently Tested) - -**Authentication Flow:** -- Begin registration → finish registration → session creation -- Begin login → finish login → session creation -- Session validation and expiration -- WebAuthn ceremony with mock credentials - -**Stream Management:** -- Add stream → save to JSON → retrieve -- Delete stream with authorization checks -- Toggle publish status -- Filter streams by visibility/ownership - -**Scraping Pipeline:** -- Fetch Reddit listing -- Extract F1 posts -- Walk comments recursively -- Deduplicate URLs -- Merge with existing links - -### E2E Test Candidates (Not Currently Tested) - -**HTTP Endpoints:** -- Full registration flow (POST /api/auth/register/begin, /api/auth/register/finish) -- Full login flow (POST /api/auth/login/begin, /api/auth/login/finish) -- Stream CRUD operations -- Public stream viewing -- Scrape triggering and result retrieval - -## Critical Untested Paths - -**High Risk - Security:** -- Authentication middleware context injection (`internal/server/middleware.go` lines 33-43) -- Admin authorization checks (line 62) -- CSRF origin validation (line 78-88) -- Private address filtering in proxy (line 77-80 in `internal/proxy/proxy.go`) -- Rate limiting enforcement (line 62-65 in `internal/proxy/proxy.go`) - -**High Risk - Data Integrity:** -- Concurrent access to store files via mutex protection (no verification that race conditions are prevented) -- JSON read/write atomicity with temp files (lines 41-52 in `internal/store/store.go`) -- Session expiration cleanup (lines 83-98 in `internal/store/sessions.go`) -- Stream deduplication during scraping (lines 65-85 in `internal/scraper/scraper.go`) - -**Medium Risk - Business Logic:** -- F1 post detection with negative keywords (lines 272-285 in `internal/scraper/reddit.go`) -- URL normalization for deduplication (line 262-270) -- Retry logic with rate limit backoff (line 183-208) - -## What Needs Testing - -### Unit Test Suggestions - -```go -// Example: Test username validation -func TestUsernameValidation(t *testing.T) { - tests := []struct { - username string - valid bool - }{ - {"valid123", true}, - {"valid_name", true}, - {"ab", false}, // too short - {"invalid-char", false}, // invalid character - {"", false}, // empty - } - // usernameRe.MatchString(username) for each test case -} - -// Example: Test F1 post detection -func TestIsF1Post(t *testing.T) { - tests := []struct { - title string - expected bool - }{ - {"F1 GP Race - Monaco", true}, - {"Formula 1 Practice", true}, - {"Help with F1 key binding", false}, // negative keyword - {"Random post about cars", false}, - } - // isF1Post(title) for each test case -} - -// Example: Test URL normalization -func TestNormalizeURL(t *testing.T) { - // Check that different URL formats normalize to same string - // Check case-insensitivity and trailing slash handling -} - -// Example: Test rate limiting -func TestRateLimiting(t *testing.T) { - p := New(10 * time.Second) - ip := "192.168.1.1" - - // First burst allowed - for i := 0; i < 5; i++ { - if !p.allowRequest(ip) { - t.Fail() - } - } - - // Burst exhausted - if p.allowRequest(ip) { - t.Fail() - } - - // Wait and verify replenishment - time.Sleep(10 * time.Second) - if !p.allowRequest(ip) { - t.Fail() - } -} -``` - -### Integration Test Suggestions - -```go -// Example: Test store operations with concurrency -func TestConcurrentStreamOperations(t *testing.T) { - st, _ := store.New(t.TempDir()) - - // Concurrent adds from multiple goroutines - // Verify no data corruption - // Verify final count is correct -} - -// Example: Test scraper deduplication -func TestScraperDeduplication(t *testing.T) { - // Create scraper with test store - // Mock Reddit response with duplicate URLs - // Verify only unique URLs are stored - // Verify normalization works (http vs https, trailing slashes) -} - -// Example: Test auth middleware -func TestAuthMiddleware(t *testing.T) { - st, _ := store.New(t.TempDir()) - auth, _ := auth.New(st, ...) - - // Create test token - // Make request with session cookie - // Verify user injected into context -} -``` - -## Recommended Testing Strategy - -1. **Phase 1 - Unit Tests (Highest Priority):** - - Validation functions (username regex, F1 keywords) - - String utilities (URL normalization, truncate) - - Rate limiting algorithm - - Private host detection - -2. **Phase 2 - Integration Tests:** - - Store operations with concurrency (verify mutex protection) - - Scraper pipeline (Reddit fetch → parse → deduplicate → save) - - Auth ceremony flow with mock WebAuthn - - Stream CRUD with permission checks - -3. **Phase 3 - E2E Tests:** - - Full HTTP request flows - - Middleware chain validation - - Session management across endpoints - -## Testing Patterns to Establish - -**Once framework chosen (Go: testing or testify):** - -- Use `t.TempDir()` for store tests to avoid file conflicts -- Mock HTTP responses for scraper tests -- Use `net/http/httptest` for handler testing -- Mock WebAuthn responses for auth tests -- Table-driven tests for validation logic -- Parallel test execution with `-race` flag for concurrency detection - -**Coverage gaps to close:** -- All error paths in store operations -- Session expiration edge cases -- Concurrent access scenarios -- HTTP header validation -- CORS/origin validation - ---- - -*Testing analysis: 2026-02-17* diff --git a/stacks/f1-stream/files/.planning/config.json b/stacks/f1-stream/files/.planning/config.json deleted file mode 100644 index 758c1fd8..00000000 --- a/stacks/f1-stream/files/.planning/config.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "mode": "yolo", - "depth": "standard", - "parallelization": true, - "commit_docs": true, - "model_profile": "quality", - "workflow": { - "research": true, - "plan_check": true, - "verifier": true - } -} diff --git a/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-01-PLAN.md b/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-01-PLAN.md deleted file mode 100644 index ec92eb20..00000000 --- a/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-01-PLAN.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -phase: 01-scraper-validation -plan: 01 -type: execute -wave: 1 -depends_on: [] -files_modified: - - internal/scraper/validate.go - - internal/scraper/validate_test.go - - internal/scraper/scraper.go - - main.go -autonomous: true -requirements: - - SCRP-01 - - SCRP-02 - - SCRP-03 - - SCRP-04 - -must_haves: - truths: - - "Scraper still discovers F1-related posts using keyword filtering (existing isF1Post behavior unchanged)" - - "Each newly scraped URL is fetched and inspected for video/player content markers before being saved to scraped_links.json" - - "URLs without video content markers are discarded and do not appear in scraped_links.json" - - "Validation uses a configurable timeout (SCRAPER_VALIDATE_TIMEOUT env var, default 10s) that prevents slow sites from blocking the scrape cycle" - artifacts: - - path: "internal/scraper/validate.go" - provides: "URL validation logic with video marker detection" - contains: "func validateLinks" - - path: "internal/scraper/validate_test.go" - provides: "Unit tests for marker detection and content type checks" - contains: "func TestContainsVideoMarkers" - - path: "internal/scraper/scraper.go" - provides: "Updated Scraper struct with validateTimeout field and validation call in scrape()" - contains: "validateTimeout" - - path: "main.go" - provides: "SCRAPER_VALIDATE_TIMEOUT env var configuration" - contains: "SCRAPER_VALIDATE_TIMEOUT" - key_links: - - from: "internal/scraper/scraper.go" - to: "internal/scraper/validate.go" - via: "validateLinks call in scrape() between URL extraction and merge" - pattern: "validateLinks\\(links" - - from: "main.go" - to: "internal/scraper/scraper.go" - via: "scraper.New() call with validateTimeout parameter" - pattern: "scraper\\.New\\(st.*validateTimeout" ---- - - -Add URL validation to the scraper pipeline so that each extracted URL is proxy-fetched and inspected for video/player content markers before being saved. URLs without video markers are discarded at the source. - -Purpose: Eliminate junk links (blog posts, news articles, social media) from scraped results so users only see actual stream pages. -Output: Working validation step integrated into scraper pipeline, with unit tests and configurable timeout. - - - -@/Users/viktorbarzin/.claude/get-shit-done/workflows/execute-plan.md -@/Users/viktorbarzin/.claude/get-shit-done/templates/summary.md - - - -@.planning/PROJECT.md -@.planning/ROADMAP.md -@.planning/STATE.md -@.planning/phases/01-scraper-validation/01-RESEARCH.md - -@internal/scraper/scraper.go -@internal/scraper/reddit.go -@internal/models/models.go -@main.go - - - - - - Task 1: Create validate.go with video marker detection - internal/scraper/validate.go - -Create `internal/scraper/validate.go` in package `scraper` with the following: - -1. Define `videoMarkers` string slice (case-insensitive markers checked against lowercased HTML body): - - HTML5: `= 3`). - - Iterate over links. For each, call `hasVideoContent(client, link.URL)`. If true, keep the link. If false, log: `scraper: discarded %s (no video markers)` using `truncate(link.URL, 60)`. - - Return the filtered slice. - -5. Implement `hasVideoContent(client *http.Client, rawURL string) bool`: - - Create GET request with `User-Agent` set to the existing `userAgent` constant from `reddit.go`. - - Execute request. On error, log and return false. - - Check status code: if < 200 or >= 400, return false. - - Check Content-Type header (lowercased) against `videoContentTypes` -- if match, return true (it's a direct video file). - - If Content-Type is not `text/html` or `application/xhtml`, return false (not a video file, not an HTML page to inspect). - - Read body with `io.LimitReader` (2MB limit). - - Return `containsVideoMarkers(strings.ToLower(string(body)))`. - -6. Implement `containsVideoMarkers(loweredBody string) bool`: - - Iterate over `videoMarkers`, return true on first `strings.Contains` match. - -7. Implement `isDirectVideoContentType(ct string) bool`: - - Lowercase ct, iterate `videoContentTypes`, return true on first `strings.Contains` match. - -Imports needed: `io`, `log`, `net/http`, `strings`, `time`, and `f1-stream/internal/models`. - -Do NOT use `golang.org/x/net/html` (reserved for Phase 4). This is detection, not extraction -- string matching is sufficient. - - -Run `cd /Users/viktorbarzin/code/infra/modules/kubernetes/f1-stream/files && go build ./...` -- must compile without errors. - - -`validate.go` exists with `validateLinks`, `hasVideoContent`, `containsVideoMarkers`, `isDirectVideoContentType` functions. The file compiles as part of the `scraper` package. - - - - - Task 2: Wire validation into scraper pipeline and add config - internal/scraper/scraper.go, main.go - -**In `internal/scraper/scraper.go`:** - -1. Add `validateTimeout time.Duration` field to the `Scraper` struct. - -2. Update `New()` signature to accept `validateTimeout` parameter: - ```go - func New(s *store.Store, interval time.Duration, validateTimeout time.Duration) *Scraper { - return &Scraper{store: s, interval: interval, validateTimeout: validateTimeout} - } - ``` - -3. In `scrape()` method, add validation step between the `scrapeReddit()` return and the merge-with-existing logic. Insert AFTER the line `log.Printf("scraper: reddit scrape completed in %v, got %d links", ...)` and BEFORE the line `existing, err := s.store.LoadScrapedLinks()`: - - ```go - // Validate links - only keep those with video content markers - if len(links) > 0 { - validated := validateLinks(links, s.validateTimeout) - log.Printf("scraper: validated %d/%d links as streams", len(validated), len(links)) - links = validated - } - ``` - - This preserves SCRP-01: existing keyword filtering in `scrapeReddit()` via `isF1Post()` runs first, then validation filters the results. - -**In `main.go`:** - -1. Add `validateTimeout` env var read after the existing `scrapeInterval` line: - ```go - validateTimeout := envDuration("SCRAPER_VALIDATE_TIMEOUT", 10*time.Second) - ``` - -2. Update the `scraper.New()` call to pass the new parameter: - ```go - sc := scraper.New(st, scrapeInterval, validateTimeout) - ``` - -Both changes are minimal and follow the existing configuration pattern used for `SCRAPE_INTERVAL`, `PROXY_TIMEOUT`, etc. - - -Run `cd /Users/viktorbarzin/code/infra/modules/kubernetes/f1-stream/files && go build ./...` -- must compile without errors. Then run `go vet ./...` -- no issues. - - -`Scraper` struct has `validateTimeout` field. `New()` accepts 3 parameters. `scrape()` calls `validateLinks` between extraction and merge. `main.go` reads `SCRAPER_VALIDATE_TIMEOUT` env var (default 10s) and passes it to `scraper.New()`. - - - - - Task 3: Add unit tests for validation functions - internal/scraper/validate_test.go - -Create `internal/scraper/validate_test.go` in package `scraper` with the following test functions: - -**`TestContainsVideoMarkers`** - table-driven test covering: -- Positive cases (should return true): - - ` - -Run `cd /Users/viktorbarzin/code/infra/modules/kubernetes/f1-stream/files && go test ./internal/scraper/ -v -run "TestContainsVideoMarkers|TestIsDirectVideoContentType"` -- all tests pass. - - -`validate_test.go` exists with `TestContainsVideoMarkers` (8+ positive, 4+ negative cases) and `TestIsDirectVideoContentType` (6+ positive, 5+ negative cases). All tests pass. - - - - - - -1. `go build ./...` compiles without errors -2. `go vet ./...` reports no issues -3. `go test ./internal/scraper/ -v` -- all tests pass -4. Verify `validate.go` contains the `videoMarkers` slice with at least 15 markers -5. Verify `scraper.go:scrape()` calls `validateLinks` between `scrapeReddit()` return and `LoadScrapedLinks()` -6. Verify `main.go` reads `SCRAPER_VALIDATE_TIMEOUT` with default `10*time.Second` -7. Verify the existing `isF1Post` keyword filtering in `scrapeReddit()` is untouched (SCRP-01) - - - -- The scraper pipeline compiles and all tests pass -- `validateLinks` is called in `scrape()` after URL extraction but before merge, filtering out URLs without video markers -- The validation timeout is configurable via `SCRAPER_VALIDATE_TIMEOUT` env var (default 10s) -- Existing F1 keyword filtering behavior is preserved unchanged -- No new external dependencies are introduced (stdlib only) - - - -After completion, create `.planning/phases/01-scraper-validation/01-01-SUMMARY.md` - diff --git a/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-01-SUMMARY.md b/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-01-SUMMARY.md deleted file mode 100644 index bd4b7d41..00000000 --- a/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-01-SUMMARY.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -phase: 01-scraper-validation -plan: 01 -subsystem: scraper -tags: [go, http, video-detection, content-validation, streaming] - -# Dependency graph -requires: [] -provides: - - "URL validation pipeline with video marker detection (validateLinks)" - - "Configurable validation timeout via SCRAPER_VALIDATE_TIMEOUT env var" - - "Video content type and HTML marker detection functions" -affects: [02-health-checks, 04-link-extraction] - -# Tech tracking -tech-stack: - added: [] - patterns: - - "Pipeline filter pattern: scrapeReddit -> validateLinks -> merge" - - "String-match video detection (no DOM parsing) for Phase 1 speed" - - "2MB body limit for HTML inspection to prevent memory issues" - -key-files: - created: - - internal/scraper/validate.go - - internal/scraper/validate_test.go - modified: - - internal/scraper/scraper.go - - main.go - -key-decisions: - - "String matching over DOM parsing for video detection (DOM reserved for Phase 4)" - - "2MB body limit to prevent memory issues on large pages" - - "3 redirect limit to avoid infinite redirect chains" - -patterns-established: - - "Pipeline filter: validate scraped links before merge into store" - - "Env var config pattern: envDuration for timeout configuration" - -requirements-completed: [SCRP-01, SCRP-02, SCRP-03, SCRP-04] - -# Metrics -duration: 3min -completed: 2026-02-17 ---- - -# Phase 1 Plan 1: Scraper Validation Summary - -**URL validation pipeline with 18 video/player markers filtering scraped links before store merge, configurable via SCRAPER_VALIDATE_TIMEOUT** - -## Performance - -- **Duration:** 3 min -- **Started:** 2026-02-17T20:49:16Z -- **Completed:** 2026-02-17T20:51:54Z -- **Tasks:** 3 -- **Files modified:** 4 - -## Accomplishments -- Created validate.go with 18 video/player markers covering HTML5, HLS, DASH, and 10+ player libraries -- Wired validateLinks into scrape() pipeline between URL extraction and store merge -- Added SCRAPER_VALIDATE_TIMEOUT env var (default 10s) following existing config patterns -- Added 25 unit tests (10 positive + 4 negative marker tests, 6 positive + 5 negative content type tests) - -## Task Commits - -Each task was committed atomically: - -1. **Task 1: Create validate.go with video marker detection** - `adeb478` (feat) -2. **Task 2: Wire validation into scraper pipeline and add config** - `22d29db` (feat) -3. **Task 3: Add unit tests for validation functions** - `6c5cc02` (test) - -## Files Created/Modified -- `internal/scraper/validate.go` - URL validation with video marker detection (validateLinks, hasVideoContent, containsVideoMarkers, isDirectVideoContentType) -- `internal/scraper/validate_test.go` - Table-driven unit tests for marker detection and content type checks (25 cases) -- `internal/scraper/scraper.go` - Added validateTimeout field and validateLinks call in scrape() -- `main.go` - Added SCRAPER_VALIDATE_TIMEOUT env var read (default 10s) - -## Decisions Made -- Used string matching (not DOM parsing) for video detection -- DOM parsing reserved for Phase 4 link extraction -- Set 2MB body read limit to prevent memory issues on large streaming pages -- Limited redirects to 3 to avoid infinite redirect chains on sketchy stream sites -- Validation runs sequentially (not concurrent) to avoid overwhelming target sites - -## Deviations from Plan - -None - plan executed exactly as written. - -## Issues Encountered -None. - -## User Setup Required - -None - no external service configuration required. - -## Next Phase Readiness -- Validation pipeline is integrated and tested, ready for health check layer (Phase 2) -- The validateLinks function provides the filtering foundation that health checks will build upon -- No blockers or concerns - -## Self-Check: PASSED - -All 5 files verified present. All 3 task commits verified in git log. - ---- -*Phase: 01-scraper-validation* -*Completed: 2026-02-17* diff --git a/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-RESEARCH.md b/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-RESEARCH.md deleted file mode 100644 index dd8f043f..00000000 --- a/stacks/f1-stream/files/.planning/phases/01-scraper-validation/01-RESEARCH.md +++ /dev/null @@ -1,599 +0,0 @@ -# Phase 1: Scraper Validation - Research - -**Researched:** 2026-02-17 -**Domain:** HTTP content fetching and HTML video/player content detection in Go -**Confidence:** HIGH - -## Summary - -Phase 1 adds a validation step to the existing Reddit scraper pipeline. Currently, the scraper extracts ALL URLs from F1-related Reddit posts and saves them to `scraped_links.json` without verifying whether they point to actual stream pages. The validation step will proxy-fetch each extracted URL (reusing the existing proxy's HTTP client pattern) and inspect the HTML response for video/player content markers before saving. - -The implementation is straightforward because the codebase already has all the infrastructure needed: HTTP fetching with timeouts (used in both `internal/scraper/reddit.go` and `internal/proxy/proxy.go`), URL validation, and the scraper pipeline with deduplication. The new code is a validation function inserted between URL extraction and saving, operating on the same `[]models.ScrapedLink` type. - -**Primary recommendation:** Add a `validateStreamURL` function in a new file `internal/scraper/validate.go` that uses string-based content matching (not full HTML parsing) to detect video markers, with `golang.org/x/net/html` reserved for Phase 4 (video extraction). Keep it simple: fetch the page, lowercase the body, check for known patterns. This avoids adding a dependency for Phase 1 while Phase 2 will reuse the same validation logic for health checks. - - -## Phase Requirements - -| ID | Description | Research Support | -|----|-------------|-----------------| -| SCRP-01 | Scraper filters Reddit posts by F1 keywords before extracting URLs (existing behavior, preserve) | Existing `isF1Post()` function in `reddit.go` lines 272-285 handles this. No changes needed -- just ensure the validation step is added AFTER URL extraction, not replacing the keyword filter. | -| SCRP-02 | Scraper validates each extracted URL by proxy-fetching it and checking for video/player content markers | New `validateStreamURL()` function fetches URL with configurable timeout, reads response body, checks for video content markers (see "Video Content Markers" section below for complete list). Reuse existing HTTP client pattern from `reddit.go:88`. | -| SCRP-03 | URLs that don't look like streams (no video markers detected) are discarded before saving | Filter applied in `scraper.go:scrape()` between URL extraction (line 57) and merge/save (line 60). Only URLs passing validation are included in the `links` slice passed to the merge step. | -| SCRP-04 | Validation has a configurable timeout (default 10s) to avoid blocking on slow sites | Add `SCRAPER_VALIDATE_TIMEOUT` environment variable read in `main.go`, passed to `scraper.New()`. Use `context.WithTimeout` on per-URL fetch to enforce deadline. Default 10 seconds. | - - -## Standard Stack - -### Core - -| Library | Version | Purpose | Why Standard | -|---------|---------|---------|--------------| -| `net/http` | stdlib | HTTP client for fetching URLs | Already used throughout codebase (`reddit.go`, `proxy.go`). No external dependency needed. | -| `strings` | stdlib | Case-insensitive string matching for content markers | Already used extensively. `strings.Contains` on lowercased body is the simplest approach for marker detection. | -| `regexp` | stdlib | Pattern matching for HLS/DASH URLs in page source | Already used in `reddit.go` for URL extraction. Needed for matching `.m3u8` and `.mpd` URL patterns in HTML content. | -| `context` | stdlib | Timeout enforcement per URL validation | Already used in scraper (`scraper.go:Run`). `context.WithTimeout` provides per-request deadline. | -| `io` | stdlib | `io.LimitReader` for response body size limiting | Already used in `proxy.go` and `reddit.go` for body size limits. | - -### Supporting - -| Library | Version | Purpose | When to Use | -|---------|---------|---------|-------------| -| `golang.org/x/net/html` | latest | Full HTML DOM parsing | NOT needed for Phase 1. Reserve for Phase 4 (video source extraction). String matching is sufficient for detection. | -| `sync` | stdlib | WaitGroup for parallel validation | If parallel validation is desired. But sequential is simpler and respects rate limits of target sites. | - -### Alternatives Considered - -| Instead of | Could Use | Tradeoff | -|------------|-----------|----------| -| String matching on body | `golang.org/x/net/html` DOM parsing | DOM parsing is more accurate but adds a dependency and complexity. For Phase 1 (detection, not extraction), string matching is sufficient. Phase 4 needs DOM parsing for actual source extraction. | -| Sequential URL validation | `sync.WaitGroup` parallel validation | Parallel is faster but risks triggering rate limits on target sites and complicates error handling. Sequential with timeout is simpler and predictable. | -| Custom HTTP client | Reuse proxy's `*http.Client` | The proxy client has redirect limits and timeout already configured. But the scraper should have its own client with validation-specific timeout. Keep them independent. | - -**Installation:** -```bash -# No new dependencies needed for Phase 1. All stdlib. -# golang.org/x/net/html deferred to Phase 4. -``` - -## Architecture Patterns - -### Where Validation Fits in the Pipeline - -``` -Current flow: - scrapeReddit() -> []models.ScrapedLink -> merge with existing -> save - -New flow: - scrapeReddit() -> []models.ScrapedLink -> validateLinks() -> []models.ScrapedLink -> merge with existing -> save -``` - -The validation step is a filter function that takes a slice of scraped links and returns only those that pass validation. This keeps the existing pipeline intact and makes the validation step independently testable. - -### Recommended File Structure - -``` -internal/scraper/ - scraper.go # Orchestrator (existing, add validateTimeout field + call validateLinks) - reddit.go # Reddit API scraping (existing, no changes) - validate.go # NEW: validateStreamURL(), validateLinks(), content marker definitions -``` - -### Pattern 1: Validation as a Filter Function - -**What:** A pure filter function that takes `[]models.ScrapedLink` and returns the subset that pass validation. -**When to use:** When adding a validation/filter step to an existing pipeline. -**Example:** - -```go -// internal/scraper/validate.go - -// validateLinks filters links to only those with video content markers. -// Each URL is fetched with the given timeout and inspected for markers. -func validateLinks(links []models.ScrapedLink, timeout time.Duration) []models.ScrapedLink { - client := &http.Client{Timeout: timeout} - var valid []models.ScrapedLink - for _, link := range links { - if hasVideoContent(client, link.URL) { - valid = append(valid, link) - } else { - log.Printf("scraper: discarded %s (no video markers)", truncate(link.URL, 60)) - } - } - return valid -} - -// hasVideoContent fetches a URL and checks for video/player content markers. -func hasVideoContent(client *http.Client, rawURL string) bool { - req, err := http.NewRequest("GET", rawURL, nil) - if err != nil { - return false - } - req.Header.Set("User-Agent", userAgent) // reuse existing constant - - resp, err := client.Do(req) - if err != nil { - log.Printf("scraper: validate fetch error for %s: %v", truncate(rawURL, 60), err) - return false - } - defer resp.Body.Close() - - // Only inspect HTML responses - ct := resp.Header.Get("Content-Type") - if !strings.Contains(ct, "text/html") && !strings.Contains(ct, "application/xhtml") { - // Could be a direct video file (.m3u8, .mpd, .mp4) which is valid - if isDirectVideoContentType(ct) { - return true - } - return false - } - - body, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024)) // 2MB limit for validation - if err != nil { - return false - } - - return containsVideoMarkers(strings.ToLower(string(body))) -} -``` - -### Pattern 2: Configuration Via Struct Field - -**What:** Pass validation timeout through the existing `Scraper` struct, configured from `main.go` env vars. -**When to use:** Following existing codebase pattern where all config flows through `main.go` -> constructor. -**Example:** - -```go -// internal/scraper/scraper.go -type Scraper struct { - store *store.Store - interval time.Duration - validateTimeout time.Duration // NEW - mu sync.Mutex -} - -func New(s *store.Store, interval time.Duration, validateTimeout time.Duration) *Scraper { - return &Scraper{store: s, interval: interval, validateTimeout: validateTimeout} -} - -// In main.go: -validateTimeout := envDuration("SCRAPER_VALIDATE_TIMEOUT", 10*time.Second) -sc := scraper.New(st, scrapeInterval, validateTimeout) -``` - -### Pattern 3: Integration Point in scrape() - -**What:** Call validateLinks between scrapeReddit return and merge step. -**When to use:** Minimal change to existing scrape flow. -**Example:** - -```go -// In scraper.go:scrape() - between lines 57 and 60 -links, err := scrapeReddit() -if err != nil { - // ... existing error handling -} -log.Printf("scraper: reddit scrape completed in %v, got %d links", time.Since(start).Round(time.Millisecond), len(links)) - -// NEW: validate links before merging -if len(links) > 0 { - validated := validateLinks(links, s.validateTimeout) - log.Printf("scraper: validated %d/%d links as streams", len(validated), len(links)) - links = validated -} - -// Continue with existing merge logic... -``` - -### Anti-Patterns to Avoid - -- **Fetching URLs inside the Reddit API loop:** Validation should happen after all URLs are collected from Reddit, not interleaved with Reddit API calls. This keeps the Reddit API calls fast and avoids mixing rate-limit concerns. -- **Using the proxy's HTTP handler for internal validation:** The proxy (`internal/proxy/proxy.go`) is designed as an HTTP handler for client-facing requests with IP-based rate limiting. The scraper should use its own HTTP client without rate limiting since it is a trusted internal caller. -- **Modifying the ScrapedLink model to track validation state:** For Phase 1, validation is a binary filter (pass or discard). Adding validation metadata to the model is premature and adds complexity to the store layer. If needed in Phase 2 for health checking, it can be added then. -- **Full HTML DOM parsing for detection:** Using `golang.org/x/net/html` to parse the full DOM tree just to detect presence of video tags is overkill. String matching on lowercased HTML body is sufficient for detection. DOM parsing is needed in Phase 4 for actual source URL extraction. - -## Don't Hand-Roll - -| Problem | Don't Build | Use Instead | Why | -|---------|-------------|-------------|-----| -| HTTP fetching with timeout | Custom TCP client | `net/http.Client` with `Timeout` field | stdlib handles redirects, TLS, timeouts, connection pooling | -| HTML content inspection | Full DOM parser | `strings.Contains` on lowercased body | Detection (yes/no) does not need structural parsing; string matching is faster and simpler | -| URL scheme validation | Manual string prefix check | `net/url.Parse` + scheme check | Already used in codebase; handles edge cases | -| Concurrent timeout enforcement | Manual goroutine + channel | `context.WithTimeout` + `http.NewRequestWithContext` | stdlib integration; cancels in-flight requests properly | - -**Key insight:** Phase 1 is a detection problem (does this page look like a stream?), not an extraction problem (what is the stream URL?). Detection can be done with string matching. Extraction (Phase 4) needs DOM parsing. - -## Video Content Markers - -### HIGH confidence markers (any one of these strongly indicates a stream page) - -**HTML Tags:** -- `` tags or player references -- those are injected by JS after page load. -**Why it happens:** HTTP fetching returns raw HTML; no JavaScript execution. -**How to avoid:** This is an accepted limitation per the requirements doc ("Full browser automation (Puppeteer/Playwright)" is Out of Scope). The marker list includes JavaScript library references (e.g., `hls.js`, `video.js`) which ARE present in the raw HTML even before execution. Most streaming sites include their player library in ``, true}, - {"video.js library", ``, true}, - {"jwplayer", `
`, true}, - {"no markers", `

Hello world

`, false}, - {"reddit link page", `Click here`, false}, - {"blog post", `
F1 race results...
`, false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := containsVideoMarkers(tt.body) - if result != tt.expected { - t.Errorf("containsVideoMarkers(%q) = %v, want %v", truncate(tt.body, 40), result, tt.expected) - } - }) - } -} -``` - -## State of the Art - -| Old Approach | Current Approach | When Changed | Impact | -|--------------|------------------|--------------|--------| -| Save all URLs from F1 posts | Will validate each URL before saving | Phase 1 (now) | Eliminates junk links at the source | -| No content inspection | String-based marker detection | Phase 1 (now) | Simple, fast, no external dependencies | -| Static marker list | Static marker list (sufficient for now) | - | May need updating as new players emerge; easily extensible | - -**Why not use browser automation:** -The REQUIREMENTS.md explicitly marks "Full browser automation (Puppeteer/Playwright)" as Out of Scope. HTTP-based checks with string matching catch the majority of stream pages because player library ` -``` - -**2. Update `streamCard()` in streams.js:** - -The current `streamCard()` function renders an iframe immediately. Change the approach: - -a. The card initially renders with a loading state placeholder instead of an iframe: -```html -
-
-
-
-
-
-
- ${escapeHtml(stream.title)} -
- ${externalBtn} - ${deleteBtn} -
-
-
-``` - -b. After cards are rendered in the DOM (after `grid.innerHTML = ...`), call a new function `tryExtractVideos(streams)` that attempts extraction for each stream. - -**3. Create `async function tryExtractVideos(streams)`:** - -For each stream, call `tryExtractVideo(stream)` concurrently using `Promise.allSettled`. - -**4. Create `async function tryExtractVideo(stream)`:** - -- Fetch `GET /api/streams/${stream.id}/extract` -- If response is OK and `sources` array is non-empty: - - Pick the best source: prefer "hls" type, then "dash", then "mp4"/"webm" - - Call `renderNativePlayer(stream.id, source)` to replace the loading placeholder -- If response fails or sources is empty: - - Call `renderIframeFallback(stream.id, stream.url)` to show the existing iframe - -**5. Create `function renderNativePlayer(streamId, source)`:** - -Get the wrapper element `player-wrap-${streamId}`. - -For HLS sources (source.type === "hls"): -```javascript -const video = document.createElement('video'); -video.controls = true; -video.autoplay = false; -video.style.width = '100%'; -video.style.height = '100%'; -video.setAttribute('playsinline', ''); - -if (Hls.isSupported()) { - const hls = new Hls(); - hls.loadSource(source.url); - hls.attachMedia(video); -} else if (video.canPlayType('application/vnd.apple.mpegurl')) { - // Native HLS support (Safari) - video.src = source.url; -} -``` - -For MP4/WebM sources: -```javascript -const video = document.createElement('video'); -video.controls = true; -video.autoplay = false; -video.style.width = '100%'; -video.style.height = '100%'; -video.setAttribute('playsinline', ''); -video.src = source.url; -``` - -For DASH sources (skip for now, just fall back to iframe — DASH requires dash.js which is heavier): -- Call `renderIframeFallback(streamId, stream.url)` instead. - -Replace the loading overlay content with the video element. Remove the spinner. Add a "loaded" class to the loading overlay. - -**6. Create `function renderIframeFallback(streamId, streamURL)`:** - -Get the wrapper element and replace its innerHTML with the existing iframe markup: -```javascript -const wrap = document.getElementById(`player-wrap-${streamId}`); -if (!wrap) return; -wrap.innerHTML = ` -
-
-
- -`; -``` - -**7. Update `loadPublicStreams()` and `loadMyStreams()`:** - -After `grid.innerHTML = streams.map(...)`, add `tryExtractVideos(streams)` call. The existing `sortStreamsByHealth` call should remain after it. - -**Important:** Do NOT block the initial render. The cards show immediately with loading spinners. Extraction runs asynchronously and replaces the spinner with either a native player or an iframe as results come in. - -**Error handling:** If the fetch to `/api/streams/{id}/extract` throws (network error, timeout), silently fall back to iframe. Log to console but do not show user-facing errors for extraction failures — the iframe fallback is the safety net. - - -1. Open `static/index.html` in a text editor and confirm the HLS.js script tag is present before other JS scripts. -2. Open `static/js/streams.js` and confirm: - - `streamCard()` no longer renders an iframe directly - - `tryExtractVideos()` and `tryExtractVideo()` functions exist - - `renderNativePlayer()` and `renderIframeFallback()` functions exist - - `loadPublicStreams()` calls `tryExtractVideos()` -3. Run `cd /Users/viktorbarzin/code/infra/modules/kubernetes/f1-stream/files && go build ./...` to confirm the Go project still compiles (no Go changes, but verify no accidental edits). - - -- HLS.js loaded via CDN in index.html -- Stream cards attempt extraction first, render native HTML5 video player for HLS/MP4/WebM sources -- Iframe fallback works when extraction fails or returns no sources -- No visual regression for streams without extractable video sources - - - - - - -1. `static/index.html` includes HLS.js CDN script tag -2. `static/js/streams.js` has extraction-first card rendering logic -3. `streamCard()` renders placeholder, not iframe, as initial state -4. `tryExtractVideo()` calls `/api/streams/{id}/extract` and handles success/failure -5. `renderNativePlayer()` creates HTML5 ` - - -- Streams with extractable video sources render in a native HTML5 video player with controls -- HLS streams play via hls.js (or native HLS on Safari) -- Streams without extractable sources fall back to iframe rendering (existing behavior preserved) -- No user-facing errors when extraction fails — silent fallback to iframe -- Video player has play, pause, volume, and fullscreen controls - - - -After completion, create `.planning/phases/04-video-extraction-native-playback/04-02-SUMMARY.md` - diff --git a/stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-02-SUMMARY.md b/stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-02-SUMMARY.md deleted file mode 100644 index 40927caf..00000000 --- a/stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-02-SUMMARY.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -phase: 04-video-extraction-native-playback -plan: 02 -subsystem: ui -tags: [hls-js, html5-video, native-playback, video-extraction, frontend] - -# Dependency graph -requires: - - phase: 04-video-extraction-native-playback - provides: Video source extractor API endpoint (GET /api/streams/{id}/extract) -provides: - - Extraction-first stream card rendering with native HTML5 video player - - HLS.js integration for .m3u8 playback in non-Safari browsers - - Iframe fallback for streams without extractable video sources -affects: [05-polish-monitoring, frontend, streaming-experience] - -# Tech tracking -tech-stack: - added: [hls.js@1 (CDN)] - patterns: [extraction-first rendering, progressive enhancement with fallback, priority-based source selection] - -key-files: - created: [] - modified: [static/index.html, static/js/streams.js] - -key-decisions: - - "HLS.js loaded from CDN (jsdelivr) to avoid bundling complexity" - - "Extraction runs async after card render -- loading spinner shows immediately, player replaces it" - - "DASH sources fall back to iframe (dash.js too heavy for current scope)" - - "pickBestSource priority: HLS > DASH > MP4 > WebM matches backend ordering" - - "Silent console.log on extraction failure -- no user-facing errors for extraction issues" - -patterns-established: - - "Progressive enhancement pattern: render placeholder, attempt extraction, upgrade to native or fall back to iframe" - - "Promise.allSettled for concurrent extraction across all stream cards" - -requirements-completed: [EMBED-02] - -# Metrics -duration: 2min -completed: 2026-02-17 ---- - -# Phase 04 Plan 02: Frontend Native Video Playback Summary - -**Extraction-first stream card rendering with HLS.js integration and iframe fallback for native HTML5 video playback** - -## Performance - -- **Duration:** 2 min -- **Started:** 2026-02-17T21:48:20Z -- **Completed:** 2026-02-17T21:50:03Z -- **Tasks:** 1 -- **Files modified:** 2 - -## Accomplishments -- Stream cards now attempt video extraction before falling back to iframe -- Native HTML5 video player renders for HLS, MP4, and WebM sources with standard controls -- HLS.js handles .m3u8 streams in non-Safari browsers; Safari uses native HLS support -- Iframe fallback preserves existing behavior for streams without extractable sources -- Loading spinners provide visual feedback during async extraction - -## Task Commits - -Each task was committed atomically: - -1. **Task 1: Add HLS.js and update streamCard for native video playback** - `2a40af9` (feat) - -**Plan metadata:** (pending final docs commit) - -## Files Created/Modified -- `static/index.html` - Added HLS.js CDN script tag before other JS scripts -- `static/js/streams.js` - Extraction-first rendering: streamCard renders placeholder, tryExtractVideos/tryExtractVideo call extract API, renderNativePlayer creates HTML5 video element, renderIframeFallback preserves existing iframe approach - -## Decisions Made -- HLS.js loaded from jsDelivr CDN rather than self-hosted -- avoids build tooling while keeping the library current -- DASH sources intentionally fall back to iframe -- dash.js is heavier and DASH is lower priority than HLS -- Extraction errors logged to console only -- user sees iframe fallback seamlessly, no error UI needed -- pickBestSource uses same priority ordering (HLS > DASH > MP4 > WebM) established in backend extractor - -## Deviations from Plan - -None - plan executed exactly as written. - -## Issues Encountered -- Go module cache sandbox permission error during build verification; resolved with temporary GOPATH (same workaround as 04-01, environment constraint only) - -## User Setup Required - -None - no external service configuration required. - -## Next Phase Readiness -- Phase 04 (Video Extraction & Native Playback) is now complete -- Streams with extractable video sources play in native HTML5 player -- Streams without extractable sources continue to work via iframe fallback -- Ready for Phase 05 (Polish & Monitoring) if planned - ---- -*Phase: 04-video-extraction-native-playback* -*Completed: 2026-02-17* - -## Self-Check: PASSED - -- FOUND: static/index.html -- FOUND: static/js/streams.js -- FOUND: 04-02-SUMMARY.md -- FOUND: commit 2a40af9 diff --git a/stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-VERIFICATION.md b/stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-VERIFICATION.md deleted file mode 100644 index 27156391..00000000 --- a/stacks/f1-stream/files/.planning/phases/04-video-extraction-native-playback/04-VERIFICATION.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -phase: 04-video-extraction-native-playback -verified: 2026-02-17T22:00:00Z -status: passed -score: 11/11 must-haves verified -re_verification: false ---- - -# Phase 4: Video Extraction and Native Playback Verification Report - -**Phase Goal:** When a stream URL contains an extractable video source, users watch it in a clean native HTML5 player instead of loading the third-party page - -**Verified:** 2026-02-17T22:00:00Z - -**Status:** passed - -**Re-verification:** No — initial verification - -## Goal Achievement - -### Observable Truths - -| # | Truth | Status | Evidence | -|---|-------|--------|----------| -| 1 | GET /api/streams/{id}/extract returns a JSON response with extracted video source URL and type when the stream page contains a video source | ✓ VERIFIED | Endpoint exists in server.go:83, handler at server.go:242-295 returns JSON with sources array and stream_id | -| 2 | Extractor can find HLS .m3u8 URLs from video/source src attributes and script tag contents | ✓ VERIFIED | DOM extraction at extractor.go:166-192, regex patterns at extractor.go:196,201, matches .m3u8 in video/source/iframe src | -| 3 | Extractor can find DASH .mpd URLs from video/source src attributes and script tag contents | ✓ VERIFIED | DOM extraction at extractor.go:166-192, regex patterns at extractor.go:197,202, matches .mpd in video/source/iframe src | -| 4 | Extractor can find direct MP4/WebM URLs from video/source src attributes | ✓ VERIFIED | DOM extraction at extractor.go:166-192, regex patterns at extractor.go:198-199, matches .mp4/.webm in video/source/iframe src | -| 5 | Extractor can find video URLs from jwplayer, video.js, and hls.js setup calls in script tags | ✓ VERIFIED | Regex patterns at extractor.go:200-202 for JWPlayer (file:), hls.js/video.js (src:=), script extraction at extractor.go:206-223 | -| 6 | GET /api/streams/{id}/extract returns empty result (not error) when no video source is found | ✓ VERIFIED | Returns []VideoSource{} at extractor.go:66,306 with nil error when no sources found | -| 7 | When a stream has an extractable HLS source, the user sees a native video player on the app page instead of an iframe loading the third-party site | ✓ VERIFIED | tryExtractVideo at streams.js:172-189 fetches extract endpoint, renderNativePlayer at streams.js:200-228 creates HTML5 video element | -| 8 | When a stream has an extractable MP4/WebM source, the user sees a native HTML5 video element playing the stream | ✓ VERIFIED | renderNativePlayer at streams.js:200-228 handles mp4/webm by setting video.src directly (line 223) | -| 9 | When extraction fails or returns no sources, the user sees the existing iframe fallback (no regression) | ✓ VERIFIED | tryExtractVideo calls renderIframeFallback at streams.js:188 on error/empty sources, renderIframeFallback at streams.js:230-246 creates iframe element | -| 10 | HLS streams play using hls.js library when the browser does not support HLS natively | ✓ VERIFIED | HLS.js loaded from CDN at index.html:162, renderNativePlayer checks Hls.isSupported() at streams.js:212, creates new Hls() at streams.js:213-215, Safari native fallback at streams.js:216-217 | -| 11 | The video player has standard controls (play, pause, volume, fullscreen) | ✓ VERIFIED | video.controls = true at streams.js:205, HTML5 video element provides standard browser controls including play, pause, volume, fullscreen | - -**Score:** 11/11 truths verified - -### Required Artifacts - -| Artifact | Expected | Status | Details | -|----------|----------|--------|---------| -| `internal/extractor/extractor.go` | Video source URL extraction from HTML pages | ✓ VERIFIED | 326 lines, exports Extract function and VideoSource type, implements DOM parsing with golang.org/x/net/html and regex extraction from script tags | -| `internal/server/server.go` | API endpoint for video extraction | ✓ VERIFIED | Route registered at line 83, handler at lines 242-295, calls extractor.Extract, returns JSON with sources array and Cache-Control headers | -| `static/index.html` | HLS.js library script tag | ✓ VERIFIED | HLS.js CDN script tag at line 162 before other JS scripts | -| `static/js/streams.js` | Updated streamCard with native video player support | ✓ VERIFIED | 398 lines total, includes tryExtractVideos (168-170), tryExtractVideo (172-189), renderNativePlayer (200-228), renderIframeFallback (230-246), pickBestSource (191-198) | - -### Key Link Verification - -| From | To | Via | Status | Details | -|------|----|----|--------|---------| -| internal/server/server.go | internal/extractor/extractor.go | handler calls extractor.Extract | ✓ WIRED | Import at server.go:13, call at server.go:282 with client and streamURL parameters | -| internal/server/server.go | internal/store | handler looks up stream by ID | ✓ WIRED | Import at server.go:16, LoadStreams() call at server.go:246, iterates to find stream by ID at lines 255-264 | -| static/js/streams.js | /api/streams/{id}/extract | fetch call to extract endpoint | ✓ WIRED | fetch call at streams.js:174 with template literal for stream ID, response parsed as JSON at line 176 | -| static/js/streams.js | Hls | HLS.js library for .m3u8 playback | ✓ WIRED | Hls.isSupported() check at streams.js:212, new Hls() instantiation at streams.js:213, loadSource/attachMedia at streams.js:214-215 | - -### Requirements Coverage - -| Requirement | Source Plan | Description | Status | Evidence | -|-------------|------------|-------------|--------|----------| -| EMBED-01 | 04-01-PLAN.md | Proxy fetches stream page and attempts to extract direct video source URL (HLS .m3u8, DASH .mpd, direct MP4/WebM, or embedded video player source) | ✓ SATISFIED | Extractor package at internal/extractor/extractor.go implements all extraction types: HLS (lines 107,117,147,196,201,229), DASH (lines 109,120,148,197,202,235), MP4 (lines 111,149,198), WebM (lines 113,150,199), JWPlayer/video.js/hls.js patterns (lines 200-202). Server-side extraction via handleExtractVideo at server.go:242-295 | -| EMBED-02 | 04-02-PLAN.md | When direct video source is found, render it in a minimal HTML5 video player on the app's own page (no third-party page loaded) | ✓ SATISFIED | renderNativePlayer at streams.js:200-228 creates HTML5 video element with controls=true (line 205), integrates HLS.js for .m3u8 sources (lines 212-215), sets src directly for mp4/webm (line 223), replaces loading placeholder in player-wrap div preventing third-party page load | - -### Anti-Patterns Found - -None detected. - -Scanned files: -- `internal/extractor/extractor.go`: No TODO/FIXME/placeholder comments, no empty implementations, substantive extraction logic -- `internal/server/server.go`: Handler implementation complete, proper error handling, cache headers set -- `static/js/streams.js`: No TODO/FIXME/placeholder comments, complete extraction-first rendering logic -- `static/index.html`: HLS.js script tag present, no issues - -### Human Verification Required - -None. All verification completed programmatically. - -### Phase Summary - -Phase 4 successfully delivers video extraction and native playback capability. The backend extractor can identify HLS, DASH, MP4, and WebM sources from both DOM elements and script tags. The frontend attempts extraction first and upgrades to a native HTML5 video player when sources are found, falling back to iframe rendering when extraction fails or returns no results. - -**Key accomplishments:** -- Server-side video source extraction with multiple strategies (DOM parsing + regex script extraction) -- Native HTML5 video player with HLS.js integration for .m3u8 streams -- Progressive enhancement pattern: render placeholder, attempt extraction, upgrade or fallback -- No breaking changes to existing iframe fallback behavior -- 5-minute cache on extraction endpoint to reduce upstream load -- Priority-based source selection (HLS > DASH > MP4 > WebM) - -**Technical quality:** -- All artifacts exist, substantive, and properly wired -- No anti-patterns detected -- Consistent error handling with silent fallback to iframe -- User-Agent and timeout patterns match existing proxy/scraper conventions -- Proper use of golang.org/x/net/html for DOM parsing -- HLS.js loaded from CDN with browser capability detection - -**Requirements fulfilled:** -- EMBED-01: Video source extraction from stream pages ✓ -- EMBED-02: Native HTML5 video player rendering ✓ - -Phase goal achieved. Users can now watch streams with extractable video sources in a clean native player without loading third-party pages. - ---- - -_Verified: 2026-02-17T22:00:00Z_ - -_Verifier: Claude (gsd-verifier)_ diff --git a/stacks/f1-stream/files/.planning/phases/05-sandbox-proxy-hardening/05-01-PLAN.md b/stacks/f1-stream/files/.planning/phases/05-sandbox-proxy-hardening/05-01-PLAN.md deleted file mode 100644 index de31a10d..00000000 --- a/stacks/f1-stream/files/.planning/phases/05-sandbox-proxy-hardening/05-01-PLAN.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -phase: 05-sandbox-proxy-hardening -plan: 01 -type: execute -wave: 1 -depends_on: [] -files_modified: [internal/proxy/sanitize.go, internal/proxy/blocklist.go, internal/proxy/proxy.go, internal/server/server.go] -autonomous: true -requirements: [EMBED-06, EMBED-07, EMBED-08] - -must_haves: - truths: - - "Proxied HTML content has known ad/tracker scripts and domains stripped before serving" - - "Relative URLs in proxied content are rewritten to route through the proxy" - - "All proxied content is served with strict CSP headers scoped to the sandbox context" - artifacts: - - path: "internal/proxy/sanitize.go" - provides: "HTML sanitizer that strips ads, rewrites URLs, and adds CSP" - contains: "func Sanitize" - - path: "internal/proxy/blocklist.go" - provides: "Ad/tracker domain blocklist for script filtering" - contains: "blockedDomains" - - path: "internal/proxy/proxy.go" - provides: "New /proxy/sandbox endpoint serving sanitized content" - contains: "ServeSandbox" - - path: "internal/server/server.go" - provides: "Route registration for sandbox proxy endpoint" - contains: "proxy/sandbox" - key_links: - - from: "internal/server/server.go" - to: "internal/proxy/proxy.go" - via: "route registration for /proxy/sandbox" - pattern: "proxy/sandbox.*ServeSandbox" - - from: "internal/proxy/proxy.go" - to: "internal/proxy/sanitize.go" - via: "ServeSandbox calls Sanitize" - pattern: "Sanitize\\(" ---- - - -Backend proxy hardening: sanitize proxied HTML content by stripping ad/tracker scripts, rewriting relative URLs through the proxy, and serving with strict CSP headers. - -Purpose: When the frontend shadow DOM sandbox fetches proxied page content, the backend must deliver clean HTML free of ad scripts with working sub-resources and strict content security policy. - -Output: A new `/proxy/sandbox` endpoint that serves sanitized HTML for shadow DOM injection. - - - -@/Users/viktorbarzin/.claude/get-shit-done/workflows/execute-plan.md -@/Users/viktorbarzin/.claude/get-shit-done/templates/summary.md - - - -@.planning/PROJECT.md -@.planning/ROADMAP.md -@.planning/STATE.md - -@internal/proxy/proxy.go -@internal/server/server.go -@internal/extractor/extractor.go - - - - - - Task 1: Create HTML sanitizer with ad/tracker stripping and URL rewriting - internal/proxy/sanitize.go, internal/proxy/blocklist.go - -Create `internal/proxy/blocklist.go`: -- Define a `var blockedDomains = map[string]bool{...}` containing well-known ad/tracker domains. Include at least 30-40 entries covering: doubleclick.net, googlesyndication.com, googleadservices.com, google-analytics.com, facebook.net, connect.facebook.net, adservice.google.com, pagead2.googlesyndication.com, cdn.taboola.com, cdn.outbrain.com, ads.yahoo.com, amazon-adsystem.com, adsrvr.org, criteo.com, quantserve.com, scorecardresearch.com, serving-sys.com, rubiconproject.com, pubmatic.com, moatads.com, chartbeat.com, newrelic.com, nr-data.net, hotjar.com, mixpanel.com, segment.com, amplitude.com, popads.net, popcash.net, propellerads.com, adsterra.com, exoclick.com, juicyads.com, trafficjunky.com, etc. -- Define `func IsBlockedDomain(host string) bool` that checks the hostname and its parent domains against the blocklist. For example, if host is "ads.example.com" and "example.com" is blocked, return true. Walk up the domain labels. - -Create `internal/proxy/sanitize.go`: -- Import `golang.org/x/net/html` (already in go.mod). -- Define `func Sanitize(doc *html.Node, baseURL *url.URL, proxyPrefix string) string` that: - 1. Walks the DOM tree and removes ` - diff --git a/stacks/f1-stream/files/internal/auth/auth.go b/stacks/f1-stream/files/internal/auth/auth.go deleted file mode 100644 index f73121dc..00000000 --- a/stacks/f1-stream/files/internal/auth/auth.go +++ /dev/null @@ -1,359 +0,0 @@ -package auth - -import ( - "crypto/rand" - "encoding/json" - "fmt" - "log" - "net/http" - "regexp" - "sync" - "time" - - "f1-stream/internal/models" - "f1-stream/internal/store" - - "github.com/go-webauthn/webauthn/webauthn" -) - -var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_]{3,30}$`) - -type Auth struct { - store *store.Store - webauthn *webauthn.WebAuthn - adminUsername string - sessionTTL time.Duration - - // In-memory storage for WebAuthn ceremony session data (short-lived) - regSessions map[string]*webauthn.SessionData - loginSessions map[string]*webauthn.SessionData - mu sync.Mutex -} - -func New(s *store.Store, rpDisplayName, rpID string, rpOrigins []string, adminUsername string, sessionTTL time.Duration) (*Auth, error) { - wconfig := &webauthn.Config{ - RPDisplayName: rpDisplayName, - RPID: rpID, - RPOrigins: rpOrigins, - } - w, err := webauthn.New(wconfig) - if err != nil { - return nil, fmt.Errorf("webauthn init: %w", err) - } - return &Auth{ - store: s, - webauthn: w, - adminUsername: adminUsername, - sessionTTL: sessionTTL, - regSessions: make(map[string]*webauthn.SessionData), - loginSessions: make(map[string]*webauthn.SessionData), - }, nil -} - -// BeginRegistration starts the WebAuthn registration ceremony. -func (a *Auth) BeginRegistration(w http.ResponseWriter, r *http.Request) { - var req struct { - Username string `json:"username"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest) - return - } - if !usernameRe.MatchString(req.Username) { - http.Error(w, `{"error":"username must be 3-30 chars, alphanumeric or underscore"}`, http.StatusBadRequest) - return - } - - existing, err := a.store.GetUserByName(req.Username) - if err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - if existing != nil { - http.Error(w, `{"error":"username already taken"}`, http.StatusConflict) - return - } - - id, err := randomID() - if err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - - isAdmin := false - if a.adminUsername != "" && req.Username == a.adminUsername { - isAdmin = true - } else if a.adminUsername == "" { - count, err := a.store.UserCount() - if err == nil && count == 0 { - isAdmin = true - } - } - - user := &models.User{ - ID: id, - Username: req.Username, - IsAdmin: isAdmin, - CreatedAt: time.Now(), - } - - options, session, err := a.webauthn.BeginRegistration(user) - if err != nil { - log.Printf("BeginRegistration error: %v", err) - http.Error(w, `{"error":"failed to begin registration"}`, http.StatusInternalServerError) - return - } - - a.mu.Lock() - a.regSessions[req.Username] = session - a.mu.Unlock() - - // Clean up session after 5 minutes - go func() { - time.Sleep(5 * time.Minute) - a.mu.Lock() - delete(a.regSessions, req.Username) - a.mu.Unlock() - }() - - // Store user temporarily - will be committed on finish - // We create the user now so FinishRegistration can look it up - if err := a.store.CreateUser(*user); err != nil { - http.Error(w, `{"error":"failed to create user"}`, http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(options) -} - -// FinishRegistration completes the WebAuthn registration ceremony. -func (a *Auth) FinishRegistration(w http.ResponseWriter, r *http.Request) { - var req struct { - Username string `json:"username"` - } - // Username is passed as query param since body is the attestation response - username := r.URL.Query().Get("username") - if username == "" { - // Try to decode from a wrapper - http.Error(w, `{"error":"username required"}`, http.StatusBadRequest) - return - } - req.Username = username - - a.mu.Lock() - session, ok := a.regSessions[req.Username] - if ok { - delete(a.regSessions, req.Username) - } - a.mu.Unlock() - - if !ok { - http.Error(w, `{"error":"no registration in progress"}`, http.StatusBadRequest) - return - } - - user, err := a.store.GetUserByName(req.Username) - if err != nil || user == nil { - http.Error(w, `{"error":"user not found"}`, http.StatusBadRequest) - return - } - - credential, err := a.webauthn.FinishRegistration(user, *session, r) - if err != nil { - log.Printf("FinishRegistration error: %v", err) - http.Error(w, `{"error":"registration failed"}`, http.StatusBadRequest) - return - } - - user.Credentials = append(user.Credentials, *credential) - if err := a.store.UpdateUserCredentials(user.ID, user.Credentials); err != nil { - http.Error(w, `{"error":"failed to save credential"}`, http.StatusInternalServerError) - return - } - - // Create session - token, err := a.store.CreateSession(user.ID, a.sessionTTL) - if err != nil { - http.Error(w, `{"error":"failed to create session"}`, http.StatusInternalServerError) - return - } - http.SetCookie(w, &http.Cookie{ - Name: "session", - Value: token, - Path: "/", - HttpOnly: true, - SameSite: http.SameSiteStrictMode, - Secure: r.TLS != nil, - MaxAge: int(a.sessionTTL.Seconds()), - }) - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]interface{}{ - "id": user.ID, - "username": user.Username, - "is_admin": user.IsAdmin, - }) -} - -// BeginLogin starts the WebAuthn login ceremony. -func (a *Auth) BeginLogin(w http.ResponseWriter, r *http.Request) { - var req struct { - Username string `json:"username"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest) - return - } - - user, err := a.store.GetUserByName(req.Username) - if err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - if user == nil { - http.Error(w, `{"error":"user not found"}`, http.StatusNotFound) - return - } - if len(user.Credentials) == 0 { - http.Error(w, `{"error":"no credentials registered"}`, http.StatusBadRequest) - return - } - - options, session, err := a.webauthn.BeginLogin(user) - if err != nil { - log.Printf("BeginLogin error: %v", err) - http.Error(w, `{"error":"failed to begin login"}`, http.StatusInternalServerError) - return - } - - a.mu.Lock() - a.loginSessions[req.Username] = session - a.mu.Unlock() - - go func() { - time.Sleep(5 * time.Minute) - a.mu.Lock() - delete(a.loginSessions, req.Username) - a.mu.Unlock() - }() - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(options) -} - -// FinishLogin completes the WebAuthn login ceremony. -func (a *Auth) FinishLogin(w http.ResponseWriter, r *http.Request) { - username := r.URL.Query().Get("username") - if username == "" { - http.Error(w, `{"error":"username required"}`, http.StatusBadRequest) - return - } - - a.mu.Lock() - session, ok := a.loginSessions[username] - if ok { - delete(a.loginSessions, username) - } - a.mu.Unlock() - - if !ok { - http.Error(w, `{"error":"no login in progress"}`, http.StatusBadRequest) - return - } - - user, err := a.store.GetUserByName(username) - if err != nil || user == nil { - http.Error(w, `{"error":"user not found"}`, http.StatusBadRequest) - return - } - - credential, err := a.webauthn.FinishLogin(user, *session, r) - if err != nil { - log.Printf("FinishLogin error: %v", err) - http.Error(w, `{"error":"login failed"}`, http.StatusUnauthorized) - return - } - - // Update credential sign count - for i, c := range user.Credentials { - if string(c.ID) == string(credential.ID) { - user.Credentials[i].Authenticator.SignCount = credential.Authenticator.SignCount - break - } - } - if err := a.store.UpdateUserCredentials(user.ID, user.Credentials); err != nil { - log.Printf("Failed to update credential sign count: %v", err) - } - - token, err := a.store.CreateSession(user.ID, a.sessionTTL) - if err != nil { - http.Error(w, `{"error":"failed to create session"}`, http.StatusInternalServerError) - return - } - http.SetCookie(w, &http.Cookie{ - Name: "session", - Value: token, - Path: "/", - HttpOnly: true, - SameSite: http.SameSiteStrictMode, - Secure: r.TLS != nil, - MaxAge: int(a.sessionTTL.Seconds()), - }) - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]interface{}{ - "id": user.ID, - "username": user.Username, - "is_admin": user.IsAdmin, - }) -} - -// Logout clears the session. -func (a *Auth) Logout(w http.ResponseWriter, r *http.Request) { - cookie, err := r.Cookie("session") - if err == nil { - a.store.DeleteSession(cookie.Value) - } - http.SetCookie(w, &http.Cookie{ - Name: "session", - Value: "", - Path: "/", - HttpOnly: true, - MaxAge: -1, - }) - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"ok":true}`)) -} - -// Me returns the current user info. -func (a *Auth) Me(w http.ResponseWriter, r *http.Request) { - user := UserFromContext(r.Context()) - if user == nil { - http.Error(w, `{"error":"not authenticated"}`, http.StatusUnauthorized) - return - } - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]interface{}{ - "id": user.ID, - "username": user.Username, - "is_admin": user.IsAdmin, - }) -} - -// GetSessionUser returns the user for a session token. -func (a *Auth) GetSessionUser(token string) (*models.User, error) { - sess, err := a.store.GetSession(token) - if err != nil || sess == nil { - return nil, err - } - return a.store.GetUserByID(sess.UserID) -} - -func randomID() (string, error) { - b := make([]byte, 16) - if _, err := rand.Read(b); err != nil { - return "", err - } - return fmt.Sprintf("%x", b), nil -} diff --git a/stacks/f1-stream/files/internal/auth/context.go b/stacks/f1-stream/files/internal/auth/context.go deleted file mode 100644 index 8cc314f4..00000000 --- a/stacks/f1-stream/files/internal/auth/context.go +++ /dev/null @@ -1,20 +0,0 @@ -package auth - -import ( - "context" - - "f1-stream/internal/models" -) - -type contextKey string - -const userKey contextKey = "user" - -func ContextWithUser(ctx context.Context, user *models.User) context.Context { - return context.WithValue(ctx, userKey, user) -} - -func UserFromContext(ctx context.Context) *models.User { - user, _ := ctx.Value(userKey).(*models.User) - return user -} diff --git a/stacks/f1-stream/files/internal/extractor/browser.go b/stacks/f1-stream/files/internal/extractor/browser.go deleted file mode 100644 index 740d7eaa..00000000 --- a/stacks/f1-stream/files/internal/extractor/browser.go +++ /dev/null @@ -1,38 +0,0 @@ -package extractor - -import ( - "log" - "os/exec" -) - -const maxConcurrentSessions = 10 - -var sessionSem chan struct{} - -// Init starts dbus, PulseAudio, and prepares the session semaphore. -func Init() { - // Start dbus (Chrome needs it for accessibility/service queries) - if err := exec.Command("mkdir", "-p", "/var/run/dbus").Run(); err == nil { - if err := exec.Command("dbus-daemon", "--system", "--nofork").Start(); err != nil { - log.Printf("extractor: warning: failed to start dbus: %v", err) - } - } - - if err := exec.Command("pulseaudio", "--start", "--exit-idle-time=-1").Run(); err != nil { - log.Printf("extractor: warning: failed to start PulseAudio: %v", err) - } - // Create a null-sink as the default audio target for all sessions - exec.Command("pactl", "load-module", "module-null-sink", - "sink_name=virtual_sink", - "sink_properties=device.description=VirtualSink").Run() - exec.Command("pactl", "set-default-sink", "virtual_sink").Run() - - sessionSem = make(chan struct{}, maxConcurrentSessions) - log.Println("extractor: initialized") -} - -// Stop kills PulseAudio. -func Stop() { - exec.Command("pulseaudio", "--kill").Run() - log.Println("extractor: stopped") -} diff --git a/stacks/f1-stream/files/internal/extractor/capture.go b/stacks/f1-stream/files/internal/extractor/capture.go deleted file mode 100644 index b58bcec3..00000000 --- a/stacks/f1-stream/files/internal/extractor/capture.go +++ /dev/null @@ -1,167 +0,0 @@ -package extractor - -import ( - "fmt" - "log" - "os" - "os/exec" - "sync/atomic" - "time" -) - -var displayCounter int64 = 99 - -func nextDisplay() int { - return int(atomic.AddInt64(&displayCounter, 1)) -} - -// Capture manages an Xvfb display and separate ffmpeg pipelines for video and audio. -// Audio capture is best-effort — if PulseAudio is unavailable, video still works. -type Capture struct { - display int - xvfbCmd *exec.Cmd - videoCmd *exec.Cmd - audioCmd *exec.Cmd - videoR *os.File // IVF pipe reader (VP8 frames) - audioR *os.File // OGG pipe reader (Opus frames) -} - -// NewCapture starts Xvfb on the given display and two ffmpeg processes: -// one for video (x11grab → VP8/IVF) and one for audio (pulse → Opus/OGG). -// Audio is best-effort — if it fails to start, video still works and audioR -// is set to a pipe that will return EOF immediately. -func NewCapture(display, width, height int) (*Capture, error) { - c := &Capture{display: display} - - // Start Xvfb - screen := fmt.Sprintf("%dx%dx24", width, height) - c.xvfbCmd = exec.Command("Xvfb", fmt.Sprintf(":%d", display), - "-screen", "0", screen, "-ac", "-nolisten", "tcp") - if err := c.xvfbCmd.Start(); err != nil { - return nil, fmt.Errorf("capture: failed to start Xvfb: %w", err) - } - - // Wait for Xvfb to be ready (X11 socket must exist) - ready := false - for i := 0; i < 50; i++ { - socketPath := fmt.Sprintf("/tmp/.X11-unix/X%d", display) - if _, err := os.Stat(socketPath); err == nil { - ready = true - break - } - time.Sleep(100 * time.Millisecond) - } - if !ready { - c.xvfbCmd.Process.Kill() - c.xvfbCmd.Wait() - return nil, fmt.Errorf("capture: Xvfb did not start in time for display :%d", display) - } - - // --- Video pipeline (required) --- - videoR, videoW, err := os.Pipe() - if err != nil { - c.cleanup() - return nil, fmt.Errorf("capture: video pipe: %w", err) - } - - c.videoCmd = exec.Command("ffmpeg", - "-loglevel", "warning", - "-f", "x11grab", "-framerate", "30", - "-video_size", fmt.Sprintf("%dx%d", width, height), - "-i", fmt.Sprintf(":%d", display), - "-c:v", "libvpx", - "-quality", "realtime", "-cpu-used", "8", - "-deadline", "realtime", "-b:v", "2M", "-g", "30", - "-f", "ivf", "pipe:3", - ) - c.videoCmd.ExtraFiles = []*os.File{videoW} - c.videoCmd.Stdout = os.Stderr - c.videoCmd.Stderr = os.Stderr - - if err := c.videoCmd.Start(); err != nil { - videoR.Close() - videoW.Close() - c.cleanup() - return nil, fmt.Errorf("capture: failed to start video ffmpeg: %w", err) - } - videoW.Close() - c.videoR = videoR - - go func() { - if err := c.videoCmd.Wait(); err != nil { - log.Printf("capture: video ffmpeg exited on display :%d: %v", display, err) - } - }() - - // --- Audio pipeline (best-effort) --- - audioR, audioW, err := os.Pipe() - if err != nil { - log.Printf("capture: audio pipe failed on display :%d: %v (continuing without audio)", display, err) - // Provide a closed pipe so StreamAudio gets EOF immediately - r, w, _ := os.Pipe() - w.Close() - c.audioR = r - log.Printf("capture: started display :%d (%dx%d) (video only)", display, width, height) - return c, nil - } - - c.audioCmd = exec.Command("ffmpeg", - "-loglevel", "warning", - "-f", "pulse", "-i", "virtual_sink.monitor", - "-c:a", "libopus", - "-b:a", "128k", "-application", "lowdelay", - "-f", "ogg", "pipe:3", - ) - c.audioCmd.ExtraFiles = []*os.File{audioW} - c.audioCmd.Stdout = os.Stderr - c.audioCmd.Stderr = os.Stderr - - if err := c.audioCmd.Start(); err != nil { - log.Printf("capture: audio ffmpeg failed to start on display :%d: %v (continuing without audio)", display, err) - audioR.Close() - audioW.Close() - // Provide a closed pipe so StreamAudio gets EOF immediately - r, w, _ := os.Pipe() - w.Close() - c.audioR = r - c.audioCmd = nil - log.Printf("capture: started display :%d (%dx%d) (video only)", display, width, height) - return c, nil - } - audioW.Close() - c.audioR = audioR - - go func() { - if err := c.audioCmd.Wait(); err != nil { - log.Printf("capture: audio ffmpeg exited on display :%d: %v", display, err) - } - }() - - log.Printf("capture: started display :%d (%dx%d) (video + audio)", display, width, height) - return c, nil -} - -func (c *Capture) cleanup() { - if c.xvfbCmd != nil && c.xvfbCmd.Process != nil { - c.xvfbCmd.Process.Kill() - c.xvfbCmd.Wait() - } -} - -// Close stops ffmpeg processes, Xvfb, and releases pipe resources. -func (c *Capture) Close() { - if c.videoCmd != nil && c.videoCmd.Process != nil { - c.videoCmd.Process.Kill() - } - if c.audioCmd != nil && c.audioCmd.Process != nil { - c.audioCmd.Process.Kill() - } - if c.videoR != nil { - c.videoR.Close() - } - if c.audioR != nil { - c.audioR.Close() - } - c.cleanup() - log.Printf("capture: stopped display :%d", c.display) -} diff --git a/stacks/f1-stream/files/internal/extractor/session.go b/stacks/f1-stream/files/internal/extractor/session.go deleted file mode 100644 index 3178f4a4..00000000 --- a/stacks/f1-stream/files/internal/extractor/session.go +++ /dev/null @@ -1,383 +0,0 @@ -package extractor - -import ( - "context" - "encoding/json" - "fmt" - "log" - "net" - "net/http" - "os" - "os/exec" - "sync" - "time" - - "github.com/chromedp/cdproto/fetch" - "github.com/chromedp/cdproto/input" - "github.com/chromedp/cdproto/network" - "github.com/chromedp/cdproto/page" - "github.com/chromedp/chromedp" - "github.com/gobwas/ws" - "github.com/gobwas/ws/wsutil" - "github.com/pion/webrtc/v4" -) - -const ( - sessionTimeout = 5 * time.Minute - defaultViewportW = 1280 - defaultViewportH = 720 - turnCredentialTTL = 24 * time.Hour -) - -var ( - turnURL string - turnSharedSecret string - turnInternalURL string -) - -// SetTURNConfig sets the TURN server URL, shared secret, and optional internal URL. -// The internal URL is used by pion (server-side) to avoid hairpin NAT issues. -// The public URL is sent to the browser client. -func SetTURNConfig(url, secret, internalURL string) { - turnURL = url - turnSharedSecret = secret - turnInternalURL = internalURL - if turnInternalURL == "" { - turnInternalURL = "turn:coturn.coturn.svc.cluster.local:3478" - } - log.Printf("extractor: TURN configured: public=%s internal=%s", url, turnInternalURL) -} - -var adDomains = []string{ - "doubleclick.net", "googlesyndication.com", "googleadservices.com", - "google-analytics.com", "adnxs.com", "criteo.com", "outbrain.com", - "taboola.com", "amazon-adsystem.com", "popads.net", "popcash.net", - "juicyads.com", "exoclick.com", "trafficjunky.com", "propellerads.com", - "adsterra.com", "hilltopads.net", "revcontent.com", "mgid.com", -} - -type inputMsg struct { - Type string `json:"type"` - X float64 `json:"x"` - Y float64 `json:"y"` - Button int `json:"button"` - DeltaX float64 `json:"deltaX"` - DeltaY float64 `json:"deltaY"` - Key string `json:"key"` - Code string `json:"code"` - Mods int `json:"modifiers"` - Width int `json:"width"` - Height int `json:"height"` - SDP string `json:"sdp"` - Candidate *webrtc.ICECandidateInit `json:"candidate"` -} - -// HandleBrowserSession upgrades to WebSocket and runs a remote browser session -// with WebRTC video/audio streaming and CDP input relay. -func HandleBrowserSession(w http.ResponseWriter, r *http.Request, pageURL string) { - // Check session capacity - select { - case sessionSem <- struct{}{}: - defer func() { <-sessionSem }() - default: - http.Error(w, `{"error":"too many active browser sessions"}`, http.StatusServiceUnavailable) - return - } - - conn, _, _, err := ws.UpgradeHTTP(r, w) - if err != nil { - log.Printf("extractor: session: ws upgrade failed: %v", err) - return - } - defer conn.Close() - - ctx, cancel := context.WithCancel(r.Context()) - defer cancel() - - // Allocate display and start capture pipeline - display := nextDisplay() - viewW, viewH := defaultViewportW, defaultViewportH - - cap, err := NewCapture(display, viewW, viewH) - if err != nil { - sendWSError(conn, "failed to start capture: "+err.Error()) - log.Printf("extractor: session: capture error: %v", err) - return - } - defer cap.Close() - - // Start Chrome on the virtual display - opts := append(chromedp.DefaultExecAllocatorOptions[:], - chromedp.Flag("headless", false), - chromedp.Flag("no-sandbox", true), - chromedp.Flag("disable-gpu", true), - chromedp.Flag("disable-software-rasterizer", true), - chromedp.Flag("disable-dev-shm-usage", true), - chromedp.Flag("disable-extensions", true), - chromedp.Flag("disable-background-networking", true), - chromedp.ModifyCmdFunc(func(cmd *exec.Cmd) { - cmd.Env = append(os.Environ(), fmt.Sprintf("DISPLAY=:%d", display)) - }), - chromedp.Flag("autoplay-policy", "no-user-gesture-required"), - chromedp.Flag("window-size", fmt.Sprintf("%d,%d", viewW, viewH)), - chromedp.WSURLReadTimeout(30 * time.Second), - ) - allocCtx, allocCancel := chromedp.NewExecAllocator(ctx, opts...) - defer allocCancel() - - tabCtx, tabCancel := chromedp.NewContext(allocCtx) - defer tabCancel() - - var wsMu sync.Mutex - - // Build ICE servers for pion (server-side) — uses internal TURN URL to avoid hairpin NAT - iceServers := []webrtc.ICEServer{ - {URLs: []string{"stun:stun.l.google.com:19302"}}, - } - var turnCreds *TURNCredentials - if turnURL != "" && turnSharedSecret != "" { - // Server-side: use internal k8s DNS for TURN to bypass NAT - internalCreds := GenerateTURNCredentials(turnInternalURL, turnSharedSecret, turnCredentialTTL) - turnCreds = &internalCreds - iceServers = append(iceServers, webrtc.ICEServer{ - URLs: internalCreds.URLs, - Username: internalCreds.Username, - Credential: internalCreds.Credential, - CredentialType: webrtc.ICECredentialTypePassword, - }) - } - - // Build ad-blocking fetch patterns - adPatterns := make([]*fetch.RequestPattern, 0, len(adDomains)) - for _, domain := range adDomains { - adPatterns = append(adPatterns, &fetch.RequestPattern{ - URLPattern: fmt.Sprintf("*://*.%s/*", domain), - }) - } - - // Set up event listeners before navigation - chromedp.ListenTarget(tabCtx, func(ev interface{}) { - switch e := ev.(type) { - case *fetch.EventRequestPaused: - go chromedp.Run(tabCtx, fetch.FailRequest(e.RequestID, network.ErrorReasonBlockedByClient)) - case *page.EventFrameNavigated: - if e.Frame.ParentID == "" { - go sendURLUpdate(tabCtx, conn, &wsMu, e.Frame.URL) - } - case *page.EventNavigatedWithinDocument: - go sendURLUpdate(tabCtx, conn, &wsMu, e.URL) - } - }) - - // Enable fetch interception (ad blocking) and navigate - if err := chromedp.Run(tabCtx, - fetch.Enable().WithPatterns(adPatterns), - chromedp.Navigate(pageURL), - chromedp.WaitReady("body"), - ); err != nil { - sendWSError(conn, "navigation failed") - log.Printf("extractor: session: navigate error for %s: %v", pageURL, err) - return - } - - // Create WebRTC media stream - mediaStream, err := NewMediaStream(iceServers, func(c *webrtc.ICECandidate) { - data, _ := json.Marshal(map[string]interface{}{ - "type": "ice", - "candidate": c.ToJSON(), - }) - wsMu.Lock() - wsutil.WriteServerMessage(conn, ws.OpText, data) - wsMu.Unlock() - }, cancel) - if err != nil { - sendWSError(conn, "WebRTC setup failed") - log.Printf("extractor: session: webrtc error: %v", err) - return - } - defer mediaStream.Close() - - // Create and send SDP offer - sdp, err := mediaStream.Offer() - if err != nil { - sendWSError(conn, "WebRTC offer failed") - log.Printf("extractor: session: offer error: %v", err) - return - } - - // Send ICE config to client — uses PUBLIC TURN URL (for browser to reach from internet) - clientICE := []map[string]interface{}{ - {"urls": []string{"stun:stun.l.google.com:19302"}}, - } - if turnCreds != nil { - // Client-side: use public IP for TURN (browser connects from internet) - publicCreds := GenerateTURNCredentials(turnURL, turnSharedSecret, turnCredentialTTL) - clientICE = append(clientICE, map[string]interface{}{ - "urls": publicCreds.URLs, - "username": publicCreds.Username, - "credential": publicCreds.Credential, - }) - } - iceMsg, _ := json.Marshal(map[string]interface{}{ - "type": "iceServers", - "iceServers": clientICE, - }) - wsMu.Lock() - wsutil.WriteServerMessage(conn, ws.OpText, iceMsg) - wsMu.Unlock() - - offerMsg, _ := json.Marshal(map[string]interface{}{ - "type": "offer", - "sdp": sdp, - }) - wsMu.Lock() - wsutil.WriteServerMessage(conn, ws.OpText, offerMsg) - wsMu.Unlock() - - // Send ready message with viewport dimensions - readyMsg, _ := json.Marshal(map[string]interface{}{ - "type": "ready", - "width": viewW, - "height": viewH, - }) - wsMu.Lock() - wsutil.WriteServerMessage(conn, ws.OpText, readyMsg) - wsMu.Unlock() - - // Start streaming video and audio from capture pipes - go mediaStream.StreamVideo(cap.videoR, ctx) - go mediaStream.StreamAudio(cap.audioR, ctx) - - log.Printf("extractor: session: started for %s (display :%d)", pageURL, display) - - // Inactivity timer — cancels session after no client input - inactivity := time.NewTimer(sessionTimeout) - defer inactivity.Stop() - go func() { - select { - case <-inactivity.C: - log.Printf("extractor: session: inactivity timeout for %s", pageURL) - cancel() - case <-ctx.Done(): - } - }() - - // Read loop — process signaling and input messages - for { - msgs, err := wsutil.ReadClientMessage(conn, nil) - if err != nil { - break - } - for _, m := range msgs { - if m.OpCode != ws.OpText { - continue - } - - // Reset inactivity timer - if !inactivity.Stop() { - select { - case <-inactivity.C: - default: - } - } - inactivity.Reset(sessionTimeout) - - var msg inputMsg - if err := json.Unmarshal(m.Payload, &msg); err != nil { - continue - } - - switch msg.Type { - case "answer": - if err := mediaStream.SetAnswer(msg.SDP); err != nil { - log.Printf("extractor: session: set answer error: %v", err) - } - case "ice": - if msg.Candidate != nil { - if err := mediaStream.AddICECandidate(*msg.Candidate); err != nil { - log.Printf("extractor: session: add ICE error: %v", err) - } - } - case "back": - chromedp.Run(tabCtx, chromedp.NavigateBack()) - case "forward": - chromedp.Run(tabCtx, chromedp.NavigateForward()) - default: - handleInput(tabCtx, &msg) - } - } - } - - log.Printf("extractor: session: ended for %s", pageURL) -} - -func handleInput(ctx context.Context, msg *inputMsg) { - switch msg.Type { - case "mousemove": - chromedp.Run(ctx, - input.DispatchMouseEvent(input.MouseMoved, msg.X, msg.Y)) - case "mousedown": - chromedp.Run(ctx, - input.DispatchMouseEvent(input.MousePressed, msg.X, msg.Y). - WithButton(mapButton(msg.Button)).WithClickCount(1)) - case "mouseup": - chromedp.Run(ctx, - input.DispatchMouseEvent(input.MouseReleased, msg.X, msg.Y). - WithButton(mapButton(msg.Button))) - case "scroll": - chromedp.Run(ctx, - input.DispatchMouseEvent(input.MouseWheel, msg.X, msg.Y). - WithDeltaX(msg.DeltaX).WithDeltaY(msg.DeltaY)) - case "keydown": - chromedp.Run(ctx, - input.DispatchKeyEvent(input.KeyDown). - WithKey(msg.Key).WithCode(msg.Code). - WithModifiers(input.Modifier(msg.Mods))) - case "keyup": - chromedp.Run(ctx, - input.DispatchKeyEvent(input.KeyUp). - WithKey(msg.Key).WithCode(msg.Code). - WithModifiers(input.Modifier(msg.Mods))) - } -} - -func mapButton(jsButton int) input.MouseButton { - switch jsButton { - case 1: - return input.Middle - case 2: - return input.Right - default: - return input.Left - } -} - -func sendURLUpdate(tabCtx context.Context, conn net.Conn, mu *sync.Mutex, currentURL string) { - var canBack, canForward bool - var entries []*page.NavigationEntry - var currentIndex int64 - - if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error { - var err error - currentIndex, entries, err = page.GetNavigationHistory().Do(ctx) - return err - })); err == nil { - canBack = currentIndex > 0 - canForward = int(currentIndex) < len(entries)-1 - } - - data, _ := json.Marshal(map[string]interface{}{ - "type": "url", - "url": currentURL, - "canBack": canBack, - "canForward": canForward, - }) - mu.Lock() - wsutil.WriteServerMessage(conn, ws.OpText, data) - mu.Unlock() -} - -func sendWSError(conn net.Conn, msg string) { - data, _ := json.Marshal(map[string]string{"type": "error", "message": msg}) - wsutil.WriteServerMessage(conn, ws.OpText, data) -} diff --git a/stacks/f1-stream/files/internal/extractor/webrtc.go b/stacks/f1-stream/files/internal/extractor/webrtc.go deleted file mode 100644 index e6e1731f..00000000 --- a/stacks/f1-stream/files/internal/extractor/webrtc.go +++ /dev/null @@ -1,248 +0,0 @@ -package extractor - -import ( - "context" - "crypto/hmac" - "crypto/sha1" - "encoding/base64" - "fmt" - "io" - "log" - "time" - - "github.com/pion/webrtc/v4" - "github.com/pion/webrtc/v4/pkg/media" - "github.com/pion/webrtc/v4/pkg/media/ivfreader" - "github.com/pion/webrtc/v4/pkg/media/oggreader" -) - -// TURNCredentials holds ephemeral TURN credentials generated from a shared secret. -type TURNCredentials struct { - URLs []string `json:"urls"` - Username string `json:"username"` - Credential string `json:"credential"` -} - -// GenerateTURNCredentials creates time-limited TURN credentials using the -// shared secret (TURN REST API / coturn --use-auth-secret). -func GenerateTURNCredentials(turnURL, sharedSecret string, ttl time.Duration) TURNCredentials { - expiry := time.Now().Add(ttl).Unix() - username := fmt.Sprintf("%d", expiry) - - mac := hmac.New(sha1.New, []byte(sharedSecret)) - mac.Write([]byte(username)) - credential := base64.StdEncoding.EncodeToString(mac.Sum(nil)) - - return TURNCredentials{ - URLs: []string{turnURL}, - Username: username, - Credential: credential, - } -} - -// MediaStream wraps a pion WebRTC PeerConnection with VP8 video and Opus audio tracks. -type MediaStream struct { - pc *webrtc.PeerConnection - videoTrack *webrtc.TrackLocalStaticSample - audioTrack *webrtc.TrackLocalStaticSample -} - -// NewMediaStream creates a PeerConnection with VP8 + Opus tracks and an ICE callback. -// The cancel function is called when ICE fails to trigger session cleanup. -func NewMediaStream(iceServers []webrtc.ICEServer, onICE func(*webrtc.ICECandidate), cancel context.CancelFunc) (*MediaStream, error) { - config := webrtc.Configuration{ - ICEServers: iceServers, - } - - pc, err := webrtc.NewPeerConnection(config) - if err != nil { - return nil, err - } - - videoTrack, err := webrtc.NewTrackLocalStaticSample( - webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8}, - "video", "stream", - ) - if err != nil { - pc.Close() - return nil, err - } - - audioTrack, err := webrtc.NewTrackLocalStaticSample( - webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus}, - "audio", "stream", - ) - if err != nil { - pc.Close() - return nil, err - } - - if _, err = pc.AddTrack(videoTrack); err != nil { - pc.Close() - return nil, err - } - if _, err = pc.AddTrack(audioTrack); err != nil { - pc.Close() - return nil, err - } - - pc.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) { - log.Printf("webrtc: ICE connection state: %s", state.String()) - if state == webrtc.ICEConnectionStateFailed { - log.Printf("webrtc: ICE failed, cancelling session") - cancel() - return - } - if state == webrtc.ICEConnectionStateConnected { - // Log selected candidate pair - if stats := pc.GetStats(); stats != nil { - for _, s := range stats { - if cp, ok := s.(webrtc.ICECandidatePairStats); ok && cp.Nominated { - log.Printf("webrtc: selected candidate pair: local=%s remote=%s", - cp.LocalCandidateID, cp.RemoteCandidateID) - } - } - } - // Start periodic stats logging - go func() { - ticker := time.NewTicker(10 * time.Second) - defer ticker.Stop() - for range ticker.C { - if pc.ICEConnectionState() != webrtc.ICEConnectionStateConnected && - pc.ICEConnectionState() != webrtc.ICEConnectionStateCompleted { - return - } - stats := pc.GetStats() - for _, s := range stats { - if out, ok := s.(webrtc.OutboundRTPStreamStats); ok { - log.Printf("webrtc: outbound-rtp kind=%s bytes=%d packets=%d", - out.Kind, out.BytesSent, out.PacketsSent) - } - } - } - }() - } - }) - - pc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) { - log.Printf("webrtc: peer connection state: %s", state.String()) - }) - - pc.OnICECandidate(func(c *webrtc.ICECandidate) { - if c != nil { - log.Printf("webrtc: gathered ICE candidate: type=%s addr=%s:%d", - c.Typ.String(), c.Address, c.Port) - if onICE != nil { - onICE(c) - } - } - }) - - return &MediaStream{ - pc: pc, - videoTrack: videoTrack, - audioTrack: audioTrack, - }, nil -} - -// Offer creates an SDP offer, sets it as local description, and returns the SDP string. -func (m *MediaStream) Offer() (string, error) { - offer, err := m.pc.CreateOffer(nil) - if err != nil { - return "", err - } - if err := m.pc.SetLocalDescription(offer); err != nil { - return "", err - } - return offer.SDP, nil -} - -// SetAnswer sets the remote SDP answer. -func (m *MediaStream) SetAnswer(sdp string) error { - return m.pc.SetRemoteDescription(webrtc.SessionDescription{ - Type: webrtc.SDPTypeAnswer, - SDP: sdp, - }) -} - -// AddICECandidate adds a remote ICE candidate. -func (m *MediaStream) AddICECandidate(init webrtc.ICECandidateInit) error { - return m.pc.AddICECandidate(init) -} - -// StreamVideo reads VP8 frames from an IVF stream and writes them to the video track. -// Blocks until the reader returns an error or the context is cancelled. -func (m *MediaStream) StreamVideo(r io.Reader, ctx context.Context) { - ivf, _, err := ivfreader.NewWith(r) - if err != nil { - log.Printf("webrtc: ivf reader error: %v", err) - return - } - - duration := time.Second / 30 - - for { - select { - case <-ctx.Done(): - return - default: - } - - frame, _, err := ivf.ParseNextFrame() - if err != nil { - if err != io.EOF { - log.Printf("webrtc: video frame error: %v", err) - } - return - } - - if err := m.videoTrack.WriteSample(media.Sample{ - Data: frame, - Duration: duration, - }); err != nil { - log.Printf("webrtc: video write error: %v", err) - return - } - } -} - -// StreamAudio reads Opus pages from an OGG stream and writes them to the audio track. -// Blocks until the reader returns an error or the context is cancelled. -func (m *MediaStream) StreamAudio(r io.Reader, ctx context.Context) { - ogg, _, err := oggreader.NewWith(r) - if err != nil { - log.Printf("webrtc: ogg reader error: %v", err) - return - } - - for { - select { - case <-ctx.Done(): - return - default: - } - - page, _, err := ogg.ParseNextPage() - if err != nil { - if err != io.EOF { - log.Printf("webrtc: audio page error: %v", err) - } - return - } - - if err := m.audioTrack.WriteSample(media.Sample{ - Data: page, - Duration: 20 * time.Millisecond, - }); err != nil { - log.Printf("webrtc: audio write error: %v", err) - return - } - } -} - -// Close closes the underlying PeerConnection. -func (m *MediaStream) Close() { - if m.pc != nil { - m.pc.Close() - } -} diff --git a/stacks/f1-stream/files/internal/healthcheck/healthcheck.go b/stacks/f1-stream/files/internal/healthcheck/healthcheck.go deleted file mode 100644 index 217f4803..00000000 --- a/stacks/f1-stream/files/internal/healthcheck/healthcheck.go +++ /dev/null @@ -1,188 +0,0 @@ -package healthcheck - -import ( - "context" - "log" - "net/http" - "sync" - "time" - - "f1-stream/internal/models" - "f1-stream/internal/store" -) - -const unhealthyThreshold = 5 - -const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" - -// isReachable sends a GET request and returns true if the server responds with -// an HTTP 2xx or 3xx status code. -func isReachable(client *http.Client, rawURL string) bool { - req, err := http.NewRequest("GET", rawURL, nil) - if err != nil { - return false - } - req.Header.Set("User-Agent", userAgent) - - resp, err := client.Do(req) - if err != nil { - return false - } - defer resp.Body.Close() - - return resp.StatusCode >= 200 && resp.StatusCode < 400 -} - -type HealthChecker struct { - store *store.Store - interval time.Duration - timeout time.Duration - client *http.Client - mu sync.Mutex -} - -func New(s *store.Store, interval, timeout time.Duration) *HealthChecker { - return &HealthChecker{ - store: s, - interval: interval, - timeout: timeout, - client: &http.Client{ - Timeout: timeout, - CheckRedirect: func(req *http.Request, via []*http.Request) error { - if len(via) >= 3 { - return http.ErrUseLastResponse - } - return nil - }, - }, - } -} - -func (hc *HealthChecker) Run(ctx context.Context) { - log.Printf("healthcheck: starting with interval=%v timeout=%v", hc.interval, hc.timeout) - hc.checkAll() - - ticker := time.NewTicker(hc.interval) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - log.Println("healthcheck: shutting down") - return - case <-ticker.C: - hc.checkAll() - } - } -} - -func (hc *HealthChecker) checkAll() { - hc.mu.Lock() - defer hc.mu.Unlock() - - start := time.Now() - urls := hc.collectURLs() - log.Printf("healthcheck: checking %d URLs", len(urls)) - - existing, err := hc.store.LoadHealthStates() - if err != nil { - log.Printf("healthcheck: failed to load health states: %v", err) - existing = nil - } - - stateMap := make(map[string]*models.HealthState, len(existing)) - for i := range existing { - stateMap[existing[i].URL] = &existing[i] - } - - now := time.Now() - var recovered, newlyUnhealthy int - - for _, url := range urls { - st, exists := stateMap[url] - if !exists { - st = &models.HealthState{ - URL: url, - Healthy: true, - } - stateMap[url] = st - } - - ok := isReachable(hc.client, url) - - if ok { - if !st.Healthy { - log.Printf("healthcheck: recovered %s", truncate(url, 80)) - recovered++ - } - st.ConsecutiveFailures = 0 - st.Healthy = true - } else { - st.ConsecutiveFailures++ - if st.ConsecutiveFailures >= unhealthyThreshold && st.Healthy { - st.Healthy = false - log.Printf("healthcheck: marking unhealthy after %d failures: %s", st.ConsecutiveFailures, truncate(url, 80)) - newlyUnhealthy++ - } - } - st.LastCheckTime = now - } - - // Prune orphaned entries: only keep states whose URL is in the current set - urlSet := make(map[string]bool, len(urls)) - for _, u := range urls { - urlSet[u] = true - } - var finalStates []models.HealthState - healthyCount := 0 - for _, st := range stateMap { - if urlSet[st.URL] { - finalStates = append(finalStates, *st) - if st.Healthy { - healthyCount++ - } - } - } - - if err := hc.store.SaveHealthStates(finalStates); err != nil { - log.Printf("healthcheck: failed to save health states: %v", err) - } - - log.Printf("healthcheck: done in %v, checked=%d healthy=%d recovered=%d newly_unhealthy=%d", - time.Since(start).Round(time.Millisecond), len(urls), healthyCount, recovered, newlyUnhealthy) -} - -func (hc *HealthChecker) collectURLs() []string { - seen := make(map[string]bool) - - streams, err := hc.store.LoadStreams() - if err != nil { - log.Printf("healthcheck: failed to load streams: %v", err) - } else { - for _, s := range streams { - seen[s.URL] = true - } - } - - scraped, err := hc.store.LoadScrapedLinks() - if err != nil { - log.Printf("healthcheck: failed to load scraped links: %v", err) - } else { - for _, l := range scraped { - seen[l.URL] = true - } - } - - urls := make([]string, 0, len(seen)) - for u := range seen { - urls = append(urls, u) - } - return urls -} - -func truncate(s string, maxLen int) string { - if len(s) <= maxLen { - return s - } - return s[:maxLen] + "..." -} diff --git a/stacks/f1-stream/files/internal/hlsproxy/hlsproxy.go b/stacks/f1-stream/files/internal/hlsproxy/hlsproxy.go deleted file mode 100644 index 24410af7..00000000 --- a/stacks/f1-stream/files/internal/hlsproxy/hlsproxy.go +++ /dev/null @@ -1,209 +0,0 @@ -package hlsproxy - -import ( - "bufio" - "encoding/base64" - "io" - "log" - "net/http" - "net/url" - "strings" -) - -// NewHandler returns an http.Handler for /hls/{base64url_encoded_full_url}. -// It proxies HLS playlists and segments, rewriting m3u8 URLs to route -// through the proxy and forwarding X-Hls-Forward-* headers upstream. -func NewHandler() http.Handler { - client := &http.Client{ - Timeout: 30_000_000_000, // 30s - CheckRedirect: func(req *http.Request, via []*http.Request) error { - if len(via) >= 5 { - return http.ErrUseLastResponse - } - return nil - }, - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method == http.MethodOptions { - setCORS(w) - w.WriteHeader(http.StatusNoContent) - return - } - - // Parse: /hls/{base64url_encoded_full_url} - trimmed := strings.TrimPrefix(r.URL.Path, "/hls/") - if trimmed == "" || trimmed == r.URL.Path { - http.Error(w, "bad hls proxy URL", http.StatusBadRequest) - return - } - - // Decode the full upstream URL from base64url - upstreamURL, err := base64.RawURLEncoding.DecodeString(trimmed) - if err != nil { - http.Error(w, "invalid base64url", http.StatusBadRequest) - return - } - target := string(upstreamURL) - - parsed, err := url.Parse(target) - if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") { - http.Error(w, "invalid upstream URL", http.StatusBadRequest) - return - } - - log.Printf("hlsproxy: %s -> %s", r.URL.Path, target) - - upReq, err := http.NewRequestWithContext(r.Context(), http.MethodGet, target, nil) - if err != nil { - http.Error(w, "failed to create request", http.StatusInternalServerError) - return - } - - // Set Referer and Origin. If the URL has a ?domain= param (CDN segments), - // use that domain as the origin so the CDN accepts the request. - refererOrigin := parsed.Scheme + "://" + parsed.Host - if domainParam := parsed.Query().Get("domain"); domainParam != "" { - refererOrigin = "https://" + domainParam - } - upReq.Header.Set("Referer", refererOrigin+"/") - upReq.Header.Set("Origin", refererOrigin) - upReq.Header.Set("User-Agent", r.Header.Get("User-Agent")) - - // Forward X-Hls-Forward-* headers (strip prefix) - for key, vals := range r.Header { - if strings.HasPrefix(key, "X-Hls-Forward-") { - realKey := strings.TrimPrefix(key, "X-Hls-Forward-") - for _, v := range vals { - upReq.Header.Set(realKey, v) - } - } - } - - resp, err := client.Do(upReq) - if err != nil { - log.Printf("hlsproxy: upstream fetch failed: %v", err) - http.Error(w, "upstream fetch failed", http.StatusBadGateway) - return - } - defer resp.Body.Close() - - log.Printf("hlsproxy: %s <- %d (%s)", truncPath(r.URL.Path, 60), resp.StatusCode, resp.Header.Get("Content-Type")) - - setCORS(w) - - ct := resp.Header.Get("Content-Type") - isM3U8 := strings.Contains(ct, "mpegurl") || - strings.Contains(ct, "x-mpegURL") || - strings.HasSuffix(parsed.Path, ".m3u8") - - if isM3U8 { - w.Header().Set("Content-Type", "application/vnd.apple.mpegurl") - w.WriteHeader(resp.StatusCode) - rewriteM3U8(w, resp.Body, target) - return - } - - // Stream segment or other content directly - for key, vals := range resp.Header { - lk := strings.ToLower(key) - if lk == "content-type" || lk == "content-length" || lk == "cache-control" || lk == "accept-ranges" { - for _, v := range vals { - w.Header().Add(key, v) - } - } - } - w.WriteHeader(resp.StatusCode) - io.Copy(w, resp.Body) - }) -} - -// rewriteM3U8 reads an m3u8 playlist from r, rewrites segment/playlist URLs -// to route through /hls/{b64}, and writes the result to w. -func rewriteM3U8(w io.Writer, r io.Reader, playlistURL string) { - base, err := url.Parse(playlistURL) - if err != nil { - io.Copy(w, r) - return - } - - scanner := bufio.NewScanner(r) - scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) - - for scanner.Scan() { - line := scanner.Text() - - if strings.HasPrefix(line, "#") { - // Rewrite URI="..." in directives like #EXT-X-KEY, #EXT-X-MAP - rewritten := rewriteURIAttribute(line, base) - w.Write([]byte(rewritten)) - w.Write([]byte("\n")) - continue - } - - // Non-comment, non-empty lines are URLs - trimmed := strings.TrimSpace(line) - if trimmed == "" { - w.Write([]byte("\n")) - continue - } - - resolved := resolveURL(base, trimmed) - encoded := encodeHLSURL(resolved) - w.Write([]byte(encoded)) - w.Write([]byte("\n")) - } -} - -// rewriteURIAttribute rewrites URI="..." attributes in HLS directives. -func rewriteURIAttribute(line string, base *url.URL) string { - // Look for URI="..." (case insensitive) - uriIdx := strings.Index(strings.ToUpper(line), "URI=\"") - if uriIdx == -1 { - return line - } - - // Find the actual position (preserving original case) - prefix := line[:uriIdx+5] // everything up to and including URI=" - rest := line[uriIdx+5:] - endQuote := strings.Index(rest, "\"") - if endQuote == -1 { - return line - } - - uri := rest[:endQuote] - suffix := rest[endQuote:] // closing quote and anything after - - resolved := resolveURL(base, uri) - encoded := encodeHLSURL(resolved) - - return prefix + encoded + suffix -} - -// resolveURL resolves a potentially relative URL against a base URL. -func resolveURL(base *url.URL, ref string) string { - refURL, err := url.Parse(ref) - if err != nil { - return ref - } - return base.ResolveReference(refURL).String() -} - -// encodeHLSURL encodes a full URL into /hls/{base64url} format. -func encodeHLSURL(fullURL string) string { - encoded := base64.RawURLEncoding.EncodeToString([]byte(fullURL)) - return "/hls/" + encoded -} - -func setCORS(w http.ResponseWriter) { - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "*") -} - -func truncPath(s string, n int) string { - if len(s) <= n { - return s - } - return s[:n] + "..." -} diff --git a/stacks/f1-stream/files/internal/models/models.go b/stacks/f1-stream/files/internal/models/models.go deleted file mode 100644 index b6798cc5..00000000 --- a/stacks/f1-stream/files/internal/models/models.go +++ /dev/null @@ -1,53 +0,0 @@ -package models - -import ( - "time" - - "github.com/go-webauthn/webauthn/webauthn" -) - -type User struct { - ID string `json:"id"` - Username string `json:"username"` - IsAdmin bool `json:"is_admin"` - Credentials []webauthn.Credential `json:"credentials"` - CreatedAt time.Time `json:"created_at"` -} - -// WebAuthn interface implementation -func (u *User) WebAuthnID() []byte { return []byte(u.ID) } -func (u *User) WebAuthnName() string { return u.Username } -func (u *User) WebAuthnDisplayName() string { return u.Username } -func (u *User) WebAuthnCredentials() []webauthn.Credential { return u.Credentials } - -type Stream struct { - ID string `json:"id"` - URL string `json:"url"` - Title string `json:"title"` - SubmittedBy string `json:"submitted_by"` - Published bool `json:"published"` - Source string `json:"source"` - CreatedAt time.Time `json:"created_at"` -} - -type ScrapedLink struct { - ID string `json:"id"` - URL string `json:"url"` - Title string `json:"title"` - Source string `json:"source"` - ScrapedAt time.Time `json:"scraped_at"` - Stale bool `json:"stale"` -} - -type Session struct { - Token string `json:"token"` - UserID string `json:"user_id"` - ExpiresAt time.Time `json:"expires_at"` -} - -type HealthState struct { - URL string `json:"url"` - ConsecutiveFailures int `json:"consecutive_failures"` - LastCheckTime time.Time `json:"last_check_time"` - Healthy bool `json:"healthy"` -} diff --git a/stacks/f1-stream/files/internal/playerconfig/playerconfig.go b/stacks/f1-stream/files/internal/playerconfig/playerconfig.go deleted file mode 100644 index 3ebbb549..00000000 --- a/stacks/f1-stream/files/internal/playerconfig/playerconfig.go +++ /dev/null @@ -1,512 +0,0 @@ -package playerconfig - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "log" - "net/http" - "regexp" - "strings" - "sync" - "time" -) - -// PlayerConfig is returned by the /api/streams/{id}/player-config endpoint. -type PlayerConfig struct { - Type string `json:"type"` - HLSURL string `json:"hls_url,omitempty"` - AuthToken string `json:"auth_token,omitempty"` - ChannelKey string `json:"channel_key,omitempty"` - ChannelSalt string `json:"channel_salt,omitempty"` - Timestamp string `json:"timestamp,omitempty"` - AuthModURL string `json:"auth_mod_url,omitempty"` - ServerKey string `json:"server_key,omitempty"` - Error string `json:"error,omitempty"` -} - -type cacheEntry struct { - config *PlayerConfig - expiresAt time.Time -} - -// Service handles stream type detection and DaddyLive config extraction. -type Service struct { - client *http.Client - mu sync.RWMutex - cache map[string]*cacheEntry -} - -// New creates a new playerconfig Service. -func New() *Service { - return &Service{ - client: &http.Client{ - Timeout: 15 * time.Second, - }, - cache: make(map[string]*cacheEntry), - } -} - -// DetectStreamType returns "hls", "daddylive", "vipleague", or "proxy" based on the URL. -func DetectStreamType(rawURL string) string { - lower := strings.ToLower(rawURL) - - if strings.HasSuffix(strings.SplitN(lower, "?", 2)[0], ".m3u8") { - return "hls" - } - - daddyPatterns := []string{"dlhd.link", "dlhd.sx", "dlhd.dad", "daddylive", "ksohls.ru"} - for _, p := range daddyPatterns { - if strings.Contains(lower, p) { - return "daddylive" - } - } - - vipPatterns := []string{"vipleague.io", "vipleague.im", "vipleague.cc", "casthill.net"} - for _, p := range vipPatterns { - if strings.Contains(lower, p) { - return "vipleague" - } - } - - return "proxy" -} - -// GetConfig returns a PlayerConfig for the given stream URL. -func (s *Service) GetConfig(ctx context.Context, rawURL string) *PlayerConfig { - streamType := DetectStreamType(rawURL) - - switch streamType { - case "hls": - encoded := base64.RawURLEncoding.EncodeToString([]byte(rawURL)) - return &PlayerConfig{ - Type: "hls", - HLSURL: "/hls/" + encoded, - } - - case "daddylive": - return s.getDaddyLiveConfig(ctx, rawURL) - - case "vipleague": - return s.getVIPLeagueConfig(ctx, rawURL) - - default: - return &PlayerConfig{Type: "proxy"} - } -} - -// Channel ID extraction patterns -var channelIDPatterns = []*regexp.Regexp{ - regexp.MustCompile(`stream-(\d+)\.php`), - regexp.MustCompile(`[?&]id=(\d+)`), - regexp.MustCompile(`/(\d+)\.php`), -} - -// Page content extraction patterns -var ( - iframeRe = regexp.MustCompile(`]*src=["'](https?://[^"']*ksohls\.ru[^"']*)["']`) - authTokenRe = regexp.MustCompile(`authToken\s*[:=]\s*['"]([^'"]+)['"]`) - channelKeyRe = regexp.MustCompile(`channelKey\s*[:=]\s*['"]([^'"]+)['"]`) - channelSaltRe = regexp.MustCompile(`channelSalt\s*[:=]\s*['"]([^'"]+)['"]`) - timestampRe = regexp.MustCompile(`timestamp\s*[:=]\s*['"]?(\d+)['"]?`) - authModRe = regexp.MustCompile(`]*src=["'](https?://[^"']*aiaged\.fun[^"']*obfuscated[^"']*)["']`) -) - -func (s *Service) getDaddyLiveConfig(ctx context.Context, rawURL string) *PlayerConfig { - // Check cache - s.mu.RLock() - if entry, ok := s.cache[rawURL]; ok && time.Now().Before(entry.expiresAt) { - s.mu.RUnlock() - return entry.config - } - s.mu.RUnlock() - - config := s.fetchDaddyLiveConfig(ctx, rawURL) - - // Cache the result (even errors, to avoid hammering) - s.mu.Lock() - s.cache[rawURL] = &cacheEntry{ - config: config, - expiresAt: time.Now().Add(1 * time.Hour), - } - s.mu.Unlock() - - return config -} - -func (s *Service) fetchDaddyLiveConfig(ctx context.Context, rawURL string) *PlayerConfig { - // Step 1: Extract channel ID from URL - channelID := "" - for _, re := range channelIDPatterns { - if m := re.FindStringSubmatch(rawURL); len(m) > 1 { - channelID = m[1] - break - } - } - if channelID == "" { - return &PlayerConfig{Type: "proxy", Error: "could not extract channel ID"} - } - - log.Printf("playerconfig: DaddyLive channel=%s from %s", channelID, rawURL) - return s.fetchDaddyLiveConfigByID(ctx, channelID) -} - -func (s *Service) fetchDaddyLiveConfigByID(ctx context.Context, channelID string) *PlayerConfig { - // Step 2: Fetch the cast page to find the ksohls iframe - castURL := fmt.Sprintf("https://dlhd.link/cast/stream-%s.php", channelID) - castBody, err := s.fetchPage(ctx, castURL, "https://dlhd.link/") - if err != nil { - log.Printf("playerconfig: failed to fetch cast page: %v", err) - return &PlayerConfig{Type: "proxy", Error: "failed to fetch cast page"} - } - - // Step 3: Extract ksohls iframe URL - iframeMatch := iframeRe.FindStringSubmatch(castBody) - if iframeMatch == nil { - log.Printf("playerconfig: no ksohls iframe found in cast page") - return &PlayerConfig{Type: "proxy", Error: "no ksohls iframe found"} - } - ksohURL := iframeMatch[1] - - // Step 4: Fetch the ksohls page - referer := fmt.Sprintf("https://dlhd.link/stream/stream-%s.php", channelID) - ksohBody, err := s.fetchPage(ctx, ksohURL, referer) - if err != nil { - log.Printf("playerconfig: failed to fetch ksohls page: %v", err) - return &PlayerConfig{Type: "proxy", Error: "failed to fetch ksohls page"} - } - - // Step 5: Extract auth params from ksohls page - config := &PlayerConfig{Type: "daddylive"} - - if m := authTokenRe.FindStringSubmatch(ksohBody); len(m) > 1 { - config.AuthToken = m[1] - } - if m := channelKeyRe.FindStringSubmatch(ksohBody); len(m) > 1 { - config.ChannelKey = m[1] - } - if m := channelSaltRe.FindStringSubmatch(ksohBody); len(m) > 1 { - config.ChannelSalt = m[1] - } - if m := timestampRe.FindStringSubmatch(ksohBody); len(m) > 1 { - config.Timestamp = m[1] - } - if m := authModRe.FindStringSubmatch(ksohBody); len(m) > 1 { - config.AuthModURL = m[1] - } - - if config.ChannelKey == "" { - log.Printf("playerconfig: no channelKey found in ksohls page") - return &PlayerConfig{Type: "proxy", Error: "no channelKey found"} - } - - // Step 6: Server lookup - lookupURL := fmt.Sprintf("https://chevy.soyspace.cyou/server_lookup?channel_id=%s", config.ChannelKey) - lookupBody, err := s.fetchPage(ctx, lookupURL, "") - if err != nil { - log.Printf("playerconfig: server lookup failed: %v", err) - return &PlayerConfig{Type: "proxy", Error: "server lookup failed"} - } - - var lookupResp struct { - ServerKey string `json:"server_key"` - } - if err := json.Unmarshal([]byte(lookupBody), &lookupResp); err != nil || lookupResp.ServerKey == "" { - log.Printf("playerconfig: failed to parse server lookup: %v body=%s", err, lookupBody) - return &PlayerConfig{Type: "proxy", Error: "server lookup parse failed"} - } - config.ServerKey = lookupResp.ServerKey - - // Step 7: Build m3u8 URL - m3u8URL := fmt.Sprintf("https://chevy.soyspace.cyou/proxy/%s/%s/mono.m3u8", - config.ServerKey, config.ChannelKey) - encoded := base64.RawURLEncoding.EncodeToString([]byte(m3u8URL)) - config.HLSURL = "/hls/" + encoded - - log.Printf("playerconfig: DaddyLive config ready channel=%s server=%s", config.ChannelKey, config.ServerKey) - return config -} - -// VIPLeague/casthill resolution - -var zmidRe = regexp.MustCompile(`(?:const|var|let)\s+zmid\s*=\s*["']([^"']+)["']`) -var casthillVRe = regexp.MustCompile(`[?&]v=([^&]+)`) - -func (s *Service) getVIPLeagueConfig(ctx context.Context, rawURL string) *PlayerConfig { - // Check cache using normalized URL - s.mu.RLock() - if entry, ok := s.cache[rawURL]; ok && time.Now().Before(entry.expiresAt) { - s.mu.RUnlock() - return entry.config - } - s.mu.RUnlock() - - config := s.fetchVIPLeagueConfig(ctx, rawURL) - - s.mu.Lock() - s.cache[rawURL] = &cacheEntry{ - config: config, - expiresAt: time.Now().Add(1 * time.Hour), - } - s.mu.Unlock() - - return config -} - -func (s *Service) fetchVIPLeagueConfig(ctx context.Context, rawURL string) *PlayerConfig { - lower := strings.ToLower(rawURL) - - var zmid string - - if strings.Contains(lower, "casthill.net") { - // Extract zmid from casthill URL query param ?v=... - if m := casthillVRe.FindStringSubmatch(rawURL); len(m) > 1 { - zmid = m[1] - } - } - - if zmid == "" { - // Try to fetch VIPLeague page and extract zmid from JavaScript - body, err := s.fetchPage(ctx, rawURL, "") - if err != nil { - log.Printf("playerconfig: failed to fetch VIPLeague page: %v, trying URL-based extraction", err) - } else { - if m := zmidRe.FindStringSubmatch(body); len(m) > 1 { - zmid = m[1] - } - } - } - - if zmid == "" { - // Fallback: extract slug from URL path and use it directly for channel matching - // e.g. /f-1/sky-sports-f1-streaming → "sky sports f1" - zmid = extractSlugFromURL(rawURL) - if zmid != "" { - log.Printf("playerconfig: extracted slug %q from URL path", zmid) - } - } - - if zmid == "" { - log.Printf("playerconfig: no zmid found for VIPLeague URL %s", rawURL) - return &PlayerConfig{Type: "proxy", Error: "no zmid found in VIPLeague page"} - } - - log.Printf("playerconfig: VIPLeague zmid=%q from %s", zmid, rawURL) - - channelID, err := s.resolveChannelID(ctx, zmid) - if err != nil { - log.Printf("playerconfig: failed to resolve zmid %q: %v", zmid, err) - return &PlayerConfig{Type: "proxy", Error: fmt.Sprintf("failed to resolve zmid: %v", err)} - } - - log.Printf("playerconfig: resolved zmid=%q to DaddyLive channel=%s", zmid, channelID) - return s.fetchDaddyLiveConfigByID(ctx, channelID) -} - -// extractSlugFromURL extracts a channel-matching slug from a VIPLeague URL path. -// e.g. "https://vipleague.io/f-1/sky-sports-f1-streaming" → "sky sports f1" -// Strips common suffixes like "-streaming", "-live-stream", "-live", etc. -func extractSlugFromURL(rawURL string) string { - // Get the last path segment - path := rawURL - if idx := strings.Index(path, "?"); idx != -1 { - path = path[:idx] - } - path = strings.TrimRight(path, "/") - lastSlash := strings.LastIndex(path, "/") - if lastSlash == -1 { - return "" - } - slug := path[lastSlash+1:] - - // Strip common suffixes - for _, suffix := range []string{"-streaming", "-live-stream", "-stream", "-live", "-online", "-free"} { - slug = strings.TrimSuffix(slug, suffix) - } - - // Replace hyphens with spaces for matching against channel names - slug = strings.ReplaceAll(slug, "-", " ") - slug = strings.TrimSpace(slug) - - if slug == "" || len(slug) < 3 { - return "" - } - return slug -} - -var channelLinkRe = regexp.MustCompile(`]*href=["'][^"']*watch\.php\?id=(\d+)["'][^>]*data-title=["']([^"']+)["']`) -var channelLinkRe2 = regexp.MustCompile(`]*data-title=["']([^"']+)["'][^>]*href=["'][^"']*watch\.php\?id=(\d+)["']`) - -func (s *Service) resolveChannelID(ctx context.Context, zmid string) (string, error) { - channels, err := s.getChannelIndex(ctx) - if err != nil { - return "", err - } - - zmidLower := strings.ToLower(zmid) - - // Build tokens: if zmid contains spaces, split on spaces; otherwise use tokenizer - var tokens []string - if strings.Contains(zmidLower, " ") { - for _, word := range strings.Fields(zmidLower) { - if len(word) >= 2 { - tokens = append(tokens, word) - } - } - } else { - tokens = tokenize(zmidLower) - } - - bestID := "" - bestScore := 0 - bestNameLen := 0 - - for id, name := range channels { - score := 0 - for _, tok := range tokens { - if strings.Contains(name, tok) { - score++ - } - } - // Tiebreaker: prefer shorter names (more specific match) and - // English/UK channels which tend to have shorter names - if score > bestScore || (score == bestScore && score > 0 && len(name) < bestNameLen) { - bestScore = score - bestID = id - bestNameLen = len(name) - } - } - - if bestID == "" || bestScore == 0 { - return "", fmt.Errorf("no channel matched zmid %q (tried %d channels)", zmid, len(channels)) - } - - log.Printf("playerconfig: zmid=%q matched channel %s (%s) with score %d/%d", - zmid, bestID, channels[bestID], bestScore, len(tokens)) - return bestID, nil -} - -func (s *Service) getChannelIndex(ctx context.Context) (map[string]string, error) { - const cacheKey = "__channel_index__" - - s.mu.RLock() - if entry, ok := s.cache[cacheKey]; ok && time.Now().Before(entry.expiresAt) { - s.mu.RUnlock() - // Decode from the Error field (ab)used as storage - var idx map[string]string - if err := json.Unmarshal([]byte(entry.config.Error), &idx); err == nil { - return idx, nil - } - } - s.mu.RUnlock() - - body, err := s.fetchPage(ctx, "https://dlhd.link/24-7-channels.php", "https://dlhd.link/") - if err != nil { - return nil, fmt.Errorf("failed to fetch channel index: %w", err) - } - - channels := make(map[string]string) - - // Try both attribute orderings - for _, m := range channelLinkRe.FindAllStringSubmatch(body, -1) { - channels[m[1]] = strings.ToLower(strings.TrimSpace(m[2])) - } - for _, m := range channelLinkRe2.FindAllStringSubmatch(body, -1) { - channels[m[2]] = strings.ToLower(strings.TrimSpace(m[1])) - } - - if len(channels) == 0 { - return nil, fmt.Errorf("no channels found in 24/7 page (%d bytes)", len(body)) - } - - log.Printf("playerconfig: loaded %d channels from DaddyLive 24/7 page", len(channels)) - - // Cache as JSON in a fake PlayerConfig entry - encoded, _ := json.Marshal(channels) - s.mu.Lock() - s.cache[cacheKey] = &cacheEntry{ - config: &PlayerConfig{Error: string(encoded)}, - expiresAt: time.Now().Add(6 * time.Hour), - } - s.mu.Unlock() - - return channels, nil -} - -// tokenize splits a zmid slug into meaningful tokens. -// e.g. "skyf1" -> ["sky", "f1"], "daznf1" -> ["dazn", "f1"] -func tokenize(zmid string) []string { - // Common known prefixes/suffixes in sports streaming slugs - knownTokens := []string{ - "sky", "sports", "f1", "dazn", "espn", "fox", "bein", "bt", - "star", "nbc", "cbs", "tnt", "abc", "tsn", "supersport", - "canal", "rtl", "viaplay", "premier", "main", "event", - "arena", "action", "cricket", "football", "tennis", "golf", - "racing", "news", "extra", "max", "hd", "uhd", - } - - var tokens []string - remaining := zmid - - for len(remaining) > 0 { - matched := false - for _, tok := range knownTokens { - if strings.HasPrefix(remaining, tok) { - tokens = append(tokens, tok) - remaining = remaining[len(tok):] - matched = true - break - } - } - if !matched { - // Try numeric suffix (like channel numbers) - i := 0 - for i < len(remaining) && remaining[i] >= '0' && remaining[i] <= '9' { - i++ - } - if i > 0 { - tokens = append(tokens, remaining[:i]) - remaining = remaining[i:] - } else { - // Skip single character and try again - remaining = remaining[1:] - } - } - } - - // If tokenization produced nothing useful, use the whole zmid as a single token - if len(tokens) == 0 { - tokens = []string{zmid} - } - - return tokens -} - -func (s *Service) fetchPage(ctx context.Context, pageURL, referer string) (string, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, pageURL, nil) - if err != nil { - return "", err - } - req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") - if referer != "" { - req.Header.Set("Referer", referer) - } - - resp, err := s.client.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("status %d from %s", resp.StatusCode, pageURL) - } - - body, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024)) // 2MB max - if err != nil { - return "", err - } - return string(body), nil -} diff --git a/stacks/f1-stream/files/internal/proxy/proxy.go b/stacks/f1-stream/files/internal/proxy/proxy.go deleted file mode 100644 index 2796c929..00000000 --- a/stacks/f1-stream/files/internal/proxy/proxy.go +++ /dev/null @@ -1,473 +0,0 @@ -package proxy - -import ( - "encoding/base64" - "fmt" - "io" - "log" - "net/http" - "net/url" - "regexp" - "strings" -) - -// hopHeaders are headers that should not be forwarded by proxies. -var hopHeaders = map[string]bool{ - "Connection": true, - "Keep-Alive": true, - "Proxy-Authenticate": true, - "Proxy-Authorization": true, - "Te": true, - "Trailers": true, - "Transfer-Encoding": true, - "Upgrade": true, -} - -// antiFrameHeaders are headers we strip to allow iframe embedding. -var antiFrameHeaders = []string{ - "X-Frame-Options", - "Content-Security-Policy", - "Content-Security-Policy-Report-Only", - "X-Content-Type-Options", -} - -// forwardHeaders are request headers we copy from the client to the upstream. -// NOTE: Accept-Encoding is intentionally omitted so Go's Transport handles -// compression transparently (adds gzip, auto-decompresses response body). -// This ensures we can do text replacements on HTML/CSS bodies. -var forwardHeaders = []string{ - "User-Agent", - "Accept", - "Accept-Language", - "Cookie", - "Referer", - "Range", - "If-None-Match", - "If-Modified-Since", - "Cache-Control", -} - -// jsShimTemplate is injected into HTML responses to intercept JS-initiated requests. -// It patches fetch, XMLHttpRequest, WebSocket, and EventSource to route through the proxy. -const jsShimTemplate = `` - -// NewHandler returns an http.Handler that serves the reverse proxy at /proxy/. -// URL structure: /proxy/{base64_origin}/{path...} -func NewHandler() http.Handler { - client := &http.Client{ - Timeout: 30 * 1000000000, // 30s - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse // don't follow redirects - }, - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Parse: /proxy/{base64_origin}/{path...} - trimmed := strings.TrimPrefix(r.URL.Path, "/proxy/") - if trimmed == "" || trimmed == r.URL.Path { - http.Error(w, "bad proxy URL", http.StatusBadRequest) - return - } - - // Split into base64 segment and remaining path - slashIdx := strings.Index(trimmed, "/") - var b64Origin, pathAndQuery string - if slashIdx == -1 { - b64Origin = trimmed - pathAndQuery = "/" - } else { - b64Origin = trimmed[:slashIdx] - pathAndQuery = trimmed[slashIdx:] - } - - originBytes, err := base64.RawURLEncoding.DecodeString(b64Origin) - if err != nil { - // Try standard encoding with padding - originBytes, err = base64.StdEncoding.DecodeString(b64Origin) - if err != nil { - http.Error(w, "invalid base64 origin", http.StatusBadRequest) - return - } - } - origin := string(originBytes) - - // Validate origin is a valid URL - originURL, err := url.Parse(origin) - if err != nil || (originURL.Scheme != "http" && originURL.Scheme != "https") { - http.Error(w, "invalid origin URL", http.StatusBadRequest) - return - } - - // Build upstream URL - targetURL := origin + pathAndQuery - if r.URL.RawQuery != "" { - targetURL += "?" + r.URL.RawQuery - } - - log.Printf("proxy: %s %s -> %s", r.Method, r.URL.Path, targetURL) - - // Create upstream request - upReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body) - if err != nil { - http.Error(w, "failed to create request", http.StatusInternalServerError) - return - } - - // Copy selected headers - for _, h := range forwardHeaders { - if v := r.Header.Get(h); v != "" { - upReq.Header.Set(h, v) - } - } - // Reconstruct the original Referer from the client's proxy-rewritten Referer. - // The client sends e.g. "https://f1.viktorbarzin.me/proxy/{b64origin}/path" - // and we need to decode that back to "https://original.com/path". - upReq.Header.Set("Referer", decodeProxyReferer(r.Header.Get("Referer"), origin)) - - // Fetch upstream - resp, err := client.Do(upReq) - if err != nil { - log.Printf("proxy: upstream fetch failed: %v", err) - http.Error(w, "upstream fetch failed", http.StatusBadGateway) - return - } - defer resp.Body.Close() - - log.Printf("proxy: %s %s <- %d (%s)", r.Method, r.URL.Path, resp.StatusCode, resp.Header.Get("Content-Type")) - - // Handle redirects: rewrite Location header through proxy - if resp.StatusCode >= 300 && resp.StatusCode < 400 { - loc := resp.Header.Get("Location") - if loc != "" { - rewritten := rewriteRedirect(loc, origin, b64Origin) - w.Header().Set("Location", rewritten) - log.Printf("proxy: redirect %s -> %s", loc, rewritten) - } - w.WriteHeader(resp.StatusCode) - return - } - - // Copy response headers, stripping anti-frame, hop-by-hop, and encoding headers. - // Content-Encoding is stripped because Go's Transport already decompressed the body. - // Content-Length is stripped because we may rewrite the body (changing its length). - for key, vals := range resp.Header { - if hopHeaders[key] { - continue - } - if strings.EqualFold(key, "Content-Encoding") || strings.EqualFold(key, "Content-Length") { - continue - } - skip := false - for _, ah := range antiFrameHeaders { - if strings.EqualFold(key, ah) { - skip = true - break - } - } - if skip { - continue - } - for _, v := range vals { - w.Header().Add(key, v) - } - } - - // Add permissive CORS headers so cross-origin XHR/fetch from the iframe works - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "*") - - w.WriteHeader(resp.StatusCode) - - // For HTML responses, rewrite URLs and inject JS shim - ct := resp.Header.Get("Content-Type") - if strings.Contains(ct, "text/html") { - body, err := io.ReadAll(resp.Body) - if err != nil { - log.Printf("proxy: failed to read HTML body: %v", err) - return - } - rewritten := rewriteHTML(string(body), origin, b64Origin) - w.Write([]byte(rewritten)) - return - } - - // For CSS responses, rewrite url() references - if strings.Contains(ct, "text/css") { - body, err := io.ReadAll(resp.Body) - if err != nil { - log.Printf("proxy: failed to read CSS body: %v", err) - return - } - rewritten := rewriteCSS(string(body), origin, b64Origin) - w.Write([]byte(rewritten)) - return - } - - // For JavaScript responses, strip debugger statements - if strings.Contains(ct, "javascript") || strings.Contains(ct, "ecmascript") { - body, err := io.ReadAll(resp.Body) - if err != nil { - log.Printf("proxy: failed to read JS body: %v", err) - return - } - cleaned := debuggerStmtRe.ReplaceAllString(string(body), "/* */") - w.Write([]byte(cleaned)) - return - } - - // Stream other responses directly - io.Copy(w, resp.Body) - }) -} - -// rewriteRedirect rewrites a Location header value to route through the proxy. -func rewriteRedirect(loc, origin, b64Origin string) string { - // Absolute URL on the same origin - if strings.HasPrefix(loc, origin) { - path := strings.TrimPrefix(loc, origin) - return "/proxy/" + b64Origin + path - } - // Absolute URL on a different origin — proxy it too - parsed, err := url.Parse(loc) - if err != nil { - return loc - } - if parsed.IsAbs() { - newOrigin := parsed.Scheme + "://" + parsed.Host - newB64 := base64.RawURLEncoding.EncodeToString([]byte(newOrigin)) - return "/proxy/" + newB64 + parsed.RequestURI() - } - // Relative URL — it will resolve naturally - return loc -} - -// Precompiled regexes for root-relative URL rewriting in HTML attributes. -// Matches src="/...", href="/...", action="/...", poster="/..." but NOT "//..." (protocol-relative). -var rootRelativeAttrRe = regexp.MustCompile(`((?:src|href|action|poster|data)\s*=\s*["'])/([^/"'][^"']*)`) - -// Matches url("/...") or url('/...') or url(/...) in inline styles — but NOT url("//...") -var rootRelativeCSSRe = regexp.MustCompile(`(url\(\s*["']?)/([^/"')[^"')]*)(["']?\s*\))`) - -// disableDevtoolRe matches )?`) - -// adScriptRe matches )?`) - -// adInlineRe matches inline `) - -// contextMenuBlockRe matches inline scripts that block right-click and dev tools shortcuts. -var contextMenuBlockRe = regexp.MustCompile(`(?i)]*>\s*document\.addEventListener\(\s*'contextmenu'[\s\S]{0,500}?`) - -// debuggerStmtRe matches debugger statements in JavaScript. -var debuggerStmtRe = regexp.MustCompile(`\bdebugger\b\s*;?`) - -// rewriteHTML replaces URLs and injects the JS shim to intercept runtime requests. -func rewriteHTML(body, origin, b64Origin string) string { - proxyPrefix := "/proxy/" + b64Origin - - // 1. Rewrite absolute URLs matching the target origin - escaped := regexp.QuoteMeta(origin) - absRe := regexp.MustCompile(escaped + `(/[^"'\s>)]*)?`) - body = absRe.ReplaceAllStringFunc(body, func(match string) string { - path := strings.TrimPrefix(match, origin) - if path == "" { - path = "/" - } - return proxyPrefix + path - }) - - // 2. Rewrite root-relative URLs in HTML attributes (src="/...", href="/...", etc.) - // Skip URLs already rewritten by step 1 (starting with /proxy/) - body = rootRelativeAttrRe.ReplaceAllStringFunc(body, func(match string) string { - m := rootRelativeAttrRe.FindStringSubmatch(match) - if len(m) < 3 { - return match - } - // m[2] is the path after the leading "/", skip if already proxied - if strings.HasPrefix(m[2], "proxy/") { - return match - } - return m[1] + proxyPrefix + "/" + m[2] - }) - - // 3. Rewrite root-relative URLs in inline CSS url() references - // Skip URLs already rewritten by step 1 (starting with /proxy/) - body = rootRelativeCSSRe.ReplaceAllStringFunc(body, func(match string) string { - m := rootRelativeCSSRe.FindStringSubmatch(match) - if len(m) < 4 { - return match - } - if strings.HasPrefix(m[2], "proxy/") { - return match - } - return m[1] + proxyPrefix + "/" + m[2] + m[3] - }) - - // 4. Strip anti-debugging scripts (disable-devtool, devtools-detect) - body = disableDevtoolRe.ReplaceAllString(body, "") - - // 4b. Strip ad/popup scripts and context menu blockers - body = adScriptRe.ReplaceAllString(body, "") - body = adInlineRe.ReplaceAllString(body, "") - body = contextMenuBlockRe.ReplaceAllString(body, "") - - // 4c. Strip debugger statements from inline scripts - body = debuggerStmtRe.ReplaceAllString(body, "/* */") - - // 5. Inject JS shim right after to intercept fetch/XHR/WebSocket - shim := fmt.Sprintf(jsShimTemplate, b64Origin, origin) - headIdx := strings.Index(strings.ToLower(body), "") - if headIdx != -1 { - insertPos := headIdx + len("") - body = body[:insertPos] + shim + body[insertPos:] - } else { - // No tag — prepend to body - body = shim + body - } - - return body -} - -// rewriteCSS replaces root-relative url() references in CSS to route through the proxy. -func rewriteCSS(body, origin, b64Origin string) string { - proxyPrefix := "/proxy/" + b64Origin - - // Rewrite absolute URLs matching origin - escaped := regexp.QuoteMeta(origin) - absRe := regexp.MustCompile(escaped + `(/[^"'\s)]*)?`) - body = absRe.ReplaceAllStringFunc(body, func(match string) string { - path := strings.TrimPrefix(match, origin) - if path == "" { - path = "/" - } - return proxyPrefix + path - }) - - // Rewrite root-relative url() references, skip already-proxied - body = rootRelativeCSSRe.ReplaceAllStringFunc(body, func(match string) string { - m := rootRelativeCSSRe.FindStringSubmatch(match) - if len(m) < 4 { - return match - } - if strings.HasPrefix(m[2], "proxy/") { - return match - } - return m[1] + proxyPrefix + "/" + m[2] + m[3] - }) - - return body -} - -// decodeProxyReferer takes the client's Referer (which points to a proxy URL) -// and decodes it back to the original upstream URL. This is critical for -// cross-origin requests where the upstream checks the Referer (e.g. HLS servers). -// Falls back to origin+"/" if decoding fails. -func decodeProxyReferer(clientReferer, fallbackOrigin string) string { - if clientReferer == "" { - return fallbackOrigin + "/" - } - - // Find /proxy/ in the Referer URL path - idx := strings.Index(clientReferer, "/proxy/") - if idx == -1 { - return fallbackOrigin + "/" - } - - // Extract everything after /proxy/ - rest := clientReferer[idx+len("/proxy/"):] - if rest == "" { - return fallbackOrigin + "/" - } - - // Split into base64 segment and remaining path - slashIdx := strings.Index(rest, "/") - var b64Seg, pathPart string - if slashIdx == -1 { - b64Seg = rest - pathPart = "/" - } else { - b64Seg = rest[:slashIdx] - pathPart = rest[slashIdx:] - } - - // Decode the base64 origin - originBytes, err := base64.RawURLEncoding.DecodeString(b64Seg) - if err != nil { - originBytes, err = base64.StdEncoding.DecodeString(b64Seg) - if err != nil { - return fallbackOrigin + "/" - } - } - - return string(originBytes) + pathPart -} diff --git a/stacks/f1-stream/files/internal/scraper/reddit.go b/stacks/f1-stream/files/internal/scraper/reddit.go deleted file mode 100644 index 2599ffb8..00000000 --- a/stacks/f1-stream/files/internal/scraper/reddit.go +++ /dev/null @@ -1,327 +0,0 @@ -package scraper - -import ( - "crypto/rand" - "encoding/json" - "fmt" - "io" - "log" - "math" - "net/http" - "net/url" - "regexp" - "strings" - "time" - - "f1-stream/internal/models" -) - -const ( - subredditURL = "https://www.reddit.com/r/motorsportsstreams2/new.json?limit=25" - userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" - requestDelay = 1 * time.Second -) - -var ( - urlRe = regexp.MustCompile(`https?://[^\s\)\]\>"]+`) - - // Keywords in post title that indicate F1 content (matched case-insensitively) - f1Keywords = []string{ - "f1", - "formula 1", - "formula one", - "formula1", - "grand prix", - "gp qualifying", - "gp race", - "gp sprint", - "gp practice", - } - - f1NegativeKeywords = []string{ - "f1 key", - "function 1", - "help f1", - } - - // URLs to filter out (not stream sources) - filteredDomains = map[string]bool{ - "reddit.com": true, - "www.reddit.com": true, - "imgur.com": true, - "i.imgur.com": true, - "redd.it": true, - "i.redd.it": true, - "v.redd.it": true, - "youtu.be": true, - "youtube.com": true, - "twitter.com": true, - "x.com": true, - } -) - -type redditListing struct { - Data struct { - Children []struct { - Data struct { - Title string `json:"title"` - SelfText string `json:"selftext"` - Permalink string `json:"permalink"` - CreatedUTC float64 `json:"created_utc"` - } `json:"data"` - } `json:"children"` - } `json:"data"` -} - -type redditComments []struct { - Data struct { - Children []struct { - Data struct { - Body string `json:"body"` - Replies json.RawMessage `json:"replies"` - } `json:"data"` - } `json:"children"` - } `json:"data"` -} - -func scrapeReddit() ([]models.ScrapedLink, error) { - client := &http.Client{Timeout: 15 * time.Second} - var allLinks []models.ScrapedLink - seen := make(map[string]bool) - - log.Printf("scraper: fetching listing from %s", subredditURL) - listing, err := fetchJSON[redditListing](client, subredditURL) - if err != nil { - return nil, fmt.Errorf("fetch listing: %w", err) - } - - totalPosts := len(listing.Data.Children) - matchedPosts := 0 - log.Printf("scraper: got %d posts from listing", totalPosts) - - for _, child := range listing.Data.Children { - post := child.Data - - if !isF1Post(post.Title) { - log.Printf("scraper: skipped post: %s", truncate(post.Title, 60)) - continue - } - - matchedPosts++ - log.Printf("scraper: matched post: %s", truncate(post.Title, 60)) - - selftextLinks := extractURLs(post.SelfText, post.Title) - log.Printf("scraper: extracted %d URLs from selftext of %q", len(selftextLinks), truncate(post.Title, 40)) - for _, link := range selftextLinks { - norm := normalizeURL(link.URL) - if !seen[norm] { - seen[norm] = true - allLinks = append(allLinks, link) - } - } - - time.Sleep(requestDelay) - commentsURL := fmt.Sprintf("https://www.reddit.com%s.json", post.Permalink) - comments, err := fetchJSONWithRetry[redditComments](client, commentsURL, 3) - if err != nil { - log.Printf("scraper: failed to fetch comments for %s: %v", post.Permalink, err) - continue - } - - commentURLCount := 0 - walkComments(*comments, func(body string) { - links := extractURLs(body, post.Title) - commentURLCount += len(links) - for _, link := range links { - norm := normalizeURL(link.URL) - if !seen[norm] { - seen[norm] = true - allLinks = append(allLinks, link) - } - } - }) - log.Printf("scraper: extracted %d URLs from comments of %q", commentURLCount, truncate(post.Title, 40)) - - time.Sleep(requestDelay) - } - - log.Printf("scraper: summary — matched %d/%d posts, extracted %d unique URLs", matchedPosts, totalPosts, len(allLinks)) - return allLinks, nil -} - -func fetchJSON[T any](client *http.Client, rawURL string) (*T, error) { - req, err := http.NewRequest("GET", rawURL, nil) - if err != nil { - return nil, err - } - req.Header.Set("User-Agent", userAgent) - - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - log.Printf("scraper: GET %s -> %d", truncate(rawURL, 80), resp.StatusCode) - - if resp.StatusCode != 200 { - return nil, fmt.Errorf("status %d", resp.StatusCode) - } - - body, err := io.ReadAll(io.LimitReader(resp.Body, 5*1024*1024)) - if err != nil { - return nil, err - } - - var result T - if err := json.Unmarshal(body, &result); err != nil { - return nil, err - } - return &result, nil -} - -func fetchJSONWithRetry[T any](client *http.Client, rawURL string, maxRetries int) (*T, error) { - var lastErr error - for attempt := 0; attempt <= maxRetries; attempt++ { - result, err := fetchJSON[T](client, rawURL) - if err == nil { - return result, nil - } - lastErr = err - - errMsg := err.Error() - if strings.Contains(errMsg, "status 429") { - log.Printf("scraper: rate limited on %s, backing off 30s", truncate(rawURL, 60)) - time.Sleep(30 * time.Second) - continue - } - if strings.Contains(errMsg, "status 502") || strings.Contains(errMsg, "status 503") { - backoff := time.Duration(math.Pow(2, float64(attempt))) * time.Second - log.Printf("scraper: server error on %s, retry %d/%d in %v", truncate(rawURL, 60), attempt+1, maxRetries, backoff) - time.Sleep(backoff) - continue - } - - return nil, err - } - return nil, fmt.Errorf("after %d retries: %w", maxRetries, lastErr) -} - -// deobfuscateText normalises obfuscated URLs commonly posted on Reddit to -// evade auto-moderation. Examples: -// - "pitsport . xyz/watch/f1" → "https://pitsport.xyz/watch/f1" -// - "dlhd dot link" → "https://dlhd.link" -func deobfuscateText(text string) string { - // Common TLDs used in streaming links. - tlds := `(?:com|net|org|xyz|link|info|live|tv|me|cc|to|io|co|stream|site|fun|top|club|watch|racing)` - - // 1. Replace " dot " (case-insensitive) between word-like parts that - // look like domain components: "dlhd dot link" → "dlhd.link" - dotWord := regexp.MustCompile(`(?i)(\b\w[\w-]*)\s+dot\s+(` + tlds + `\b)`) - text = dotWord.ReplaceAllString(text, "${1}.${2}") - - // 2. Collapse spaces around dots in domain-like strings: - // "pitsport . xyz" → "pitsport.xyz" - spaceDot := regexp.MustCompile(`(\b\w[\w-]*)\s*\.\s*(` + tlds + `\b)`) - text = spaceDot.ReplaceAllString(text, "${1}.${2}") - - // 3. Prepend https:// to bare domain-like strings that the URL regex - // would otherwise miss (no scheme present). - bareDomain := regexp.MustCompile(`(?:^|[\s(>\[])(\w[\w-]*\.` + tlds + `(?:/[^\s)\]<"]*)?)`) - text = bareDomain.ReplaceAllStringFunc(text, func(m string) string { - // Preserve the leading whitespace/punctuation character. - trimmed := strings.TrimLeft(m, " \t\n(>[") - prefix := m[:len(m)-len(trimmed)] - if strings.HasPrefix(trimmed, "http://") || strings.HasPrefix(trimmed, "https://") { - return m - } - return prefix + "https://" + trimmed - }) - - return text -} - -func extractURLs(text, postTitle string) []models.ScrapedLink { - text = deobfuscateText(text) - matches := urlRe.FindAllString(text, -1) - var links []models.ScrapedLink - filtered := 0 - for _, u := range matches { - u = strings.TrimRight(u, ".,;:!?)") - - parsed, err := url.Parse(u) - if err != nil { - continue - } - if filteredDomains[parsed.Hostname()] { - filtered++ - continue - } - - id := make([]byte, 16) - if _, err := rand.Read(id); err != nil { - continue - } - - links = append(links, models.ScrapedLink{ - ID: fmt.Sprintf("%x", id), - URL: u, - Title: postTitle, - Source: "r/motorsportsstreams2", - ScrapedAt: time.Now(), - }) - } - if filtered > 0 { - log.Printf("scraper: filtered %d URLs from known domains in %q", filtered, truncate(postTitle, 40)) - } - return links -} - -func walkComments(comments redditComments, fn func(string)) { - for _, listing := range comments { - for _, child := range listing.Data.Children { - if child.Data.Body != "" { - fn(child.Data.Body) - } - // Recurse into replies - if len(child.Data.Replies) > 0 && child.Data.Replies[0] == '{' { - var nested redditComments - if err := json.Unmarshal([]byte("["+string(child.Data.Replies)+"]"), &nested); err == nil { - walkComments(nested, fn) - } - } - } - } -} - -func normalizeURL(u string) string { - parsed, err := url.Parse(u) - if err != nil { - return strings.ToLower(u) - } - parsed.Host = strings.ToLower(parsed.Host) - path := strings.TrimRight(parsed.Path, "/") - return fmt.Sprintf("%s://%s%s", parsed.Scheme, parsed.Host, path) -} - -func isF1Post(title string) bool { - lower := strings.ToLower(title) - for _, neg := range f1NegativeKeywords { - if strings.Contains(lower, neg) { - return false - } - } - for _, kw := range f1Keywords { - if strings.Contains(lower, kw) { - return true - } - } - return false -} - -func truncate(s string, maxLen int) string { - if len(s) <= maxLen { - return s - } - return s[:maxLen] + "..." -} diff --git a/stacks/f1-stream/files/internal/scraper/scraper.go b/stacks/f1-stream/files/internal/scraper/scraper.go deleted file mode 100644 index 8d1956d4..00000000 --- a/stacks/f1-stream/files/internal/scraper/scraper.go +++ /dev/null @@ -1,105 +0,0 @@ -package scraper - -import ( - "context" - "log" - "sync" - "time" - - "f1-stream/internal/models" - "f1-stream/internal/store" -) - -type Scraper struct { - store *store.Store - interval time.Duration - validateTimeout time.Duration - mu sync.Mutex -} - -func New(s *store.Store, interval time.Duration, validateTimeout time.Duration) *Scraper { - return &Scraper{store: s, interval: interval, validateTimeout: validateTimeout} -} - -func (s *Scraper) Run(ctx context.Context) { - log.Printf("scraper: starting with interval %v", s.interval) - // Run immediately on start - s.scrape() - - ticker := time.NewTicker(s.interval) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - log.Println("scraper: shutting down") - return - case <-ticker.C: - s.scrape() - } - } -} - -func (s *Scraper) TriggerScrape() { - go s.scrape() -} - -func (s *Scraper) scrape() { - s.mu.Lock() - defer s.mu.Unlock() - - start := time.Now() - log.Println("scraper: starting scrape") - links, err := scrapeReddit() - if err != nil { - log.Printf("scraper: error after %v: %v", time.Since(start).Round(time.Millisecond), err) - return - } - log.Printf("scraper: reddit scrape completed in %v, got %d links", time.Since(start).Round(time.Millisecond), len(links)) - - // Merge with existing links, filtering out non-F1 entries - existing, err := s.store.LoadScrapedLinks() - if err != nil { - log.Printf("scraper: failed to load existing links: %v", err) - existing = nil - } - seen := make(map[string]bool) - var filtered []models.ScrapedLink - for _, l := range existing { - if !isF1Post(l.Title) { - continue - } - norm := normalizeURL(l.URL) - seen[norm] = true - filtered = append(filtered, l) - } - existing = filtered - - added := 0 - for _, l := range links { - norm := normalizeURL(l.URL) - if !seen[norm] { - existing = append(existing, l) - seen[norm] = true - added++ - } - } - - if err := s.store.SaveScrapedLinks(existing); err != nil { - log.Printf("scraper: failed to save: %v", err) - return - } - - // Auto-publish newly validated links as streams - for _, l := range links { - if err := s.store.PublishScrapedStream(l.URL, l.Title); err != nil { - u := l.URL - if len(u) > 80 { - u = u[:80] + "..." - } - log.Printf("scraper: failed to auto-publish %s: %v", u, err) - } - } - - log.Printf("scraper: done in %v, added %d new links (total: %d)", time.Since(start).Round(time.Millisecond), added, len(existing)) -} diff --git a/stacks/f1-stream/files/internal/scraper/validate.go b/stacks/f1-stream/files/internal/scraper/validate.go deleted file mode 100644 index 97ab9772..00000000 --- a/stacks/f1-stream/files/internal/scraper/validate.go +++ /dev/null @@ -1,142 +0,0 @@ -package scraper - -import ( - "io" - "log" - "net/http" - "strings" - "time" - - "f1-stream/internal/models" -) - -// videoMarkers are substrings checked (case-insensitively) against the HTML -// body to detect the presence of a video player or streaming manifest. -var videoMarkers = []string{ - // HTML5 video element - "= 3 { - return http.ErrUseLastResponse - } - return nil - }, - } - - var kept []models.ScrapedLink - for _, link := range links { - if HasVideoContent(client, link.URL) { - kept = append(kept, link) - } else { - log.Printf("scraper: discarded %s (no video markers)", truncate(link.URL, 60)) - } - } - return kept -} - -// HasVideoContent performs a GET request for rawURL and returns true if the -// response is a direct video file (by Content-Type) or an HTML page that -// contains at least one video marker substring. -func HasVideoContent(client *http.Client, rawURL string) bool { - req, err := http.NewRequest("GET", rawURL, nil) - if err != nil { - log.Printf("scraper: validate request error for %s: %v", truncate(rawURL, 60), err) - return false - } - req.Header.Set("User-Agent", userAgent) - - resp, err := client.Do(req) - if err != nil { - log.Printf("scraper: validate fetch error for %s: %v", truncate(rawURL, 60), err) - return false - } - defer resp.Body.Close() - - if resp.StatusCode < 200 || resp.StatusCode >= 400 { - return false - } - - ct := strings.ToLower(resp.Header.Get("Content-Type")) - - // Direct video content type — no need to inspect body. - if isDirectVideoContentType(ct) { - return true - } - - // Only inspect HTML pages for markers. - if !strings.Contains(ct, "text/html") && !strings.Contains(ct, "application/xhtml") { - return false - } - - body, err := io.ReadAll(io.LimitReader(resp.Body, validateBodyLimit)) - if err != nil { - log.Printf("scraper: validate read error for %s: %v", truncate(rawURL, 60), err) - return false - } - - return containsVideoMarkers(strings.ToLower(string(body))) -} - -// containsVideoMarkers returns true if loweredBody contains any known video -// player or streaming marker substring. -func containsVideoMarkers(loweredBody string) bool { - for _, marker := range videoMarkers { - if strings.Contains(loweredBody, marker) { - return true - } - } - return false -} - -// isDirectVideoContentType returns true if ct (already lowercased) matches a -// known video content type. -func isDirectVideoContentType(ct string) bool { - ct = strings.ToLower(ct) - for _, vct := range videoContentTypes { - if strings.Contains(ct, vct) { - return true - } - } - return false -} diff --git a/stacks/f1-stream/files/internal/scraper/validate_test.go b/stacks/f1-stream/files/internal/scraper/validate_test.go deleted file mode 100644 index 54511b94..00000000 --- a/stacks/f1-stream/files/internal/scraper/validate_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package scraper - -import "testing" - -func TestContainsVideoMarkers(t *testing.T) { - tests := []struct { - name string - body string - want bool - }{ - // Positive cases - { - name: "video tag", - body: `
`, - want: true, - }, - { - name: "HLS manifest reference", - body: `var url = "https://cdn.example.com/live.m3u8";`, - want: true, - }, - { - name: "DASH manifest reference", - body: ``, - want: true, - }, - { - name: "HLS.js library", - body: ``, - want: true, - }, - { - name: "Video.js library", - body: ``, - want: true, - }, - { - name: "JW Player", - body: `
`, - want: true, - }, - { - name: "Clappr player", - body: ``, - want: true, - }, - { - name: "Flowplayer", - body: ``, - want: true, - }, - { - name: "Plyr player", - body: ``, - want: true, - }, - { - name: "Shaka Player", - body: ``, - want: true, - }, - // Negative cases - { - name: "plain HTML", - body: `

Hello world

`, - want: false, - }, - { - name: "reddit link page", - body: `Click here`, - want: false, - }, - { - name: "blog post", - body: `
F1 race results and analysis...
`, - want: false, - }, - { - name: "empty string", - body: "", - want: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := containsVideoMarkers(tt.body) - if got != tt.want { - t.Errorf("containsVideoMarkers(%q) = %v, want %v", truncate(tt.body, 60), got, tt.want) - } - }) - } -} - -func TestIsDirectVideoContentType(t *testing.T) { - tests := []struct { - name string - ct string - want bool - }{ - // Positive cases - {name: "video/mp4", ct: "video/mp4", want: true}, - {name: "video/webm", ct: "video/webm", want: true}, - {name: "HLS content type", ct: "application/x-mpegurl", want: true}, - {name: "Apple HLS content type", ct: "application/vnd.apple.mpegurl", want: true}, - {name: "DASH content type", ct: "application/dash+xml", want: true}, - {name: "video with params", ct: "video/mp4; charset=utf-8", want: true}, - // Negative cases - {name: "text/html", ct: "text/html", want: false}, - {name: "application/json", ct: "application/json", want: false}, - {name: "image/png", ct: "image/png", want: false}, - {name: "text/plain", ct: "text/plain", want: false}, - {name: "empty string", ct: "", want: false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := isDirectVideoContentType(tt.ct) - if got != tt.want { - t.Errorf("isDirectVideoContentType(%q) = %v, want %v", tt.ct, got, tt.want) - } - }) - } -} diff --git a/stacks/f1-stream/files/internal/server/middleware.go b/stacks/f1-stream/files/internal/server/middleware.go deleted file mode 100644 index cd849c0b..00000000 --- a/stacks/f1-stream/files/internal/server/middleware.go +++ /dev/null @@ -1,93 +0,0 @@ -package server - -import ( - "log" - "net/http" - "strings" - - "f1-stream/internal/auth" -) - -func LoggingMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Printf("%s %s %s", r.Method, r.URL.Path, r.RemoteAddr) - next.ServeHTTP(w, r) - }) -} - -func RecoveryMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer func() { - if err := recover(); err != nil { - log.Printf("panic: %v", err) - http.Error(w, "internal server error", http.StatusInternalServerError) - } - }() - next.ServeHTTP(w, r) - }) -} - -// AuthMiddleware injects user into context if session cookie is present. -func AuthMiddleware(a *auth.Auth) func(http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - cookie, err := r.Cookie("session") - if err == nil && cookie.Value != "" { - user, err := a.GetSessionUser(cookie.Value) - if err == nil && user != nil { - r = r.WithContext(auth.ContextWithUser(r.Context(), user)) - } - } - next.ServeHTTP(w, r) - }) - } -} - -// RequireAuth rejects unauthenticated requests. -func RequireAuth(next http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil { - http.Error(w, `{"error":"authentication required"}`, http.StatusUnauthorized) - return - } - next(w, r) - } -} - -// RequireAdmin rejects non-admin requests. -func RequireAdmin(next http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - if user == nil || !user.IsAdmin { - http.Error(w, `{"error":"admin access required"}`, http.StatusForbidden) - return - } - next(w, r) - } -} - -// OriginCheck validates Origin header on mutation requests (CSRF protection). -func OriginCheck(allowedOrigins []string) func(http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != "GET" && r.Method != "HEAD" && r.Method != "OPTIONS" { - origin := r.Header.Get("Origin") - if origin != "" { - allowed := false - for _, o := range allowedOrigins { - if strings.EqualFold(origin, o) { - allowed = true - break - } - } - if !allowed { - http.Error(w, `{"error":"origin not allowed"}`, http.StatusForbidden) - return - } - } - } - next.ServeHTTP(w, r) - }) - } -} diff --git a/stacks/f1-stream/files/internal/server/server.go b/stacks/f1-stream/files/internal/server/server.go deleted file mode 100644 index 6aefdf9c..00000000 --- a/stacks/f1-stream/files/internal/server/server.go +++ /dev/null @@ -1,338 +0,0 @@ -package server - -import ( - "encoding/json" - "html" - "log" - "net/http" - "strings" - - "f1-stream/internal/auth" - "f1-stream/internal/extractor" - "f1-stream/internal/hlsproxy" - "f1-stream/internal/playerconfig" - "f1-stream/internal/proxy" - "f1-stream/internal/scraper" - "f1-stream/internal/store" -) - -type Server struct { - store *store.Store - auth *auth.Auth - scraper *scraper.Scraper - playerConfig *playerconfig.Service - mux *http.ServeMux - headlessEnabled bool -} - -func New(s *store.Store, a *auth.Auth, sc *scraper.Scraper, pc *playerconfig.Service, origins []string, headlessEnabled bool) *Server { - srv := &Server{ - store: s, - auth: a, - scraper: sc, - playerConfig: pc, - mux: http.NewServeMux(), - headlessEnabled: headlessEnabled, - } - srv.registerRoutes(origins) - return srv -} - -func (s *Server) Handler() http.Handler { - return s.mux -} - -func (s *Server) registerRoutes(origins []string) { - // Apply middleware chain - authMw := AuthMiddleware(s.auth) - originMw := OriginCheck(origins) - - // Static files - fs := http.FileServer(http.Dir("static")) - s.mux.Handle("GET /static/", http.StripPrefix("/static/", fs)) - s.mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/" { - http.NotFound(w, r) - return - } - http.ServeFile(w, r, "static/index.html") - }) - - // Health - s.mux.HandleFunc("GET /api/health", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"status":"ok"}`)) - }) - - // Reverse proxy for iframe embedding (strips anti-framing headers) - proxyHandler := proxy.NewHandler() - s.mux.Handle("GET /proxy/", proxyHandler) - s.mux.Handle("POST /proxy/", proxyHandler) - s.mux.Handle("HEAD /proxy/", proxyHandler) - s.mux.Handle("OPTIONS /proxy/", proxyHandler) - - // HLS proxy for native video playback - hlsHandler := hlsproxy.NewHandler() - s.mux.Handle("GET /hls/", hlsHandler) - s.mux.Handle("OPTIONS /hls/", hlsHandler) - - // Public API - wrap with middleware - wrapAll := func(h http.HandlerFunc) http.Handler { - return RecoveryMiddleware(LoggingMiddleware(originMw(authMw(h)))) - } - - // Auth endpoints - s.mux.Handle("POST /api/auth/register/begin", wrapAll(s.auth.BeginRegistration)) - s.mux.Handle("POST /api/auth/register/finish", wrapAll(s.auth.FinishRegistration)) - s.mux.Handle("POST /api/auth/login/begin", wrapAll(s.auth.BeginLogin)) - s.mux.Handle("POST /api/auth/login/finish", wrapAll(s.auth.FinishLogin)) - s.mux.Handle("POST /api/auth/logout", wrapAll(s.auth.Logout)) - s.mux.Handle("GET /api/auth/me", wrapAll(s.auth.Me)) - - // Public streams - s.mux.Handle("GET /api/streams/public", wrapAll(s.handlePublicStreams)) - s.mux.Handle("GET /api/streams/{id}/browse", wrapAll(s.handleBrowseStream)) - s.mux.Handle("GET /api/streams/{id}/player-config", wrapAll(s.handlePlayerConfig)) - - // Scraped links - s.mux.Handle("GET /api/scraped", wrapAll(s.handleScrapedLinks)) - s.mux.Handle("POST /api/scraped/refresh", wrapAll(s.handleTriggerScrape)) - s.mux.Handle("POST /api/scraped/{id}/import", wrapAll(s.handleImportScraped)) - - // Authenticated endpoints - s.mux.Handle("GET /api/streams/mine", wrapAll(RequireAuth(s.handleMyStreams))) - s.mux.Handle("POST /api/streams", wrapAll(s.handleSubmitStream)) - s.mux.Handle("DELETE /api/streams/{id}", wrapAll(s.handleDeleteStream)) - - // Admin endpoints - s.mux.Handle("PUT /api/streams/{id}/publish", wrapAll(RequireAdmin(s.handleTogglePublish))) - s.mux.Handle("GET /api/admin/streams", wrapAll(RequireAdmin(s.handleAllStreams))) - s.mux.Handle("POST /api/admin/scrape", wrapAll(RequireAdmin(s.handleTriggerScrape))) -} - -func (s *Server) handlePublicStreams(w http.ResponseWriter, r *http.Request) { - streams, err := s.store.PublicStreams() - if err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(streams) -} - -func (s *Server) handleScrapedLinks(w http.ResponseWriter, r *http.Request) { - links, err := s.store.GetActiveScrapedLinks() - if err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json") - if links == nil { - w.Write([]byte("[]")) - return - } - json.NewEncoder(w).Encode(links) -} - -func (s *Server) handleImportScraped(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - link, err := s.store.GetScrapedLinkByID(id) - if err != nil { - http.Error(w, `{"error":"not found"}`, http.StatusNotFound) - return - } - if err := s.store.PublishScrapedStream(link.URL, link.Title); err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"ok":true}`)) -} - -func (s *Server) handleMyStreams(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - streams, err := s.store.UserStreams(user.ID) - if err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json") - if streams == nil { - w.Write([]byte("[]")) - return - } - json.NewEncoder(w).Encode(streams) -} - -func (s *Server) handleSubmitStream(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - - var req struct { - URL string `json:"url"` - Title string `json:"title"` - } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest) - return - } - - req.URL = strings.TrimSpace(req.URL) - req.Title = strings.TrimSpace(req.Title) - - if req.URL == "" { - http.Error(w, `{"error":"url required"}`, http.StatusBadRequest) - return - } - if len(req.URL) > 2048 { - http.Error(w, `{"error":"url too long"}`, http.StatusBadRequest) - return - } - if !strings.HasPrefix(req.URL, "https://") && !strings.HasPrefix(req.URL, "http://") { - http.Error(w, `{"error":"url must start with http:// or https://"}`, http.StatusBadRequest) - return - } - if req.Title == "" { - req.Title = req.URL - } - req.Title = html.EscapeString(req.Title) - - submittedBy := "anonymous" - published := true - if user != nil { - submittedBy = user.ID - published = false - } - - stream, err := s.store.AddStream(req.URL, req.Title, submittedBy, published, "user") - if err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - json.NewEncoder(w).Encode(stream) -} - -func (s *Server) handleDeleteStream(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - id := r.PathValue("id") - - var userID string - var isAdmin bool - if user != nil { - userID = user.ID - isAdmin = user.IsAdmin - } - - if err := s.store.DeleteStream(id, userID, isAdmin); err != nil { - if strings.Contains(err.Error(), "not authorized") { - http.Error(w, `{"error":"not authorized"}`, http.StatusForbidden) - return - } - if strings.Contains(err.Error(), "not found") { - http.Error(w, `{"error":"not found"}`, http.StatusNotFound) - return - } - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"ok":true}`)) -} - -func (s *Server) handleTogglePublish(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - if err := s.store.TogglePublish(id); err != nil { - http.Error(w, `{"error":"stream not found"}`, http.StatusNotFound) - return - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"ok":true}`)) -} - -func (s *Server) handleAllStreams(w http.ResponseWriter, r *http.Request) { - streams, err := s.store.LoadStreams() - if err != nil { - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(streams) -} - -func (s *Server) handleTriggerScrape(w http.ResponseWriter, r *http.Request) { - s.scraper.TriggerScrape() - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"ok":true,"message":"scrape triggered"}`)) -} - -func (s *Server) handleBrowseStream(w http.ResponseWriter, r *http.Request) { - if !s.headlessEnabled { - http.Error(w, `{"error":"browser sessions not available"}`, http.StatusNotFound) - return - } - - id := r.PathValue("id") - streams, err := s.store.LoadStreams() - if err != nil { - log.Printf("server: browse: failed to load streams: %v", err) - http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError) - return - } - - var streamURL string - var found bool - for _, st := range streams { - if st.ID == id { - if !st.Published { - http.Error(w, `{"error":"stream not found"}`, http.StatusNotFound) - return - } - streamURL = st.URL - found = true - break - } - } - if !found { - http.Error(w, `{"error":"stream not found"}`, http.StatusNotFound) - return - } - - extractor.HandleBrowserSession(w, r, streamURL) -} - -func (s *Server) handlePlayerConfig(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - streams, err := s.store.LoadStreams() - if err != nil { - log.Printf("server: player-config: failed to load streams: %v", err) - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(playerconfig.PlayerConfig{Type: "proxy"}) - return - } - - var streamURL string - var found bool - for _, st := range streams { - if st.ID == id { - if !st.Published { - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(playerconfig.PlayerConfig{Type: "proxy"}) - return - } - streamURL = st.URL - found = true - break - } - } - if !found { - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(playerconfig.PlayerConfig{Type: "proxy"}) - return - } - - config := s.playerConfig.GetConfig(r.Context(), streamURL) - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(config) -} diff --git a/stacks/f1-stream/files/internal/store/health.go b/stacks/f1-stream/files/internal/store/health.go deleted file mode 100644 index a261209f..00000000 --- a/stacks/f1-stream/files/internal/store/health.go +++ /dev/null @@ -1,37 +0,0 @@ -package store - -import ( - "f1-stream/internal/models" -) - -func (s *Store) LoadHealthStates() ([]models.HealthState, error) { - s.healthMu.RLock() - defer s.healthMu.RUnlock() - var states []models.HealthState - if err := readJSON(s.filePath("health_state.json"), &states); err != nil { - return nil, err - } - return states, nil -} - -func (s *Store) SaveHealthStates(states []models.HealthState) error { - s.healthMu.Lock() - defer s.healthMu.Unlock() - return writeJSON(s.filePath("health_state.json"), states) -} - -// HealthMap returns a map of URL -> Healthy status. It reads the health state -// file directly without acquiring healthMu to avoid deadlock when called from -// methods that already hold other locks (e.g., PublicStreams, GetActiveScrapedLinks). -// URLs not present in the map are implicitly healthy. -func (s *Store) HealthMap() map[string]bool { - var states []models.HealthState - if err := readJSON(s.filePath("health_state.json"), &states); err != nil { - return make(map[string]bool) - } - m := make(map[string]bool, len(states)) - for _, st := range states { - m[st.URL] = st.Healthy - } - return m -} diff --git a/stacks/f1-stream/files/internal/store/scraped.go b/stacks/f1-stream/files/internal/store/scraped.go deleted file mode 100644 index b25faef9..00000000 --- a/stacks/f1-stream/files/internal/store/scraped.go +++ /dev/null @@ -1,63 +0,0 @@ -package store - -import ( - "fmt" - "time" - - "f1-stream/internal/models" -) - -func (s *Store) LoadScrapedLinks() ([]models.ScrapedLink, error) { - s.scrapedMu.RLock() - defer s.scrapedMu.RUnlock() - var links []models.ScrapedLink - if err := readJSON(s.filePath("scraped_links.json"), &links); err != nil { - return nil, err - } - return links, nil -} - -func (s *Store) SaveScrapedLinks(links []models.ScrapedLink) error { - s.scrapedMu.Lock() - defer s.scrapedMu.Unlock() - return writeJSON(s.filePath("scraped_links.json"), links) -} - -func (s *Store) GetScrapedLinkByID(id string) (models.ScrapedLink, error) { - s.scrapedMu.RLock() - defer s.scrapedMu.RUnlock() - var links []models.ScrapedLink - if err := readJSON(s.filePath("scraped_links.json"), &links); err != nil { - return models.ScrapedLink{}, err - } - for _, l := range links { - if l.ID == id { - return l, nil - } - } - return models.ScrapedLink{}, fmt.Errorf("not found") -} - -func (s *Store) GetActiveScrapedLinks() ([]models.ScrapedLink, error) { - s.scrapedMu.RLock() - defer s.scrapedMu.RUnlock() - var links []models.ScrapedLink - if err := readJSON(s.filePath("scraped_links.json"), &links); err != nil { - return nil, err - } - healthMap := s.HealthMap() - now := time.Now() - var active []models.ScrapedLink - for _, l := range links { - l.Stale = now.Sub(l.ScrapedAt) > 7*24*time.Hour - if l.Stale { - continue - } - // Filter unhealthy scraped links. URLs not in healthMap are assumed healthy. - if healthy, exists := healthMap[l.URL]; exists && !healthy { - continue - } - active = append(active, l) - } - return active, nil -} diff --git a/stacks/f1-stream/files/internal/store/sessions.go b/stacks/f1-stream/files/internal/store/sessions.go deleted file mode 100644 index 67702cd3..00000000 --- a/stacks/f1-stream/files/internal/store/sessions.go +++ /dev/null @@ -1,98 +0,0 @@ -package store - -import ( - "crypto/rand" - "encoding/hex" - "fmt" - "time" - - "f1-stream/internal/models" -) - -func (s *Store) LoadSessions() ([]models.Session, error) { - s.sessionsMu.RLock() - defer s.sessionsMu.RUnlock() - var sessions []models.Session - if err := readJSON(s.filePath("sessions.json"), &sessions); err != nil { - return nil, err - } - return sessions, nil -} - -func (s *Store) CreateSession(userID string, ttl time.Duration) (string, error) { - s.sessionsMu.Lock() - defer s.sessionsMu.Unlock() - var sessions []models.Session - if err := readJSON(s.filePath("sessions.json"), &sessions); err != nil { - return "", err - } - b := make([]byte, 32) - if _, err := rand.Read(b); err != nil { - return "", err - } - token := hex.EncodeToString(b) - sess := models.Session{ - Token: token, - UserID: userID, - ExpiresAt: time.Now().Add(ttl), - } - sessions = append(sessions, sess) - if err := writeJSON(s.filePath("sessions.json"), sessions); err != nil { - return "", err - } - return token, nil -} - -func (s *Store) GetSession(token string) (*models.Session, error) { - s.sessionsMu.RLock() - defer s.sessionsMu.RUnlock() - var sessions []models.Session - if err := readJSON(s.filePath("sessions.json"), &sessions); err != nil { - return nil, err - } - for _, sess := range sessions { - if sess.Token == token && time.Now().Before(sess.ExpiresAt) { - return &sess, nil - } - } - return nil, nil -} - -func (s *Store) DeleteSession(token string) error { - s.sessionsMu.Lock() - defer s.sessionsMu.Unlock() - var sessions []models.Session - if err := readJSON(s.filePath("sessions.json"), &sessions); err != nil { - return err - } - var updated []models.Session - found := false - for _, sess := range sessions { - if sess.Token == token { - found = true - continue - } - updated = append(updated, sess) - } - if !found { - return fmt.Errorf("session not found") - } - return writeJSON(s.filePath("sessions.json"), updated) -} - -func (s *Store) CleanExpiredSessions() error { - s.sessionsMu.Lock() - defer s.sessionsMu.Unlock() - var sessions []models.Session - if err := readJSON(s.filePath("sessions.json"), &sessions); err != nil { - return err - } - now := time.Now() - var valid []models.Session - for _, sess := range sessions { - if now.Before(sess.ExpiresAt) { - valid = append(valid, sess) - } - } - return writeJSON(s.filePath("sessions.json"), valid) -} diff --git a/stacks/f1-stream/files/internal/store/store.go b/stacks/f1-stream/files/internal/store/store.go deleted file mode 100644 index dd9911da..00000000 --- a/stacks/f1-stream/files/internal/store/store.go +++ /dev/null @@ -1,53 +0,0 @@ -package store - -import ( - "encoding/json" - "os" - "path/filepath" - "sync" -) - -type Store struct { - dir string - streamsMu sync.RWMutex - usersMu sync.RWMutex - scrapedMu sync.RWMutex - sessionsMu sync.RWMutex - healthMu sync.RWMutex -} - -func New(dir string) (*Store, error) { - if err := os.MkdirAll(dir, 0755); err != nil { - return nil, err - } - return &Store{dir: dir}, nil -} - -func (s *Store) filePath(name string) string { - return filepath.Join(s.dir, name) -} - -// readJSON reads a JSON file into the target. Returns nil if file doesn't exist. -func readJSON(path string, target interface{}) error { - data, err := os.ReadFile(path) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return err - } - return json.Unmarshal(data, target) -} - -// writeJSON atomically writes target as JSON to path using temp-file-then-rename. -func writeJSON(path string, data interface{}) error { - b, err := json.MarshalIndent(data, "", " ") - if err != nil { - return err - } - tmp := path + ".tmp" - if err := os.WriteFile(tmp, b, 0644); err != nil { - return err - } - return os.Rename(tmp, path) -} diff --git a/stacks/f1-stream/files/internal/store/streams.go b/stacks/f1-stream/files/internal/store/streams.go deleted file mode 100644 index 600d4bd9..00000000 --- a/stacks/f1-stream/files/internal/store/streams.go +++ /dev/null @@ -1,176 +0,0 @@ -package store - -import ( - "crypto/rand" - "encoding/hex" - "fmt" - "time" - - "f1-stream/internal/models" -) - -func (s *Store) LoadStreams() ([]models.Stream, error) { - s.streamsMu.RLock() - defer s.streamsMu.RUnlock() - var streams []models.Stream - if err := readJSON(s.filePath("streams.json"), &streams); err != nil { - return nil, err - } - return streams, nil -} - -func (s *Store) PublicStreams() ([]models.Stream, error) { - s.streamsMu.RLock() - defer s.streamsMu.RUnlock() - var streams []models.Stream - if err := readJSON(s.filePath("streams.json"), &streams); err != nil { - return nil, err - } - healthMap := s.HealthMap() - var pub []models.Stream - for _, st := range streams { - if !st.Published { - continue - } - // Filter unhealthy streams. URLs not in healthMap are assumed healthy (new/unchecked). - if healthy, exists := healthMap[st.URL]; exists && !healthy { - continue - } - pub = append(pub, st) - } - return pub, nil -} - -func (s *Store) UserStreams(userID string) ([]models.Stream, error) { - s.streamsMu.RLock() - defer s.streamsMu.RUnlock() - var streams []models.Stream - if err := readJSON(s.filePath("streams.json"), &streams); err != nil { - return nil, err - } - var result []models.Stream - for _, st := range streams { - if st.SubmittedBy == userID { - result = append(result, st) - } - } - return result, nil -} - -func (s *Store) AddStream(url, title, submittedBy string, published bool, source string) (models.Stream, error) { - s.streamsMu.Lock() - defer s.streamsMu.Unlock() - var streams []models.Stream - if err := readJSON(s.filePath("streams.json"), &streams); err != nil { - return models.Stream{}, err - } - id, err := randomID() - if err != nil { - return models.Stream{}, err - } - st := models.Stream{ - ID: id, - URL: url, - Title: title, - SubmittedBy: submittedBy, - Published: published, - Source: source, - CreatedAt: time.Now(), - } - streams = append(streams, st) - if err := writeJSON(s.filePath("streams.json"), streams); err != nil { - return models.Stream{}, err - } - return st, nil -} - -func (s *Store) PublishScrapedStream(url, title string) error { - s.streamsMu.Lock() - defer s.streamsMu.Unlock() - var streams []models.Stream - if err := readJSON(s.filePath("streams.json"), &streams); err != nil { - return err - } - // Deduplicate: skip if URL already exists in streams - for _, st := range streams { - if st.URL == url { - return nil - } - } - id, err := randomID() - if err != nil { - return err - } - streams = append(streams, models.Stream{ - ID: id, - URL: url, - Title: title, - SubmittedBy: "scraper", - Published: true, - Source: "scraped", - CreatedAt: time.Now(), - }) - return writeJSON(s.filePath("streams.json"), streams) -} - -func (s *Store) DeleteStream(id, userID string, isAdmin bool) error { - s.streamsMu.Lock() - defer s.streamsMu.Unlock() - var streams []models.Stream - if err := readJSON(s.filePath("streams.json"), &streams); err != nil { - return err - } - var updated []models.Stream - found := false - for _, st := range streams { - if st.ID == id { - if userID != "" && !isAdmin && st.SubmittedBy != userID { - return fmt.Errorf("not authorized") - } - found = true - continue - } - updated = append(updated, st) - } - if !found { - return fmt.Errorf("stream not found") - } - return writeJSON(s.filePath("streams.json"), updated) -} - -func (s *Store) TogglePublish(id string) error { - s.streamsMu.Lock() - defer s.streamsMu.Unlock() - var streams []models.Stream - if err := readJSON(s.filePath("streams.json"), &streams); err != nil { - return err - } - for i, st := range streams { - if st.ID == id { - streams[i].Published = !st.Published - return writeJSON(s.filePath("streams.json"), streams) - } - } - return fmt.Errorf("stream not found") -} - -func (s *Store) SeedStreams(defaults []models.Stream) error { - s.streamsMu.Lock() - defer s.streamsMu.Unlock() - var existing []models.Stream - if err := readJSON(s.filePath("streams.json"), &existing); err != nil { - return err - } - if len(existing) > 0 { - return nil - } - return writeJSON(s.filePath("streams.json"), defaults) -} - -func randomID() (string, error) { - b := make([]byte, 16) - if _, err := rand.Read(b); err != nil { - return "", err - } - return hex.EncodeToString(b), nil -} diff --git a/stacks/f1-stream/files/internal/store/users.go b/stacks/f1-stream/files/internal/store/users.go deleted file mode 100644 index 8f9bf775..00000000 --- a/stacks/f1-stream/files/internal/store/users.go +++ /dev/null @@ -1,91 +0,0 @@ -package store - -import ( - "fmt" - - "f1-stream/internal/models" - - "github.com/go-webauthn/webauthn/webauthn" -) - -func (s *Store) LoadUsers() ([]models.User, error) { - s.usersMu.RLock() - defer s.usersMu.RUnlock() - var users []models.User - if err := readJSON(s.filePath("users.json"), &users); err != nil { - return nil, err - } - return users, nil -} - -func (s *Store) GetUserByName(username string) (*models.User, error) { - s.usersMu.RLock() - defer s.usersMu.RUnlock() - var users []models.User - if err := readJSON(s.filePath("users.json"), &users); err != nil { - return nil, err - } - for _, u := range users { - if u.Username == username { - return &u, nil - } - } - return nil, nil -} - -func (s *Store) GetUserByID(id string) (*models.User, error) { - s.usersMu.RLock() - defer s.usersMu.RUnlock() - var users []models.User - if err := readJSON(s.filePath("users.json"), &users); err != nil { - return nil, err - } - for _, u := range users { - if u.ID == id { - return &u, nil - } - } - return nil, nil -} - -func (s *Store) CreateUser(user models.User) error { - s.usersMu.Lock() - defer s.usersMu.Unlock() - var users []models.User - if err := readJSON(s.filePath("users.json"), &users); err != nil { - return err - } - for _, u := range users { - if u.Username == user.Username { - return fmt.Errorf("username already exists") - } - } - users = append(users, user) - return writeJSON(s.filePath("users.json"), users) -} - -func (s *Store) UpdateUserCredentials(userID string, creds []webauthn.Credential) error { - s.usersMu.Lock() - defer s.usersMu.Unlock() - var users []models.User - if err := readJSON(s.filePath("users.json"), &users); err != nil { - return err - } - for i, u := range users { - if u.ID == userID { - users[i].Credentials = creds - return writeJSON(s.filePath("users.json"), users) - } - } - return fmt.Errorf("user not found") -} - -func (s *Store) UserCount() (int, error) { - s.usersMu.RLock() - defer s.usersMu.RUnlock() - var users []models.User - if err := readJSON(s.filePath("users.json"), &users); err != nil { - return 0, err - } - return len(users), nil -} diff --git a/stacks/f1-stream/files/main.go b/stacks/f1-stream/files/main.go deleted file mode 100644 index 880ebc8c..00000000 --- a/stacks/f1-stream/files/main.go +++ /dev/null @@ -1,163 +0,0 @@ -package main - -import ( - "context" - "fmt" - "log" - "net/http" - "os" - "os/signal" - "strings" - "syscall" - "time" - - "f1-stream/internal/auth" - "f1-stream/internal/extractor" - "f1-stream/internal/healthcheck" - "f1-stream/internal/models" - "f1-stream/internal/playerconfig" - "f1-stream/internal/scraper" - "f1-stream/internal/server" - "f1-stream/internal/store" -) - -func main() { - listenAddr := envOr("LISTEN_ADDR", ":8080") - dataDir := envOr("DATA_DIR", "/data") - scrapeInterval := envDuration("SCRAPE_INTERVAL", 15*time.Minute) - validateTimeout := envDuration("SCRAPER_VALIDATE_TIMEOUT", 10*time.Second) - adminUsername := os.Getenv("ADMIN_USERNAME") - sessionTTL := envDuration("SESSION_TTL", 720*time.Hour) - headlessEnabled := os.Getenv("HEADLESS_EXTRACT_ENABLED") == "true" - rpID := envOr("WEBAUTHN_RPID", "localhost") - rpOrigin := envOr("WEBAUTHN_ORIGIN", "http://localhost:8080") - rpDisplayName := envOr("WEBAUTHN_DISPLAY_NAME", "F1 Stream") - - // Initialize store - st, err := store.New(dataDir) - if err != nil { - log.Fatalf("failed to init store: %v", err) - } - - // Seed default streams - if err := st.SeedStreams(defaultStreams()); err != nil { - log.Printf("warning: failed to seed streams: %v", err) - } - - // Initialize auth - origins := strings.Split(rpOrigin, ",") - a, err := auth.New(st, rpDisplayName, rpID, origins, adminUsername, sessionTTL) - if err != nil { - log.Fatalf("failed to init auth: %v", err) - } - - // Initialize scraper - sc := scraper.New(st, scrapeInterval, validateTimeout) - - // Initialize health checker - healthInterval := envDuration("HEALTH_CHECK_INTERVAL", 5*time.Minute) - healthTimeout := envDuration("HEALTH_CHECK_TIMEOUT", 10*time.Second) - hc := healthcheck.New(st, healthInterval, healthTimeout) - - // Initialize server - pc := playerconfig.New() - srv := server.New(st, a, sc, pc, origins, headlessEnabled) - - // Start scraper in background - ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) - defer cancel() - - // Initialize headless browser if enabled - if headlessEnabled { - extractor.Init() - defer extractor.Stop() - // Configure TURN server if provided - if turnURL := os.Getenv("TURN_URL"); turnURL != "" { - turnSecret := os.Getenv("TURN_SHARED_SECRET") - turnInternalURL := os.Getenv("TURN_INTERNAL_URL") - extractor.SetTURNConfig(turnURL, turnSecret, turnInternalURL) - } - log.Println("headless video extraction enabled") - } - - go sc.Run(ctx) - go hc.Run(ctx) - - // Clean expired sessions periodically - go func() { - sessionTicker := time.NewTicker(1 * time.Hour) - defer sessionTicker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-sessionTicker.C: - st.CleanExpiredSessions() - } - } - }() - - httpSrv := &http.Server{ - Addr: listenAddr, - Handler: srv.Handler(), - } - - go func() { - <-ctx.Done() - log.Println("shutting down server...") - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second) - defer shutdownCancel() - httpSrv.Shutdown(shutdownCtx) - }() - - log.Printf("starting server on %s", listenAddr) - if err := httpSrv.ListenAndServe(); err != http.ErrServerClosed { - log.Fatalf("server error: %v", err) - } - log.Println("server stopped") -} - -func defaultStreams() []models.Stream { - now := time.Now() - streams := []struct { - url, title string - }{ - {"https://wearechecking.live/streams-pages/motorsports", "WeAreChecking - Motorsports"}, - {"https://vipleague.im/formula-1-schedule-streaming-links", "VIPLeague - F1"}, - {"https://www.vipbox.lc/", "VIPBox"}, - {"https://f1box.me/", "F1Box"}, - {"https://1stream.vip/formula-1-streams/", "1Stream - F1"}, - } - var result []models.Stream - for i, s := range streams { - result = append(result, models.Stream{ - ID: fmt.Sprintf("default-%d", i), - URL: s.url, - Title: s.title, - SubmittedBy: "system", - Published: true, - Source: "system", - CreatedAt: now, - }) - } - return result -} - -func envOr(key, fallback string) string { - if v := os.Getenv(key); v != "" { - return v - } - return fallback -} - -func envDuration(key string, fallback time.Duration) time.Duration { - if v := os.Getenv(key); v != "" { - d, err := time.ParseDuration(v) - if err != nil { - log.Printf("warning: invalid %s=%q, using default %v", key, v, fallback) - return fallback - } - return d - } - return fallback -} diff --git a/stacks/f1-stream/files/node_modules/.package-lock.json b/stacks/f1-stream/files/node_modules/.package-lock.json deleted file mode 100644 index 8ec5bf72..00000000 --- a/stacks/f1-stream/files/node_modules/.package-lock.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "files", - "lockfileVersion": 3, - "requires": true, - "packages": {} -} diff --git a/stacks/f1-stream/files/package-lock.json b/stacks/f1-stream/files/package-lock.json deleted file mode 100644 index 8ec5bf72..00000000 --- a/stacks/f1-stream/files/package-lock.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "files", - "lockfileVersion": 3, - "requires": true, - "packages": {} -} diff --git a/stacks/f1-stream/files/package.json b/stacks/f1-stream/files/package.json deleted file mode 100644 index 0967ef42..00000000 --- a/stacks/f1-stream/files/package.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/stacks/f1-stream/files/redeploy.sh b/stacks/f1-stream/files/redeploy.sh index d84acb7f..e436a6ce 100755 --- a/stacks/f1-stream/files/redeploy.sh +++ b/stacks/f1-stream/files/redeploy.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash set -e -docker build -t viktorbarzin/f1-stream . -docker push viktorbarzin/f1-stream +docker buildx build --platform linux/amd64 --provenance=false \ + -t viktorbarzin/f1-stream:v2.0.1 -t viktorbarzin/f1-stream:latest \ + --push . kubectl -n f1-stream rollout restart deployment f1-stream diff --git a/stacks/f1-stream/files/static/css/custom.css b/stacks/f1-stream/files/static/css/custom.css deleted file mode 100644 index 269b4fa8..00000000 --- a/stacks/f1-stream/files/static/css/custom.css +++ /dev/null @@ -1,1455 +0,0 @@ -/* ===== F1 Streams — Dark Theme ===== */ - -/* --- Design Tokens --- */ -:root { - /* Backgrounds */ - --bg-base: #0f0f13; - --bg-surface: #1a1a24; - --bg-elevated: #252536; - --bg-input: #14141e; - - /* Accent */ - --accent-red: #e10600; - --accent-red-hover: #ff1a14; - --accent-red-glow: rgba(225, 6, 0, 0.35); - --accent-teal: #00d2be; - --accent-teal-glow: rgba(0, 210, 190, 0.25); - - /* Text */ - --text-primary: #f0f0f5; - --text-secondary: #a0a0b4; - --text-disabled: #5a5a6e; - - /* Status */ - --status-green: #00c853; - --status-yellow: #ffc107; - --status-red: #ff3d3d; - - /* Borders & Shadows */ - --border-color: #2a2a3d; - --border-subtle: #1f1f30; - --shadow-card: 0 2px 8px rgba(0, 0, 0, 0.4); - --shadow-elevated: 0 8px 32px rgba(0, 0, 0, 0.6); - --shadow-glow-red: 0 0 20px var(--accent-red-glow); - - /* Spacing */ - --radius-sm: 6px; - --radius-md: 10px; - --radius-lg: 14px; - --radius-pill: 999px; - - /* Transitions */ - --transition-fast: 0.15s ease; - --transition-normal: 0.25s ease; - --transition-slow: 0.4s ease; - - /* Pico overrides */ - --pico-primary: var(--accent-red); - --pico-primary-hover: var(--accent-red-hover); - --pico-background-color: var(--bg-base); - --pico-card-background-color: var(--bg-surface); - --pico-card-border-color: var(--border-color); - --pico-color: var(--text-primary); - --pico-muted-color: var(--text-secondary); - --pico-form-element-background-color: var(--bg-input); - --pico-form-element-border-color: var(--border-color); - --pico-form-element-color: var(--text-primary); - --pico-form-element-focus-color: var(--accent-red); -} - -.hidden { display: none !important; } - -/* --- Base --- */ -*, *::before, *::after { - box-sizing: border-box; -} - -body { - background: var(--bg-base); - color: var(--text-primary); - font-family: 'Inter', system-ui, -apple-system, sans-serif; - min-height: 100vh; - margin: 0; -} - -h1, h2, h3, h4, h5, h6, -.brand-title, .tab-btn, button { - font-family: 'Titillium Web', 'Inter', system-ui, sans-serif; -} - -/* --- Header --- */ -header { - background: var(--bg-surface); - border-bottom: none; - padding: 0.75rem 1.5rem; - display: flex; - justify-content: space-between; - align-items: center; - position: relative; -} - -.header-left { - display: flex; - align-items: center; - gap: 0.75rem; -} - -.f1-logo { - background: var(--accent-red); - color: #fff; - font-family: 'Titillium Web', sans-serif; - font-weight: 900; - font-size: 1.4rem; - padding: 0.15rem 0.6rem; - border-radius: var(--radius-sm); - letter-spacing: -0.5px; - line-height: 1.2; - user-select: none; -} - -.brand-title { - font-size: 1.35rem; - font-weight: 700; - color: var(--text-primary); - margin: 0; - line-height: 1.2; -} - -h1.brand-title { - margin: 0; - font-size: 1.35rem; -} - -.brand-subtitle { - font-size: 0.7rem; - color: var(--text-secondary); - text-transform: uppercase; - letter-spacing: 1.5px; - font-weight: 400; -} - -.live-indicator { - display: inline-flex; - align-items: center; - gap: 0.35rem; - font-size: 0.7rem; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 1px; - color: var(--status-green); - margin-left: 0.5rem; -} - -.live-dot { - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--status-green); - animation: pulse-dot 1.5s ease-in-out infinite; -} - -@keyframes pulse-dot { - 0%, 100% { opacity: 1; box-shadow: 0 0 0 0 rgba(0, 200, 83, 0.6); } - 50% { opacity: 0.7; box-shadow: 0 0 0 6px rgba(0, 200, 83, 0); } -} - -/* Racing stripe */ -.racing-stripe { - height: 3px; - background: linear-gradient(90deg, var(--accent-red) 0%, var(--accent-red) 50%, var(--accent-teal) 75%, var(--status-yellow) 100%); -} - -/* Auth button */ -header .auth-section { - display: flex; - align-items: center; - gap: 0.75rem; -} - -header .auth-section span { - color: var(--text-secondary); - font-size: 0.85rem; -} - -header .auth-section button, -header .auth-section #login-btn { - background: transparent; - border: 1px solid var(--border-color); - color: var(--text-primary); - padding: 0.4rem 1rem; - border-radius: var(--radius-pill); - font-size: 0.85rem; - font-weight: 600; - cursor: pointer; - transition: all var(--transition-fast); - margin: 0; -} - -header .auth-section button:hover, -header .auth-section #login-btn:hover { - border-color: var(--accent-red); - color: var(--accent-red); - box-shadow: 0 0 12px var(--accent-red-glow); -} - -/* --- Navigation --- */ -.tabs { - display: flex; - gap: 0.5rem; - padding: 0.6rem 1.5rem; - background: var(--bg-surface); - border-bottom: 1px solid var(--border-subtle); - position: sticky; - top: 0; - z-index: 100; - align-items: center; -} - -.hamburger { - display: none; - background: none; - border: none; - color: var(--text-primary); - font-size: 1.5rem; - cursor: pointer; - padding: 0.25rem; - margin: 0; - line-height: 1; -} - -.tab-btn { - background: transparent; - border: 1px solid transparent; - border-radius: var(--radius-pill); - color: var(--text-secondary); - padding: 0.45rem 1rem; - cursor: pointer; - font-size: 0.85rem; - font-weight: 600; - text-transform: uppercase; - letter-spacing: 0.5px; - transition: all var(--transition-fast); - display: inline-flex; - align-items: center; - gap: 0.4rem; - margin: 0; - white-space: nowrap; -} - -.tab-btn svg { - width: 16px; - height: 16px; - flex-shrink: 0; -} - -.tab-btn:hover { - color: var(--text-primary); - background: var(--bg-elevated); - border-color: var(--border-color); -} - -.tab-btn.active { - background: var(--accent-red); - color: #fff; - border-color: var(--accent-red); - box-shadow: 0 0 14px var(--accent-red-glow); - font-weight: 700; -} - -/* --- Tab Content --- */ -.tab-content { - display: none; - padding: 1rem 1.5rem; - animation: fadeIn 0.3s ease; -} - -.tab-content.active { - display: block; -} - -@keyframes fadeIn { - from { opacity: 0; transform: translateY(6px); } - to { opacity: 1; transform: translateY(0); } -} - -/* --- Stream Grid --- */ -.stream-grid { - display: flex; - flex-wrap: wrap; - gap: 1.25rem; -} - -/* --- Stream Card --- */ -.stream-card { - background: var(--bg-surface); - border: 1px solid var(--border-color); - border-radius: var(--radius-md); - overflow: hidden; - display: flex; - flex-direction: column; - transition: border-color var(--transition-normal), box-shadow var(--transition-normal); - position: relative; - width: 280px; - min-width: 220px; - cursor: pointer; -} - -.stream-card::before { - content: ''; - position: absolute; - top: 0; - left: 0; - right: 0; - height: 3px; - background: linear-gradient(90deg, var(--accent-red), var(--accent-teal)); - opacity: 0; - transition: opacity var(--transition-normal); -} - -.stream-card:hover { - border-color: var(--accent-red); - box-shadow: 0 4px 20px rgba(225, 6, 0, 0.15); -} - -.stream-card:hover::before { - opacity: 1; -} - -.stream-card .card-body { - padding: 1.5rem 1rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 0.5rem; - flex: 1; -} - -.stream-card .card-icon { - width: 40px; - height: 40px; - color: var(--text-secondary); -} - -.stream-card .card-icon svg { - width: 100%; - height: 100%; -} - -.stream-card .card-title { - font-size: 0.9rem; - font-weight: 600; - color: var(--text-primary); - text-align: center; - word-break: break-word; -} - -.stream-card .card-url { - font-size: 0.7rem; - color: var(--text-disabled); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - max-width: 100%; -} - -/* Loading spinner */ -.spinner { - width: 36px; - height: 36px; - border: 3px solid var(--border-color); - border-top-color: var(--accent-red); - border-radius: 50%; - animation: spin 0.8s linear infinite; -} - -@keyframes spin { - to { transform: rotate(360deg); } -} - -.stream-card .card-bar { - display: flex; - justify-content: space-between; - align-items: center; - padding: 0.6rem 0.75rem; - gap: 0.5rem; - flex-shrink: 0; - border-top: 1px solid var(--border-subtle); -} - -.stream-card .card-bar .title { - font-size: 0.85rem; - color: var(--text-primary); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - flex: 1; - font-weight: 500; -} - -.stream-card .card-bar .card-actions { - display: flex; - gap: 0.35rem; - align-items: center; -} - -.card-actions .icon-btn { - background: transparent; - border: 1px solid var(--border-color); - color: var(--text-secondary); - width: 32px; - height: 32px; - border-radius: var(--radius-sm); - display: inline-flex; - align-items: center; - justify-content: center; - cursor: pointer; - padding: 0; - margin: 0; - transition: all var(--transition-fast); -} - -.card-actions .icon-btn svg { - width: 16px; - height: 16px; -} - -.card-actions .icon-btn:hover { - color: var(--text-primary); - border-color: var(--text-secondary); - background: var(--bg-elevated); -} - -.card-actions .icon-btn.danger:hover { - color: var(--status-red); - border-color: var(--status-red); - background: rgba(255, 61, 61, 0.1); -} - -/* --- Submit Form --- */ -.submit-form-card { - background: var(--bg-surface); - border: 1px solid var(--border-color); - border-radius: var(--radius-md); - padding: 1rem; - margin-bottom: 1rem; -} - -.submit-form { - display: flex; - gap: 0.75rem; - align-items: flex-end; - margin-bottom: 0; -} - -.submit-form input { - background: var(--bg-input); - border: 1px solid var(--border-color); - color: var(--text-primary); - border-radius: var(--radius-sm); - padding: 0.55rem 0.75rem; - font-size: 0.9rem; - margin-bottom: 0; - transition: border-color var(--transition-fast), box-shadow var(--transition-fast); -} - -.submit-form input::placeholder { - color: var(--text-disabled); -} - -.submit-form input:focus { - outline: none; - border-color: var(--accent-red); - box-shadow: 0 0 0 3px var(--accent-red-glow); -} - -.submit-form button { - white-space: nowrap; - margin-bottom: 0; -} - -/* --- Buttons --- */ -button, [type="submit"] { - font-family: 'Titillium Web', 'Inter', sans-serif; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.5px; - font-size: 0.85rem; - border-radius: var(--radius-sm); - cursor: pointer; - transition: all var(--transition-fast); -} - -.btn-primary, .submit-form button, .section-header button { - background: var(--accent-red); - border: none; - color: #fff; - padding: 0.55rem 1.25rem; - border-radius: var(--radius-sm); -} - -.btn-primary:hover, .submit-form button:hover, .section-header button:hover { - background: var(--accent-red-hover); - box-shadow: var(--shadow-glow-red); - transform: translateY(-1px); -} - -.btn-secondary { - background: transparent; - border: 1px solid var(--border-color); - color: var(--text-secondary); - padding: 0.55rem 1.25rem; -} - -.btn-secondary:hover { - border-color: var(--text-secondary); - color: var(--text-primary); - background: var(--bg-elevated); -} - -.btn-danger-sm { - background: transparent; - border: 1px solid var(--status-red); - color: var(--status-red); - padding: 0.3rem 0.7rem; - font-size: 0.75rem; -} - -.btn-danger-sm:hover { - background: rgba(255, 61, 61, 0.15); -} - -.btn-primary-sm { - background: var(--accent-red); - border: none; - color: #fff; - padding: 0.3rem 0.7rem; - font-size: 0.75rem; -} - -.btn-primary-sm:hover { - background: var(--accent-red-hover); - box-shadow: 0 0 10px var(--accent-red-glow); -} - -.btn-secondary-sm { - background: transparent; - border: 1px solid var(--border-color); - color: var(--text-secondary); - padding: 0.3rem 0.7rem; - font-size: 0.75rem; -} - -.btn-secondary-sm:hover { - border-color: var(--text-secondary); - color: var(--text-primary); -} - -/* --- Reddit Links --- */ -.section-header { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 1rem; -} - -.section-header h3 { - margin: 0; - font-family: 'Titillium Web', sans-serif; - font-weight: 700; - color: var(--text-primary); - font-size: 1.1rem; -} - -.section-header button svg { - width: 16px; - height: 16px; - vertical-align: -2px; - margin-right: 0.3rem; -} - -.link-list { - list-style: none; - padding: 0; - margin: 0; -} - -.link-list li { - background: var(--bg-surface); - border: 1px solid var(--border-color); - border-radius: var(--radius-sm); - padding: 0.75rem 1rem; - margin-bottom: 0.5rem; - display: flex; - justify-content: space-between; - align-items: center; - gap: 1rem; - transition: all var(--transition-fast); - animation: slideIn var(--transition-slow) ease both; -} - -.link-list li:hover { - border-color: var(--accent-teal); - transform: translateX(4px); - background: var(--bg-elevated); -} - -@keyframes slideIn { - from { opacity: 0; transform: translateX(-12px); } - to { opacity: 1; transform: translateX(0); } -} - -.link-list li:nth-child(1) { animation-delay: 0s; } -.link-list li:nth-child(2) { animation-delay: 0.04s; } -.link-list li:nth-child(3) { animation-delay: 0.08s; } -.link-list li:nth-child(4) { animation-delay: 0.12s; } -.link-list li:nth-child(5) { animation-delay: 0.16s; } -.link-list li:nth-child(6) { animation-delay: 0.2s; } -.link-list li:nth-child(7) { animation-delay: 0.24s; } -.link-list li:nth-child(8) { animation-delay: 0.28s; } -.link-list li:nth-child(9) { animation-delay: 0.32s; } -.link-list li:nth-child(10) { animation-delay: 0.36s; } - -.link-list li .link-title { - flex: 1; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.link-list li .link-title a { - color: var(--text-primary); - text-decoration: none; - transition: color var(--transition-fast); -} - -.link-list li .link-title a:hover { - color: var(--accent-teal); -} - -.link-source-badge { - font-size: 0.7rem; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.5px; - padding: 0.2rem 0.6rem; - border-radius: var(--radius-pill); - background: rgba(0, 210, 190, 0.12); - color: var(--accent-teal); - white-space: nowrap; - border: 1px solid rgba(0, 210, 190, 0.25); -} - -.link-open-icon { - color: var(--text-disabled); - flex-shrink: 0; - transition: color var(--transition-fast); -} - -.link-open-icon-wrap { - display: inline-flex; - align-items: center; - text-decoration: none; - flex-shrink: 0; -} - -.link-list li:hover .link-open-icon, -.link-open-icon-wrap:hover .link-open-icon { - color: var(--accent-teal); -} - -.badge-imported { - background: rgba(0, 210, 190, 0.15); - color: var(--accent-teal); - border: 1px solid rgba(0, 210, 190, 0.3); -} - -.btn-import { - background: var(--accent-teal); - border: none; - color: var(--bg-base); - padding: 0.25rem 0.65rem; - font-size: 0.75rem; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.5px; - border-radius: var(--radius-pill); - cursor: pointer; - white-space: nowrap; - flex-shrink: 0; - transition: all var(--transition-fast); -} - -.btn-import:hover { - background: #00e8d0; - box-shadow: 0 0 12px var(--accent-teal-glow); - transform: translateY(-1px); -} - -/* --- Admin --- */ -.admin-stats { - display: flex; - gap: 1rem; - margin-bottom: 1.5rem; -} - -.stat-card { - background: var(--bg-surface); - border: 1px solid var(--border-color); - border-radius: var(--radius-md); - padding: 1rem 1.25rem; - flex: 1; - text-align: center; -} - -.stat-card .stat-number { - font-family: 'Titillium Web', sans-serif; - font-size: 2rem; - font-weight: 700; - color: var(--text-primary); - line-height: 1; -} - -.stat-card .stat-label { - font-size: 0.7rem; - text-transform: uppercase; - letter-spacing: 1px; - color: var(--text-secondary); - margin-top: 0.3rem; -} - -.admin-stream { - display: flex; - justify-content: space-between; - align-items: center; - background: var(--bg-surface); - border: 1px solid var(--border-color); - border-radius: var(--radius-sm); - padding: 0.75rem 1rem; - margin-bottom: 0.5rem; - gap: 1rem; - transition: border-color var(--transition-fast); -} - -.admin-stream:hover { - border-color: var(--accent-red); -} - -.admin-stream .info { - flex: 1; - overflow: hidden; - display: flex; - align-items: center; - gap: 0.75rem; -} - -.status-dot { - width: 10px; - height: 10px; - border-radius: 50%; - flex-shrink: 0; -} - -.status-dot.published { - background: var(--status-green); - box-shadow: 0 0 6px rgba(0, 200, 83, 0.5); - animation: pulse-dot 1.5s ease-in-out infinite; -} - -.status-dot.draft { - background: var(--status-yellow); -} - -.admin-stream .info .stream-details { - overflow: hidden; -} - -.admin-stream .info .stream-title { - font-weight: 600; - color: var(--text-primary); - display: flex; - align-items: center; - gap: 0.5rem; - flex-wrap: wrap; -} - -.admin-stream .info .stream-url { - font-size: 0.8rem; - color: var(--text-disabled); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.admin-stream .info .stream-submitter { - font-size: 0.75rem; - color: var(--text-secondary); -} - -.admin-stream .actions { - display: flex; - gap: 0.5rem; - flex-shrink: 0; -} - -.badge { - display: inline-block; - font-size: 0.65rem; - padding: 0.15rem 0.5rem; - border-radius: var(--radius-pill); - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.5px; -} - -.badge-published { - background: rgba(0, 200, 83, 0.15); - color: var(--status-green); - border: 1px solid rgba(0, 200, 83, 0.3); -} - -.badge-draft { - background: rgba(255, 193, 7, 0.15); - color: var(--status-yellow); - border: 1px solid rgba(255, 193, 7, 0.3); -} - -/* --- Empty State --- */ -.empty-state { - text-align: center; - padding: 4rem 1.5rem; - color: var(--text-secondary); -} - -.empty-state .empty-icon { - font-size: 3rem; - margin-bottom: 1rem; - display: block; -} - -.empty-state .empty-title { - font-family: 'Titillium Web', sans-serif; - font-size: 1.1rem; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 1px; - color: var(--text-primary); - margin-bottom: 0.5rem; -} - -.empty-state .empty-desc { - font-size: 0.9rem; - color: var(--text-disabled); - max-width: 360px; - margin: 0 auto; -} - -/* --- Auth Dialog --- */ -dialog { - border: none; - padding: 0; - background: transparent; - max-width: 420px; - width: 90%; -} - -dialog::backdrop { - background: rgba(0, 0, 0, 0.7); - backdrop-filter: blur(6px); -} - -dialog > article { - background: var(--bg-elevated); - border: 1px solid var(--border-color); - border-radius: var(--radius-lg); - padding: 2rem 1.5rem 1.5rem; - position: relative; - box-shadow: var(--shadow-elevated); - animation: dialogIn 0.3s ease; - max-width: none; -} - -@keyframes dialogIn { - from { opacity: 0; transform: translateY(20px) scale(0.96); } - to { opacity: 1; transform: translateY(0) scale(1); } -} - -.dialog-close { - position: absolute; - top: 0.75rem; - right: 0.75rem; - background: none; - border: none; - color: var(--text-disabled); - font-size: 1.3rem; - cursor: pointer; - padding: 0.25rem 0.5rem; - margin: 0; - border-radius: var(--radius-sm); - line-height: 1; - transition: color var(--transition-fast); -} - -.dialog-close:hover { - color: var(--text-primary); -} - -.dialog-logo { - text-align: center; - margin-bottom: 1rem; -} - -.dialog-logo .f1-logo { - font-size: 1.8rem; - padding: 0.2rem 0.8rem; - display: inline-block; -} - -dialog .dialog-title { - text-align: center; - font-family: 'Titillium Web', sans-serif; - font-size: 1.3rem; - font-weight: 700; - color: var(--text-primary); - margin: 0 0 0.25rem; -} - -dialog .dialog-subtitle { - text-align: center; - font-size: 0.85rem; - color: var(--text-secondary); - margin: 0 0 1.25rem; -} - -/* Segmented control tabs */ -dialog .dialog-tabs { - display: flex; - background: var(--bg-input); - border-radius: var(--radius-pill); - padding: 3px; - margin-bottom: 1.5rem; - gap: 0; -} - -dialog .dialog-tab-btn { - flex: 1; - background: none; - border: none; - border-radius: var(--radius-pill); - color: var(--text-secondary); - padding: 0.45rem; - margin: 0; - cursor: pointer; - font-size: 0.85rem; - font-weight: 600; - text-transform: uppercase; - transition: all var(--transition-fast); -} - -dialog .dialog-tab-btn.active { - background: var(--accent-red); - color: #fff; - box-shadow: 0 2px 8px var(--accent-red-glow); -} - -dialog label { - display: block; - margin-bottom: 0.35rem; - font-size: 0.8rem; - color: var(--text-secondary); - text-transform: uppercase; - letter-spacing: 0.5px; - font-weight: 600; -} - -dialog input[type="text"] { - width: 100%; - margin-bottom: 0.25rem; - background: var(--bg-input); - border: 1px solid var(--border-color); - color: var(--text-primary); - border-radius: var(--radius-sm); - padding: 0.6rem 0.75rem; - font-size: 0.9rem; - box-sizing: border-box; - transition: border-color var(--transition-fast), box-shadow var(--transition-fast); -} - -dialog input[type="text"]:focus { - outline: none; - border-color: var(--accent-red); - box-shadow: 0 0 0 3px var(--accent-red-glow); -} - -dialog .error-msg { - color: var(--status-red); - font-size: 0.8rem; - min-height: 1.25rem; - margin-bottom: 0.75rem; -} - -dialog .auth-form-group button { - width: 100%; - margin-bottom: 0; - background: var(--accent-red); - border: none; - color: #fff; - padding: 0.65rem; - border-radius: var(--radius-sm); - font-size: 0.9rem; - display: inline-flex; - align-items: center; - justify-content: center; - gap: 0.5rem; -} - -dialog .auth-form-group button:hover { - background: var(--accent-red-hover); - box-shadow: var(--shadow-glow-red); -} - -dialog .dialog-cancel { - width: 100%; - margin-top: 0.75rem; - margin-bottom: 0; - background: transparent; - border: 1px solid var(--border-color); - color: var(--text-secondary); - padding: 0.55rem; -} - -dialog .dialog-cancel:hover { - border-color: var(--text-secondary); - color: var(--text-primary); -} - -/* --- Toast Notifications --- */ -.toast-container { - position: fixed; - top: 1rem; - right: 1rem; - z-index: 10000; - display: flex; - flex-direction: column; - gap: 0.5rem; - pointer-events: none; - max-width: 380px; -} - -.toast { - background: var(--bg-elevated); - border: 1px solid var(--border-color); - border-radius: var(--radius-md); - padding: 0.75rem 1rem; - display: flex; - align-items: center; - gap: 0.6rem; - box-shadow: var(--shadow-elevated); - pointer-events: auto; - animation: toastIn 0.3s ease; - border-left: 4px solid var(--border-color); - font-size: 0.9rem; - color: var(--text-primary); -} - -.toast.toast-out { - animation: toastOut 0.25s ease forwards; -} - -.toast.success { border-left-color: var(--status-green); } -.toast.error { border-left-color: var(--status-red); } -.toast.warning { border-left-color: var(--status-yellow); } -.toast.info { border-left-color: var(--accent-teal); } - -.toast-icon { - font-size: 1.1rem; - flex-shrink: 0; -} - -.toast-message { - flex: 1; -} - -.toast-close { - background: none; - border: none; - color: var(--text-disabled); - cursor: pointer; - padding: 0; - margin: 0; - font-size: 1rem; - line-height: 1; -} - -.toast-close:hover { - color: var(--text-primary); -} - -@keyframes toastIn { - from { opacity: 0; transform: translateX(40px); } - to { opacity: 1; transform: translateX(0); } -} - -@keyframes toastOut { - from { opacity: 1; transform: translateX(0); } - to { opacity: 0; transform: translateX(40px); } -} - -/* --- Confirm Dialog --- */ -.confirm-overlay { - position: fixed; - inset: 0; - background: rgba(0, 0, 0, 0.6); - backdrop-filter: blur(4px); - z-index: 10001; - display: flex; - align-items: center; - justify-content: center; - animation: fadeIn 0.2s ease; -} - -.confirm-box { - background: var(--bg-elevated); - border: 1px solid var(--border-color); - border-radius: var(--radius-lg); - padding: 1.5rem; - max-width: 360px; - width: 90%; - box-shadow: var(--shadow-elevated); - animation: dialogIn 0.25s ease; -} - -.confirm-box .confirm-msg { - font-size: 1rem; - color: var(--text-primary); - margin-bottom: 1.25rem; - text-align: center; -} - -.confirm-box .confirm-actions { - display: flex; - gap: 0.75rem; - justify-content: center; -} - -.confirm-box .confirm-actions button { - padding: 0.5rem 1.5rem; - font-size: 0.85rem; - border-radius: var(--radius-sm); - min-width: 90px; -} - -/* --- Reddit Viewer Overlay --- */ -.reddit-viewer { - position: fixed; - top: 90px; - bottom: 0; - left: 0; - right: 0; - z-index: 1000; - background: var(--bg-base); - display: flex; - flex-direction: column; - animation: fadeIn 0.2s ease; -} - -.reddit-viewer-bar { - display: flex; - justify-content: space-between; - align-items: center; - padding: 0.6rem 1rem; - gap: 0.75rem; - flex-shrink: 0; - border-bottom: 1px solid var(--border-subtle); - background: var(--bg-surface); -} - -.reddit-viewer-title { - font-size: 0.9rem; - font-weight: 600; - color: var(--text-primary); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - flex: 1; -} - -.reddit-viewer-close { - background: none; - border: none; - color: var(--text-disabled); - font-size: 1.4rem; - cursor: pointer; - padding: 0.25rem 0.5rem; - margin: 0; - border-radius: var(--radius-sm); - line-height: 1; - transition: color var(--transition-fast); - flex-shrink: 0; -} - -.reddit-viewer-close:hover { - color: var(--text-primary); -} - -.reddit-viewer-content { - flex: 1; - overflow: auto; - position: relative; -} - -.reddit-viewer-content .loading-overlay { - position: absolute; - inset: 0; - display: flex; - align-items: center; - justify-content: center; - background: var(--bg-base); - z-index: 2; -} - -/* --- Browser Session Viewer Overlay --- */ -.browser-viewer { - display: flex; - flex-direction: column; - min-height: calc(100vh - 120px); - border: 2px solid var(--border-color); - border-radius: var(--radius-md); - overflow: hidden; - background: var(--bg-base); - margin: 0; -} - -.browser-viewer-bar { - display: flex; - align-items: center; - padding: 0.5rem 0.75rem; - gap: 0.5rem; - flex-shrink: 0; - border-bottom: 2px solid var(--border-color); - background: var(--bg-surface); -} - -.browser-url-icon { - width: 16px; - height: 16px; - flex-shrink: 0; - color: var(--text-disabled); -} - -.browser-url-bar { - flex: 1; - background: var(--bg-input); - border: 1px solid var(--border-color); - border-radius: var(--radius-sm); - padding: 0.35rem 0.75rem; - overflow: hidden; - min-width: 0; - display: flex; - align-items: center; - gap: 0.5rem; -} - -.browser-url-text { - font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace; - font-size: 0.8rem; - color: var(--text-secondary); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -.browser-viewer-status { - font-size: 0.75rem; - color: var(--text-secondary); - white-space: nowrap; - flex-shrink: 0; -} - -.browser-viewer-status.connected { - color: var(--status-green); -} - -.browser-open-btn { - display: inline-flex; - align-items: center; - justify-content: center; - width: 32px; - height: 32px; - color: var(--text-secondary); - border: 1px solid var(--border-color); - border-radius: var(--radius-sm); - background: transparent; - cursor: pointer; - transition: all var(--transition-fast); - flex-shrink: 0; - text-decoration: none; -} - -.browser-open-btn:hover { - color: var(--text-primary); - border-color: var(--text-secondary); - background: var(--bg-elevated); -} - -.browser-open-btn svg { - width: 16px; - height: 16px; -} - -.browser-viewer-close { - background: none; - border: 1px solid var(--accent-red); - color: var(--accent-red); - font-size: 1.2rem; - cursor: pointer; - padding: 0.15rem 0.6rem; - margin: 0; - border-radius: var(--radius-sm); - line-height: 1; - transition: all var(--transition-fast); - flex-shrink: 0; - font-weight: 600; -} - -.browser-viewer-close:hover { - background: var(--accent-red); - color: #fff; -} - -.browser-viewer-content { - flex: 1; - overflow: hidden; - position: relative; - background: #000; - min-height: calc(100vh - 180px); -} - -.browser-video { - max-width: 100%; - max-height: 100%; - cursor: default; - display: block; -} - -.browser-iframe { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - border: none; -} - -#clappr-player { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: #000; -} - -.browser-viewer-content .loading-overlay { - position: absolute; - inset: 0; - display: flex; - align-items: center; - justify-content: center; - background: var(--bg-base); - z-index: 2; -} - -/* --- Footer --- */ -footer { - text-align: center; - padding: 1.5rem; - margin-top: 2rem; - border-top: 1px solid var(--border-subtle); - color: var(--text-disabled); - font-size: 0.8rem; -} - -footer p { - margin: 0; -} - -/* --- Responsive --- */ -@media (max-width: 640px) { - .stream-card { - width: 100%; - } - - header { - flex-direction: column; - gap: 0.5rem; - padding: 0.6rem 1rem; - } - - .tabs { - padding: 0.5rem 1rem; - flex-wrap: wrap; - gap: 0.35rem; - } - - .hamburger { - display: flex; - align-items: center; - } - - .tabs .tab-btn { - display: none; - } - - .tabs.open .tab-btn { - display: inline-flex; - width: 100%; - justify-content: center; - } - - .submit-form { - flex-direction: column; - } - - .submit-form input, - .submit-form button { - width: 100%; - } - - .admin-stream { - flex-direction: column; - align-items: flex-start; - gap: 0.75rem; - } - - .admin-stream .actions { - width: 100%; - justify-content: flex-end; - } - - .admin-stats { - flex-direction: column; - } - - .toast-container { - left: 1rem; - right: 1rem; - max-width: none; - } - - .tab-btn { - font-size: 0.8rem; - padding: 0.4rem 0.8rem; - } - - .link-list li { - flex-direction: column; - align-items: flex-start; - gap: 0.5rem; - } -} - -@media (max-width: 480px) { - .brand-subtitle { - display: none; - } -} diff --git a/stacks/f1-stream/files/static/css/pico.min.css b/stacks/f1-stream/files/static/css/pico.min.css deleted file mode 100644 index e10ec26d..00000000 --- a/stacks/f1-stream/files/static/css/pico.min.css +++ /dev/null @@ -1,4 +0,0 @@ -@charset "UTF-8";/*! - * Pico CSS ✨ v2.1.1 (https://picocss.com) - * Copyright 2019-2025 - Licensed under MIT - */:host,:root{--pico-font-family-emoji:"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--pico-font-family-sans-serif:system-ui,"Segoe UI",Roboto,Oxygen,Ubuntu,Cantarell,Helvetica,Arial,"Helvetica Neue",sans-serif,var(--pico-font-family-emoji);--pico-font-family-monospace:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace,var(--pico-font-family-emoji);--pico-font-family:var(--pico-font-family-sans-serif);--pico-line-height:1.5;--pico-font-weight:400;--pico-font-size:100%;--pico-text-underline-offset:0.1rem;--pico-border-radius:0.25rem;--pico-border-width:0.0625rem;--pico-outline-width:0.125rem;--pico-transition:0.2s ease-in-out;--pico-spacing:1rem;--pico-typography-spacing-vertical:1rem;--pico-block-spacing-vertical:var(--pico-spacing);--pico-block-spacing-horizontal:var(--pico-spacing);--pico-grid-column-gap:var(--pico-spacing);--pico-grid-row-gap:var(--pico-spacing);--pico-form-element-spacing-vertical:0.75rem;--pico-form-element-spacing-horizontal:1rem;--pico-group-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-group-box-shadow-focus-with-button:0 0 0 var(--pico-outline-width) var(--pico-primary-focus);--pico-group-box-shadow-focus-with-input:0 0 0 0.0625rem var(--pico-form-element-border-color);--pico-modal-overlay-backdrop-filter:blur(0.375rem);--pico-nav-element-spacing-vertical:1rem;--pico-nav-element-spacing-horizontal:0.5rem;--pico-nav-link-spacing-vertical:0.5rem;--pico-nav-link-spacing-horizontal:0.5rem;--pico-nav-breadcrumb-divider:">";--pico-icon-checkbox:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(255, 255, 255)' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-minus:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(255, 255, 255)' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='5' y1='12' x2='19' y2='12'%3E%3C/line%3E%3C/svg%3E");--pico-icon-chevron:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-date:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='16' y1='2' x2='16' y2='6'%3E%3C/line%3E%3Cline x1='8' y1='2' x2='8' y2='6'%3E%3C/line%3E%3Cline x1='3' y1='10' x2='21' y2='10'%3E%3C/line%3E%3C/svg%3E");--pico-icon-time:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cpolyline points='12 6 12 12 16 14'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-search:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E");--pico-icon-close:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='18' y1='6' x2='6' y2='18'%3E%3C/line%3E%3Cline x1='6' y1='6' x2='18' y2='18'%3E%3C/line%3E%3C/svg%3E");--pico-icon-loading:url("data:image/svg+xml,%3Csvg fill='none' height='24' width='24' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg' %3E%3Cstyle%3E g %7B animation: rotate 2s linear infinite; transform-origin: center center; %7D circle %7B stroke-dasharray: 75,100; stroke-dashoffset: -5; animation: dash 1.5s ease-in-out infinite; stroke-linecap: round; %7D @keyframes rotate %7B 0%25 %7B transform: rotate(0deg); %7D 100%25 %7B transform: rotate(360deg); %7D %7D @keyframes dash %7B 0%25 %7B stroke-dasharray: 1,100; stroke-dashoffset: 0; %7D 50%25 %7B stroke-dasharray: 44.5,100; stroke-dashoffset: -17.5; %7D 100%25 %7B stroke-dasharray: 44.5,100; stroke-dashoffset: -62; %7D %7D %3C/style%3E%3Cg%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='rgb(136, 145, 164)' stroke-width='4' /%3E%3C/g%3E%3C/svg%3E")}@media (min-width:576px){:host,:root{--pico-font-size:106.25%}}@media (min-width:768px){:host,:root{--pico-font-size:112.5%}}@media (min-width:1024px){:host,:root{--pico-font-size:118.75%}}@media (min-width:1280px){:host,:root{--pico-font-size:125%}}@media (min-width:1536px){:host,:root{--pico-font-size:131.25%}}a{--pico-text-decoration:underline}a.contrast,a.secondary{--pico-text-decoration:underline}small{--pico-font-size:0.875em}h1,h2,h3,h4,h5,h6{--pico-font-weight:700}h1{--pico-font-size:2rem;--pico-line-height:1.125;--pico-typography-spacing-top:3rem}h2{--pico-font-size:1.75rem;--pico-line-height:1.15;--pico-typography-spacing-top:2.625rem}h3{--pico-font-size:1.5rem;--pico-line-height:1.175;--pico-typography-spacing-top:2.25rem}h4{--pico-font-size:1.25rem;--pico-line-height:1.2;--pico-typography-spacing-top:1.874rem}h5{--pico-font-size:1.125rem;--pico-line-height:1.225;--pico-typography-spacing-top:1.6875rem}h6{--pico-font-size:1rem;--pico-line-height:1.25;--pico-typography-spacing-top:1.5rem}tfoot td,tfoot th,thead td,thead th{--pico-font-weight:600;--pico-border-width:0.1875rem}code,kbd,pre,samp{--pico-font-family:var(--pico-font-family-monospace)}kbd{--pico-font-weight:bolder}:where(select,textarea),input:not([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]){--pico-outline-width:0.0625rem}[type=search]{--pico-border-radius:5rem}[type=checkbox],[type=radio]{--pico-border-width:0.125rem}[type=checkbox][role=switch]{--pico-border-width:0.1875rem}details.dropdown summary:not([role=button]){--pico-outline-width:0.0625rem}nav details.dropdown summary:focus-visible{--pico-outline-width:0.125rem}[role=search]{--pico-border-radius:5rem}[role=group]:has(button.secondary:focus,[type=submit].secondary:focus,[type=button].secondary:focus,[role=button].secondary:focus),[role=search]:has(button.secondary:focus,[type=submit].secondary:focus,[type=button].secondary:focus,[role=button].secondary:focus){--pico-group-box-shadow-focus-with-button:0 0 0 var(--pico-outline-width) var(--pico-secondary-focus)}[role=group]:has(button.contrast:focus,[type=submit].contrast:focus,[type=button].contrast:focus,[role=button].contrast:focus),[role=search]:has(button.contrast:focus,[type=submit].contrast:focus,[type=button].contrast:focus,[role=button].contrast:focus){--pico-group-box-shadow-focus-with-button:0 0 0 var(--pico-outline-width) var(--pico-contrast-focus)}[role=group] [role=button],[role=group] [type=button],[role=group] [type=submit],[role=group] button,[role=search] [role=button],[role=search] [type=button],[role=search] [type=submit],[role=search] button{--pico-form-element-spacing-horizontal:2rem}details summary[role=button]:not(.outline)::after{filter:brightness(0) invert(1)}[aria-busy=true]:not(input,select,textarea):is(button,[type=submit],[type=button],[type=reset],[role=button]):not(.outline)::before{filter:brightness(0) invert(1)}:host(:not([data-theme=dark])),:root:not([data-theme=dark]),[data-theme=light]{color-scheme:light;--pico-background-color:#fff;--pico-color:#373c44;--pico-text-selection-color:rgba(2, 154, 232, 0.25);--pico-muted-color:#646b79;--pico-muted-border-color:rgb(231, 234, 239.5);--pico-primary:#0172ad;--pico-primary-background:#0172ad;--pico-primary-border:var(--pico-primary-background);--pico-primary-underline:rgba(1, 114, 173, 0.5);--pico-primary-hover:#015887;--pico-primary-hover-background:#02659a;--pico-primary-hover-border:var(--pico-primary-hover-background);--pico-primary-hover-underline:var(--pico-primary-hover);--pico-primary-focus:rgba(2, 154, 232, 0.5);--pico-primary-inverse:#fff;--pico-secondary:#5d6b89;--pico-secondary-background:#525f7a;--pico-secondary-border:var(--pico-secondary-background);--pico-secondary-underline:rgba(93, 107, 137, 0.5);--pico-secondary-hover:#48536b;--pico-secondary-hover-background:#48536b;--pico-secondary-hover-border:var(--pico-secondary-hover-background);--pico-secondary-hover-underline:var(--pico-secondary-hover);--pico-secondary-focus:rgba(93, 107, 137, 0.25);--pico-secondary-inverse:#fff;--pico-contrast:#181c25;--pico-contrast-background:#181c25;--pico-contrast-border:var(--pico-contrast-background);--pico-contrast-underline:rgba(24, 28, 37, 0.5);--pico-contrast-hover:#000;--pico-contrast-hover-background:#000;--pico-contrast-hover-border:var(--pico-contrast-hover-background);--pico-contrast-hover-underline:var(--pico-secondary-hover);--pico-contrast-focus:rgba(93, 107, 137, 0.25);--pico-contrast-inverse:#fff;--pico-box-shadow:0.0145rem 0.029rem 0.174rem rgba(129, 145, 181, 0.01698),0.0335rem 0.067rem 0.402rem rgba(129, 145, 181, 0.024),0.0625rem 0.125rem 0.75rem rgba(129, 145, 181, 0.03),0.1125rem 0.225rem 1.35rem rgba(129, 145, 181, 0.036),0.2085rem 0.417rem 2.502rem rgba(129, 145, 181, 0.04302),0.5rem 1rem 6rem rgba(129, 145, 181, 0.06),0 0 0 0.0625rem rgba(129, 145, 181, 0.015);--pico-h1-color:#2d3138;--pico-h2-color:#373c44;--pico-h3-color:#424751;--pico-h4-color:#4d535e;--pico-h5-color:#5c6370;--pico-h6-color:#646b79;--pico-mark-background-color:rgb(252.5, 230.5, 191.5);--pico-mark-color:#0f1114;--pico-ins-color:rgb(28.5, 105.5, 84);--pico-del-color:rgb(136, 56.5, 53);--pico-blockquote-border-color:var(--pico-muted-border-color);--pico-blockquote-footer-color:var(--pico-muted-color);--pico-button-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-button-hover-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-table-border-color:var(--pico-muted-border-color);--pico-table-row-stripped-background-color:rgba(111, 120, 135, 0.0375);--pico-code-background-color:rgb(243, 244.5, 246.75);--pico-code-color:#646b79;--pico-code-kbd-background-color:var(--pico-color);--pico-code-kbd-color:var(--pico-background-color);--pico-form-element-background-color:rgb(251, 251.5, 252.25);--pico-form-element-selected-background-color:#dfe3eb;--pico-form-element-border-color:#cfd5e2;--pico-form-element-color:#23262c;--pico-form-element-placeholder-color:var(--pico-muted-color);--pico-form-element-active-background-color:#fff;--pico-form-element-active-border-color:var(--pico-primary-border);--pico-form-element-focus-color:var(--pico-primary-border);--pico-form-element-disabled-opacity:0.5;--pico-form-element-invalid-border-color:rgb(183.5, 105.5, 106.5);--pico-form-element-invalid-active-border-color:rgb(200.25, 79.25, 72.25);--pico-form-element-invalid-focus-color:var(--pico-form-element-invalid-active-border-color);--pico-form-element-valid-border-color:rgb(76, 154.5, 137.5);--pico-form-element-valid-active-border-color:rgb(39, 152.75, 118.75);--pico-form-element-valid-focus-color:var(--pico-form-element-valid-active-border-color);--pico-switch-background-color:#bfc7d9;--pico-switch-checked-background-color:var(--pico-primary-background);--pico-switch-color:#fff;--pico-switch-thumb-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-range-border-color:#dfe3eb;--pico-range-active-border-color:#bfc7d9;--pico-range-thumb-border-color:var(--pico-background-color);--pico-range-thumb-color:var(--pico-secondary-background);--pico-range-thumb-active-color:var(--pico-primary-background);--pico-accordion-border-color:var(--pico-muted-border-color);--pico-accordion-active-summary-color:var(--pico-primary-hover);--pico-accordion-close-summary-color:var(--pico-color);--pico-accordion-open-summary-color:var(--pico-muted-color);--pico-card-background-color:var(--pico-background-color);--pico-card-border-color:var(--pico-muted-border-color);--pico-card-box-shadow:var(--pico-box-shadow);--pico-card-sectioning-background-color:rgb(251, 251.5, 252.25);--pico-dropdown-background-color:#fff;--pico-dropdown-border-color:#eff1f4;--pico-dropdown-box-shadow:var(--pico-box-shadow);--pico-dropdown-color:var(--pico-color);--pico-dropdown-hover-background-color:#eff1f4;--pico-loading-spinner-opacity:0.5;--pico-modal-overlay-background-color:rgba(232, 234, 237, 0.75);--pico-progress-background-color:#dfe3eb;--pico-progress-color:var(--pico-primary-background);--pico-tooltip-background-color:var(--pico-contrast-background);--pico-tooltip-color:var(--pico-contrast-inverse);--pico-icon-valid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-invalid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(200.25, 79.25, 72.25)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='8' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='16' x2='12.01' y2='16'%3E%3C/line%3E%3C/svg%3E")}:host(:not([data-theme=dark])) input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]),:root:not([data-theme=dark]) input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]),[data-theme=light] input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]){--pico-form-element-focus-color:var(--pico-primary-focus)}@media only screen and (prefers-color-scheme:dark){:host(:not([data-theme])),:root:not([data-theme]){color-scheme:dark;--pico-background-color:rgb(19, 22.5, 30.5);--pico-color:#c2c7d0;--pico-text-selection-color:rgba(1, 170, 255, 0.1875);--pico-muted-color:#7b8495;--pico-muted-border-color:#202632;--pico-primary:#01aaff;--pico-primary-background:#0172ad;--pico-primary-border:var(--pico-primary-background);--pico-primary-underline:rgba(1, 170, 255, 0.5);--pico-primary-hover:#79c0ff;--pico-primary-hover-background:#017fc0;--pico-primary-hover-border:var(--pico-primary-hover-background);--pico-primary-hover-underline:var(--pico-primary-hover);--pico-primary-focus:rgba(1, 170, 255, 0.375);--pico-primary-inverse:#fff;--pico-secondary:#969eaf;--pico-secondary-background:#525f7a;--pico-secondary-border:var(--pico-secondary-background);--pico-secondary-underline:rgba(150, 158, 175, 0.5);--pico-secondary-hover:#b3b9c5;--pico-secondary-hover-background:#5d6b89;--pico-secondary-hover-border:var(--pico-secondary-hover-background);--pico-secondary-hover-underline:var(--pico-secondary-hover);--pico-secondary-focus:rgba(144, 158, 190, 0.25);--pico-secondary-inverse:#fff;--pico-contrast:#dfe3eb;--pico-contrast-background:#eff1f4;--pico-contrast-border:var(--pico-contrast-background);--pico-contrast-underline:rgba(223, 227, 235, 0.5);--pico-contrast-hover:#fff;--pico-contrast-hover-background:#fff;--pico-contrast-hover-border:var(--pico-contrast-hover-background);--pico-contrast-hover-underline:var(--pico-contrast-hover);--pico-contrast-focus:rgba(207, 213, 226, 0.25);--pico-contrast-inverse:#000;--pico-box-shadow:0.0145rem 0.029rem 0.174rem rgba(7, 8.5, 12, 0.01698),0.0335rem 0.067rem 0.402rem rgba(7, 8.5, 12, 0.024),0.0625rem 0.125rem 0.75rem rgba(7, 8.5, 12, 0.03),0.1125rem 0.225rem 1.35rem rgba(7, 8.5, 12, 0.036),0.2085rem 0.417rem 2.502rem rgba(7, 8.5, 12, 0.04302),0.5rem 1rem 6rem rgba(7, 8.5, 12, 0.06),0 0 0 0.0625rem rgba(7, 8.5, 12, 0.015);--pico-h1-color:#f0f1f3;--pico-h2-color:#e0e3e7;--pico-h3-color:#c2c7d0;--pico-h4-color:#b3b9c5;--pico-h5-color:#a4acba;--pico-h6-color:#8891a4;--pico-mark-background-color:#014063;--pico-mark-color:#fff;--pico-ins-color:#62af9a;--pico-del-color:rgb(205.5, 126, 123);--pico-blockquote-border-color:var(--pico-muted-border-color);--pico-blockquote-footer-color:var(--pico-muted-color);--pico-button-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-button-hover-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-table-border-color:var(--pico-muted-border-color);--pico-table-row-stripped-background-color:rgba(111, 120, 135, 0.0375);--pico-code-background-color:rgb(26, 30.5, 40.25);--pico-code-color:#8891a4;--pico-code-kbd-background-color:var(--pico-color);--pico-code-kbd-color:var(--pico-background-color);--pico-form-element-background-color:rgb(28, 33, 43.5);--pico-form-element-selected-background-color:#2a3140;--pico-form-element-border-color:#2a3140;--pico-form-element-color:#e0e3e7;--pico-form-element-placeholder-color:#8891a4;--pico-form-element-active-background-color:rgb(26, 30.5, 40.25);--pico-form-element-active-border-color:var(--pico-primary-border);--pico-form-element-focus-color:var(--pico-primary-border);--pico-form-element-disabled-opacity:0.5;--pico-form-element-invalid-border-color:rgb(149.5, 74, 80);--pico-form-element-invalid-active-border-color:rgb(183.25, 63.5, 59);--pico-form-element-invalid-focus-color:var(--pico-form-element-invalid-active-border-color);--pico-form-element-valid-border-color:#2a7b6f;--pico-form-element-valid-active-border-color:rgb(22, 137, 105.5);--pico-form-element-valid-focus-color:var(--pico-form-element-valid-active-border-color);--pico-switch-background-color:#333c4e;--pico-switch-checked-background-color:var(--pico-primary-background);--pico-switch-color:#fff;--pico-switch-thumb-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-range-border-color:#202632;--pico-range-active-border-color:#2a3140;--pico-range-thumb-border-color:var(--pico-background-color);--pico-range-thumb-color:var(--pico-secondary-background);--pico-range-thumb-active-color:var(--pico-primary-background);--pico-accordion-border-color:var(--pico-muted-border-color);--pico-accordion-active-summary-color:var(--pico-primary-hover);--pico-accordion-close-summary-color:var(--pico-color);--pico-accordion-open-summary-color:var(--pico-muted-color);--pico-card-background-color:#181c25;--pico-card-border-color:var(--pico-card-background-color);--pico-card-box-shadow:var(--pico-box-shadow);--pico-card-sectioning-background-color:rgb(26, 30.5, 40.25);--pico-dropdown-background-color:#181c25;--pico-dropdown-border-color:#202632;--pico-dropdown-box-shadow:var(--pico-box-shadow);--pico-dropdown-color:var(--pico-color);--pico-dropdown-hover-background-color:#202632;--pico-loading-spinner-opacity:0.5;--pico-modal-overlay-background-color:rgba(7.5, 8.5, 10, 0.75);--pico-progress-background-color:#202632;--pico-progress-color:var(--pico-primary-background);--pico-tooltip-background-color:var(--pico-contrast-background);--pico-tooltip-color:var(--pico-contrast-inverse);--pico-icon-valid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(42, 123, 111)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-invalid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(149.5, 74, 80)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='8' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='16' x2='12.01' y2='16'%3E%3C/line%3E%3C/svg%3E")}:host(:not([data-theme])) input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]),:root:not([data-theme]) input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]){--pico-form-element-focus-color:var(--pico-primary-focus)}:host(:not([data-theme])) details summary[role=button].contrast:not(.outline)::after,:root:not([data-theme]) details summary[role=button].contrast:not(.outline)::after{filter:brightness(0)}:host(:not([data-theme])) [aria-busy=true]:not(input,select,textarea).contrast:is(button,[type=submit],[type=button],[type=reset],[role=button]):not(.outline)::before,:root:not([data-theme]) [aria-busy=true]:not(input,select,textarea).contrast:is(button,[type=submit],[type=button],[type=reset],[role=button]):not(.outline)::before{filter:brightness(0)}}[data-theme=dark]{color-scheme:dark;--pico-background-color:rgb(19, 22.5, 30.5);--pico-color:#c2c7d0;--pico-text-selection-color:rgba(1, 170, 255, 0.1875);--pico-muted-color:#7b8495;--pico-muted-border-color:#202632;--pico-primary:#01aaff;--pico-primary-background:#0172ad;--pico-primary-border:var(--pico-primary-background);--pico-primary-underline:rgba(1, 170, 255, 0.5);--pico-primary-hover:#79c0ff;--pico-primary-hover-background:#017fc0;--pico-primary-hover-border:var(--pico-primary-hover-background);--pico-primary-hover-underline:var(--pico-primary-hover);--pico-primary-focus:rgba(1, 170, 255, 0.375);--pico-primary-inverse:#fff;--pico-secondary:#969eaf;--pico-secondary-background:#525f7a;--pico-secondary-border:var(--pico-secondary-background);--pico-secondary-underline:rgba(150, 158, 175, 0.5);--pico-secondary-hover:#b3b9c5;--pico-secondary-hover-background:#5d6b89;--pico-secondary-hover-border:var(--pico-secondary-hover-background);--pico-secondary-hover-underline:var(--pico-secondary-hover);--pico-secondary-focus:rgba(144, 158, 190, 0.25);--pico-secondary-inverse:#fff;--pico-contrast:#dfe3eb;--pico-contrast-background:#eff1f4;--pico-contrast-border:var(--pico-contrast-background);--pico-contrast-underline:rgba(223, 227, 235, 0.5);--pico-contrast-hover:#fff;--pico-contrast-hover-background:#fff;--pico-contrast-hover-border:var(--pico-contrast-hover-background);--pico-contrast-hover-underline:var(--pico-contrast-hover);--pico-contrast-focus:rgba(207, 213, 226, 0.25);--pico-contrast-inverse:#000;--pico-box-shadow:0.0145rem 0.029rem 0.174rem rgba(7, 8.5, 12, 0.01698),0.0335rem 0.067rem 0.402rem rgba(7, 8.5, 12, 0.024),0.0625rem 0.125rem 0.75rem rgba(7, 8.5, 12, 0.03),0.1125rem 0.225rem 1.35rem rgba(7, 8.5, 12, 0.036),0.2085rem 0.417rem 2.502rem rgba(7, 8.5, 12, 0.04302),0.5rem 1rem 6rem rgba(7, 8.5, 12, 0.06),0 0 0 0.0625rem rgba(7, 8.5, 12, 0.015);--pico-h1-color:#f0f1f3;--pico-h2-color:#e0e3e7;--pico-h3-color:#c2c7d0;--pico-h4-color:#b3b9c5;--pico-h5-color:#a4acba;--pico-h6-color:#8891a4;--pico-mark-background-color:#014063;--pico-mark-color:#fff;--pico-ins-color:#62af9a;--pico-del-color:rgb(205.5, 126, 123);--pico-blockquote-border-color:var(--pico-muted-border-color);--pico-blockquote-footer-color:var(--pico-muted-color);--pico-button-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-button-hover-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-table-border-color:var(--pico-muted-border-color);--pico-table-row-stripped-background-color:rgba(111, 120, 135, 0.0375);--pico-code-background-color:rgb(26, 30.5, 40.25);--pico-code-color:#8891a4;--pico-code-kbd-background-color:var(--pico-color);--pico-code-kbd-color:var(--pico-background-color);--pico-form-element-background-color:rgb(28, 33, 43.5);--pico-form-element-selected-background-color:#2a3140;--pico-form-element-border-color:#2a3140;--pico-form-element-color:#e0e3e7;--pico-form-element-placeholder-color:#8891a4;--pico-form-element-active-background-color:rgb(26, 30.5, 40.25);--pico-form-element-active-border-color:var(--pico-primary-border);--pico-form-element-focus-color:var(--pico-primary-border);--pico-form-element-disabled-opacity:0.5;--pico-form-element-invalid-border-color:rgb(149.5, 74, 80);--pico-form-element-invalid-active-border-color:rgb(183.25, 63.5, 59);--pico-form-element-invalid-focus-color:var(--pico-form-element-invalid-active-border-color);--pico-form-element-valid-border-color:#2a7b6f;--pico-form-element-valid-active-border-color:rgb(22, 137, 105.5);--pico-form-element-valid-focus-color:var(--pico-form-element-valid-active-border-color);--pico-switch-background-color:#333c4e;--pico-switch-checked-background-color:var(--pico-primary-background);--pico-switch-color:#fff;--pico-switch-thumb-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-range-border-color:#202632;--pico-range-active-border-color:#2a3140;--pico-range-thumb-border-color:var(--pico-background-color);--pico-range-thumb-color:var(--pico-secondary-background);--pico-range-thumb-active-color:var(--pico-primary-background);--pico-accordion-border-color:var(--pico-muted-border-color);--pico-accordion-active-summary-color:var(--pico-primary-hover);--pico-accordion-close-summary-color:var(--pico-color);--pico-accordion-open-summary-color:var(--pico-muted-color);--pico-card-background-color:#181c25;--pico-card-border-color:var(--pico-card-background-color);--pico-card-box-shadow:var(--pico-box-shadow);--pico-card-sectioning-background-color:rgb(26, 30.5, 40.25);--pico-dropdown-background-color:#181c25;--pico-dropdown-border-color:#202632;--pico-dropdown-box-shadow:var(--pico-box-shadow);--pico-dropdown-color:var(--pico-color);--pico-dropdown-hover-background-color:#202632;--pico-loading-spinner-opacity:0.5;--pico-modal-overlay-background-color:rgba(7.5, 8.5, 10, 0.75);--pico-progress-background-color:#202632;--pico-progress-color:var(--pico-primary-background);--pico-tooltip-background-color:var(--pico-contrast-background);--pico-tooltip-color:var(--pico-contrast-inverse);--pico-icon-valid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(42, 123, 111)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-invalid:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(149.5, 74, 80)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='8' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='16' x2='12.01' y2='16'%3E%3C/line%3E%3C/svg%3E")}[data-theme=dark] input:is([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[type=file]){--pico-form-element-focus-color:var(--pico-primary-focus)}[data-theme=dark] details summary[role=button].contrast:not(.outline)::after{filter:brightness(0)}[data-theme=dark] [aria-busy=true]:not(input,select,textarea).contrast:is(button,[type=submit],[type=button],[type=reset],[role=button]):not(.outline)::before{filter:brightness(0)}[type=checkbox],[type=radio],[type=range],progress{accent-color:var(--pico-primary)}*,::after,::before{box-sizing:border-box;background-repeat:no-repeat}::after,::before{text-decoration:inherit;vertical-align:inherit}:where(:host),:where(:root){-webkit-tap-highlight-color:transparent;-webkit-text-size-adjust:100%;-moz-text-size-adjust:100%;text-size-adjust:100%;background-color:var(--pico-background-color);color:var(--pico-color);font-weight:var(--pico-font-weight);font-size:var(--pico-font-size);line-height:var(--pico-line-height);font-family:var(--pico-font-family);text-underline-offset:var(--pico-text-underline-offset);text-rendering:optimizeLegibility;overflow-wrap:break-word;-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{width:100%;margin:0}main{display:block}body>footer,body>header,body>main{padding-block:var(--pico-block-spacing-vertical)}section{margin-bottom:var(--pico-block-spacing-vertical)}.container,.container-fluid{width:100%;margin-right:auto;margin-left:auto;padding-right:var(--pico-spacing);padding-left:var(--pico-spacing)}@media (min-width:576px){.container{max-width:510px;padding-right:0;padding-left:0}}@media (min-width:768px){.container{max-width:700px}}@media (min-width:1024px){.container{max-width:950px}}@media (min-width:1280px){.container{max-width:1200px}}@media (min-width:1536px){.container{max-width:1450px}}.grid{grid-column-gap:var(--pico-grid-column-gap);grid-row-gap:var(--pico-grid-row-gap);display:grid;grid-template-columns:1fr}@media (min-width:768px){.grid{grid-template-columns:repeat(auto-fit,minmax(0%,1fr))}}.grid>*{min-width:0}.overflow-auto{overflow:auto}b,strong{font-weight:bolder}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}address,blockquote,dl,ol,p,pre,table,ul{margin-top:0;margin-bottom:var(--pico-typography-spacing-vertical);color:var(--pico-color);font-style:normal;font-weight:var(--pico-font-weight)}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:var(--pico-typography-spacing-vertical);color:var(--pico-color);font-weight:var(--pico-font-weight);font-size:var(--pico-font-size);line-height:var(--pico-line-height);font-family:var(--pico-font-family)}h1{--pico-color:var(--pico-h1-color)}h2{--pico-color:var(--pico-h2-color)}h3{--pico-color:var(--pico-h3-color)}h4{--pico-color:var(--pico-h4-color)}h5{--pico-color:var(--pico-h5-color)}h6{--pico-color:var(--pico-h6-color)}:where(article,address,blockquote,dl,figure,form,ol,p,pre,table,ul)~:is(h1,h2,h3,h4,h5,h6){margin-top:var(--pico-typography-spacing-top)}p{margin-bottom:var(--pico-typography-spacing-vertical)}hgroup{margin-bottom:var(--pico-typography-spacing-vertical)}hgroup>*{margin-top:0;margin-bottom:0}hgroup>:not(:first-child):last-child{--pico-color:var(--pico-muted-color);--pico-font-weight:unset;font-size:1rem}:where(ol,ul) li{margin-bottom:calc(var(--pico-typography-spacing-vertical) * .25)}:where(dl,ol,ul) :where(dl,ol,ul){margin:0;margin-top:calc(var(--pico-typography-spacing-vertical) * .25)}ul li{list-style:square}mark{padding:.125rem .25rem;background-color:var(--pico-mark-background-color);color:var(--pico-mark-color);vertical-align:baseline}blockquote{display:block;margin:var(--pico-typography-spacing-vertical) 0;padding:var(--pico-spacing);border-right:none;border-left:.25rem solid var(--pico-blockquote-border-color);border-inline-start:0.25rem solid var(--pico-blockquote-border-color);border-inline-end:none}blockquote footer{margin-top:calc(var(--pico-typography-spacing-vertical) * .5);color:var(--pico-blockquote-footer-color)}abbr[title]{border-bottom:1px dotted;text-decoration:none;cursor:help}ins{color:var(--pico-ins-color);text-decoration:none}del{color:var(--pico-del-color)}::-moz-selection{background-color:var(--pico-text-selection-color)}::selection{background-color:var(--pico-text-selection-color)}:where(a:not([role=button])),[role=link]{--pico-color:var(--pico-primary);--pico-background-color:transparent;--pico-underline:var(--pico-primary-underline);outline:0;background-color:var(--pico-background-color);color:var(--pico-color);-webkit-text-decoration:var(--pico-text-decoration);text-decoration:var(--pico-text-decoration);text-decoration-color:var(--pico-underline);text-underline-offset:0.125em;transition:background-color var(--pico-transition),color var(--pico-transition),box-shadow var(--pico-transition),-webkit-text-decoration var(--pico-transition);transition:background-color var(--pico-transition),color var(--pico-transition),text-decoration var(--pico-transition),box-shadow var(--pico-transition);transition:background-color var(--pico-transition),color var(--pico-transition),text-decoration var(--pico-transition),box-shadow var(--pico-transition),-webkit-text-decoration var(--pico-transition)}:where(a:not([role=button])):is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[role=link]:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-primary-hover);--pico-underline:var(--pico-primary-hover-underline);--pico-text-decoration:underline}:where(a:not([role=button])):focus-visible,[role=link]:focus-visible{box-shadow:0 0 0 var(--pico-outline-width) var(--pico-primary-focus)}:where(a:not([role=button])).secondary,[role=link].secondary{--pico-color:var(--pico-secondary);--pico-underline:var(--pico-secondary-underline)}:where(a:not([role=button])).secondary:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[role=link].secondary:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-secondary-hover);--pico-underline:var(--pico-secondary-hover-underline)}:where(a:not([role=button])).contrast,[role=link].contrast{--pico-color:var(--pico-contrast);--pico-underline:var(--pico-contrast-underline)}:where(a:not([role=button])).contrast:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[role=link].contrast:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-contrast-hover);--pico-underline:var(--pico-contrast-hover-underline)}a[role=button]{display:inline-block}button{margin:0;overflow:visible;font-family:inherit;text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[role=button],[type=button],[type=file]::file-selector-button,[type=reset],[type=submit],button{--pico-background-color:var(--pico-primary-background);--pico-border-color:var(--pico-primary-border);--pico-color:var(--pico-primary-inverse);--pico-box-shadow:var(--pico-button-box-shadow, 0 0 0 rgba(0, 0, 0, 0));padding:var(--pico-form-element-spacing-vertical) var(--pico-form-element-spacing-horizontal);border:var(--pico-border-width) solid var(--pico-border-color);border-radius:var(--pico-border-radius);outline:0;background-color:var(--pico-background-color);box-shadow:var(--pico-box-shadow);color:var(--pico-color);font-weight:var(--pico-font-weight);font-size:1rem;line-height:var(--pico-line-height);text-align:center;text-decoration:none;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:background-color var(--pico-transition),border-color var(--pico-transition),color var(--pico-transition),box-shadow var(--pico-transition)}[role=button]:is(:hover,:active,:focus),[role=button]:is([aria-current]:not([aria-current=false])),[type=button]:is(:hover,:active,:focus),[type=button]:is([aria-current]:not([aria-current=false])),[type=file]::file-selector-button:is(:hover,:active,:focus),[type=file]::file-selector-button:is([aria-current]:not([aria-current=false])),[type=reset]:is(:hover,:active,:focus),[type=reset]:is([aria-current]:not([aria-current=false])),[type=submit]:is(:hover,:active,:focus),[type=submit]:is([aria-current]:not([aria-current=false])),button:is(:hover,:active,:focus),button:is([aria-current]:not([aria-current=false])){--pico-background-color:var(--pico-primary-hover-background);--pico-border-color:var(--pico-primary-hover-border);--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0));--pico-color:var(--pico-primary-inverse)}[role=button]:focus,[role=button]:is([aria-current]:not([aria-current=false])):focus,[type=button]:focus,[type=button]:is([aria-current]:not([aria-current=false])):focus,[type=file]::file-selector-button:focus,[type=file]::file-selector-button:is([aria-current]:not([aria-current=false])):focus,[type=reset]:focus,[type=reset]:is([aria-current]:not([aria-current=false])):focus,[type=submit]:focus,[type=submit]:is([aria-current]:not([aria-current=false])):focus,button:focus,button:is([aria-current]:not([aria-current=false])):focus{--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0)),0 0 0 var(--pico-outline-width) var(--pico-primary-focus)}[type=button],[type=reset],[type=submit]{margin-bottom:var(--pico-spacing)}:is(button,[type=submit],[type=button],[role=button]).secondary,[type=file]::file-selector-button,[type=reset]{--pico-background-color:var(--pico-secondary-background);--pico-border-color:var(--pico-secondary-border);--pico-color:var(--pico-secondary-inverse);cursor:pointer}:is(button,[type=submit],[type=button],[role=button]).secondary:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[type=file]::file-selector-button:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[type=reset]:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-background-color:var(--pico-secondary-hover-background);--pico-border-color:var(--pico-secondary-hover-border);--pico-color:var(--pico-secondary-inverse)}:is(button,[type=submit],[type=button],[role=button]).secondary:focus,:is(button,[type=submit],[type=button],[role=button]).secondary:is([aria-current]:not([aria-current=false])):focus,[type=file]::file-selector-button:focus,[type=file]::file-selector-button:is([aria-current]:not([aria-current=false])):focus,[type=reset]:focus,[type=reset]:is([aria-current]:not([aria-current=false])):focus{--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0)),0 0 0 var(--pico-outline-width) var(--pico-secondary-focus)}:is(button,[type=submit],[type=button],[role=button]).contrast{--pico-background-color:var(--pico-contrast-background);--pico-border-color:var(--pico-contrast-border);--pico-color:var(--pico-contrast-inverse)}:is(button,[type=submit],[type=button],[role=button]).contrast:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-background-color:var(--pico-contrast-hover-background);--pico-border-color:var(--pico-contrast-hover-border);--pico-color:var(--pico-contrast-inverse)}:is(button,[type=submit],[type=button],[role=button]).contrast:focus,:is(button,[type=submit],[type=button],[role=button]).contrast:is([aria-current]:not([aria-current=false])):focus{--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0)),0 0 0 var(--pico-outline-width) var(--pico-contrast-focus)}:is(button,[type=submit],[type=button],[role=button]).outline,[type=reset].outline{--pico-background-color:transparent;--pico-color:var(--pico-primary);--pico-border-color:var(--pico-primary)}:is(button,[type=submit],[type=button],[role=button]).outline:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[type=reset].outline:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-background-color:transparent;--pico-color:var(--pico-primary-hover);--pico-border-color:var(--pico-primary-hover)}:is(button,[type=submit],[type=button],[role=button]).outline.secondary,[type=reset].outline{--pico-color:var(--pico-secondary);--pico-border-color:var(--pico-secondary)}:is(button,[type=submit],[type=button],[role=button]).outline.secondary:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),[type=reset].outline:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-secondary-hover);--pico-border-color:var(--pico-secondary-hover)}:is(button,[type=submit],[type=button],[role=button]).outline.contrast{--pico-color:var(--pico-contrast);--pico-border-color:var(--pico-contrast)}:is(button,[type=submit],[type=button],[role=button]).outline.contrast:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){--pico-color:var(--pico-contrast-hover);--pico-border-color:var(--pico-contrast-hover)}:where(button,[type=submit],[type=reset],[type=button],[role=button])[disabled],:where(fieldset[disabled]) :is(button,[type=submit],[type=button],[type=reset],[role=button]){opacity:.5;pointer-events:none}:where(table){width:100%;border-collapse:collapse;border-spacing:0;text-indent:0}td,th{padding:calc(var(--pico-spacing)/ 2) var(--pico-spacing);border-bottom:var(--pico-border-width) solid var(--pico-table-border-color);background-color:var(--pico-background-color);color:var(--pico-color);font-weight:var(--pico-font-weight);text-align:left;text-align:start}tfoot td,tfoot th{border-top:var(--pico-border-width) solid var(--pico-table-border-color);border-bottom:0}table.striped tbody tr:nth-child(odd) td,table.striped tbody tr:nth-child(odd) th{background-color:var(--pico-table-row-stripped-background-color)}:where(audio,canvas,iframe,img,svg,video){vertical-align:middle}audio,video{display:inline-block}audio:not([controls]){display:none;height:0}:where(iframe){border-style:none}img{max-width:100%;height:auto;border-style:none}:where(svg:not([fill])){fill:currentColor}svg:not(:host),svg:not(:root){overflow:hidden}code,kbd,pre,samp{font-size:.875em;font-family:var(--pico-font-family)}pre code,pre samp{font-size:inherit;font-family:inherit}pre{-ms-overflow-style:scrollbar;overflow:auto}code,kbd,pre,samp{border-radius:var(--pico-border-radius);background:var(--pico-code-background-color);color:var(--pico-code-color);font-weight:var(--pico-font-weight);line-height:initial}code,kbd,samp{display:inline-block;padding:.375rem}pre{display:block;margin-bottom:var(--pico-spacing);overflow-x:auto}pre>code,pre>samp{display:block;padding:var(--pico-spacing);background:0 0;line-height:var(--pico-line-height)}kbd{background-color:var(--pico-code-kbd-background-color);color:var(--pico-code-kbd-color);vertical-align:baseline}figure{display:block;margin:0;padding:0}figure figcaption{padding:calc(var(--pico-spacing) * .5) 0;color:var(--pico-muted-color)}hr{height:0;margin:var(--pico-typography-spacing-vertical) 0;border:0;border-top:1px solid var(--pico-muted-border-color);color:inherit}[hidden],template{display:none!important}canvas{display:inline-block}input,optgroup,select,textarea{margin:0;font-size:1rem;line-height:var(--pico-line-height);font-family:inherit;letter-spacing:inherit}input{overflow:visible}select{text-transform:none}legend{max-width:100%;padding:0;color:inherit;white-space:normal}textarea{overflow:auto}[type=checkbox],[type=radio]{padding:0}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}::-moz-focus-inner{padding:0;border-style:none}:-moz-focusring{outline:0}:-moz-ui-invalid{box-shadow:none}::-ms-expand{display:none}[type=file],[type=range]{padding:0;border-width:0}input:not([type=checkbox],[type=radio],[type=range]){height:calc(1rem * var(--pico-line-height) + var(--pico-form-element-spacing-vertical) * 2 + var(--pico-border-width) * 2)}fieldset{width:100%;margin:0;margin-bottom:var(--pico-spacing);padding:0;border:0}fieldset legend,label{display:block;margin-bottom:calc(var(--pico-spacing) * .375);color:var(--pico-color);font-weight:var(--pico-form-label-font-weight,var(--pico-font-weight))}fieldset legend{margin-bottom:calc(var(--pico-spacing) * .5)}button[type=submit],input:not([type=checkbox],[type=radio]),select,textarea{width:100%}input:not([type=checkbox],[type=radio],[type=range],[type=file]),select,textarea{-webkit-appearance:none;-moz-appearance:none;appearance:none;padding:var(--pico-form-element-spacing-vertical) var(--pico-form-element-spacing-horizontal)}input,select,textarea{--pico-background-color:var(--pico-form-element-background-color);--pico-border-color:var(--pico-form-element-border-color);--pico-color:var(--pico-form-element-color);--pico-box-shadow:none;border:var(--pico-border-width) solid var(--pico-border-color);border-radius:var(--pico-border-radius);outline:0;background-color:var(--pico-background-color);box-shadow:var(--pico-box-shadow);color:var(--pico-color);font-weight:var(--pico-font-weight);transition:background-color var(--pico-transition),border-color var(--pico-transition),color var(--pico-transition),box-shadow var(--pico-transition)}:where(select,textarea):not([readonly]):is(:active,:focus),input:not([type=submit],[type=button],[type=reset],[type=checkbox],[type=radio],[readonly]):is(:active,:focus){--pico-background-color:var(--pico-form-element-active-background-color)}:where(select,textarea):not([readonly]):is(:active,:focus),input:not([type=submit],[type=button],[type=reset],[role=switch],[readonly]):is(:active,:focus){--pico-border-color:var(--pico-form-element-active-border-color)}:where(select,textarea):not([readonly]):focus,input:not([type=submit],[type=button],[type=reset],[type=range],[type=file],[readonly]):focus{--pico-box-shadow:0 0 0 var(--pico-outline-width) var(--pico-form-element-focus-color)}:where(fieldset[disabled]) :is(input:not([type=submit],[type=button],[type=reset]),select,textarea),input:not([type=submit],[type=button],[type=reset])[disabled],label[aria-disabled=true],select[disabled],textarea[disabled]{opacity:var(--pico-form-element-disabled-opacity);pointer-events:none}label[aria-disabled=true] input[disabled]{opacity:1}:where(input,select,textarea):not([type=checkbox],[type=radio],[type=date],[type=datetime-local],[type=month],[type=time],[type=week],[type=range])[aria-invalid]{padding-right:calc(var(--pico-form-element-spacing-horizontal) + 1.5rem)!important;padding-left:var(--pico-form-element-spacing-horizontal);padding-inline-start:var(--pico-form-element-spacing-horizontal)!important;padding-inline-end:calc(var(--pico-form-element-spacing-horizontal) + 1.5rem)!important;background-position:center right .75rem;background-size:1rem auto;background-repeat:no-repeat}:where(input,select,textarea):not([type=checkbox],[type=radio],[type=date],[type=datetime-local],[type=month],[type=time],[type=week],[type=range])[aria-invalid=false]:not(select){background-image:var(--pico-icon-valid)}:where(input,select,textarea):not([type=checkbox],[type=radio],[type=date],[type=datetime-local],[type=month],[type=time],[type=week],[type=range])[aria-invalid=true]:not(select){background-image:var(--pico-icon-invalid)}:where(input,select,textarea)[aria-invalid=false]{--pico-border-color:var(--pico-form-element-valid-border-color)}:where(input,select,textarea)[aria-invalid=false]:is(:active,:focus){--pico-border-color:var(--pico-form-element-valid-active-border-color)!important}:where(input,select,textarea)[aria-invalid=false]:is(:active,:focus):not([type=checkbox],[type=radio]){--pico-box-shadow:0 0 0 var(--pico-outline-width) var(--pico-form-element-valid-focus-color)!important}:where(input,select,textarea)[aria-invalid=true]{--pico-border-color:var(--pico-form-element-invalid-border-color)}:where(input,select,textarea)[aria-invalid=true]:is(:active,:focus){--pico-border-color:var(--pico-form-element-invalid-active-border-color)!important}:where(input,select,textarea)[aria-invalid=true]:is(:active,:focus):not([type=checkbox],[type=radio]){--pico-box-shadow:0 0 0 var(--pico-outline-width) var(--pico-form-element-invalid-focus-color)!important}[dir=rtl] :where(input,select,textarea):not([type=checkbox],[type=radio]):is([aria-invalid],[aria-invalid=true],[aria-invalid=false]){background-position:center left .75rem}input::-webkit-input-placeholder,input::placeholder,select:invalid,textarea::-webkit-input-placeholder,textarea::placeholder{color:var(--pico-form-element-placeholder-color);opacity:1}input:not([type=checkbox],[type=radio]),select,textarea{margin-bottom:var(--pico-spacing)}select::-ms-expand{border:0;background-color:transparent}select:not([multiple],[size]){padding-right:calc(var(--pico-form-element-spacing-horizontal) + 1.5rem);padding-left:var(--pico-form-element-spacing-horizontal);padding-inline-start:var(--pico-form-element-spacing-horizontal);padding-inline-end:calc(var(--pico-form-element-spacing-horizontal) + 1.5rem);background-image:var(--pico-icon-chevron);background-position:center right .75rem;background-size:1rem auto;background-repeat:no-repeat}select[multiple] option:checked{background:var(--pico-form-element-selected-background-color);color:var(--pico-form-element-color)}[dir=rtl] select:not([multiple],[size]){background-position:center left .75rem}textarea{display:block;resize:vertical}textarea[aria-invalid]{--pico-icon-height:calc(1rem * var(--pico-line-height) + var(--pico-form-element-spacing-vertical) * 2 + var(--pico-border-width) * 2);background-position:top right .75rem!important;background-size:1rem var(--pico-icon-height)!important}:where(input,select,textarea,fieldset,.grid)+small{display:block;width:100%;margin-top:calc(var(--pico-spacing) * -.75);margin-bottom:var(--pico-spacing);color:var(--pico-muted-color)}:where(input,select,textarea,fieldset,.grid)[aria-invalid=false]+small{color:var(--pico-ins-color)}:where(input,select,textarea,fieldset,.grid)[aria-invalid=true]+small{color:var(--pico-del-color)}label>:where(input,select,textarea){margin-top:calc(var(--pico-spacing) * .25)}label:has([type=checkbox],[type=radio]){width:-moz-fit-content;width:fit-content;cursor:pointer}[type=checkbox],[type=radio]{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:1.25em;height:1.25em;margin-top:-.125em;margin-inline-end:.5em;border-width:var(--pico-border-width);vertical-align:middle;cursor:pointer}[type=checkbox]::-ms-check,[type=radio]::-ms-check{display:none}[type=checkbox]:checked,[type=checkbox]:checked:active,[type=checkbox]:checked:focus,[type=radio]:checked,[type=radio]:checked:active,[type=radio]:checked:focus{--pico-background-color:var(--pico-primary-background);--pico-border-color:var(--pico-primary-border);background-image:var(--pico-icon-checkbox);background-position:center;background-size:.75em auto;background-repeat:no-repeat}[type=checkbox]~label,[type=radio]~label{display:inline-block;margin-bottom:0;cursor:pointer}[type=checkbox]~label:not(:last-of-type),[type=radio]~label:not(:last-of-type){margin-inline-end:1em}[type=checkbox]:indeterminate{--pico-background-color:var(--pico-primary-background);--pico-border-color:var(--pico-primary-border);background-image:var(--pico-icon-minus);background-position:center;background-size:.75em auto;background-repeat:no-repeat}[type=radio]{border-radius:50%}[type=radio]:checked,[type=radio]:checked:active,[type=radio]:checked:focus{--pico-background-color:var(--pico-primary-inverse);border-width:.35em;background-image:none}[type=checkbox][role=switch]{--pico-background-color:var(--pico-switch-background-color);--pico-color:var(--pico-switch-color);width:2.25em;height:1.25em;border:var(--pico-border-width) solid var(--pico-border-color);border-radius:1.25em;background-color:var(--pico-background-color);line-height:1.25em}[type=checkbox][role=switch]:not([aria-invalid]){--pico-border-color:var(--pico-switch-background-color)}[type=checkbox][role=switch]:before{display:block;aspect-ratio:1;height:100%;border-radius:50%;background-color:var(--pico-color);box-shadow:var(--pico-switch-thumb-box-shadow);content:"";transition:margin .1s ease-in-out}[type=checkbox][role=switch]:focus{--pico-background-color:var(--pico-switch-background-color);--pico-border-color:var(--pico-switch-background-color)}[type=checkbox][role=switch]:checked{--pico-background-color:var(--pico-switch-checked-background-color);--pico-border-color:var(--pico-switch-checked-background-color);background-image:none}[type=checkbox][role=switch]:checked::before{margin-inline-start:calc(2.25em - 1.25em)}[type=checkbox][role=switch][disabled]{--pico-background-color:var(--pico-border-color)}[type=checkbox][aria-invalid=false]:checked,[type=checkbox][aria-invalid=false]:checked:active,[type=checkbox][aria-invalid=false]:checked:focus,[type=checkbox][role=switch][aria-invalid=false]:checked,[type=checkbox][role=switch][aria-invalid=false]:checked:active,[type=checkbox][role=switch][aria-invalid=false]:checked:focus{--pico-background-color:var(--pico-form-element-valid-border-color)}[type=checkbox]:checked:active[aria-invalid=true],[type=checkbox]:checked:focus[aria-invalid=true],[type=checkbox]:checked[aria-invalid=true],[type=checkbox][role=switch]:checked:active[aria-invalid=true],[type=checkbox][role=switch]:checked:focus[aria-invalid=true],[type=checkbox][role=switch]:checked[aria-invalid=true]{--pico-background-color:var(--pico-form-element-invalid-border-color)}[type=checkbox][aria-invalid=false]:checked,[type=checkbox][aria-invalid=false]:checked:active,[type=checkbox][aria-invalid=false]:checked:focus,[type=checkbox][role=switch][aria-invalid=false]:checked,[type=checkbox][role=switch][aria-invalid=false]:checked:active,[type=checkbox][role=switch][aria-invalid=false]:checked:focus,[type=radio][aria-invalid=false]:checked,[type=radio][aria-invalid=false]:checked:active,[type=radio][aria-invalid=false]:checked:focus{--pico-border-color:var(--pico-form-element-valid-border-color)}[type=checkbox]:checked:active[aria-invalid=true],[type=checkbox]:checked:focus[aria-invalid=true],[type=checkbox]:checked[aria-invalid=true],[type=checkbox][role=switch]:checked:active[aria-invalid=true],[type=checkbox][role=switch]:checked:focus[aria-invalid=true],[type=checkbox][role=switch]:checked[aria-invalid=true],[type=radio]:checked:active[aria-invalid=true],[type=radio]:checked:focus[aria-invalid=true],[type=radio]:checked[aria-invalid=true]{--pico-border-color:var(--pico-form-element-invalid-border-color)}[type=color]::-webkit-color-swatch-wrapper{padding:0}[type=color]::-moz-focus-inner{padding:0}[type=color]::-webkit-color-swatch{border:0;border-radius:calc(var(--pico-border-radius) * .5)}[type=color]::-moz-color-swatch{border:0;border-radius:calc(var(--pico-border-radius) * .5)}input:not([type=checkbox],[type=radio],[type=range],[type=file]):is([type=date],[type=datetime-local],[type=month],[type=time],[type=week]){--pico-icon-position:0.75rem;--pico-icon-width:1rem;padding-right:calc(var(--pico-icon-width) + var(--pico-icon-position));background-image:var(--pico-icon-date);background-position:center right var(--pico-icon-position);background-size:var(--pico-icon-width) auto;background-repeat:no-repeat}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=time]{background-image:var(--pico-icon-time)}[type=date]::-webkit-calendar-picker-indicator,[type=datetime-local]::-webkit-calendar-picker-indicator,[type=month]::-webkit-calendar-picker-indicator,[type=time]::-webkit-calendar-picker-indicator,[type=week]::-webkit-calendar-picker-indicator{width:var(--pico-icon-width);margin-right:calc(var(--pico-icon-width) * -1);margin-left:var(--pico-icon-position);opacity:0}@-moz-document url-prefix(){[type=date],[type=datetime-local],[type=month],[type=time],[type=week]{padding-right:var(--pico-form-element-spacing-horizontal)!important;background-image:none!important}}[dir=rtl] :is([type=date],[type=datetime-local],[type=month],[type=time],[type=week]){text-align:right}[type=file]{--pico-color:var(--pico-muted-color);margin-left:calc(var(--pico-outline-width) * -1);padding:calc(var(--pico-form-element-spacing-vertical) * .5) 0;padding-left:var(--pico-outline-width);border:0;border-radius:0;background:0 0}[type=file]::file-selector-button{margin-right:calc(var(--pico-spacing)/ 2);padding:calc(var(--pico-form-element-spacing-vertical) * .5) var(--pico-form-element-spacing-horizontal)}[type=file]:is(:hover,:active,:focus)::file-selector-button{--pico-background-color:var(--pico-secondary-hover-background);--pico-border-color:var(--pico-secondary-hover-border)}[type=file]:focus::file-selector-button{--pico-box-shadow:var(--pico-button-hover-box-shadow, 0 0 0 rgba(0, 0, 0, 0)),0 0 0 var(--pico-outline-width) var(--pico-secondary-focus)}[type=range]{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;height:1.25rem;background:0 0}[type=range]::-webkit-slider-runnable-track{width:100%;height:.375rem;border-radius:var(--pico-border-radius);background-color:var(--pico-range-border-color);-webkit-transition:background-color var(--pico-transition),box-shadow var(--pico-transition);transition:background-color var(--pico-transition),box-shadow var(--pico-transition)}[type=range]::-moz-range-track{width:100%;height:.375rem;border-radius:var(--pico-border-radius);background-color:var(--pico-range-border-color);-moz-transition:background-color var(--pico-transition),box-shadow var(--pico-transition);transition:background-color var(--pico-transition),box-shadow var(--pico-transition)}[type=range]::-ms-track{width:100%;height:.375rem;border-radius:var(--pico-border-radius);background-color:var(--pico-range-border-color);-ms-transition:background-color var(--pico-transition),box-shadow var(--pico-transition);transition:background-color var(--pico-transition),box-shadow var(--pico-transition)}[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:1.25rem;height:1.25rem;margin-top:-.4375rem;border:2px solid var(--pico-range-thumb-border-color);border-radius:50%;background-color:var(--pico-range-thumb-color);cursor:pointer;-webkit-transition:background-color var(--pico-transition),transform var(--pico-transition);transition:background-color var(--pico-transition),transform var(--pico-transition)}[type=range]::-moz-range-thumb{-webkit-appearance:none;width:1.25rem;height:1.25rem;margin-top:-.4375rem;border:2px solid var(--pico-range-thumb-border-color);border-radius:50%;background-color:var(--pico-range-thumb-color);cursor:pointer;-moz-transition:background-color var(--pico-transition),transform var(--pico-transition);transition:background-color var(--pico-transition),transform var(--pico-transition)}[type=range]::-ms-thumb{-webkit-appearance:none;width:1.25rem;height:1.25rem;margin-top:-.4375rem;border:2px solid var(--pico-range-thumb-border-color);border-radius:50%;background-color:var(--pico-range-thumb-color);cursor:pointer;-ms-transition:background-color var(--pico-transition),transform var(--pico-transition);transition:background-color var(--pico-transition),transform var(--pico-transition)}[type=range]:active,[type=range]:focus-within{--pico-range-border-color:var(--pico-range-active-border-color);--pico-range-thumb-color:var(--pico-range-thumb-active-color)}[type=range]:active::-webkit-slider-thumb{transform:scale(1.25)}[type=range]:active::-moz-range-thumb{transform:scale(1.25)}[type=range]:active::-ms-thumb{transform:scale(1.25)}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=search]{padding-inline-start:calc(var(--pico-form-element-spacing-horizontal) + 1.75rem);background-image:var(--pico-icon-search);background-position:center left calc(var(--pico-form-element-spacing-horizontal) + .125rem);background-size:1rem auto;background-repeat:no-repeat}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=search][aria-invalid]{padding-inline-start:calc(var(--pico-form-element-spacing-horizontal) + 1.75rem)!important;background-position:center left 1.125rem,center right .75rem}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=search][aria-invalid=false]{background-image:var(--pico-icon-search),var(--pico-icon-valid)}input:not([type=checkbox],[type=radio],[type=range],[type=file])[type=search][aria-invalid=true]{background-image:var(--pico-icon-search),var(--pico-icon-invalid)}[dir=rtl] :where(input):not([type=checkbox],[type=radio],[type=range],[type=file])[type=search]{background-position:center right 1.125rem}[dir=rtl] :where(input):not([type=checkbox],[type=radio],[type=range],[type=file])[type=search][aria-invalid]{background-position:center right 1.125rem,center left .75rem}details{display:block;margin-bottom:var(--pico-spacing)}details summary{line-height:1rem;list-style-type:none;cursor:pointer;transition:color var(--pico-transition)}details summary:not([role]){color:var(--pico-accordion-close-summary-color)}details summary::-webkit-details-marker{display:none}details summary::marker{display:none}details summary::-moz-list-bullet{list-style-type:none}details summary::after{display:block;width:1rem;height:1rem;margin-inline-start:calc(var(--pico-spacing,1rem) * .5);float:right;transform:rotate(-90deg);background-image:var(--pico-icon-chevron);background-position:right center;background-size:1rem auto;background-repeat:no-repeat;content:"";transition:transform var(--pico-transition)}details summary:focus{outline:0}details summary:focus:not([role]){color:var(--pico-accordion-active-summary-color)}details summary:focus-visible:not([role]){outline:var(--pico-outline-width) solid var(--pico-primary-focus);outline-offset:calc(var(--pico-spacing,1rem) * 0.5);color:var(--pico-primary)}details summary[role=button]{width:100%;text-align:left}details summary[role=button]::after{height:calc(1rem * var(--pico-line-height,1.5))}details[open]>summary{margin-bottom:var(--pico-spacing)}details[open]>summary:not([role]):not(:focus){color:var(--pico-accordion-open-summary-color)}details[open]>summary::after{transform:rotate(0)}[dir=rtl] details summary{text-align:right}[dir=rtl] details summary::after{float:left;background-position:left center}article{margin-bottom:var(--pico-block-spacing-vertical);padding:var(--pico-block-spacing-vertical) var(--pico-block-spacing-horizontal);border-radius:var(--pico-border-radius);background:var(--pico-card-background-color);box-shadow:var(--pico-card-box-shadow)}article>footer,article>header{margin-right:calc(var(--pico-block-spacing-horizontal) * -1);margin-left:calc(var(--pico-block-spacing-horizontal) * -1);padding:calc(var(--pico-block-spacing-vertical) * .66) var(--pico-block-spacing-horizontal);background-color:var(--pico-card-sectioning-background-color)}article>header{margin-top:calc(var(--pico-block-spacing-vertical) * -1);margin-bottom:var(--pico-block-spacing-vertical);border-bottom:var(--pico-border-width) solid var(--pico-card-border-color);border-top-right-radius:var(--pico-border-radius);border-top-left-radius:var(--pico-border-radius)}article>footer{margin-top:var(--pico-block-spacing-vertical);margin-bottom:calc(var(--pico-block-spacing-vertical) * -1);border-top:var(--pico-border-width) solid var(--pico-card-border-color);border-bottom-right-radius:var(--pico-border-radius);border-bottom-left-radius:var(--pico-border-radius)}details.dropdown{position:relative;border-bottom:none}details.dropdown>a::after,details.dropdown>button::after,details.dropdown>summary::after{display:block;width:1rem;height:calc(1rem * var(--pico-line-height,1.5));margin-inline-start:.25rem;float:right;transform:rotate(0) translateX(.2rem);background-image:var(--pico-icon-chevron);background-position:right center;background-size:1rem auto;background-repeat:no-repeat;content:""}nav details.dropdown{margin-bottom:0}details.dropdown>summary:not([role]){height:calc(1rem * var(--pico-line-height) + var(--pico-form-element-spacing-vertical) * 2 + var(--pico-border-width) * 2);padding:var(--pico-form-element-spacing-vertical) var(--pico-form-element-spacing-horizontal);border:var(--pico-border-width) solid var(--pico-form-element-border-color);border-radius:var(--pico-border-radius);background-color:var(--pico-form-element-background-color);color:var(--pico-form-element-placeholder-color);line-height:inherit;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:background-color var(--pico-transition),border-color var(--pico-transition),color var(--pico-transition),box-shadow var(--pico-transition)}details.dropdown>summary:not([role]):active,details.dropdown>summary:not([role]):focus{border-color:var(--pico-form-element-active-border-color);background-color:var(--pico-form-element-active-background-color)}details.dropdown>summary:not([role]):focus{box-shadow:0 0 0 var(--pico-outline-width) var(--pico-form-element-focus-color)}details.dropdown>summary:not([role]):focus-visible{outline:0}details.dropdown>summary:not([role])[aria-invalid=false]{--pico-form-element-border-color:var(--pico-form-element-valid-border-color);--pico-form-element-active-border-color:var(--pico-form-element-valid-focus-color);--pico-form-element-focus-color:var(--pico-form-element-valid-focus-color)}details.dropdown>summary:not([role])[aria-invalid=true]{--pico-form-element-border-color:var(--pico-form-element-invalid-border-color);--pico-form-element-active-border-color:var(--pico-form-element-invalid-focus-color);--pico-form-element-focus-color:var(--pico-form-element-invalid-focus-color)}nav details.dropdown{display:inline;margin:calc(var(--pico-nav-element-spacing-vertical) * -1) 0}nav details.dropdown>summary::after{transform:rotate(0) translateX(0)}nav details.dropdown>summary:not([role]){height:calc(1rem * var(--pico-line-height) + var(--pico-nav-link-spacing-vertical) * 2);padding:calc(var(--pico-nav-link-spacing-vertical) - var(--pico-border-width) * 2) var(--pico-nav-link-spacing-horizontal)}nav details.dropdown>summary:not([role]):focus-visible{box-shadow:0 0 0 var(--pico-outline-width) var(--pico-primary-focus)}details.dropdown>summary+ul{display:flex;z-index:99;position:absolute;left:0;flex-direction:column;width:100%;min-width:-moz-fit-content;min-width:fit-content;margin:0;margin-top:var(--pico-outline-width);padding:0;border:var(--pico-border-width) solid var(--pico-dropdown-border-color);border-radius:var(--pico-border-radius);background-color:var(--pico-dropdown-background-color);box-shadow:var(--pico-dropdown-box-shadow);color:var(--pico-dropdown-color);white-space:nowrap;opacity:0;transition:opacity var(--pico-transition),transform 0s ease-in-out 1s}details.dropdown>summary+ul[dir=rtl]{right:0;left:auto}details.dropdown>summary+ul li{width:100%;margin-bottom:0;padding:calc(var(--pico-form-element-spacing-vertical) * .5) var(--pico-form-element-spacing-horizontal);list-style:none}details.dropdown>summary+ul li:first-of-type{margin-top:calc(var(--pico-form-element-spacing-vertical) * .5)}details.dropdown>summary+ul li:last-of-type{margin-bottom:calc(var(--pico-form-element-spacing-vertical) * .5)}details.dropdown>summary+ul li a{display:block;margin:calc(var(--pico-form-element-spacing-vertical) * -.5) calc(var(--pico-form-element-spacing-horizontal) * -1);padding:calc(var(--pico-form-element-spacing-vertical) * .5) var(--pico-form-element-spacing-horizontal);overflow:hidden;border-radius:0;color:var(--pico-dropdown-color);text-decoration:none;text-overflow:ellipsis}details.dropdown>summary+ul li a:active,details.dropdown>summary+ul li a:focus,details.dropdown>summary+ul li a:focus-visible,details.dropdown>summary+ul li a:hover,details.dropdown>summary+ul li a[aria-current]:not([aria-current=false]){background-color:var(--pico-dropdown-hover-background-color)}details.dropdown>summary+ul li label{width:100%}details.dropdown>summary+ul li:has(label):hover{background-color:var(--pico-dropdown-hover-background-color)}details.dropdown[open]>summary{margin-bottom:0}details.dropdown[open]>summary+ul{transform:scaleY(1);opacity:1;transition:opacity var(--pico-transition),transform 0s ease-in-out 0s}details.dropdown[open]>summary::before{display:block;z-index:1;position:fixed;width:100vw;height:100vh;inset:0;background:0 0;content:"";cursor:default}label>details.dropdown{margin-top:calc(var(--pico-spacing) * .25)}[role=group],[role=search]{display:inline-flex;position:relative;width:100%;margin-bottom:var(--pico-spacing);border-radius:var(--pico-border-radius);box-shadow:var(--pico-group-box-shadow,0 0 0 transparent);vertical-align:middle;transition:box-shadow var(--pico-transition)}[role=group] input:not([type=checkbox],[type=radio]),[role=group] select,[role=group]>*,[role=search] input:not([type=checkbox],[type=radio]),[role=search] select,[role=search]>*{position:relative;flex:1 1 auto;margin-bottom:0}[role=group] input:not([type=checkbox],[type=radio]):not(:first-child),[role=group] select:not(:first-child),[role=group]>:not(:first-child),[role=search] input:not([type=checkbox],[type=radio]):not(:first-child),[role=search] select:not(:first-child),[role=search]>:not(:first-child){margin-left:0;border-top-left-radius:0;border-bottom-left-radius:0}[role=group] input:not([type=checkbox],[type=radio]):not(:last-child),[role=group] select:not(:last-child),[role=group]>:not(:last-child),[role=search] input:not([type=checkbox],[type=radio]):not(:last-child),[role=search] select:not(:last-child),[role=search]>:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}[role=group] input:not([type=checkbox],[type=radio]):focus,[role=group] select:focus,[role=group]>:focus,[role=search] input:not([type=checkbox],[type=radio]):focus,[role=search] select:focus,[role=search]>:focus{z-index:2}[role=group] [role=button]:not(:first-child),[role=group] [type=button]:not(:first-child),[role=group] [type=reset]:not(:first-child),[role=group] [type=submit]:not(:first-child),[role=group] button:not(:first-child),[role=group] input:not([type=checkbox],[type=radio]):not(:first-child),[role=group] select:not(:first-child),[role=search] [role=button]:not(:first-child),[role=search] [type=button]:not(:first-child),[role=search] [type=reset]:not(:first-child),[role=search] [type=submit]:not(:first-child),[role=search] button:not(:first-child),[role=search] input:not([type=checkbox],[type=radio]):not(:first-child),[role=search] select:not(:first-child){margin-left:calc(var(--pico-border-width) * -1)}[role=group] [role=button],[role=group] [type=button],[role=group] [type=reset],[role=group] [type=submit],[role=group] button,[role=search] [role=button],[role=search] [type=button],[role=search] [type=reset],[role=search] [type=submit],[role=search] button{width:auto}@supports selector(:has(*)){[role=group]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus),[role=search]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus){--pico-group-box-shadow:var(--pico-group-box-shadow-focus-with-button)}[role=group]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus) input:not([type=checkbox],[type=radio]),[role=group]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus) select,[role=search]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus) input:not([type=checkbox],[type=radio]),[role=search]:has(button:focus,[type=submit]:focus,[type=button]:focus,[role=button]:focus) select{border-color:transparent}[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus),[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus){--pico-group-box-shadow:var(--pico-group-box-shadow-focus-with-input)}[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus) [role=button],[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus) [type=button],[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus) [type=submit],[role=group]:has(input:not([type=submit],[type=button]):focus,select:focus) button,[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus) [role=button],[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus) [type=button],[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus) [type=submit],[role=search]:has(input:not([type=submit],[type=button]):focus,select:focus) button{--pico-button-box-shadow:0 0 0 var(--pico-border-width) var(--pico-primary-border);--pico-button-hover-box-shadow:0 0 0 var(--pico-border-width) var(--pico-primary-hover-border)}[role=group] [role=button]:focus,[role=group] [type=button]:focus,[role=group] [type=reset]:focus,[role=group] [type=submit]:focus,[role=group] button:focus,[role=search] [role=button]:focus,[role=search] [type=button]:focus,[role=search] [type=reset]:focus,[role=search] [type=submit]:focus,[role=search] button:focus{box-shadow:none}}[role=search]>:first-child{border-top-left-radius:5rem;border-bottom-left-radius:5rem}[role=search]>:last-child{border-top-right-radius:5rem;border-bottom-right-radius:5rem}[aria-busy=true]:not(input,select,textarea,html,form){white-space:nowrap}[aria-busy=true]:not(input,select,textarea,html,form)::before{display:inline-block;width:1em;height:1em;background-image:var(--pico-icon-loading);background-size:1em auto;background-repeat:no-repeat;content:"";vertical-align:-.125em}[aria-busy=true]:not(input,select,textarea,html,form):not(:empty)::before{margin-inline-end:calc(var(--pico-spacing) * .5)}[aria-busy=true]:not(input,select,textarea,html,form):empty{text-align:center}[role=button][aria-busy=true],[type=button][aria-busy=true],[type=reset][aria-busy=true],[type=submit][aria-busy=true],a[aria-busy=true],button[aria-busy=true]{pointer-events:none}:host,:root{--pico-scrollbar-width:0px}dialog{display:flex;z-index:999;position:fixed;top:0;right:0;bottom:0;left:0;align-items:center;justify-content:center;width:inherit;min-width:100%;height:inherit;min-height:100%;padding:0;border:0;-webkit-backdrop-filter:var(--pico-modal-overlay-backdrop-filter);backdrop-filter:var(--pico-modal-overlay-backdrop-filter);background-color:var(--pico-modal-overlay-background-color);color:var(--pico-color)}dialog>article{width:100%;max-height:calc(100vh - var(--pico-spacing) * 2);margin:var(--pico-spacing);overflow:auto}@media (min-width:576px){dialog>article{max-width:510px}}@media (min-width:768px){dialog>article{max-width:700px}}dialog>article>header>*{margin-bottom:0}dialog>article>header .close,dialog>article>header :is(a,button)[rel=prev]{margin:0;margin-left:var(--pico-spacing);padding:0;float:right}dialog>article>footer{text-align:right}dialog>article>footer [role=button],dialog>article>footer button{margin-bottom:0}dialog>article>footer [role=button]:not(:first-of-type),dialog>article>footer button:not(:first-of-type){margin-left:calc(var(--pico-spacing) * .5)}dialog>article .close,dialog>article :is(a,button)[rel=prev]{display:block;width:1rem;height:1rem;margin-top:calc(var(--pico-spacing) * -1);margin-bottom:var(--pico-spacing);margin-left:auto;border:none;background-image:var(--pico-icon-close);background-position:center;background-size:auto 1rem;background-repeat:no-repeat;background-color:transparent;opacity:.5;transition:opacity var(--pico-transition)}dialog>article .close:is([aria-current]:not([aria-current=false]),:hover,:active,:focus),dialog>article :is(a,button)[rel=prev]:is([aria-current]:not([aria-current=false]),:hover,:active,:focus){opacity:1}dialog:not([open]),dialog[open=false]{display:none}.modal-is-open{padding-right:var(--pico-scrollbar-width,0);overflow:hidden;pointer-events:none;touch-action:none}.modal-is-open dialog{pointer-events:auto;touch-action:auto}:where(.modal-is-opening,.modal-is-closing) dialog,:where(.modal-is-opening,.modal-is-closing) dialog>article{animation-duration:.2s;animation-timing-function:ease-in-out;animation-fill-mode:both}:where(.modal-is-opening,.modal-is-closing) dialog{animation-duration:.8s;animation-name:modal-overlay}:where(.modal-is-opening,.modal-is-closing) dialog>article{animation-delay:.2s;animation-name:modal}.modal-is-closing dialog,.modal-is-closing dialog>article{animation-delay:0s;animation-direction:reverse}@keyframes modal-overlay{from{-webkit-backdrop-filter:none;backdrop-filter:none;background-color:transparent}}@keyframes modal{from{transform:translateY(-100%);opacity:0}}:where(nav li)::before{float:left;content:"​"}nav,nav ul{display:flex}nav{justify-content:space-between;overflow:visible}nav ol,nav ul{align-items:center;margin-bottom:0;padding:0;list-style:none}nav ol:first-of-type,nav ul:first-of-type{margin-left:calc(var(--pico-nav-element-spacing-horizontal) * -1)}nav ol:last-of-type,nav ul:last-of-type{margin-right:calc(var(--pico-nav-element-spacing-horizontal) * -1)}nav li{display:inline-block;margin:0;padding:var(--pico-nav-element-spacing-vertical) var(--pico-nav-element-spacing-horizontal)}nav li :where(a,[role=link]){display:inline-block;margin:calc(var(--pico-nav-link-spacing-vertical) * -1) calc(var(--pico-nav-link-spacing-horizontal) * -1);padding:var(--pico-nav-link-spacing-vertical) var(--pico-nav-link-spacing-horizontal);border-radius:var(--pico-border-radius)}nav li :where(a,[role=link]):not(:hover){text-decoration:none}nav li [role=button],nav li [type=button],nav li button,nav li input:not([type=checkbox],[type=radio],[type=range],[type=file]),nav li select{height:auto;margin-right:inherit;margin-bottom:0;margin-left:inherit;padding:calc(var(--pico-nav-link-spacing-vertical) - var(--pico-border-width) * 2) var(--pico-nav-link-spacing-horizontal)}nav[aria-label=breadcrumb]{align-items:center;justify-content:start}nav[aria-label=breadcrumb] ul li:not(:first-child){margin-inline-start:var(--pico-nav-link-spacing-horizontal)}nav[aria-label=breadcrumb] ul li a{margin:calc(var(--pico-nav-link-spacing-vertical) * -1) 0;margin-inline-start:calc(var(--pico-nav-link-spacing-horizontal) * -1)}nav[aria-label=breadcrumb] ul li:not(:last-child)::after{display:inline-block;position:absolute;width:calc(var(--pico-nav-link-spacing-horizontal) * 4);margin:0 calc(var(--pico-nav-link-spacing-horizontal) * -1);content:var(--pico-nav-breadcrumb-divider);color:var(--pico-muted-color);text-align:center;text-decoration:none;white-space:nowrap}nav[aria-label=breadcrumb] a[aria-current]:not([aria-current=false]){background-color:transparent;color:inherit;text-decoration:none;pointer-events:none}aside li,aside nav,aside ol,aside ul{display:block}aside li{padding:calc(var(--pico-nav-element-spacing-vertical) * .5) var(--pico-nav-element-spacing-horizontal)}aside li a{display:block}aside li [role=button]{margin:inherit}[dir=rtl] nav[aria-label=breadcrumb] ul li:not(:last-child) ::after{content:"\\"}progress{display:inline-block;vertical-align:baseline}progress{-webkit-appearance:none;-moz-appearance:none;display:inline-block;appearance:none;width:100%;height:.5rem;margin-bottom:calc(var(--pico-spacing) * .5);overflow:hidden;border:0;border-radius:var(--pico-border-radius);background-color:var(--pico-progress-background-color);color:var(--pico-progress-color)}progress::-webkit-progress-bar{border-radius:var(--pico-border-radius);background:0 0}progress[value]::-webkit-progress-value{background-color:var(--pico-progress-color);-webkit-transition:inline-size var(--pico-transition);transition:inline-size var(--pico-transition)}progress::-moz-progress-bar{background-color:var(--pico-progress-color)}@media (prefers-reduced-motion:no-preference){progress:indeterminate{background:var(--pico-progress-background-color) linear-gradient(to right,var(--pico-progress-color) 30%,var(--pico-progress-background-color) 30%) top left/150% 150% no-repeat;animation:progress-indeterminate 1s linear infinite}progress:indeterminate[value]::-webkit-progress-value{background-color:transparent}progress:indeterminate::-moz-progress-bar{background-color:transparent}}@media (prefers-reduced-motion:no-preference){[dir=rtl] progress:indeterminate{animation-direction:reverse}}@keyframes progress-indeterminate{0%{background-position:200% 0}100%{background-position:-200% 0}}[data-tooltip]{position:relative}[data-tooltip]:not(a,button,input,[role=button]){border-bottom:1px dotted;text-decoration:none;cursor:help}[data-tooltip]::after,[data-tooltip]::before,[data-tooltip][data-placement=top]::after,[data-tooltip][data-placement=top]::before{display:block;z-index:99;position:absolute;bottom:100%;left:50%;padding:.25rem .5rem;overflow:hidden;transform:translate(-50%,-.25rem);border-radius:var(--pico-border-radius);background:var(--pico-tooltip-background-color);content:attr(data-tooltip);color:var(--pico-tooltip-color);font-style:normal;font-weight:var(--pico-font-weight);font-size:.875rem;text-decoration:none;text-overflow:ellipsis;white-space:nowrap;opacity:0;pointer-events:none}[data-tooltip]::after,[data-tooltip][data-placement=top]::after{padding:0;transform:translate(-50%,0);border-top:.3rem solid;border-right:.3rem solid transparent;border-left:.3rem solid transparent;border-radius:0;background-color:transparent;content:"";color:var(--pico-tooltip-background-color)}[data-tooltip][data-placement=bottom]::after,[data-tooltip][data-placement=bottom]::before{top:100%;bottom:auto;transform:translate(-50%,.25rem)}[data-tooltip][data-placement=bottom]:after{transform:translate(-50%,-.3rem);border:.3rem solid transparent;border-bottom:.3rem solid}[data-tooltip][data-placement=left]::after,[data-tooltip][data-placement=left]::before{top:50%;right:100%;bottom:auto;left:auto;transform:translate(-.25rem,-50%)}[data-tooltip][data-placement=left]:after{transform:translate(.3rem,-50%);border:.3rem solid transparent;border-left:.3rem solid}[data-tooltip][data-placement=right]::after,[data-tooltip][data-placement=right]::before{top:50%;right:auto;bottom:auto;left:100%;transform:translate(.25rem,-50%)}[data-tooltip][data-placement=right]:after{transform:translate(-.3rem,-50%);border:.3rem solid transparent;border-right:.3rem solid}[data-tooltip]:focus::after,[data-tooltip]:focus::before,[data-tooltip]:hover::after,[data-tooltip]:hover::before{opacity:1}@media (hover:hover) and (pointer:fine){[data-tooltip]:focus::after,[data-tooltip]:focus::before,[data-tooltip]:hover::after,[data-tooltip]:hover::before{--pico-tooltip-slide-to:translate(-50%, -0.25rem);transform:translate(-50%,.75rem);animation-duration:.2s;animation-fill-mode:forwards;animation-name:tooltip-slide;opacity:0}[data-tooltip]:focus::after,[data-tooltip]:hover::after{--pico-tooltip-caret-slide-to:translate(-50%, 0rem);transform:translate(-50%,-.25rem);animation-name:tooltip-caret-slide}[data-tooltip][data-placement=bottom]:focus::after,[data-tooltip][data-placement=bottom]:focus::before,[data-tooltip][data-placement=bottom]:hover::after,[data-tooltip][data-placement=bottom]:hover::before{--pico-tooltip-slide-to:translate(-50%, 0.25rem);transform:translate(-50%,-.75rem);animation-name:tooltip-slide}[data-tooltip][data-placement=bottom]:focus::after,[data-tooltip][data-placement=bottom]:hover::after{--pico-tooltip-caret-slide-to:translate(-50%, -0.3rem);transform:translate(-50%,-.5rem);animation-name:tooltip-caret-slide}[data-tooltip][data-placement=left]:focus::after,[data-tooltip][data-placement=left]:focus::before,[data-tooltip][data-placement=left]:hover::after,[data-tooltip][data-placement=left]:hover::before{--pico-tooltip-slide-to:translate(-0.25rem, -50%);transform:translate(.75rem,-50%);animation-name:tooltip-slide}[data-tooltip][data-placement=left]:focus::after,[data-tooltip][data-placement=left]:hover::after{--pico-tooltip-caret-slide-to:translate(0.3rem, -50%);transform:translate(.05rem,-50%);animation-name:tooltip-caret-slide}[data-tooltip][data-placement=right]:focus::after,[data-tooltip][data-placement=right]:focus::before,[data-tooltip][data-placement=right]:hover::after,[data-tooltip][data-placement=right]:hover::before{--pico-tooltip-slide-to:translate(0.25rem, -50%);transform:translate(-.75rem,-50%);animation-name:tooltip-slide}[data-tooltip][data-placement=right]:focus::after,[data-tooltip][data-placement=right]:hover::after{--pico-tooltip-caret-slide-to:translate(-0.3rem, -50%);transform:translate(-.05rem,-50%);animation-name:tooltip-caret-slide}}@keyframes tooltip-slide{to{transform:var(--pico-tooltip-slide-to);opacity:1}}@keyframes tooltip-caret-slide{50%{opacity:0}to{transform:var(--pico-tooltip-caret-slide-to);opacity:1}}[aria-controls]{cursor:pointer}[aria-disabled=true],[disabled]{cursor:not-allowed}[aria-hidden=false][hidden]{display:initial}[aria-hidden=false][hidden]:not(:focus){clip:rect(0,0,0,0);position:absolute}[tabindex],a,area,button,input,label,select,summary,textarea{-ms-touch-action:manipulation}[dir=rtl]{direction:rtl}@media (prefers-reduced-motion:reduce){:not([aria-busy=true]),:not([aria-busy=true])::after,:not([aria-busy=true])::before{background-attachment:initial!important;animation-duration:1ms!important;animation-delay:-1ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important;transition-delay:0s!important;transition-duration:0s!important}} \ No newline at end of file diff --git a/stacks/f1-stream/files/static/index.html b/stacks/f1-stream/files/static/index.html deleted file mode 100644 index 00565e7c..00000000 --- a/stacks/f1-stream/files/static/index.html +++ /dev/null @@ -1,205 +0,0 @@ - - - - - - F1 Streams - - - - - - - - - - - - -
-
- -
-

Streams

-
Live Racing Hub
-
- -
-
- -
-
-
- - - -
-
-
-
- - - -
-
-
- -
- -
-
-

Reddit Links

- -
- - -
- -
-
-
- - - -
-
-
- -
- -
-
-

All Streams

- -
-
-
-
- - - -
- -
-

Stream links are user-submitted and scraped from Reddit. No streams are hosted on this site.

-
- - - -
- - -

Welcome

-

Sign in with your passkey to manage streams

- -
- - -
- -
- - -
- -
- - - - -
-
- - -
- - - - - - - - - - - - - - - diff --git a/stacks/f1-stream/files/static/js/app.js b/stacks/f1-stream/files/static/js/app.js deleted file mode 100644 index def95036..00000000 --- a/stacks/f1-stream/files/static/js/app.js +++ /dev/null @@ -1,121 +0,0 @@ -// Toast notification system -const TOAST_ICONS = { - success: '\u2705', - error: '\u274C', - warning: '\u26A0\uFE0F', - info: '\u2139\uFE0F' -}; - -function showToast(message, type = 'info', duration = 4000) { - const container = document.getElementById('toast-container'); - const toast = document.createElement('div'); - toast.className = `toast ${type}`; - toast.innerHTML = ` - ${TOAST_ICONS[type] || TOAST_ICONS.info} - ${escapeHtml(message)} - - `; - container.appendChild(toast); - - if (duration > 0) { - setTimeout(() => dismissToast(toast), duration); - } -} - -function dismissToast(toast) { - if (!toast || toast.classList.contains('toast-out')) return; - toast.classList.add('toast-out'); - toast.addEventListener('animationend', () => toast.remove()); -} - -// Confirm dialog (replaces window.confirm) -function showConfirm(message) { - return new Promise((resolve) => { - const overlay = document.createElement('div'); - overlay.className = 'confirm-overlay'; - overlay.innerHTML = ` -
-
${escapeHtml(message)}
-
- - -
-
- `; - document.body.appendChild(overlay); - - overlay.querySelector('#confirm-ok').addEventListener('click', () => { - overlay.remove(); - resolve(true); - }); - overlay.querySelector('#confirm-cancel').addEventListener('click', () => { - overlay.remove(); - resolve(false); - }); - overlay.addEventListener('click', (e) => { - if (e.target === overlay) { - overlay.remove(); - resolve(false); - } - }); - }); -} - -// Mobile nav hamburger toggle -function toggleMobileNav() { - const tabs = document.getElementById('tabs'); - tabs.classList.toggle('open'); -} - -// Tab switching -function switchTab(tab) { - closeRedditViewer(); - - document.querySelectorAll('.tab-btn').forEach(b => { - b.classList.toggle('active', b.dataset.tab === tab); - }); - document.querySelectorAll('.tab-content').forEach(c => { - c.classList.toggle('active', c.id === 'content-' + tab); - }); - - // Close mobile nav - document.getElementById('tabs').classList.remove('open'); - - // Load data for the tab - switch (tab) { - case 'streams': - loadPublicStreams(); - break; - case 'reddit': - loadRedditLinks(); - break; - case 'mine': - loadMyStreams(); - break; - case 'admin': - loadAdminStreams(); - break; - } -} - -// Initialize -document.addEventListener('DOMContentLoaded', async () => { - checkAuth(); - await loadPublicStreams(); - - const grid = document.getElementById('stream-grid'); - const badge = document.getElementById('live-badge'); - if (badge && grid && grid.children.length > 0) { - badge.hidden = false; - } -}); - -// Close Reddit viewer on Escape -document.addEventListener('keydown', (e) => { - if (e.key === 'Escape') { - const viewer = document.getElementById('reddit-viewer'); - if (viewer && !viewer.classList.contains('hidden')) { - closeRedditViewer(); - } - } -}); diff --git a/stacks/f1-stream/files/static/js/auth.js b/stacks/f1-stream/files/static/js/auth.js deleted file mode 100644 index 70852893..00000000 --- a/stacks/f1-stream/files/static/js/auth.js +++ /dev/null @@ -1,219 +0,0 @@ -// WebAuthn helper: base64url encode/decode -function bufToBase64url(buf) { - const bytes = new Uint8Array(buf); - let str = ''; - for (const b of bytes) str += String.fromCharCode(b); - return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); -} - -function base64urlToBuf(b64) { - const pad = b64.length % 4; - if (pad) b64 += '='.repeat(4 - pad); - const str = atob(b64.replace(/-/g, '+').replace(/_/g, '/')); - const buf = new Uint8Array(str.length); - for (let i = 0; i < str.length; i++) buf[i] = str.charCodeAt(i); - return buf.buffer; -} - -let currentUser = null; - -function showAuthDialog() { - document.getElementById('auth-dialog').showModal(); -} - -function switchAuthTab(tab, evt) { - const btns = document.querySelectorAll('.dialog-tab-btn'); - btns.forEach(b => b.classList.remove('active')); - evt.target.classList.add('active'); - - document.getElementById('auth-login-form').style.display = tab === 'login' ? 'block' : 'none'; - document.getElementById('auth-register-form').style.display = tab === 'register' ? 'block' : 'none'; - document.getElementById('login-error').textContent = ''; - document.getElementById('register-error').textContent = ''; -} - -async function doRegister() { - const username = document.getElementById('register-username').value.trim(); - const errEl = document.getElementById('register-error'); - errEl.textContent = ''; - - if (!username || username.length < 3) { - errEl.textContent = 'Username must be at least 3 characters'; - return; - } - - try { - // Step 1: Begin registration - const beginResp = await fetch('/api/auth/register/begin', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ username }) - }); - - if (!beginResp.ok) { - const err = await beginResp.json(); - errEl.textContent = err.error || 'Registration failed'; - return; - } - - const options = await beginResp.json(); - - // Convert base64url fields to ArrayBuffers - options.publicKey.challenge = base64urlToBuf(options.publicKey.challenge); - options.publicKey.user.id = base64urlToBuf(options.publicKey.user.id); - if (options.publicKey.excludeCredentials) { - options.publicKey.excludeCredentials = options.publicKey.excludeCredentials.map(c => ({ - ...c, - id: base64urlToBuf(c.id) - })); - } - - // Step 2: Create credential via browser - const credential = await navigator.credentials.create(options); - - // Step 3: Finish registration - const attestation = { - id: credential.id, - rawId: bufToBase64url(credential.rawId), - type: credential.type, - response: { - attestationObject: bufToBase64url(credential.response.attestationObject), - clientDataJSON: bufToBase64url(credential.response.clientDataJSON) - } - }; - - const finishResp = await fetch(`/api/auth/register/finish?username=${encodeURIComponent(username)}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(attestation) - }); - - if (!finishResp.ok) { - const err = await finishResp.json(); - errEl.textContent = err.error || 'Registration failed'; - return; - } - - const user = await finishResp.json(); - setLoggedIn(user); - document.getElementById('auth-dialog').close(); - } catch (e) { - console.error('Registration error:', e); - errEl.textContent = e.message || 'Registration failed'; - } -} - -async function doLogin() { - const username = document.getElementById('login-username').value.trim(); - const errEl = document.getElementById('login-error'); - errEl.textContent = ''; - - if (!username) { - errEl.textContent = 'Username required'; - return; - } - - try { - // Step 1: Begin login - const beginResp = await fetch('/api/auth/login/begin', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ username }) - }); - - if (!beginResp.ok) { - const err = await beginResp.json(); - errEl.textContent = err.error || 'Login failed'; - return; - } - - const options = await beginResp.json(); - - // Convert base64url fields - options.publicKey.challenge = base64urlToBuf(options.publicKey.challenge); - if (options.publicKey.allowCredentials) { - options.publicKey.allowCredentials = options.publicKey.allowCredentials.map(c => ({ - ...c, - id: base64urlToBuf(c.id) - })); - } - - // Step 2: Get assertion via browser - const assertion = await navigator.credentials.get(options); - - // Step 3: Finish login - const assertionData = { - id: assertion.id, - rawId: bufToBase64url(assertion.rawId), - type: assertion.type, - response: { - authenticatorData: bufToBase64url(assertion.response.authenticatorData), - clientDataJSON: bufToBase64url(assertion.response.clientDataJSON), - signature: bufToBase64url(assertion.response.signature), - userHandle: assertion.response.userHandle ? bufToBase64url(assertion.response.userHandle) : '' - } - }; - - const finishResp = await fetch(`/api/auth/login/finish?username=${encodeURIComponent(username)}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(assertionData) - }); - - if (!finishResp.ok) { - const err = await finishResp.json(); - errEl.textContent = err.error || 'Login failed'; - return; - } - - const user = await finishResp.json(); - setLoggedIn(user); - document.getElementById('auth-dialog').close(); - } catch (e) { - console.error('Login error:', e); - errEl.textContent = e.message || 'Login failed'; - } -} - -async function doLogout() { - await fetch('/api/auth/logout', { method: 'POST' }); - setLoggedOut(); -} - -function setLoggedIn(user) { - currentUser = user; - const section = document.getElementById('auth-section'); - section.innerHTML = ` - Hi, ${escapeHtml(user.username)} - - `; - document.getElementById('tab-mine').classList.remove('hidden'); - if (user.is_admin) { - document.getElementById('tab-admin').classList.remove('hidden'); - } -} - -function setLoggedOut() { - currentUser = null; - const section = document.getElementById('auth-section'); - section.innerHTML = ''; - document.getElementById('tab-mine').classList.add('hidden'); - document.getElementById('tab-admin').classList.add('hidden'); - // Switch to streams tab if on a protected tab - const activeTab = document.querySelector('.tab-btn.active'); - if (activeTab && (activeTab.dataset.tab === 'mine' || activeTab.dataset.tab === 'admin')) { - switchTab('streams'); - } -} - -async function checkAuth() { - try { - const resp = await fetch('/api/auth/me'); - if (resp.ok) { - const user = await resp.json(); - setLoggedIn(user); - } - } catch (e) { - // Not logged in - } -} diff --git a/stacks/f1-stream/files/static/js/player.js b/stacks/f1-stream/files/static/js/player.js deleted file mode 100644 index 9fde23bb..00000000 --- a/stacks/f1-stream/files/static/js/player.js +++ /dev/null @@ -1,216 +0,0 @@ -// player.js — Native HLS player management using HLS.js directly - -var _hlsInstance = null; -var _videoElement = null; - -/** - * Fetch player config for a stream from the backend. - * Returns {type: "hls"|"daddylive"|"proxy", hls_url, auth_token, ...} - */ -async function getPlayerConfig(streamId) { - try { - const resp = await fetch('/api/streams/' + streamId + '/player-config'); - if (!resp.ok) return { type: 'proxy' }; - return await resp.json(); - } catch (e) { - console.error('Failed to fetch player config:', e); - return { type: 'proxy' }; - } -} - -/** - * Decode a /hls/{b64} URL back to the original upstream URL. - */ -function decodeHLSURL(proxyURL) { - if (!proxyURL || typeof proxyURL !== 'string') return proxyURL; - var m = proxyURL.match(/\/hls\/([A-Za-z0-9_-]+)/); - if (!m) return proxyURL; - try { - // base64url decode - var b64 = m[1].replace(/-/g, '+').replace(/_/g, '/'); - // pad - while (b64.length % 4 !== 0) b64 += '='; - return atob(b64); - } catch (e) { - return proxyURL; - } -} - -/** - * Create an HLS.js player for a plain HLS stream. - */ -function createHLSPlayer(containerSelector, hlsURL) { - destroyNativePlayer(); - _buildPlayer(containerSelector, hlsURL, {}); -} - -/** - * Create an HLS.js player for DaddyLive streams with auth module integration. - */ -function createDaddyLivePlayer(containerSelector, config) { - destroyNativePlayer(); - - if (config.auth_mod_url) { - _loadAuthModAndPlay(containerSelector, config); - } else { - _buildPlayer(containerSelector, config.hls_url, {}); - } -} - -function _loadAuthModAndPlay(containerSelector, config) { - var script = document.createElement('script'); - script.src = config.auth_mod_url; - script.onload = function () { - _createDaddyLivePlayerWithAuth(containerSelector, config); - }; - script.onerror = function () { - console.warn('Failed to load auth module, falling back to direct HLS'); - _buildPlayer(containerSelector, config.hls_url, {}); - }; - document.head.appendChild(script); -} - -function _createDaddyLivePlayerWithAuth(containerSelector, config) { - var hlsConfig = {}; - - // If EPlayerAuth is available, set up xhr wrapping - if (typeof EPlayerAuth !== 'undefined' && typeof EPlayerAuth.init === 'function') { - try { - EPlayerAuth.init({ - authToken: config.auth_token, - channelKey: config.channel_key, - channelSalt: config.channel_salt, - timestamp: config.timestamp, - serverKey: config.server_key - }); - - if (typeof EPlayerAuth.getXhrSetup === 'function') { - var origSetup = EPlayerAuth.getXhrSetup(); - hlsConfig.xhrSetup = function (xhr, url) { - // Decode the real upstream URL from our /hls/{b64} proxy path - var realURL = decodeHLSURL(url); - - // Create interceptor to capture headers the auth module sets - var captured = {}; - var fakeXHR = { - setRequestHeader: function (k, v) { captured[k] = v; } - }; - - try { - origSetup(fakeXHR, realURL); - } catch (e) { - console.warn('Auth xhrSetup error:', e); - } - - // Re-set captured headers with forwarding prefix - for (var k in captured) { - if (captured.hasOwnProperty(k)) { - xhr.setRequestHeader('X-Hls-Forward-' + k, captured[k]); - } - } - }; - } - } catch (e) { - console.warn('EPlayerAuth init failed:', e); - } - } - - _buildPlayer(containerSelector, config.hls_url, hlsConfig); -} - -/** - * Build an HLS.js player with a