Compare commits

..
3 Commits
Author SHA1 Message Date
kiskaadee b3ca28b8ef journal: record daily log for 2026-09-25
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 9s
2026-09-25 21:26:25 -05:00
kiskaadee a65c29c070 project(magnetflix): promote architecture blueprint and active plans to landing page 2026-09-25 21:24:23 -05:00
kiskaadee 7c4380b757 plan(magnetflix): add cross-browser extension integration plan 2026-09-25 21:23:25 -05:00
3 changed files with 317 additions and 13 deletions

No files matched your search

+157 -13
View File
@@ -5,25 +5,169 @@ tags:
- media
- streaming
- torrent
- web
- grpc
- fastapi
- architecture
---
# 🎬 MagNetFlix
# 🎬 MagNetFlix — System Architecture & Media Pipeline
## 📌 Project Overview
MagNetFlix is an integrated media application designed for exploring, streaming, and indexing media content.
MagNetFlix is an automated, self-hosted media acquisition, verification, and library organization platform. It bridges the gap between web-browsed movie requests (magnet URIs) and structured, verified Jellyfin/Plex media storage through an audited gRPC pipeline behind Authelia SSO.
---
## 🎯 Architecture & Components
- **Frontend / Client**: Web UI for browsing media catalog, managing queues, and playback.
- **Backend Services**: API layer, scrapers/indexers, metadata fetchers (TMDB/OMDb), and torrent client bridge.
- **Data Persistence**: Database storage for library states, watch progress, and torrent sessions.
## 🏛️ System Topology & Architecture
When managing a self-hosted media library, manual acquisition requires downloading torrents, monitoring progress, manually weeding out garbage/malicious scripts (`.exe`, `.bat`), and renaming folders to match IMDb/TMDB conventions. In multi-user setups, tracking who requested what and auditing download states is chaotic without a unified log.
MagNetFlix resolves this with an automated end-to-end pipeline:
- **Client Ingestion**: Captures magnet links via a cross-browser extension or web dashboard.
- **FastAPI BFF Gateway**: Manages authentication via Authelia SSO headers, exposes REST/SSE endpoints, and coordinates requests.
- **gRPC Worker Pipeline**: Sandboxed download coordinator utilizing Transmission RPC in an isolated staging scratch disk.
- **Security Sanitizer**: Enforces path traversal checks, file extension whitelists, and largest-file feature film selection while purging malicious scripts.
- **TMDB Metadata Verification**: Validates the IMDb ID against TMDB metadata and matches token similarity with the downloaded torrent payload.
- **Library Relocator**: Formats and places verified video and subtitle files into the canonical Jellyfin/Plex structure.
```mermaid
flowchart TB
subgraph ClientLayer ["Client & Ingestion Layer"]
Ext["MagNetFlix Browser Extension\n(Firefox / Chromium)"]
WebUI["Web Pairing Dashboard\n(FastAPI / Jinja / Tailwind)"]
end
subgraph Edge ["Public Edge (Reverse Proxy & SSO)"]
Traefik["Traefik Reverse Proxy\n(magnetflix.roadtotech.me)"]
Authelia["Authelia SSO\n(Forward Auth)"]
Traefik <-->|Forward Auth| Authelia
end
subgraph CoreServices ["Core Internal Services (Docker Monorepo)"]
BFF["FastAPI BFF Gateway\n(services/bff)"]
Worker["gRPC Pipeline Worker\n(services/worker)"]
DB[("SQLite 3 (WAL Mode)\nAudit & Job State Store")]
Torrent["Transmission Daemon\n(RPC Engine)"]
end
subgraph ProcessingPipeline ["Worker Pipeline Stages"]
Sanitizer["Media Sanitizer\n(Allowlist & Anti-Traversal)"]
TMDB["TMDB Metadata Client\n(Token Overlap Check)"]
StorageMgr["Library Relocator\n(Canonical Renamer)"]
end
subgraph Storage ["Persistent Storage Mounts"]
Staging[("/data/staging/<job_id>\nScratch Disk")]
Library[("/media/movies\nJellyfin / Plex Media Root")]
end
Ext -->|"Redirect / Pair"| Traefik
WebUI -->|HTTP POST| Traefik
Traefik -->|HTTP + Remote-User| BFF
BFF -->|gRPC SubmitDownload| Worker
BFF <-->|gRPC Event Stream (SSE)| Worker
Worker --> DB
Worker -->|RPC| Torrent
Torrent --> Staging
Worker --> Sanitizer
Sanitizer --> Staging
Worker --> TMDB
Worker --> StorageMgr
StorageMgr --> Library
```
### Job State Machine & Lifecycle Rules
The pipeline worker enforces a linear, finite state machine with terminal failure handling and startup crash recovery:
```mermaid
stateDiagram
[*] --> QUEUED: SubmitDownload(magnet, imdb_id)
QUEUED --> DOWNLOADING: Transmission starts transfer
DOWNLOADING --> SCANNING: Download reaches 100%
DOWNLOADING --> FAILED: Torrent error / stalled timeout
SCANNING --> VERIFYING_METADATA: Sanitizer allowlist passes
SCANNING --> FAILED: Disallowed files / no valid video
VERIFYING_METADATA --> ORGANIZING: TMDB metadata matches torrent
VERIFYING_METADATA --> FAILED: Lookup failed / title mismatch
ORGANIZING --> COMPLETED: Relocated & renamed into library
ORGANIZING --> FAILED: Disk full / permission error
COMPLETED --> [*]
FAILED --> [*]
```
#### Key Invariants
1. **Crash & Restart Recovery**: Upon worker startup, all orphaned non-terminal jobs in the SQLite database automatically transition to `FAILED` (`"Worker restarted during execution"`).
2. **Strict Idempotency**: Submissions are rejected if a non-terminal job for the same `imdb_id` is currently in-flight, or if `/media/movies/*[imdbid-{imdb_id}]` already exists in the media library.
3. **Sandbox Scrubbing**: Staging directories (`/data/staging/<job_id>/`) are purged immediately upon reaching `COMPLETED` or `FAILED`.
### Security & Media Sanitizer Specification
The sanitizer strictly guards the file-system boundary before any file is moved to the permanent library:
- **Anti-Traversal**: Blocks symlinks, hardlinks, or relative paths escaping the staging root (`..`).
- **File Allowlist**:
- *Allowed Video*: `.mkv`, `.mp4`, `.avi`, `.webm`
- *Allowed Subtitles*: `.srt`, `.vtt`, `.sub`, `.ass`
- *Forbidden / Immediate Quarantine*: `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.lnk`, `.iso`, `.zip`, `.rar`.
- **Largest File Rule**:
- Files containing `sample` in the filename or under 100 MB are discarded.
- The single largest valid video file is chosen as the primary feature film.
---
## 📋 Roadmaps & Action Items
- [ ] Decouple into a standalone Git repository with isolated Docker build files.
- [ ] Configure GitHub Actions / Gitea Actions to build container images on release.
- [ ] Define declarative Traefik reverse proxy routing (`magnetflix.roadtotech.me`).
- [ ] Implement healthcheck endpoints and integrate with `appctl`.
## 📍 Source Code & Locations
| Component | Location / URL | Description |
| :--- | :--- | :--- |
| **Main Monorepo (Forge)** | [MagNetFlix](https://gitea.roadtotech.me/kiskaadee/MagNetFlix) | Canonical Git repository housing `services/bff`, `services/worker`, and `proto/` |
| **Workstation Path** | `~/Projects/active/MagNetFlix` | Active local monorepo development checkout |
| **Extension PoC (Local)** | `~/Projects/learning/extensions/magnetflix-extension` | Working Firefox/Chromium WebExtension prototype |
| **Production Ingress** | [magnetflix.roadtotech.me](https://magnetflix.roadtotech.me) | Traefik entrypoint with Authelia forward authentication |
---
## 💬 Open Discussions
No open architectural discussions at this time.
---
## 🚧 Work in Progress (Active Plans)
Implementation roadmaps currently in progress (`status: active`) that are actively being executed or scheduled for deployment:
1. 🟡 [**MagNetFlix Cross-Browser Extension Integration**](plans/browser-extension-integration.md) `[Active]`
- Actionable implementation plan for evolving the working proof-of-concept into a production-grade cross-browser extension with web dashboard handoff and Traefik/Authelia SSO integration.
### Phased Roadmap Overview
```mermaid
flowchart LR
M1["Milestone 1\nWorkspace & Protobuf\n(Completed)"] --> M2["Milestone 2\nWorker & Sanitizer Engine\n(Next)"]
M2 --> M3["Milestone 3\nBFF Gateway & Web UI\n(In Planning)"]
M3 --> M4["Milestone 4\nEdge Deployment & SSO\n(In Planning)"]
M4 --> M5["Milestone 5\nProduction Extension\n(PoC Built)"]
```
- **Milestone 2: Worker Engine & Pipeline Modules** *(Next Priority)*: SQLAlchemy 2.0 + SQLite (WAL mode) schema, Transmission RPC client, Media Sanitizer, TMDB token-overlap validation, and media library relocator.
- **Milestone 3: BFF Gateway & Live Dashboard**: FastAPI gateway, Authelia SSO header middleware, Server-Sent Events (SSE) `/api/v1/movies/events`, and pairing dashboard `/pair?magnet=...`.
- **Milestone 4: Edge Deployment & Production Packaging**: Multi-stage Dockerfiles, Docker Compose production stack with Traefik labels and healthchecks.
- **Milestone 5: Production Cross-Browser Extension Rollout**: Extension packaging for Firefox AMO / Chrome Web Store, magnet link redirection, and context menus.
---
## 🛠️ Canonical Guides & Runbooks
No canonical operational runbooks written yet.
---
## 🏛️ Completed Milestones & Resolved Discussions
Archived and foundational documentation for completed milestones:
### Completed Milestones
* 🟢 **Milestone 1: Workspace & Protobuf Contracts** — Hermetic `nix develop` environment, `uv` workspace, `pipeline.proto` definitions with gRPC service contracts, and automated stub generation via `buf.yaml`.
@@ -0,0 +1,105 @@
---
type: plan
status: active
project: magnetflix
tags:
- extension
- firefox
- chrome
- plan
- webextension
---
# 🧲 Plan: MagNetFlix Cross-Browser Extension Integration
An actionable implementation plan for evolving the working proof-of-concept (PoC) into a production-grade cross-browser extension that intercepts magnet links and routes them directly to the self-hosted MagNetFlix platform.
---
## 🎯 Context & Objective
The primary entry point for acquiring media is web browsing (torrent trackers, indexers, public domain archives). Without an extension, the user must copy the magnet link, open the media server dashboard, paste the link, and manually search for the movie ID.
The **MagNetFlix Browser Extension** automates this flow:
1. Intercepts any `magnet:` URI clicked on the web before the browser hands it off to an OS client.
2. Injects a non-blocking confirmation dialog (**"Magnet link captured!"**).
3. Handoffs the captured magnet link to the self-hosted dashboard at `https://magnetflix.<DOMAIN>/pair?magnet=<url>`.
---
## 🔬 Proof of Concept (PoC) Baseline
A fully functional proof of concept has been implemented and tested:
- **Local Repository**: `~/Projects/learning/extensions/magnetflix-extension`
- **Main Forge**: `https://gitea.roadtotech.me/kiskaadee/MagNetFlix`
- **Target Browser**: Firefox (Manifest V2) with full Chromium compatibility.
### What the PoC Achieved
- **Capture-Phase Hooking**: `content.js` captures click events on `a[href^="magnet:"]` via `document.addEventListener('click', ..., true)` and suppresses native protocol hijacking with `e.preventDefault()`.
- **CSS Isolation via Shadow DOM**: The confirmation modal is injected into an isolated Shadow DOM root to prevent host page style bleeding.
- **Dynamic IMDb Search**: `app.js` executes debounced (250ms) character-by-character queries against the IMDb suggestion API, retrieving top 5 matches with posters, titles, years, IMDb IDs, and cast.
- **Fixed State Transition**: Selecting a movie locks both the magnet input and movie selection, rendering the **SEND** button.
- **FastAPI Dispatch**: Dispatches `POST http://localhost:8000/download` with `{ "magnet": "...", "imdbid": "..." }`.
---
## 🚀 Production Evolution Strategy
While the PoC embeds the pairing UI inside an internal extension page (`app.html`), the production architecture will transition to a **hybrid model**:
```mermaid
flowchart TD
subgraph Browser ["Web Browser Context"]
Click["User clicks magnet: link\non any webpage"] --> Hook["content.js hooks click\n& displays Shadow DOM modal"]
Hook -->|"Click 'Continue'"| Choice{"Extension Mode"}
end
subgraph ModeA ["Mode A: Web Dashboard Handoff (Default)"]
Choice -->|"Open Dashboard Tab"| DashURL["https://magnetflix.<DOMAIN>/pair?magnet=..."]
DashURL --> TraefikEdge["Traefik Ingress + Authelia SSO"]
TraefikEdge --> BFFPage["FastAPI BFF /pair Page\n(Full Movie Search UI)"]
BFFPage --> Submit["User selects movie & clicks SEND\n(Direct to BFF with SSO session)"]
end
subgraph ModeB ["Mode B: Standalone / Internal Mode (Self-Contained)"]
Choice -->|"Internal Extension Tab"| LocalApp["app.html (Bundled with Extension)"]
LocalApp --> APICall["POST https://magnetflix.<DOMAIN>/api/v1/downloads\n(Using Stored API Key / Token)"]
end
```
### Key Production Changes
1. **Redirect to Centralized Web Dashboard (`magnetflix.<DOMAIN>`)**:
- Clicking "Continue" opens `https://magnetflix.<DOMAIN>/pair?magnet=${encodeURIComponent(magnet)}`.
- Leverage Authelia SSO session cookies already present in the browser — no need to store sensitive API credentials in extension storage.
2. **Configurable Server URL in Options**:
- Allow user to configure their MagNetFlix base URL (e.g., `https://magnetflix.roadtotech.me` or `http://localhost:8000`).
3. **Manifest V3 / Cross-Browser Packaging**:
- Provide a dual build setup: Manifest V2 for Firefox (or MV3 with event pages) and Manifest V3 for Chromium/Edge.
---
## 📋 Phased Execution Roadmap
### Phase 1: Settings & Configurable Domain
- [ ] Add `options.html` / `options.js` for setting custom server URL:
- Default: `https://magnetflix.roadtotech.me`
- Fallback/Dev: `http://localhost:8000`
- [ ] Store preferences in `browser.storage.sync`.
- [ ] Update `popup.html` to link to settings.
### Phase 2: Web Dashboard Handoff Integration
- [ ] Implement the `/pair` route in `services/bff`:
- Renders the pairing UI currently prototyped in `app.html`.
- Populates magnet field from URL query parameter `?magnet=...`.
- Integrates Authelia authenticated user context directly from `Remote-User` header.
- [ ] Update extension `content.js` to redirect to configured server URL `/pair?magnet=...` instead of internal `app.html`.
### Phase 3: Manifest V3 & Cross-Browser Packaging
- [ ] Convert background script into service worker for Chrome MV3 compliance.
- [ ] Maintain Firefox MV2 / MV3 manifest variant for seamless installation.
- [ ] Set up `web-ext build` packaging script in monorepo or dedicated extension repo.
### Phase 4: Production Polishing & Distribution
- [ ] Add context menu entry: right click on any link -> `"Send Magnet to MagNetFlix"`.
- [ ] Self-host signed `.xpi` on `gitea.roadtotech.me` releases or submit to Firefox Add-ons / Chrome Web Store.
+55
View File
@@ -0,0 +1,55 @@
---
type: journal
project: magnetflix
date: 2026-09-25
tags:
- magnetflix
- curation
- architecture
- extension
- grpc
- fastapi
---
# Daily Journal: 2026-09-25
## Wins
### MagNetFlix Architecture Promotion & Landing Page Overhaul
- Curated and promoted the comprehensive **MagNetFlix** system architecture blueprint into the canonical project landing page at [`projects/magnetflix/README.md`](../../projects/magnetflix/README.md), replacing the outdated stub.
- Codified system topology across five decoupled layers:
- **Client Ingestion**: Firefox/Chromium WebExtension and web pairing dashboard.
- **Public Edge**: Traefik reverse proxy ingress with Authelia ForwardAuth SSO (`magnetflix.roadtotech.me`).
- **Core Services**: FastAPI BFF gateway, gRPC worker pipeline, SQLite 3 (WAL mode) job state store, and Transmission RPC engine.
- **Pipeline Stages**: Security media sanitizer, TMDB metadata token overlap verification, and canonical Jellyfin/Plex library renamer.
- **Storage**: Isolated staging scratch mount (`/data/staging/<job_id>`) and persistent library mount (`/media/movies`).
- Codified the worker finite state machine and crash recovery invariants (startup orphan cleanup transitioning non-terminal jobs to `FAILED`, idempotent deduplication on IMDb ID, and sandbox purging).
### MagNetFlix Cross-Browser Extension Integration Plan
- Promoted and normalized the active implementation roadmap at [`projects/magnetflix/plans/browser-extension-integration.md`](../../projects/magnetflix/plans/browser-extension-integration.md) (`status: active`).
- Defined the transition from the working local PoC (`~/Projects/learning/extensions/magnetflix-extension`) to a hybrid production architecture:
- Mode A (Default): Seamless handoff redirecting intercepted magnet links to the authenticated web dashboard (`https://magnetflix.<DOMAIN>/pair?magnet=...`), reusing active Authelia SSO cookies without storing secrets in the browser extension.
- Mode B (Standalone): Internal extension tab pairing via API credentials.
- Mapped out the 4-phase execution roadmap: configurable server URL settings, web dashboard handoff integration in FastAPI BFF, Manifest V3 / cross-browser packaging, and production distribution.
- Normalized machine-specific file URIs into portable semantic code references across the plan.
### Knowledge Graph Maintenance & Inbox Curation
- Conducted full inbox curation pass, eliminating draft fragmentation and clearing pending files from `inbox/`.
- Executed atomic semantic commits (`plan(magnetflix)` and `project(magnetflix)`).
- Validated vault structure via `python scripts/validate-brain.py` (0 issues across frontmatter, relative links, Mermaid diagrams, Ruff, and Pyright).
---
## Planning & Specifications
- [MagNetFlix Cross-Browser Extension Integration Plan](../../projects/magnetflix/plans/browser-extension-integration.md)
- Production plan for evolving the click-interception PoC into a cross-browser extension with web dashboard handoff and Authelia SSO integration.
- [MagNetFlix Project Landing Page](../../projects/magnetflix/README.md)
- Canonical project landing page documenting full system topology, worker state machine, security sanitizer specs, and active development milestones.
---
## Architecture & Design Decisions
### Web Dashboard Handoff vs. Extension-Side Credentials
Storing API keys or bearer tokens inside browser extension storage increases attack surface and requires token management interfaces. By adopting a web dashboard handoff model (`/pair?magnet=...`), the extension merely intercepts the magnet URI and opens a tab on the user's personal domain. The FastAPI BFF inherits the existing browser Authelia SSO session, authenticates the user transparently via `Remote-User` headers, and preserves credential hygiene.