diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
new file mode 100644
index 0000000..0800e1a
--- /dev/null
+++ b/.github/workflows/docs.yml
@@ -0,0 +1,92 @@
+name: documentation
+
+on:
+ push:
+ paths:
+ - 'docs/**'
+ - 'mkdocs.yml'
+ - 'requirements-docs.*'
+ - 'scripts/docs-*'
+ - '.github/workflows/docs.yml'
+ - 'README.md'
+ - 'Cargo.lock'
+ - 'src/config.rs'
+ - 'src/cli.rs'
+ - 'src/distribution.rs'
+ pull_request:
+ paths:
+ - 'docs/**'
+ - 'mkdocs.yml'
+ - 'requirements-docs.*'
+ - 'scripts/docs-*'
+ - '.github/workflows/docs.yml'
+ - 'README.md'
+ - 'Cargo.lock'
+ - 'src/config.rs'
+ - 'src/cli.rs'
+ - 'src/distribution.rs'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ cache: pip
+ cache-dependency-path: requirements-docs.txt
+ - name: Install locked documentation tools
+ run: python -m pip install -r requirements-docs.txt
+ - name: Install pinned Chromium
+ run: python -m playwright install --with-deps chromium
+ - name: Build and exercise the documentation
+ run: python scripts/docs-check.py
+ - name: Upload the checked site
+ uses: actions/upload-artifact@v4
+ with:
+ name: prrr-documentation
+ path: target/docs-site
+ if-no-files-found: error
+ - name: Upload Pages site
+ if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
+ uses: actions/upload-pages-artifact@v3
+ with:
+ path: target/docs-site
+
+ examples:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: Swatinem/rust-cache@v2
+ - name: Build the real documented CLI
+ run: cargo build --locked --bin prrr
+ - name: Check TOML examples and isolated provisioning workflows
+ run: python scripts/docs-examples-check.py
+
+ deploy:
+ if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
+ needs: [check, examples]
+ runs-on: ubuntu-latest
+ permissions:
+ pages: write
+ id-token: write
+ concurrency:
+ group: github-pages
+ cancel-in-progress: false
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - uses: actions/configure-pages@v5
+ - name: Deploy checked documentation
+ id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/.gitignore b/.gitignore
index 488e94d..741135c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,3 +23,7 @@ prrr-android/local.properties
.terraform/
.terraform.lock.hcl
terraform.tfvars
+
+# Python documentation check caches
+__pycache__/
+*.pyc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e7143d2..d112652 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,11 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
+### Security
+
+- Update the locked rustls dependency from 0.23.45 to 0.23.46, resolving
+ RUSTSEC-2026-0346, RUSTSEC-2026-0347, RUSTSEC-2026-0348, and RUSTSEC-2026-0349.
+
### Changed
- **Split mode no longer asks the tunnel to resolve every name on the host**
@@ -79,6 +84,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
+- Cat-themed MkDocs documentation with 22 illustrated handshake, packet-flow,
+ and routing/recovery chapters, source-checked guides, browser/example checks,
+ and deployment to GitHub Pages. The live README links the canonical site.
+
- `[routing].resources` selective resource routing: config-driven hostnames
resolved to `/32` VPN routes, with `prrr client ... route add|remove|list`
CLI (specs/frds/FRD-resource-routing.md).
diff --git a/Cargo.lock b/Cargo.lock
index cab07aa..2225036 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2505,9 +2505,9 @@ dependencies = [
[[package]]
name = "rustls"
-version = "0.23.45"
+version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
+checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"aws-lc-rs",
"log",
diff --git a/README.md b/README.md
index f65dd94..b61afdd 100644
--- a/README.md
+++ b/README.md
@@ -1,228 +1,101 @@
# prrr
-**Censorship-resistant VPN protocol.**
+
-prrr combines post-quantum cryptography, traffic obfuscation, and pluggable transports (HARP over HTTPS and MASQUE over QUIC) to provide a VPN that is indistinguishable from regular web traffic. It resists deep packet inspection, active probing, and traffic analysis attacks while maintaining high throughput on standard port 443.
+An encrypted VPN tunnel with a hybrid Noise IK + ML-KEM-768 handshake and a choice of HTTPS-based HARP or QUIC-based MASQUE transports. prrr includes Linux routing/recovery, an Android companion, client provisioning, and web administration.
-[](LICENSE)
-[](https://www.rust-lang.org/)
-[](#testing)
+[Documentation](https://mewplane.github.io/prrr/) · [Animated mechanics](https://mewplane.github.io/prrr/explanation/mechanics/) · [Security boundaries](https://mewplane.github.io/prrr/explanation/security/) · [Source](https://github.com/Mewplane/prrr)
----
+## Install
-## Features
+Build the current source with a toolchain compatible with `Cargo.lock`:
-- **Post-Quantum Security** -- Hybrid X25519 + ML-KEM-768 key exchange protects against both classical and quantum attacks.
-- **Traffic Obfuscation** -- TLS fingerprint mimicry (Chrome/Firefox profiles), adaptive padding, and timing jitter make VPN traffic indistinguishable from regular HTTPS.
-- **Active Probing Resistance** -- HMAC-BLAKE2s token authentication with decoy responses prevents server fingerprinting.
-- **HARP Transport** -- Tunnels over HTTPS/WebSocket on TCP port 443, indistinguishable from regular web traffic and resistant to UDP blocking.
-- **MASQUE/QUIC Transport (Default)** -- Alternative transport over HTTP/3 on UDP port 443 for environments where QUIC performs better.
-- **Web Admin Panel** -- Single-page application for server management, client provisioning, and real-time monitoring.
-- **Client Distribution** -- QR codes, shareable URLs, and TOML config export for easy client onboarding.
-- **Diagnostics** -- Built-in `doctor` command checks configuration, keys, connectivity, and system resources.
-- **One-Click Deployment** -- Installation scripts for Ubuntu/Debian/Fedora and a Terraform module for DigitalOcean.
-- **Zero Unsafe Code** -- `#![deny(unsafe_code)]` enforced project-wide.
-
----
-
-## Quick Start
-
-### Server
-
-```bash
-# Option 1: Installation script (Ubuntu/Debian/Fedora)
-curl -fsSL https://install.prrr.dev/server | sudo bash
-
-# Option 2: Build from source
-cargo install --path .
-prrr server --listen 0.0.0.0:443 --server-name vpn.example.com
-```
-
-### Register a Client
-
-```bash
-prrr server --config /etc/prrr/server.toml client add my-laptop
-# Outputs: name, IP address, public key, private key
-# SAVE THE PRIVATE KEY -- it is shown only once.
-
-prrr server --config /etc/prrr/server.toml client export my-laptop > my-laptop.toml
-```
-
-### Client
-
-```bash
-# Save the private key from the "client add" output
-mkdir -p ~/.local/share/prrr/keys
-echo -n "THE_PRIVATE_KEY_BASE64" | base64 -d > ~/.local/share/prrr/keys/client.key
-chmod 600 ~/.local/share/prrr/keys/client.key
-echo -e "\nprivate_key_path = \"$HOME/.local/share/prrr/keys/client.key\"" >> my-laptop.toml
-
-# Import and connect
-prrr client import my-laptop.toml
-sudo $(which prrr) client --config ~/.config/prrr/client.toml
-```
-
-See [Getting Started](docs/getting-started.md) for a complete walkthrough with troubleshooting.
-
----
-
-## Architecture
-
-```text
-Application (IP packets from TUN device)
- |
-TunnelPipeline: TUN <-> encrypt <-> transport
- |
-EncryptedChannel: ChaCha20-Poly1305 + replay protection
- |
- ├── HARP (default): 4-byte frame header + WebSocket/HTTP polling
- │ |
- │ TLS 1.3: indistinguishable from HTTPS
- │ |
- │ TCP/IP: standard port 443 traffic
- │
- └── MASQUE (legacy): HTTP Datagram framing
- |
- QUIC DATAGRAMs: quinn native datagram API
- |
- TLS 1.3 (ALPN=h3): indistinguishable from HTTP/3
- |
- UDP/IP: standard port 443 traffic
-```
-
-### Cryptographic Stack
-
-| Layer | Algorithm | Purpose |
-|-------|-----------|---------|
-| Key Exchange | X25519 + ML-KEM-768 | Hybrid classical + post-quantum |
-| Handshake | Noise IK | Mutual authentication |
-| Packet Encryption | ChaCha20-Poly1305 | AEAD with replay protection |
-| Key Derivation | HKDF-BLAKE2s | Session key derivation |
-| Probing Resistance | HMAC-BLAKE2s | Token-based authentication |
-
-See [Architecture Overview](docs/overview.md) for a detailed breakdown.
-
----
-
-## Documentation
-
-| Document | Description |
-|----------|-------------|
-| [Getting Started](docs/getting-started.md) | Installation, first connection, troubleshooting |
-| [Architecture Overview](docs/overview.md) | System design, concepts, glossary |
-| [Configuration Reference](docs/configuration.md) | All config options with defaults |
-| [CLI Reference](docs/cli.md) | Commands, flags, and usage examples |
-| [REST API Reference](docs/api.md) | Web admin endpoints and authentication |
-| [Cryptography](docs/crypto.md) | Primitives, key derivation, hybrid KEX |
-| [Handshake Protocol](docs/handshake.md) | Noise IK, hybrid handshake flow |
-| [Transport Layer](docs/transport.md) | QUIC, MASQUE framing, encrypted channels |
-| [Obfuscation](docs/obfuscation.md) | TLS mimicry, padding, probe resistance |
-| [Tunneling](docs/tunnel.md) | TUN device abstraction, packet pipeline |
-| [Security](docs/security.md) | Threat model, key zeroization, fuzzing |
-
----
-
-## Building from Source
-
-**Prerequisites:** Rust 1.85+ (edition 2024), Git
-
-```bash
-git clone https://github.com/prrr-vpn/prrr.git
+```sh
+git clone https://github.com/Mewplane/prrr.git
cd prrr
-cargo build --release
+cargo build --locked --release --bin prrr
+target/release/prrr --help
```
-The binary is at `target/release/prrr`.
+Linux clients need TUN support and privileges for socket marks and routing. The documented service uses systemd. Servers need their selected TCP/UDP endpoint, a matching trusted TLS certificate, forwarding, and NAT configured by their administrator.
----
+For a service installation, first [provision a complete client configuration](https://mewplane.github.io/prrr/how-to/provision-client/), then run:
-## Android App
-
-The Prrr Android app is in `prrr-android/`. Building requires the Android NDK and Rust cross-compilation targets.
-
-### Prerequisites
-
-```bash
-# Install Android NDK via SDK Manager or https://developer.android.com/ndk/downloads
-# Install Rust cross-compilation targets
-rustup target add aarch64-linux-android x86_64-linux-android armv7-linux-androideabi i686-linux-android
+```sh
+sudo ./deploy/client/install-client.sh ./my-laptop.toml
+sudo systemctl start prrr-client
```
-### Building
+The service runs `/usr/local/bin/prrr` with `/usr/local/bin/prrr-route`; `cargo install` into `~/.cargo/bin` does not update those paths. See [installation](https://mewplane.github.io/prrr/how-to/install/) for server setup and service updates.
-```bash
-# Full build: compile Rust native library + Gradle APK
-make android-debug
+## Use
-# Install on connected device
-make android-install
+Configure transports explicitly on both ends. An implicit server transport resolves to HARP, while an unqualified client and provisioning fallback use MASQUE. Generated configuration records the selected transport; avoid relying on conflicting defaults.
-# Gradle-only build (skip native rebuild when only editing Kotlin)
-make android-debug-apk
+On a configured server:
-# Release build
-make android-release
+```sh
+umask 077
+sudo prrr server --config /etc/prrr/server.toml \
+ --listen 0.0.0.0:443 --server-name vpn.example.net \
+ client add my-laptop > my-laptop.toml
```
-Set `NDK_HOME` if auto-detection fails:
+Replace the example domain with your real server name. The first output includes the client private key; transfer it privately and save it securely. Later exports do not recover that key.
-```bash
-NDK_HOME=/path/to/ndk make android-debug
-```
+For inspection and diagnostics:
----
+```sh
+prrr client --config /etc/prrr/client.toml doctor
+prrr client --config /etc/prrr/client.toml route list
+sudo prrr server --config /etc/prrr/server.toml client list
+```
-## Testing
+Follow [your first tunnel](https://mewplane.github.io/prrr/tutorials/first-tunnel/) to select a routing policy, verify real packet egress, and disconnect cleanly.
-prrr has 1,000+ tests covering the full protocol stack, including end-to-end data flow tests that verify packets traverse the complete encrypted pipeline across both HARP and MASQUE transports.
+## Documentation
-```bash
-make test # Run all tests
-make lint # Clippy + format check
-make bench # Performance benchmarks
-make shellcheck # Lint installation scripts
-make android-test # Android unit tests
-```
+The [browsable documentation](https://mewplane.github.io/prrr/) uses prrr's cat/key artwork and includes three illustrated walkthroughs with **22 chapters**:
-Coverage targets: 90% for critical paths, 85% overall.
+- **Handshake:** pinned identities, outer transport, Noise IK and ML-KEM exchange, authorization, and directional session keys.
+- **Packets:** TUN capture, counter/ciphertext/tag anatomy, HARP or MASQUE framing, forwarding, replies, and replay rejection.
+- **Routing and recovery:** resource routes, server/LAN bypasses, DNS gating, black-hole detection, backoff, and a fresh session on the same TUN.
----
+Animations support Play/Pause, Previous/Next, chapter seeking, speed selection, keyboard access, reduced motion, mobile portrait layouts, and complete text transcripts.
-## Deployment
+| Need | Guide |
+| --- | --- |
+| Connect one client | [First tunnel tutorial](docs/tutorials/first-tunnel.md) |
+| Set up the components | [Install](docs/how-to/install.md), [provision](docs/how-to/provision-client.md), [Android](docs/how-to/android.md) |
+| Diagnose the path | [Recover a connection](docs/how-to/recover.md) |
+| Look up exact behavior | [CLI](docs/reference/cli.md), [configuration](docs/reference/configuration.md), [protocol](docs/reference/protocol.md), [admin API](docs/reference/api.md) |
+| Understand the boundaries | [Mechanics](docs/explanation/mechanics.md), [security](docs/explanation/security.md), [glossary](docs/reference/glossary.md) |
-### Installation Scripts
+The canonical guides pin their source observations to the inspected revision. Older flat documentation remains in the repository as historical material.
-```bash
-# Server (requires root)
-curl -fsSL https://install.prrr.dev/server | sudo bash -s -- \
- --admin-pass "your-password" \
- --domain vpn.example.com
+## Security expectations
-# Client
-curl -fsSL https://install.prrr.dev/client | bash
-```
+Tunnel encryption does not hide the server address, packet timing, or volume. Browser-like TLS profiles are approximate; HTTPS carriage does not prove indistinguishability from a browser. The VPN server is a trust boundary, and normal application HTTPS remains useful beyond it.
-Supported: Ubuntu 22.04+, Debian 11+, Fedora 38+. See [docs/getting-started.md](docs/getting-started.md).
+Routing and DNS recovery can restore ordinary host egress when the tunnel fails. This is not a kill switch or proof of IPv6 capture. Keep the separate HTTP admin listener private or behind a controlled TLS proxy. Read the [security guide](https://mewplane.github.io/prrr/explanation/security/) before deployment.
-### Terraform (DigitalOcean)
+## Development and contributing
-```bash
-cd deploy/terraform
-cp terraform.tfvars.example terraform.tfvars
-# Edit with your DigitalOcean token and SSH key
-terraform init && terraform apply
+```sh
+make test
+make lint
+make shellcheck
+python3 scripts/docs-examples-check.py
```
-See [deploy/terraform/README.md](deploy/terraform/README.md) for details.
-
----
+See [CONTRIBUTING.md](CONTRIBUTING.md) and [documentation development](docs/contributing/documentation.md). Open an [issue](https://github.com/Mewplane/prrr/issues) with reproduction steps and sanitized diagnostics, or a pull request with the relevant tests. Keep private keys, client TOML, QR credentials, and unreviewed logs out of reports.
-## Contributing
+For Android, `make android-debug` builds the native library and debug app; `make android-debug-apk` builds only the Kotlin app and requires a current native library. See [the Android guide](docs/how-to/android.md).
-Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, coding standards, and the PR process.
+## Maintainers
----
+Maintained by [Mewplane](https://github.com/Mewplane) and contributors.
## License
-prrr is released under the [MIT License](LICENSE).
+[MIT](LICENSE).
diff --git a/docs/assets/prrr.png b/docs/assets/prrr.png
new file mode 100644
index 0000000..46dda06
Binary files /dev/null and b/docs/assets/prrr.png differ
diff --git a/docs/contributing/documentation.md b/docs/contributing/documentation.md
new file mode 100644
index 0000000..0c97503
--- /dev/null
+++ b/docs/contributing/documentation.md
@@ -0,0 +1,53 @@
+# Work on the documentation
+
+The site uses MkDocs Material with prrr's existing pixel cat/key artwork and the black/white/gold application palette. Markdown remains the content source; SVG walkthroughs are original illustrations of the inspected caller paths.
+
+## Preview
+
+```sh
+python3 -m venv target/docs-venv
+target/docs-venv/bin/python -m pip install -r requirements-docs.txt
+target/docs-venv/bin/python -m mkdocs serve --dev-addr 127.0.0.1:8000
+```
+
+Open `http://127.0.0.1:8000`. Fonts, scripts, artwork, animation, and search are served locally; the site does not need an external animation or font service.
+
+## Validate
+
+```sh
+target/docs-venv/bin/python -m playwright install chromium
+target/docs-venv/bin/python scripts/docs-check.py
+cargo build --locked --bin prrr
+target/docs-venv/bin/python scripts/docs-examples-check.py
+```
+
+The browser checker builds strictly and checks local links/anchors, all 22 animation chapters, state semantics, packet movement and pause, keyboard seeking, speed controls, readable portrait layouts, contrast, reduced motion, local search, transcripts without JavaScript, and print output. Linux may require Playwright's browser system dependencies.
+
+The example checker uses a private temporary HOME and custom data/key directories. It exercises the real CLI's provisioning, import, export, route edits, revocation, and sharing state. It does not start a VPN session or change host routes, and generated credentials are deleted rather than printed.
+
+The generated site and browser evidence live under ignored `target/`. The workflow checks pull requests with read-only permissions and deploys checked output from `main` to [GitHub Pages](https://mewplane.github.io/prrr/).
+
+## Keep page types distinct
+
+| Reader need | Location |
+| --- | --- |
+| Learn through a successful connection | `tutorials/` |
+| Install, provision, or recover | `how-to/` |
+| Look up fields, commands, and wire formats | `reference/` |
+| Understand mechanisms and boundaries | `explanation/` |
+
+The structure follows [Diátaxis](https://diataxis.fr/) and the tutorial conventions of the [Good Docs Project](https://thegooddocsproject.dev/). Prose and scene artwork are authored for prrr; package tooling retains its own licenses.
+
+## Keep behavior and animation aligned
+
+Implementation links pin revision `191ebaf`. When a caller path changes, update its prose, storyboard labels, field diagrams, and behavioral checks together. Read active code rather than promoting comments or parsed configuration fields into promises. Rust API reference stays with source comments and `cargo doc`.
+
+The animation engine is in `docs/javascripts/mechanics.js`. Preserve the paused default, keyboard-accessible chapter controls, speed selection, stable focus, hidden-document pause, reduced motion, and full transcripts. Reflow scenes by widget width; do not scale a desktop system map until mobile labels become unreadable. Native SVG fields and directional envelopes should teach actual mechanics.
+
+Keep the existing logo intact. The documentation uses `docs/assets/prrr.png`, copied unchanged from `assets/logo_app.png`. Use the app's dark palette and the artwork's gold accent, with visible focus and readable text contrast.
+
+Older root guides remain available in the [repository docs directory](https://github.com/Mewplane/prrr/tree/main/docs) as historical material. Root-anchored exclusions keep stale overclaims and removed functionality out of the published navigation; canonical pages should link to other canonical pages.
+
+## Contribute
+
+See [CONTRIBUTING.md](https://github.com/Mewplane/prrr/blob/main/CONTRIBUTING.md) for the project workflow. Include reader-facing behavior and relevant validation in a documentation PR. Preserve private keys, configuration credentials, and audit files outside published artifacts.
diff --git a/docs/explanation/mechanics.md b/docs/explanation/mechanics.md
new file mode 100644
index 0000000..d3952f3
--- /dev/null
+++ b/docs/explanation/mechanics.md
@@ -0,0 +1,65 @@
+---
+hide:
+ - toc
+---
+
+# How the tunnel works
+
+There are three separate questions: how the peers establish a session, how an IP packet crosses that session, and how the host chooses and recovers its network path. The walkthroughs keep those boundaries visible.
+
+[Session setup](#establish-a-session) · [Packet round trip](#follow-a-packet-and-its-reply) · [Routing and recovery](#routing-and-recovery)
+
+All illustrated values are examples. The diagrams do not open connections, inspect your network, or generate credentials. Playback starts paused; use chapter buttons to inspect a state, or **Play** and the speed control to follow messages. Reduced motion preserves chapter navigation and stops moving envelopes. Complete transcripts follow each scene.
+
+## Establish a session
+
+
+
+1. **Pinned identities.** The client holds a private Noise identity and the server's known Noise and ML-KEM public keys. The server maintains an authorization registry for client identities. Knowing how to speak the protocol does not make an identity authorized.
+2. **Outer transport.** HARP uses its HTTPS endpoint and HTTP/2, WebSocket, or polling bindings. MASQUE uses the QUIC/datagram path. Both sides must choose compatible transport settings and the client must verify the real server certificate/name.
+3. **Noise message one.** The client encapsulates a secret to the server's ML-KEM-768 key. It includes the 1088-byte KEM ciphertext inside the first Noise IK message payload. The outer transport carries that handshake message.
+4. **Authorize the client.** The server processes the first message, obtains the client's static identity, checks authorization, and decapsulates the KEM payload. Rejection prevents an application tunnel even if an outer connection exists.
+5. **Noise message two.** The server sends the second authenticated Noise message. The client completes the transcript using its pinned responder identity.
+6. **Derive directional keys.** HKDF-SHA256 uses the Noise handshake hash as salt, the ML-KEM shared secret as input, and an identity-bound info string. Its 96-byte output becomes three 32-byte keys. The encrypted packet channel uses the two directional keys; client-send is server-receive.
+7. **Tunnel ready.** The connected client installs its selected routing policy and starts the packet pipeline. A successful handshake establishes session state; successful forwarding still depends on TUN configuration, routes, and the server's network setup.
+
+The actual KDF inputs and literal info prefix are listed in [protocol reference](../reference/protocol.md#hybrid-handshake). This describes the implementation; it is not a substitute for an independent protocol security analysis.
+
+## Follow a packet and its reply
+
+
+
+1. **Application to TUN.** The host routes an application IP packet to the virtual interface when the configured policy selects that destination. Excluded destinations take the ordinary host route.
+2. **Seal the packet.** ChaCha20-Poly1305 encrypts the packet. The inner record contains an 8-byte big-endian absolute counter, ciphertext, and a 16-byte authentication tag. Four zero bytes plus the epoch-local counter form the 12-byte nonce; the encoded absolute counter is also authenticated as additional data.
+3. **Wrap the ciphertext.** HARP adds a 4-byte header before HTTP carriage. MASQUE adds its HTTP Datagram framing with quarter-stream and context IDs. These are alternative carriers of the inner channel, not additional rounds of the hybrid handshake.
+4. **Cross the network.** The outer TLS/QUIC path carries the inner ciphertext. Endpoint addresses, packet sizes, and timing remain observable. TLS termination is a separate trust boundary from inner tunnel decryption.
+5. **Verify and forward.** The server checks replay state and the AEAD tag before passing recovered IP data to the client TUN. Host forwarding and NAT move the packet toward its destination. The VPN server can observe this recovered packet; application-level HTTPS adds its own protection beyond that hop.
+6. **Destination replies.** The return IP packet reaches the server. The server uses the opposite-direction key and its independent counter to protect it for the client.
+7. **Open the return packet.** The client verifies, decrypts, and injects the accepted reply into its TUN device, where the host delivers it to the application.
+8. **Reject a replay.** Duplicate or sufficiently old counters are rejected. The default sliding window tolerates reordering across 2048 counters. Altered ciphertext fails authentication and is not forwarded as a valid IP packet.
+
+The channel's counter field is shown inside the outer carrier. It is not a claim that an ordinary network observer can read that field through outer TLS. See [exact packet and transport framing](../reference/protocol.md).
+
+## Routing and recovery
+
+
+
+1. **Select a policy.** Configure resource destinations, explicit prefixes, or the IPv4 default route. `all_traffic` and the separate `full_tunnel` LAN-exclusion switch have different jobs.
+2. **Route a resource.** Hostnames resolve to IPv4 destinations installed as `/32` routes. A separate refresh task updates them while the packet pump continues running. Initial resolution failure prevents startup; refresh failure does not justify deleting the working route set immediately.
+3. **Preserve bypasses.** Firewall marks keep the tunnel's own transport connection on the host path rather than feeding it into itself. Detected private local-LAN networks are excluded by default; `full_tunnel` can disable that automatic exclusion.
+4. **Gate tunnel DNS.** Independent probes measure configured tunnel resolver paths. Advertise responders while healthy, withdraw stale/unusable tunnel DNS when required, and retain the pinning routes so the measurement still follows the tunnel. Split routing scopes DNS ownership to the selected resources.
+5. **Detect a black hole.** The watchdog looks for repeated outbound progress without inbound progress. An established socket is not proof of working traffic. DNS probes and resource resolution run without blocking the packet pump.
+6. **Back off and reconnect.** On failure, remove tunnel routing, wait with bounded exponential backoff and jitter, and try a new connection/handshake. Ordinary host routes can apply while the tunnel is down. This is availability-oriented fallback, not fail-closed traffic blocking.
+7. **Restore the session.** A successful handshake supplies fresh keys, resets backoff, and installs routes again. The client retains its TUN across reconnects, preserving the interface and assigned client address.
+
+The [recovery guide](../how-to/recover.md) gives diagnostic commands and measured defaults. Do not treat the animation as a complete operating-system routing policy or a promise of IPv6 capture.
+
+## Source trail
+
+These observations are pinned to revision `191ebaf`:
+
+- [Client transport and handshake paths](https://github.com/Mewplane/prrr/blob/191ebaf/src/client.rs)
+- [Hybrid handshake and session keys](https://github.com/Mewplane/prrr/blob/191ebaf/src/handshake/hybrid.rs)
+- [HARP session authorization](https://github.com/Mewplane/prrr/blob/191ebaf/src/web/harp.rs)
+- [Encrypted channel](https://github.com/Mewplane/prrr/blob/191ebaf/src/transport/encrypted_channel.rs)
+- [Routing manager](https://github.com/Mewplane/prrr/blob/191ebaf/src/routing.rs) and [reconnect loop](https://github.com/Mewplane/prrr/blob/191ebaf/src/reconnect.rs)
diff --git a/docs/explanation/security.md b/docs/explanation/security.md
new file mode 100644
index 0000000..3112ce0
--- /dev/null
+++ b/docs/explanation/security.md
@@ -0,0 +1,57 @@
+# Security boundaries
+
+prrr encrypts a tunnel between a client and an operator-controlled server. Its protocol and transport choices address specific threats; they do not establish anonymity, universal censorship resistance, or an indistinguishable browser fingerprint.
+
+## Who can observe what
+
+| Boundary | What remains relevant |
+| --- | --- |
+| Local device | Private configuration, identity keys, process memory, installed binary, and OS route policy. |
+| Network path | Endpoint addresses, timing, volume, packet sizes, and observable transport characteristics. |
+| TLS terminator / relay | Outer transport information; assess where TLS actually terminates in your deployment. |
+| VPN server | Client authorization and recovered IP packets, forwarding metadata, and any unencrypted application traffic. |
+| Destination | The server's egress address and application traffic presented to it. |
+
+Application-level HTTPS is still valuable across and beyond the VPN server. A VPN does not make a compromised endpoint trustworthy.
+
+## Identity, session encryption, and certificates
+
+The inspected client and server paths integrate Noise IK and ML-KEM-768. The registry authorizes a client identity, and the session KDF binds keys to the handshake transcript and static identities. The packet channel uses directional ChaCha20-Poly1305 keys, authenticated counters, and replay tracking. Read [the exact mechanics](mechanics.md), including the KDF inputs, instead of inferring a stronger property from the label “hybrid.”
+
+Certificate verification and pinned protocol identities are separate checks. Use the real server name and a valid chain. `--insecure` disables TLS certificate verification; reserve it for controlled experiments, not the documented deployment path.
+
+Private server keys and client configurations are files. A configuration or QR code containing an inline private key is a credential. Restrict permissions, transfer it through an authenticated channel, and avoid logging it. Secret zeroization on drop reduces some memory lifetime; it does not protect against arbitrary access to a running process or a compromised host.
+
+## Traffic disguise has limits
+
+The TLS mimicry module explicitly describes approximate control over cipher/group ordering and the limitations of stock rustls. Browser profiles do not reproduce every browser extension, fingerprint, HTTP behavior, or traffic distribution. Padding, decoy pages, and HTTP carriage each change observable characteristics; their existence is not evidence that a censor cannot classify or block a deployment.
+
+The source contains probing-resistance and traffic-shaping components. Configuration parsing alone does not prove that every component is enabled on every transport/caller path. This site avoids the older blanket “undetectable” claims.
+
+## Routing is part of the security boundary
+
+Check what your actual OS policy captures. Resource routes select exact IPv4 addresses; full IPv4 routing does not establish IPv6 coverage. Local-LAN exclusions and the server-endpoint bypass intentionally leave paths outside the tunnel.
+
+The reconnect loop withdraws tunnel routes and unhealthy DNS advertisements so the ordinary host path can recover. That behavior is **not a kill switch**. If blocking all untunneled traffic is your requirement, evaluate and test an explicit host firewall policy separately; do not assume reconnect implements it.
+
+## Admin and configuration distribution
+
+The separate web admin listener serves HTTP in its active caller. Keep it loopback/private and use a controlled TLS proxy if exposing administration remotely. Bearer tokens, initial creation responses, QR codes, and configuration-sharing URLs need appropriate access control. HARP's VPN session authorization and the admin JWT are separate mechanisms.
+
+Revoking a registry identity is not the same operation as terminating every already established session. Inspect active sessions and test your operational revocation procedure.
+
+## Client-to-client sharing
+
+Sharing is opt-in and has local state plus server-side pair/registry checks. The current remote-enable verifier uses a keyed BLAKE3 MAC behind a verifier interface. Do not describe that implementation as an Ed25519 verification chain or infer hardware-backed biometric authentication from an interface name.
+
+Built-in Whisper messaging was removed from the inspected source revision. Historical messaging explanations do not describe the current application.
+
+## Source and verification
+
+- [TLS profile limitations](https://github.com/Mewplane/prrr/blob/191ebaf/src/obfuscation/tls_mimicry.rs)
+- [TLS verification](https://github.com/Mewplane/prrr/blob/191ebaf/src/transport/tls.rs)
+- [Admin listener](https://github.com/Mewplane/prrr/blob/191ebaf/src/web/mod.rs) and [authentication](https://github.com/Mewplane/prrr/blob/191ebaf/src/web/auth.rs)
+- [Sharing verifier](https://github.com/Mewplane/prrr/blob/191ebaf/src/sharing.rs)
+- [Routing](https://github.com/Mewplane/prrr/blob/191ebaf/src/routing.rs) and [recovery](https://github.com/Mewplane/prrr/blob/191ebaf/src/reconnect.rs)
+
+Run the project's tests and dependency checks for your selected revision. Passing documentation/browser tests establishes that the guides and illustrations work; it does not constitute a cryptographic audit of the protocol.
diff --git a/docs/how-to/android.md b/docs/how-to/android.md
new file mode 100644
index 0000000..2f81af0
--- /dev/null
+++ b/docs/how-to/android.md
@@ -0,0 +1,26 @@
+# Use the Android companion
+
+The Android app uses the shared Rust mobile library and Android's VPN service. It imports a client configuration and establishes the tunnel on the phone.
+
+## Build
+
+Use the checked-in Gradle wrapper and Android build scripts. Install the Android SDK/NDK and the Rust targets used by the script, then run:
+
+```sh
+make android-debug
+make android-install
+```
+
+`NDK_HOME=/path/to/ndk make android-debug` selects an explicit NDK. `make android-debug-apk` rebuilds only the Kotlin app and requires an already current native library; it is not a substitute for rebuilding changed Rust code.
+
+## Import and connect
+
+Provision a [complete client configuration](provision-client.md). Scan its QR code or use the application's import controls, check the server name and selected transport, and approve Android's VPN permission prompt. Keep the configuration and QR private: they may contain the client's private key.
+
+Confirm traffic reaches the intended server, rather than relying only on the connected indicator. Android routing and background restrictions differ from the Linux systemd service; use the app's diagnostics and status screens for that platform.
+
+## Change or remove an identity
+
+Keep the original credential securely if you need it again. An exported public-only server configuration cannot recreate a lost client private key. Provision a replacement and revoke the old identity when migrating credentials.
+
+Source: [VPN service](https://github.com/Mewplane/prrr/blob/191ebaf/prrr-android/app/src/main/kotlin/com/prrr/vpn/android/vpn/PrrrVpnService.kt), [build targets](https://github.com/Mewplane/prrr/blob/191ebaf/Makefile), [mobile crate](https://github.com/Mewplane/prrr/tree/191ebaf/prrr-mobile).
diff --git a/docs/how-to/install.md b/docs/how-to/install.md
new file mode 100644
index 0000000..0ccadbf
--- /dev/null
+++ b/docs/how-to/install.md
@@ -0,0 +1,76 @@
+# Install prrr
+
+Build the current source, install the components used by the service, and prepare a matching server/client configuration. This guide uses repository scripts rather than assuming an installer domain or published binary exists.
+
+## Requirements
+
+- Linux with `/dev/net/tun`, IP routing tools, and systemd for the documented client service.
+- A Rust toolchain compatible with the committed `Cargo.lock`, Git, a C toolchain, and `pkg-config`.
+- A server whose domain, certificate, permitted port, forwarding, and NAT you administer.
+- Administrative privileges for TUN creation, socket marks, and route changes.
+
+The workspace declares Rust 1.85; resolved dependencies can require a newer compiler. Keep `Cargo.lock` and use a compatible current stable toolchain.
+
+## Build from the real repository
+
+```sh
+git clone https://github.com/Mewplane/prrr.git
+cd prrr
+cargo build --locked --release --bin prrr
+target/release/prrr --help
+```
+
+Use a binary built for your destination's CPU and libc. Copying a build from a newer distribution to an older server can fail before prrr starts.
+
+## Deploy a server
+
+Install the built binary and prepare private state directories:
+
+```sh
+sudo install -m 755 target/release/prrr /usr/local/bin/prrr
+sudo install -d -m 700 /etc/prrr/keys /var/lib/prrr
+```
+
+Create `/etc/prrr/server.toml` from the complete [server example](../reference/configuration.md#server-configuration), replacing the domain and certificate paths. Keep it readable only by the account running the server. Use an already valid certificate for the actual server name and keep client certificate verification enabled.
+
+On the server, enable IPv4 forwarding and arrange your firewall's forwarding/NAT policy for the selected tunnel subnet (`10.66.66.0/24` in the example) through its intended Internet interface. Integrate those rules with the server's existing firewall manager rather than flushing its policy. The server process creates TUN devices; it does not replace the administrator's egress and firewall configuration.
+
+Start the server in the foreground for the first verification:
+
+```sh
+sudo /usr/local/bin/prrr server --config /etc/prrr/server.toml \
+ --listen 0.0.0.0:443 --server-name vpn.example.net
+```
+
+Use your real name and keep another administrator session available. Once the connection and forwarding checks pass, put that same command under your chosen service manager. Select a transport explicitly instead of relying on the differing fallback defaults.
+
+The repository also contains server installer scripts. Some write legacy sections such as `[keys]` and `[database]`, while the current runtime reads `[crypto]` and `[server].data_dir`. This guide uses the current manual configuration instead of treating those generated files as verified setup.
+
+| Transport | Network path | What must be reachable |
+| --- | --- | --- |
+| HARP | HTTPS-based HTTP/2, WebSocket, or polling | The selected TCP endpoint, commonly 443 |
+| MASQUE | QUIC with datagram framing | The selected UDP endpoint, commonly 443 |
+
+Run `prrr server --config /etc/prrr/server.toml doctor` to inspect configuration and dependencies. Keep any web admin listener private; its separate listener is plain HTTP unless TLS is terminated in front of it. See [admin API boundaries](../reference/api.md).
+
+## Install the Linux client
+
+First obtain a [complete client configuration](provision-client.md), then run:
+
+```sh
+sudo ./deploy/client/install-client.sh ./my-laptop.toml
+sudo systemctl start prrr-client
+```
+
+The installed paths are `/usr/local/bin/prrr`, `/usr/local/bin/prrr-route`, `/etc/prrr/client.toml`, and `/etc/systemd/system/prrr-client.service`. The configuration is copied with mode 600.
+
+`make install` and `cargo install --path .` target `~/.cargo/bin`; they do not update the service's executable or routing hook. To update a service installation while preserving its existing configuration:
+
+```sh
+make install-system
+sudo systemctl restart prrr-client
+```
+
+## Verify and undo
+
+Follow [your first connection](../tutorials/first-tunnel.md#4-verify-the-data-plane). Stop the service with `sudo systemctl stop prrr-client` and disable it with `sudo systemctl disable prrr-client` when it should not start at boot. Preserve identity/configuration files until you intentionally revoke or migrate the client.
diff --git a/docs/how-to/provision-client.md b/docs/how-to/provision-client.md
new file mode 100644
index 0000000..e761b26
--- /dev/null
+++ b/docs/how-to/provision-client.md
@@ -0,0 +1,54 @@
+# Provision and revoke a client
+
+Create an identity that the server registry can authorize, transfer its complete configuration, and retain control over its access.
+
+## Create the client once
+
+On the server:
+
+```sh
+umask 077
+sudo prrr server --config /etc/prrr/server.toml \
+ --listen 0.0.0.0:443 --server-name vpn.example.net \
+ client add my-laptop > my-laptop.toml
+```
+
+Use the server's real endpoint and configured transport. The first output includes the client's inline private key and the server's public identity/KEM keys. Treat the entire TOML and any QR code derived from it as credentials.
+
+Add `--qr` to `client add` if you need an SVG QR code for the Android scanner. Keep the generated SVG private and remove transferred copies when they are no longer needed.
+
+## Import or install
+
+For a per-user CLI configuration:
+
+```sh
+umask 077
+prrr client import ./my-laptop.toml
+chmod 600 "$HOME/.config/prrr/client.toml"
+prrr client --config "$HOME/.config/prrr/client.toml" doctor
+```
+
+Import validates the TOML structure and writes the configuration to the user's configuration directory. Applying a restrictive umask and permissions is still appropriate: the configuration can contain an inline private key.
+
+For the system service, use the [client installer](install.md#install-the-linux-client), which copies configuration to `/etc/prrr/client.toml`. On Android, use the scanner/import flow described in [the Android guide](android.md).
+
+## List and export
+
+```sh
+sudo prrr server --config /etc/prrr/server.toml client list
+sudo prrr server --config /etc/prrr/server.toml \
+ --listen 0.0.0.0:443 --server-name vpn.example.net \
+ client export my-laptop --output exported.toml
+```
+
+Export reproduces connection/public configuration without recovering the private key from the initial registration. Preserve the original client credential if you need to move it; otherwise provision a new identity and revoke the old one.
+
+## Revoke
+
+```sh
+sudo prrr server --config /etc/prrr/server.toml client remove my-laptop
+```
+
+Removal marks the registry identity as revoked for authorization. Do not infer that every existing encrypted session has been synchronously terminated: active session management is a separate server/API concern. Verify the registry and active connection state when immediate disconnection matters.
+
+Source: [CLI handlers](https://github.com/Mewplane/prrr/blob/191ebaf/src/cli.rs), [client configuration generator](https://github.com/Mewplane/prrr/blob/191ebaf/src/distribution.rs).
diff --git a/docs/how-to/recover.md b/docs/how-to/recover.md
new file mode 100644
index 0000000..fc8fbe2
--- /dev/null
+++ b/docs/how-to/recover.md
@@ -0,0 +1,55 @@
+# Recover a connection
+
+Diagnose the packet path before changing keys or repeatedly restarting a service. The running process, encrypted session, routes, and DNS advertisement are separate states.
+
+## Start with the deployed executable
+
+```sh
+systemctl cat prrr-client
+/usr/local/bin/prrr --version
+/usr/local/bin/prrr client --config /etc/prrr/client.toml doctor
+journalctl -u prrr-client -n 100
+```
+
+The service runs `/usr/local/bin/prrr`. Rebuilding a different copy in `~/.cargo/bin` does not update it. Use `make install-system` from the intended checkout to deploy the current binary and routing hook.
+
+## Locate the failing boundary
+
+| Observation | Check next |
+| --- | --- |
+| Certificate or server-name failure | Actual DNS name, trusted certificate chain, and transport endpoint; do not make disabling verification a permanent fix. |
+| Session connects but no packets return | TUN address, policy rules, server forwarding/NAT, and MTU. |
+| Only some names fail | Routing mode, resolved resource `/32` routes, and the DNS responder subset. |
+| Route changes disappear | The deployed hook and NetworkManager's handling of `prrr*`. |
+| Reconnect repeats | Transport reachability, authorization, logs, and whether the data plane works after the handshake. |
+
+```sh
+ip -4 addr show prrr0
+ip -4 rule
+ip -4 route show table 51820
+resolvectl status
+```
+
+Use your configured fwmark/table instead of 51820 if you changed it. Inspect `/run/prrr/env` locally when comparing hook state; review identifiers and endpoints before sharing diagnostics.
+
+## Understand automatic recovery
+
+The [routing animation](../explanation/mechanics.md#routing-and-recovery) shows the sequence:
+
+- Outbound progress with no inbound progress for three 5-second checks triggers the black-hole detector; an idle tunnel alone does not trigger it.
+- DNS probes run every 15 seconds, with a 2-second timeout per IPv4 responder. Only responding configured servers are advertised; pinned routes remain so probes still measure the tunnel path.
+- A DNS verdict that is not refreshed expires after a 45-second lease. The host resolver takes over instead of trusting a stale verdict indefinitely.
+- Resource DNS refresh runs independently with a 20-second budget. A stalled lookup must not stop the packet pump or watchdogs.
+- Reconnect uses bounded exponential backoff, negotiates fresh session keys, and reuses the TUN device. Routes are withdrawn while the tunnel is down.
+
+Those intervals are implementation defaults, not a guarantee that every failure is detected within one fixed duration. This behavior favors restoring the host network; it is not a traffic-blocking kill switch.
+
+## Restore the ordinary host path
+
+```sh
+sudo systemctl stop prrr-client
+ip -4 rule
+resolvectl status
+```
+
+Normal teardown runs the routing hook's down action. If a process was killed before cleanup, inspect the actual installed rules and the `do_down` action in `/usr/local/bin/prrr-route` before removing anything. Avoid deleting unrelated rules or resolver configuration.
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..70e1cac
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,64 @@
+---
+hide:
+ - toc
+---
+
+
+

+
+
PRIVATE TUNNELS · PUBLIC INTERNET
+
+# A quieter way through.
+
+Understand the tunnel you run. prrr carries encrypted IP traffic over HTTPS-based HARP or QUIC-based MASQUE, with a hybrid handshake and explicit routing and recovery policies.
+
+[Make your first connection](tutorials/first-tunnel.md){ .md-button .md-button--primary }
+[Watch the mechanics](explanation/mechanics.md){ .md-button }
+
+
+
+
+## Follow one packet
+
+
+
+1. Your application's IP packet reaches the TUN interface.
+2. prrr encrypts it with a directional session key and authenticates its counter.
+3. HARP or MASQUE carries the ciphertext to the server.
+4. The server verifies and decrypts it, then passes the packet to its configured network path.
+5. The reply travels back through the encrypted channel. A duplicate counter is rejected.
+
+These are illustrative sample packets, not your traffic. Playback starts paused; choose **Play** or a chapter. The explanation remains readable without JavaScript.
+
+## Choose your path
+
+
+
+### Get connected
+
+[Install](how-to/install.md), [provision one client](how-to/provision-client.md), then follow [your first tunnel](tutorials/first-tunnel.md).
+
+
+### Understand what happens
+
+Explore [the handshake, encrypted packet path, and recovery](explanation/mechanics.md), then read [the security boundaries](explanation/security.md).
+
+
+### Keep the route working
+
+Diagnose the data plane with [recovery checks](how-to/recover.md); use [configuration](reference/configuration.md) to choose full or resource routing.
+
+
+### Look up the details
+
+Find the [CLI](reference/cli.md), [wire formats](reference/protocol.md), [admin API](reference/api.md), and [glossary](reference/glossary.md).
+
+
+
+## What this protects—and what stays visible
+
+The tunnel encrypts traffic between its client and server. A network observer can still see the endpoint, connection timing, and traffic volume; the server remains a trust boundary. Browser-like TLS settings do not establish indistinguishability from a browser, and reconnecting is not a kill switch. See [security boundaries](explanation/security.md) before deployment.
+
+These pages describe the source at revision [`191ebaf`](https://github.com/Mewplane/prrr/tree/191ebaf). That revision removed built-in Whisper messaging. Earlier flat guides remain in the repository as historical material; this site's navigation uses the new source-checked guides.
+
+[Source](https://github.com/Mewplane/prrr) · [Report a problem](https://github.com/Mewplane/prrr/issues) · [Contribute to the docs](contributing/documentation.md)
diff --git a/docs/javascripts/mechanics.js b/docs/javascripts/mechanics.js
new file mode 100644
index 0000000..c6c8cc2
--- /dev/null
+++ b/docs/javascripts/mechanics.js
@@ -0,0 +1,549 @@
+/* Source-accurate illustrated explainers. No credentials or real network traffic. */
+(() => {
+ "use strict";
+ const NS = "http://www.w3.org/2000/svg";
+ const STEP_MS = 4800;
+ const PORTRAIT_BELOW_PX = 800;
+ let instance = 0;
+
+ const flows = {
+ handshake: {
+ title: "Two messages, a fresh encrypted session", label: "IDENTITY & HYBRID HANDSHAKE",
+ steps: [
+ ["Pinned identities", "The client starts with its Noise private key and the server's Noise and ML-KEM public keys. The server's registry must authorize that client identity.", ["client", "server"], null],
+ ["Outer transport", "HARP establishes HTTPS over TCP, using WebSocket, HTTP/2 streaming, or polling. MASQUE establishes QUIC and HTTP/3 CONNECT-UDP over UDP. Port 443 is the illustrated deployment.", ["client", "server"], "outer"],
+ ["Noise message one", "HybridInitiator encapsulates to the server's ML-KEM-768 public key. It places the KEM ciphertext inside the first Noise IK message payload and sends message one through the outer transport.", ["client", "server"], "message-one"],
+ ["Authorize client", "The server processes Noise message one, decapsulates its KEM payload, and authenticates the revealed Noise static identity against the client registry. A key exchange alone does not grant a tunnel.", ["server"], null],
+ ["Noise message two", "The server returns the second Noise IK message. The client verifies it against the pinned server identity and completes the Noise transcript.", ["server", "client"], "message-two"],
+ ["Derive session keys", "HKDF-SHA256 uses the Noise handshake hash as salt and the ML-KEM shared secret as input. Identity-bound info derives 96 bytes: tx_key, rx_key, and header_key. The packet channel consumes the first two.", ["client", "server"], null],
+ ["Tunnel ready", "The client installs routes after connection and creates an EncryptedChannel from the directional session keys. The server reverses send and receive keys. Application IP packets can now enter the tunnel.", ["client", "server"], "ready"],
+ ],
+ },
+ packets: {
+ title: "Follow one packet there and back", label: "INSIDE THE ENCRYPTED TUNNEL",
+ steps: [
+ ["Application to TUN", "The host's routing policy sends a selected application IP packet to the TUN device. Traffic excluded by that policy follows the host's ordinary routes.", ["application", "tun"], "capture"],
+ ["Seal the packet", "EncryptedChannel seals the IP packet with ChaCha20-Poly1305. Its wire form is an 8-byte big-endian counter, encrypted payload, and a 16-byte authentication tag. The counter is also authenticated as AAD.", ["tun"], null],
+ ["Wrap the ciphertext", "HARP adds a 4-byte version/type/reserved/length header before HTTP carriage. MASQUE wraps the same inner ciphertext in an HTTP Datagram with quarter-stream ID and context ID zero. These are alternative configured transports.", ["tun"], null],
+ ["Cross the network", "The encrypted packet crosses HARP over TCP or MASQUE over UDP. Outer TLS/QUIC protects transport; inner ChaCha20-Poly1305 protects the tunnel payload. Address, timing, and size metadata remain observable.", ["tun", "relay"], "outbound"],
+ ["Verify and forward", "The server checks the receive counter against its replay window and verifies AEAD before writing the recovered IP packet to its client TUN. Host forwarding and NAT then carry it toward the destination.", ["relay", "destination"], "forward"],
+ ["Destination replies", "The destination sends a reply through the server. The server encrypts that return IP packet with the opposite-direction key and an independent counter before transport back to the client.", ["destination", "relay", "tun"], "reply"],
+ ["Open the return packet", "The client checks the return counter and AEAD tag, then writes the accepted IP packet to its TUN device. The host delivers the reply to the application.", ["tun", "application"], "deliver"],
+ ["Reject a replay", "A duplicate counter or a packet older than the 2,048-packet sliding window is rejected. Tampered ciphertext fails AEAD. Rejected traffic does not reach the application's IP path.", ["relay"], "replay"],
+ ],
+ },
+ routing: {
+ title: "Choose a route, survive a broken path", label: "POLICY, DNS & RECOVERY",
+ steps: [
+ ["Select a policy", "Linux routing can select resource destinations, explicit allowed IP prefixes, or all traffic. The route hook applies that policy after connection. Automatic local-LAN exclusions are controlled separately by full_tunnel.", ["policy"], null],
+ ["Route a resource", "Configured resource hostnames resolve to IPv4 addresses installed in the policy table. A background refresher updates those routes while the packet pump keeps running; recent answers are retained for continuity.", ["policy", "tunnel"], "resource"],
+ ["Preserve bypasses", "Transport sockets carry a firewall mark so the server connection uses the host route rather than looping into its own TUN. By default, detected local RFC1918 LAN prefixes are also excluded; full_tunnel disables automatic LAN exclusions.", ["policy", "internet"], "bypass"],
+ ["Gate tunnel DNS", "Independent probes check pinned tunnel resolvers. Only responding resolvers are advertised; when none answer or the verdict expires, the hook withdraws tunnel DNS and retains the host's resolver. This is DNS availability handling, not a kill switch.", ["policy", "tunnel"], "dns"],
+ ["Detect a black hole", "The watchdog compares tunnel traffic counters. Repeated outbound progress without inbound answers triggers reconnection even when the transport reports no socket error. DNS probes and resource refresh do not block the packet pump.", ["tunnel"], null],
+ ["Back off and reconnect", "On failure the client removes tunnel routes, waits with exponential backoff and jitter, and attempts a new connection and hybrid handshake. Host routes apply while tunnel routes are down; this is not fail-closed traffic blocking.", ["tunnel", "internet"], "retry"],
+ ["Restore the session", "A successful connection resets backoff, installs routes again, and starts a packet pipeline with fresh session keys. The existing client TUN persists, so its interface and client IP survive reconnection.", ["policy", "tunnel"], "restored"],
+ ],
+ },
+ };
+
+ function html(tag, className, value) {
+ const node = document.createElement(tag);
+ node.className = className;
+ if (value !== undefined) node.textContent = value;
+ return node;
+ }
+
+ function svg(tag, attrs, parent) {
+ const node = document.createElementNS(NS, tag);
+ for (const [name, value] of Object.entries(attrs || {})) node.setAttribute(name, String(value));
+ if (parent) parent.append(node);
+ return node;
+ }
+
+ function text(parent, x, y, value, className = "", attrs = {}) {
+ const node = svg("text", {x, y, class: className, ...attrs}, parent);
+ node.textContent = value;
+ return node;
+ }
+
+ function rect(parent, x, y, width, height, className, radius = 10, attrs = {}) {
+ return svg("rect", {x, y, width, height, rx: radius, class: className, ...attrs}, parent);
+ }
+
+ function group(parent, x = 0, y = 0, attrs = {}) {
+ return svg("g", {transform: "translate(" + x + " " + y + ")", ...attrs}, parent);
+ }
+
+ function path(parent, d, className, attrs = {}) {
+ return svg("path", {d, class: className, ...attrs}, parent);
+ }
+
+ function icon(parent, kind, x, y, size = 28, className = "") {
+ const node = group(parent, x, y, {class: "sy-icon " + className, transform: "translate(" + x + " " + y + ") scale(" + size / 32 + ")"});
+ const shapes = {
+ terminal: ["M3 5h26v20H3z", "M10 30h12M16 25v5", "M8 11l4 4-4 4m8 0h7"],
+ daemon: ["M5 3h22v10H5zM5 19h22v10H5z", "M9 8h1m5 0h8M9 24h1m5 0h8M16 13v6"],
+ shield: ["M16 2l12 5v9c0 7-12 14-12 14S4 23 4 16V7z", "M10 16l4 4 8-9"],
+ };
+ for (const d of shapes[kind] || []) path(node, d, "sy-icon__stroke");
+ return node;
+ }
+
+ function device(parent, type, box, active) {
+ const node = group(parent, box.x, box.y, {"data-node": type, "data-active": String(active), class: "sy-device"});
+ rect(node, 0, 0, box.w, box.h, "sy-device__body", 12);
+ rect(node, 7, 7, box.w - 14, box.h - 14, "sy-device__screen", 7);
+ svg("circle", {cx: 20, cy: 20, r: 3, class: "sy-dot sy-pink"}, node);
+ svg("circle", {cx: 32, cy: 20, r: 3, class: "sy-dot sy-gold"}, node);
+ svg("circle", {cx: 44, cy: 20, r: 3, class: "sy-dot sy-good"}, node);
+ path(node, "M10 33H" + (box.w - 10), "sy-device__separator");
+ return node;
+ }
+
+ function boundary(parent, x, y, width, height, label) {
+ rect(parent, x, y, width, height, "sy-boundary", 16);
+ text(parent, x + 14, y + 24, label, "sy-svg-kicker");
+ }
+
+ function channel(parent, id, route, label, labelX, labelY, visible, active, marker, number) {
+ const node = svg("g", {"data-channel": id, "data-visible": String(visible), "data-active": String(active), class: "sy-channel"}, parent);
+ const line = path(node, route, "sy-channel__line", {"marker-end": "url(#" + marker + ")"});
+ if (active) line.classList.add("sy-channel__line--active");
+ rect(node, labelX - 12, labelY - 17, Math.min(260, label.length * 8 + 42), 25, "sy-channel__label-bg", 5);
+ text(node, labelX, labelY, number + " " + label, "sy-svg-small");
+ return line;
+ }
+
+ function packet(parent, line, label, compact) {
+ const node = group(parent, 0, 0, {"data-packet": "", class: "sy-mechanics__packet"});
+ const short = compact || line.getTotalLength() < 150;
+ rect(node, short ? -24 : -69, -15, short ? 48 : 138, 30, "sy-packet__body", 6);
+ if (!short) path(node, "M-59-6l10 7 10-7M-59-6v13h20V-6", "sy-packet__envelope");
+ text(node, short ? 0 : 9, 5, label, "sy-packet__text", {"data-message": label, "text-anchor": "middle"});
+ return {node, line};
+ }
+
+
+ function center(parent, x, y, value, kind = "sy-svg-small") {
+ return text(parent, x, y, value, kind, {"text-anchor": "middle"});
+ }
+
+ function actor(parent, id, box, heading, rows, active, kind = "terminal") {
+ const node = device(parent, id, box, active);
+ icon(node, kind, 16, 46, 27, "sy-gold");
+ text(node, 53, 65, heading, "sy-svg-body");
+ const rowGap = rows.length > 1 ? Math.min(28, (box.h - 18 - 98) / (rows.length - 1)) : 28;
+ rows.forEach((row, index) => text(node, 17, 98 + index * rowGap, row, "sy-svg-small" + (index === rows.length - 1 ? " sy-gold" : "")));
+ return node;
+ }
+
+ function message(parent, x, y, width, heading, rows, part = "explanation") {
+ const node = group(parent, x, y, {"data-part": part});
+ rect(node, 0, 0, width, 50 + rows.length * 27, "sy-device__screen", 9);
+ text(node, 16, 28, heading, "sy-svg-kicker");
+ rows.forEach((row, index) => text(node, 16, 58 + index * 27, row, "sy-svg-small"));
+ return node;
+ }
+
+ function connection(parent, id, route, label, x, y, active, marker, number) {
+ return channel(parent, id, route, label, x, y, active, active, marker, number);
+ }
+
+ function handshakeScene(scene, step, compact, flow, marker) {
+ const a = compact ? {x: 54, y: 55, w: 312, h: 190} : {x: 38, y: 68, w: 268, h: 230};
+ const b = compact ? {x: 54, y: 400, w: 312, h: 215} : {x: 654, y: 68, w: 268, h: 230};
+ const focus = flow.steps[step][2];
+ boundary(scene, compact ? 35 : 20, 12, compact ? 350 : 304, compact ? 252 : 306, "CLIENT · LOCAL KEY FILE");
+ boundary(scene, compact ? 35 : 636, compact ? 358 : 12, compact ? 350 : 304, compact ? 275 : 306, "SERVER · LOCAL KEY FILES");
+ const clientRows = [
+ ["Noise private key", "Pinned server Noise key", "Pinned server KEM key"],
+ ["TLS / QUIC negotiation", "Validate server certificate", "Outer channel established"],
+ ["ML-KEM-768 encapsulate", "Noise IK: e, es, s, ss", "Send protected KEM payload"],
+ ["Message one sent", "Waiting for server response", "Identity must be allowed"],
+ ["Read Noise: e, ee, se", "Verify pinned server", "Noise transcript complete"],
+ ["HKDF-SHA256", "tx_key / rx_key", "Directional keys ready"],
+ ["Routes installed", "EncryptedChannel ready", "Application traffic starts"],
+ ];
+ const serverRows = [
+ ["Noise + ML-KEM private keys", "Client identity registry", "Private material stays local"],
+ ["HTTPS or HTTP/3 endpoint", "TLS / QUIC established", "No IP tunnel yet"],
+ ["Read Noise message one", "ML-KEM decapsulation", "Recover client static key"],
+ ["Registry identity lookup", "Authorized client accepted", "Unknown identity rejected"],
+ ["Write Noise message two", "Fresh ephemeral exchange", "Return protected response"],
+ ["Same transcript + KEM secret", "Same identity-bound HKDF", "Reverse tx / rx direction"],
+ ["Per-client TUN pipeline", "AEAD + replay window", "Tunnel ready"],
+ ];
+ actor(scene, "client", a, "prrr client", clientRows[step], focus.includes("client"));
+ actor(scene, "server", b, "prrr server", serverRows[step], focus.includes("server"), "daemon");
+ if (!compact) {
+ icon(scene, "shield", 451, 83, 56, "sy-gold");
+ center(scene, 480, 163, "OUTER CHANNEL", "sy-svg-kicker");
+ center(scene, 480, 188, "TLS / QUIC", "sy-svg-body");
+ center(scene, 480, 270, "Untrusted network", "sy-svg-small sy-muted");
+ }
+ const active = flow.steps[step][3];
+ const reverse = active === "message-two";
+ const route = compact
+ ? reverse ? "M284 400V245" : "M136 245V400"
+ : reverse ? "M654 231H306" : "M306 224H654";
+ const labels = {outer: "Outer transport", "message-one": "Noise message 1", "message-two": "Noise message 2", ready: "Encrypted IP packet"};
+ let moving = null;
+ for (const id of Object.keys(labels)) {
+ const line = connection(scene, id, route, labels[id], compact ? 164 : 373, compact ? 319 : 210, active === id, marker, step + 1);
+ if (active === id) moving = {line, label: id === "message-one" ? "IK1" : id === "message-two" ? "IK2" : id === "ready" ? "IP" : "TLS"};
+ }
+ const x = compact ? 25 : 38;
+ const y = compact ? 658 : 351;
+ const width = compact ? 370 : 884;
+ if (step === 2 || step === 3) {
+ message(scene, x, y, width, "MESSAGE ONE · HYBRID EXCHANGE", compact ? ["Noise_IK_25519_ChaChaPoly_BLAKE2s", "Protected payload: ML-KEM-768 ciphertext", "KEM ciphertext: 1,088 B", "Static identity + fresh ephemeral exchange"] : ["Noise_IK_25519_ChaChaPoly_BLAKE2s · X25519 static + ephemeral exchange", "Noise payload contains the 1,088-byte ML-KEM-768 ciphertext.", "Noise verifies possession of identity keys; the registry separately authorizes the client."], "hybrid");
+ } else if (step === 5 || step === 6) {
+ message(scene, x, y, width, "KEY SCHEDULE · NOT RAW NOISE TRANSPORT", compact ? ["HKDF-SHA256 → 96 bytes", "salt = Noise handshake hash", "input = ML-KEM shared secret", "info binds both static public keys", "tx_key 32 B · rx_key 32 B · header 32 B", "Packet channel uses tx_key and rx_key"] : ["HKDF-SHA256(salt = Noise handshake hash, input = ML-KEM shared secret)", "Info: \"PhantomVPN v1\" + initiator static public key + responder static public key", "96 bytes → tx_key (32 B) · rx_key (32 B) · header_key (32 B)", "EncryptedChannel consumes the directional keys; a derived header key does not imply header encryption."], "key-schedule");
+ } else {
+ message(scene, x, y, width, "TWO LAYERS · DISTINCT JOBS", compact ? ["Outer TLS / QUIC: transport protection", "Inner Noise IK: authenticated key exchange", "ML-KEM-768: hybrid shared-secret input", "Inner AEAD: application IP encryption", "Port 443 shown; endpoints are configurable"] : ["Outer TLS / QUIC protects carriage. Noise IK authenticates the inner key exchange.", "ML-KEM-768 contributes the hybrid secret; ChaCha20-Poly1305 protects IP packets.", "Pinned keys are configured inputs. The animation never reads your files or contacts a server."], "layers");
+ }
+ return moving;
+ }
+
+ function packetAnatomy(scene, x, y, width, compact, step) {
+ const g = group(scene, x, y, {"data-part": "wire-packet"});
+ text(g, 0, 0, "INNER PACKET · CHACHA20-POLY1305", "sy-svg-kicker");
+ const parts = compact ? [
+ [0, 20, width, "counter · 8 B", "nonce", "sy-frame__version"],
+ [0, 66, width, "encrypted IP payload", "ciphertext", "sy-frame__nonce"],
+ [0, 112, width, "tag · 16 B", "tag", "sy-frame__mac"],
+ ] : [
+ [0, 20, width * .23, "counter · 8 B", "nonce", "sy-frame__version"],
+ [width * .23 + 5, 20, width * .5 - 10, "encrypted IP payload", "ciphertext", "sy-frame__nonce"],
+ [width * .73, 20, width * .27, "tag · 16 B", "tag", "sy-frame__mac"],
+ ];
+ for (const [px, py, pw, label, part, kind] of parts) {
+ rect(g, px, py, pw, 38, kind, 5, {"data-part": part});
+ center(g, px + pw / 2, py + 25, label, "sy-svg-body");
+ }
+ const noteY = compact ? 179 : 88;
+ text(g, 0, noteY, step === 7 ? "Replay rejected · duplicate counter 42" : "Example counter: 42 · AAD = 8 counter bytes", "sy-svg-small sy-gold");
+ text(g, 0, noteY + 27, compact ? "Nonce: 4 zero bytes + epoch-local counter" : "AEAD nonce = 4 zero bytes + epoch-local 64-bit counter; counter values here are examples.", "sy-svg-small sy-muted");
+ return g;
+ }
+
+ function transportAnatomy(scene, x, y, width, compact) {
+ const g = group(scene, x, y, {"data-part": "transport"});
+ rect(g, 0, 0, width, compact ? 212 : 131, "sy-device__screen", 9);
+ text(g, 16, 28, compact ? "HARP · 4-BYTE HEADER" : "HARP · 4-BYTE HEADER BEFORE CIPHERTEXT", "sy-svg-kicker");
+ const columns = [["v1 / DATA", "sy-frame__version"], ["zero · 1 B", "sy-frame__nonce"], ["len · 2 B", "sy-frame__mac"]];
+ const unit = (width - 32) / 3;
+ columns.forEach(([label, kind], index) => {
+ rect(g, 16 + index * unit, 42, unit - 4, 33, kind, 4, {"data-part": "harp-header"});
+ center(g, 14 + (index + .5) * unit, 64, label, "sy-svg-small");
+ });
+ const rows = compact ? [
+ "HARP · TCP/443 · outer TLS",
+ "WebSocket / HTTP/2 streaming / polling",
+ "MASQUE · UDP/443 · outer QUIC",
+ "HTTP Datagram: stream ID + context 0",
+ "Visible metadata: address / timing / size",
+ ] : ["HARP · TCP/443 · outer TLS → WebSocket / H2 / polling; MASQUE · UDP/443 · outer QUIC → HTTP Datagrams.", "MASQUE: quarter-stream ID + context 0 + inner ciphertext. Address / timing / size metadata remain visible."];
+ rows.forEach((row, index) => text(g, 16, 101 + index * 25, row, "sy-svg-small"));
+ }
+
+ function packetsScene(scene, step, compact, flow, marker) {
+ const boxes = compact ? {
+ application: {x: 50, y: 45, w: 320, h: 130}, tun: {x: 50, y: 257, w: 320, h: 157},
+ relay: {x: 50, y: 509, w: 320, h: 157}, destination: {x: 50, y: 752, w: 320, h: 130},
+ } : {
+ application: {x: 20, y: 94, w: 184, h: 182}, tun: {x: 265, y: 94, w: 200, h: 182},
+ relay: {x: 542, y: 94, w: 200, h: 182}, destination: {x: 797, y: 94, w: 143, h: 182},
+ };
+ const focus = flow.steps[step][2];
+ boundary(scene, compact ? 31 : 6, compact ? 15 : 50, compact ? 358 : 474, compact ? 417 : 246, "CLIENT HOST · ROUTING + AEAD");
+ actor(scene, "application", boxes.application, compact ? "Application" : "App", compact ? [step >= 6 ? "Reply delivered" : "Selected IP packet"] : ["IP packet", step >= 6 ? "Reply received" : "Route lookup", "Example flow"], focus.includes("application"));
+ actor(scene, "tun", boxes.tun, "Client TUN", compact ? [step === 1 ? "Seal with tx_key" : step >= 6 ? "Open with rx_key" : "EncryptedChannel", "Counter + AEAD tag", "Packet pump"] : ["EncryptedChannel", step >= 6 ? "rx_key → plaintext" : "tx_key → ciphertext", "Independent counters"], focus.includes("tun"), "shield");
+ actor(scene, "relay", boxes.relay, "prrr server", compact ? [step === 7 ? "Replay rejected" : "Check counter + AEAD", "Server TUN → host routing", "IP forwarding / NAT"] : [step === 7 ? "Replay rejected" : "Replay + AEAD checks", "Per-client TUN", "Host forwarding / NAT"], focus.includes("relay"), "daemon");
+ actor(scene, "destination", boxes.destination, compact ? "Destination" : "Website", compact ? [step >= 5 ? "Return IP packet" : "Application endpoint"] : ["Destination", step >= 5 ? "IP reply" : "IP request", "Own TLS if used"], focus.includes("destination"));
+ const specs = compact ? [
+ ["capture", "M170 175V257", "Selected IP", 188, 218, "IP"],
+ ["outbound", "M170 414V509", "Inner ciphertext", 188, 463, "AEAD"],
+ ["forward", "M170 666V752", "Recovered IP", 188, 711, "IP"],
+ ["reply", "M370 587H399V335H370", "Return ciphertext", 183, 463, "RX"],
+ ["deliver", "M50 336H21V110H50", "Accepted reply", 55, 227, "IP"],
+ ["replay", "M170 414V509", "Duplicate counter", 188, 463, "42"],
+ ] : [
+ ["capture", "M204 181H265", "IP", 218, 158, "IP"],
+ ["outbound", "M465 181H542", "Ciphertext", 464, 158, "AEAD"],
+ ["forward", "M742 181H797", "IP", 755, 158, "IP"],
+ ["reply", "M642 276V320H365V276", "Opposite-direction key + counter", 437, 346, "RX"],
+ ["deliver", "M265 241H204", "IP reply", 211, 303, "IP"],
+ ["replay", "M465 181H542", "Replay", 466, 158, "42"],
+ ];
+ let moving = null;
+ if (step === 5) {
+ channel(scene, "destination-reply", compact ? "M210 752V666" : "M797 241H742", "IP reply", compact ? 229 : 751, compact ? 711 : 303, true, false, marker, 1);
+ }
+ for (const [id, route, label, x, y, payload] of specs) {
+ const active = flow.steps[step][3] === id;
+ const line = connection(scene, id, route, label, x, y, active, marker, step + 1);
+ if (active) moving = {line, label: payload};
+ }
+ const x = compact ? 25 : 27;
+ const y = compact ? 924 : 386;
+ const width = compact ? 370 : 906;
+ packetAnatomy(scene, x, y, width, compact, step);
+ const detailY = compact ? 1157 : 526;
+ if (step === 2 || step === 3) {
+ transportAnatomy(scene, x, detailY, width, compact);
+ } else {
+ message(scene, x, detailY, width, step === 7 ? "RECEIVER CHECKS" : "DIRECTION MATTERS", compact ? [step === 7 ? "2,048-packet sliding replay window" : "Client tx_key = server receive key", step === 7 ? "Duplicate / stale counter: drop" : "Server send key = client rx_key", step === 7 ? "Invalid AEAD tag: drop" : "Separate counters in both directions", "Rekey threshold: 2³² packets by default", "The website is outside the inner tunnel"] : [step === 7 ? "Duplicate / stale counter → rejected by the 2,048-packet replay window. Invalid tag → rejected by AEAD." : "The two directions use different keys and counters; server send = client receive.", "Default rekey threshold: 2³² packets. Automatic rekey derives another directional key.", "The prrr server terminates inner tunnel encryption; application TLS, when used, is a separate layer."], "receiver");
+ }
+ return moving;
+ }
+
+ function routingScene(scene, step, compact, flow, marker) {
+ const boxes = compact ? {
+ policy: {x: 50, y: 48, w: 320, h: 213}, tunnel: {x: 50, y: 371, w: 320, h: 185}, internet: {x: 50, y: 677, w: 320, h: 158},
+ } : {
+ policy: {x: 25, y: 58, w: 260, h: 242}, tunnel: {x: 407, y: 58, w: 230, h: 242}, internet: {x: 744, y: 58, w: 190, h: 242},
+ };
+ const focus = flow.steps[step][2];
+ const policyRows = [
+ ["resources: hostname / IPv4", "allowed_ips: explicit prefixes", "all_traffic: full selection", "full_tunnel: LAN bypass off"],
+ ["Resolve resource hostname", "Update policy-table /32 routes", "Refresh without pausing packets", "Retain recent DNS answers"],
+ ["Mark server transport sockets", "Bypass own tunnel", "Local LAN exception by default", "full_tunnel: LAN bypass off"],
+ ["Probe all pinned DNS targets", "No responding tunnel resolver", "Withdraw tunnel DNS", "Host DNS retained"],
+ ["Policy still installed", "Outbound progress observed", "No inbound progress", "Watchdog strikes accumulate"],
+ ["Route hook: down", "Tunnel policy removed", "Host routes apply", "No traffic-blocking kill switch"],
+ ["Route hook: up", "Policy reinstalled", "Resource refresh resumes", "Fresh session keys"],
+ ];
+ const tunnelRows = [
+ ["TUN + encrypted channel", "Configured transport", "Not every packet is selected"],
+ ["Matching resource → TUN", "Encrypted IP packet", "Host routing handles rest"],
+ ["Server socket fwmark", "No recursive tunnel route", "TUN handles selected traffic"],
+ ["DNS health gate closed", "Host DNS retained", "Data pump keeps running"],
+ ["Sent packets ↑", "Inbound answers = 0", "Strike limit → reconnect"],
+ ["Exponential backoff + jitter", "New hybrid handshake", "Same TUN device"],
+ ["Same TUN device", "Same client IP", "Fresh session keys"],
+ ];
+ actor(scene, "policy", boxes.policy, "Linux routing policy", policyRows[step], focus.includes("policy"));
+ actor(scene, "tunnel", boxes.tunnel, "prrr tunnel", tunnelRows[step], focus.includes("tunnel"), "shield");
+ actor(scene, "internet", boxes.internet, compact ? "Host route / internet" : "Host route", compact ? ["Server connection / LAN bypass", step === 5 ? "Host routes apply on failure" : "Ordinary network path"] : ["Server socket", "LAN exception", "Host resolver"], focus.includes("internet"));
+ const specs = compact ? [
+ ["resource", "M160 261V371", "Matched IP → TUN", 180, 322, "IP"],
+ ["bypass", "M370 178H399V756H370", "Server / LAN bypass", 55, 624, "HOST"],
+ ["dns", "M160 371V261", "Withdraw DNS", 180, 322, "DNS"],
+ ["retry", "M160 556V677", "Retry transport", 180, 624, "RETRY"],
+ ["restored", "M160 261V371", "Routes restored", 180, 322, "IP"],
+ ] : [
+ ["resource", "M285 162H407", "Selected IP", 297, 137, "IP"],
+ ["bypass", "M155 58V22H839V58", "Server / LAN bypass", 409, 44, "HOST"],
+ ["dns", "M407 238H285", "Withdraw DNS", 289, 270, "DNS"],
+ ["retry", "M637 162H744", "Reconnect", 640, 137, "RETRY"],
+ ["restored", "M285 162H407", "Routes up", 297, 137, "IP"],
+ ];
+ let moving = null;
+ for (const [id, route, label, x, y, payload] of specs) {
+ const active = flow.steps[step][3] === id;
+ const line = connection(scene, id, route, label, x, y, active, marker, step + 1);
+ if (active) moving = {line, label: payload};
+ }
+ const x = compact ? 25 : 25;
+ const y = compact ? 878 : 345;
+ const width = compact ? 370 : 909;
+ if (step === 3) {
+ message(scene, x, y, width, "DNS HEALTH IS MEASURED SEPARATELY", compact ? ["Probe each pinned tunnel resolver", "Any answer → advertise responding servers", "No answers → withdraw tunnel DNS", "Stale verdict → withdraw tunnel DNS", "Keep the host resolver available", "Recovery reopens the gate", "DNS gate is not a privacy kill switch"] : ["One silent DNS target does not suppress another responding resolver.", "No answers, an expired verdict, or a dead prober withdraws tunnel DNS advertisement.", "Host DNS remains available; a later healthy verdict can reopen the gate.", "This protects DNS availability. It does not promise fail-closed traffic or DNS-leak prevention."], "dns-gate");
+ } else if (step >= 4) {
+ message(scene, x, y, width, "RECOVERY STATE MACHINE", compact ? ["Connected → watchdog or transport failure", "Routes down → jittered backoff", "Connect → fresh hybrid handshake", "Connected → routes up", "TUN interface and client IP persist", "Failed retry doubles the delay to its cap", "Host routes apply during downtime"] : ["Connected → failure detected → routes down → jittered exponential backoff → connect → routes up", "Each successful reconnection starts a new hybrid handshake and a new EncryptedChannel.", "The client retains its TUN and IP. Host routing applies while the tunnel policy is removed.", "A watchdog observes traffic counters, not application correctness or end-to-end website health."], "recovery");
+ } else {
+ message(scene, x, y, width, "POLICY CONTROLS HAVE DIFFERENT JOBS", compact ? ["resources → resolved destination addresses", "allowed_ips → explicit network prefixes", "all_traffic → select general traffic", "full_tunnel → disable automatic LAN bypass", "fwmark → keep server transport outside TUN", "Excluded traffic uses the host route", "Examples illustrate Linux route hooks"] : ["resources selects resolved destinations; allowed_ips selects explicit prefixes; all_traffic selects general traffic.", "full_tunnel disables automatic LAN exclusions. It is separate from all_traffic.", "Firewall marks keep the server transport on the host path and prevent a routing loop.", "The Linux route-hook policy shown here is distinct from platform-specific Android VPN routing."], "policy");
+ }
+ return moving;
+ }
+
+ function drawScene(root, flow, step, compact, uid) {
+ const heights = {handshake: compact ? 932 : 578, packets: compact ? 1408 : 691, routing: compact ? 1156 : 554};
+ const height = heights[root.dataset.flow];
+ const canvas = svg("svg", {class: "sy-scene", "data-layout": compact ? "portrait" : "landscape", viewBox: "0 0 " + (compact ? 420 : 960) + " " + height, role: "img", "aria-labelledby": uid + "-title " + uid + "-desc"});
+ svg("title", {id: uid + "-title"}, canvas).textContent = flow.title + ": " + flow.steps[step][0];
+ svg("desc", {id: uid + "-desc"}, canvas).textContent = flow.steps[step][1] + " Labeled paths connect illustrated hosts. All packet counters are examples, not live traffic.";
+ const defs = svg("defs", {}, canvas);
+ const pattern = svg("pattern", {id: uid + "-grid", width: 24, height: 24, patternUnits: "userSpaceOnUse"}, defs);
+ svg("circle", {cx: 1, cy: 1, r: .8, class: "sy-grid-dot"}, pattern);
+ rect(canvas, 0, 0, compact ? 420 : 960, height, "", 0, {fill: "url(#" + uid + "-grid)"});
+ const marker = svg("marker", {id: uid + "-arrow", viewBox: "0 0 10 10", refX: 8, refY: 5, markerWidth: 7, markerHeight: 7, orient: "auto-start-reverse"}, defs);
+ path(marker, "M0 0L10 5L0 10z", "sy-arrowhead");
+ const renderer = {handshake: handshakeScene, packets: packetsScene, routing: routingScene}[root.dataset.flow];
+ const moving = renderer(canvas, step, compact, flow, uid + "-arrow");
+ const packetState = moving ? packet(canvas, moving.line, moving.label, compact) : null;
+ return {canvas, packetState};
+ }
+ function mount(root) {
+ const flow = flows[root.dataset.flow];
+ if (!flow || root.children.length) return;
+ const uid = "prrr-story-" + ++instance;
+ const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
+ let step = 0;
+ let playing = false;
+ let elapsed = 0;
+ let lastTime = null;
+ let frameId = null;
+ let speed = 1;
+ let compact = root.clientWidth < PORTRAIT_BELOW_PX;
+ let packetState = null;
+ root.setAttribute("role", "group");
+ root.setAttribute("aria-label", flow.title + " animated explanation");
+
+ const top = html("div", "sy-mechanics__top");
+ const kicker = html("span", "sy-story-label", flow.label);
+ const sample = html("span", "sy-story-sample", "Animation · example values");
+ top.append(kicker, sample);
+ const title = html("p", "sy-mechanics__title", flow.title);
+ const screen = html("div", "sy-mechanics__screen");
+ const progress = html("div", "sy-mechanics__progress");
+ progress.setAttribute("aria-hidden", "true");
+ const progressFill = html("span", "");
+ progress.append(progressFill);
+ const chapters = html("div", "sy-chapters");
+ chapters.setAttribute("aria-label", "Explanation chapters");
+ const chapterButtons = flow.steps.map((entry, index) => {
+ const button = html("button", "sy-chapter");
+ button.type = "button";
+ const number = html("span", "sy-chapter__number", String(index + 1).padStart(2, "0"));
+ button.append(number, html("span", "", entry[0]));
+ button.addEventListener("click", () => seek(index));
+ chapters.append(button);
+ return button;
+ });
+ const stage = html("div", "sy-mechanics__stage");
+ stage.setAttribute("aria-live", "polite");
+ stage.setAttribute("aria-atomic", "true");
+ const counter = html("div", "sy-mechanics__counter");
+ const heading = html("strong", "");
+ const description = html("p", "");
+ stage.append(counter, heading, description);
+ const controls = html("div", "sy-mechanics__controls");
+ const play = html("button", "sy-play", "Play");
+ const previous = html("button", "", "Previous step");
+ const next = html("button", "", "Next step");
+ const restart = html("button", "", "Restart");
+ for (const button of [play, previous, next, restart]) button.type = "button";
+ const speedLabel = html("label", "sy-speed", "Playback speed");
+ const speedInput = html("select", "");
+ speedInput.setAttribute("aria-label", "Playback speed");
+ for (const value of ["0.75", "1", "1.5"]) {
+ const option = html("option", "", value + "×");
+ option.value = value;
+ option.selected = value === "1";
+ speedInput.append(option);
+ }
+ speedLabel.append(speedInput);
+ controls.append(play, previous, next, restart, speedLabel);
+ const note = html("p", "sy-mechanics__motion-note");
+ root.append(top, title, screen, progress, chapters, stage, controls, note);
+
+ function pose(fraction) {
+ const progress = (step + (reduced.matches ? 1 : fraction)) / flow.steps.length;
+ progressFill.style.transform = "scaleX(" + progress + ")";
+ if (!packetState) return;
+ const {node, line} = packetState;
+ const phase = reduced.matches ? 1 : Math.min(1, Math.max(0, (fraction - .08) / .65));
+ const length = line.getTotalLength();
+ const point = line.getPointAtLength(length * phase);
+ node.setAttribute("transform", "translate(" + point.x + " " + point.y + ")");
+ node.style.opacity = reduced.matches ? "0" : String(phase > .92 ? (1 - phase) / .08 : 1);
+ line.style.strokeDasharray = String(length);
+ line.style.strokeDashoffset = String(length * (1 - phase));
+ }
+
+ function pause() {
+ playing = false;
+ window.cancelAnimationFrame(frameId);
+ lastTime = null;
+ root.dataset.playing = "false";
+ play.textContent = "Play";
+ play.setAttribute("aria-pressed", "false");
+ }
+
+ function render() {
+ root.dataset.step = String(step);
+ root.dataset.motion = reduced.matches ? "reduced" : "full";
+ const {canvas, packetState: moving} = drawScene(root, flow, step, compact, uid);
+ screen.replaceChildren(canvas);
+ packetState = moving;
+ counter.textContent = "Step " + (step + 1) + " of " + flow.steps.length;
+ heading.textContent = flow.steps[step][0];
+ description.textContent = flow.steps[step][1];
+ chapterButtons.forEach((button, index) => {
+ button.dataset.complete = String(index < step);
+ if (index === step) button.setAttribute("aria-current", "step");
+ else button.removeAttribute("aria-current");
+ });
+ previous.disabled = step === 0;
+ next.disabled = step === flow.steps.length - 1;
+ play.disabled = next.disabled && !playing && elapsed >= STEP_MS;
+ note.textContent = reduced.matches
+ ? "Reduced motion: diagrams stay still. Play advances captions; chapters and step controls work at your pace."
+ : "Follow the messages, pause to inspect, or choose any chapter. Illustrated traffic only; no network connection.";
+ pose(playing ? elapsed / STEP_MS : 1);
+ }
+
+ function seek(index) {
+ pause();
+ step = index;
+ elapsed = step === flow.steps.length - 1 ? STEP_MS : 0;
+ render();
+ }
+
+ function tick(now) {
+ if (!playing) return;
+ if (lastTime !== null) elapsed += (now - lastTime) * speed;
+ lastTime = now;
+ if (elapsed >= STEP_MS) {
+ if (step === flow.steps.length - 1) {
+ elapsed = STEP_MS;
+ pause();
+ render();
+ return;
+ }
+ elapsed %= STEP_MS;
+ step += 1;
+ render();
+ }
+ pose(elapsed / STEP_MS);
+ frameId = window.requestAnimationFrame(tick);
+ }
+
+ play.addEventListener("click", () => {
+ if (playing) return pause();
+ playing = true;
+ root.dataset.playing = "true";
+ play.textContent = "Pause";
+ play.setAttribute("aria-pressed", "true");
+ lastTime = null;
+ pose(elapsed / STEP_MS);
+ frameId = window.requestAnimationFrame(tick);
+ });
+ previous.addEventListener("click", () => {
+ seek(Math.max(0, step - 1));
+ if (previous.disabled) next.focus();
+ });
+ next.addEventListener("click", () => {
+ seek(Math.min(flow.steps.length - 1, step + 1));
+ if (next.disabled) restart.focus();
+ });
+ restart.addEventListener("click", () => seek(0));
+ speedInput.addEventListener("change", () => { speed = Number(speedInput.value); });
+ document.addEventListener("visibilitychange", () => { if (document.hidden) pause(); });
+ reduced.addEventListener("change", () => { pause(); render(); });
+ new ResizeObserver(() => {
+ const narrow = root.clientWidth < PORTRAIT_BELOW_PX;
+ if (compact !== narrow) { compact = narrow; render(); }
+ }).observe(root);
+ pause();
+ render();
+ }
+
+ function initialize() {
+ document.querySelectorAll(".sy-mechanics[data-flow]").forEach(mount);
+ }
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", initialize);
+ else initialize();
+})();
diff --git a/docs/reference/api.md b/docs/reference/api.md
new file mode 100644
index 0000000..a2d65eb
--- /dev/null
+++ b/docs/reference/api.md
@@ -0,0 +1,44 @@
+# Admin API reference
+
+The admin router exposes `/api/v1/` when configured. It is distinct from the VPN's identity-authorized HARP endpoints.
+
+## Listener and authentication
+
+The separate admin listener is HTTP in the active `run_web_server` path. Keep it private, or put it behind an authenticated, correctly configured TLS termination path. Do not assume `web_admin.tls_cert` turns this listener into HTTPS. The dedicated HARP TLS server is a separate caller.
+
+`POST /api/v1/auth/login` accepts `username` and `password`. The username is `admin`; the password is verified against the configured Argon2 hash. A successful response contains a bearer token. Protected routes require:
+
+```text
+Authorization: Bearer YOUR_TOKEN
+```
+
+Default session timeout is 3600 seconds. Treat tokens and first client-creation responses as secrets. Use a login request file with restricted permissions when scripting against your own HTTPS admin proxy.
+
+## Core routes
+
+| Method and path | Purpose |
+| --- | --- |
+| `GET /api/v1/server/status` | Server status and connection counts |
+| `GET /api/v1/server/config` | Non-secret server configuration summary |
+| `GET /api/v1/server/transports` | Enabled transport configuration |
+| `GET /api/v1/clients` | Client records |
+| `POST /api/v1/clients` | Create a client; capture first returned private material securely |
+| `GET /api/v1/clients/{id}` | One client record |
+| `DELETE /api/v1/clients/{id}` | Revoke a client |
+| `POST /api/v1/clients/{id}/suspend` | Suspend an identity |
+| `POST /api/v1/clients/{id}/resume` | Resume an identity |
+| `GET /api/v1/clients/{id}/config` | Export connection configuration |
+| `GET /api/v1/clients/{id}/qr` | QR representation |
+| `POST /api/v1/clients/{id}/config-url` | Create a configuration-sharing URL |
+| `GET /api/v1/stats/overview` | Overview counters |
+| `GET /api/v1/stats/traffic` | Traffic statistics |
+| `GET /api/v1/harp/sessions` | Active HARP sessions |
+| `DELETE /api/v1/harp/sessions/{session_id_hex}` | Terminate a HARP session |
+
+## VPN session routes
+
+The HARP router contains `/api/v1/harp/session`, `/stream/{session_id}`, `/upload/{session_id}`, and `/download/{session_id}`. These are VPN transport endpoints, not a reason to expose an admin bearer token to VPN clients. Session creation processes the hybrid handshake and registry identity.
+
+The cover page at `/`, SPA at `/admin`, and configuration token route `/c/{token}` have their own access and token semantics. A cover page is presentation, not an invisibility guarantee.
+
+Sources: [router definitions](https://github.com/Mewplane/prrr/blob/191ebaf/src/web/mod.rs), [authentication](https://github.com/Mewplane/prrr/blob/191ebaf/src/web/auth.rs), [handlers](https://github.com/Mewplane/prrr/blob/191ebaf/src/web/handlers.rs), [HARP session processing](https://github.com/Mewplane/prrr/blob/191ebaf/src/web/harp.rs).
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
new file mode 100644
index 0000000..5c2ef23
--- /dev/null
+++ b/docs/reference/cli.md
@@ -0,0 +1,69 @@
+# CLI reference
+
+Use `prrr --help` and the help of the relevant subcommand for the exact interface of your installed executable. The commands below are checked against revision `191ebaf`.
+
+## Command map
+
+| Command | Purpose |
+| --- | --- |
+| `prrr server` | Start the configured VPN server. |
+| `prrr server doctor` | Inspect server configuration and prerequisites. |
+| `prrr server client add NAME [--qr]` | Register a client and write its complete first configuration to stdout. |
+| `prrr server client list` | List non-revoked client records. |
+| `prrr server client export NAME [--qr] [--output PATH]` | Export public/connection configuration; the original client private key is not recovered. |
+| `prrr server client remove NAME` | Revoke the named registry client. |
+| `prrr client import SOURCE` | Import TOML or a `prrr://` configuration URL into the user's configuration directory. |
+| `prrr client doctor` | Inspect client configuration and prerequisites. |
+| `prrr client route add RESOURCE` | Add a hostname or IPv4 literal to configured resource routes. |
+| `prrr client route remove RESOURCE` | Remove a configured resource. |
+| `prrr client route list` | List configured resources. |
+| `prrr sharing enable`, `disable`, `status` | Change or inspect the local persisted sharing opt-in state. |
+
+## Placement of options
+
+Options belong to their command. Put server/client options before the nested action:
+
+```sh
+prrr server --config /etc/prrr/server.toml client list
+prrr client --config /etc/prrr/client.toml route list
+prrr client --config /etc/prrr/client.toml doctor
+```
+
+There is no top-level `prrr doctor` command.
+
+## Server options
+
+| Option | Default / effect |
+| --- | --- |
+| `--listen ADDRESS:PORT` | `0.0.0.0:443`; bind address/port used by startup. |
+| `--server-name NAME` | `localhost`; set the actual endpoint name when starting and provisioning. |
+| `--config PATH` | Optional TOML file. |
+| `--log-level LEVEL` | `info`; `PRRR_LOG_LEVEL` is also supported. |
+
+`PRRR_LISTEN` can provide the listen address. Do not infer that a similarly named TOML field overrides every CLI default: startup and export resolve fields in different places. The tutorial supplies the endpoint flags explicitly.
+
+## Client options
+
+| Option | Effect |
+| --- | --- |
+| `--server ADDRESS:PORT` | Explicit socket endpoint; otherwise resolve configured endpoint. |
+| `--server-name NAME` | TLS server name; otherwise read `[server].server_name`. |
+| `--server-public-key BASE64` | Pinned 32-byte Noise server public key. |
+| `--server-pq-public-key BASE64` | Pinned 1184-byte ML-KEM-768 encapsulation key. |
+| `--config PATH` | Client TOML file. |
+| `--insecure` | Disable certificate verification for controlled tests; keep verification on for deployed clients. |
+| `--log-level LEVEL` | `info`; also `PRRR_LOG_LEVEL`. |
+
+The server's public keys, client private key, and TLS server name serve different purposes. Importing a public-only export does not supply a missing client identity.
+
+## Editing routes
+
+```sh
+prrr client --config /etc/prrr/client.toml route add example.net
+prrr client --config /etc/prrr/client.toml route list
+prrr client --config /etc/prrr/client.toml route remove example.net
+```
+
+Use the account/privileges appropriate to the selected config file. These commands edit configuration; restart the service when applying a changed resource policy to the running client. An exact hostname does not automatically include its subdomains.
+
+Source: [argument definitions](https://github.com/Mewplane/prrr/blob/191ebaf/src/config.rs), [handlers](https://github.com/Mewplane/prrr/blob/191ebaf/src/cli.rs), [dispatch and precedence](https://github.com/Mewplane/prrr/blob/191ebaf/src/main.rs).
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
new file mode 100644
index 0000000..a7bd79d
--- /dev/null
+++ b/docs/reference/configuration.md
@@ -0,0 +1,116 @@
+# Configuration reference
+
+prrr reads TOML. Client and server files have different schemas. These examples focus on settings used by the active caller paths; parsing a field is not proof that every advertised behavior is wired to it.
+
+## Server configuration
+
+This explicit MASQUE example accompanies the first-connection tutorial:
+
+```toml
+[server]
+server_name = "vpn.example.net"
+data_dir = "/var/lib/prrr"
+max_clients = 100
+
+[network]
+subnet = "10.66.66.0/24"
+dns_servers = ["1.1.1.1", "8.8.8.8"]
+mtu = 1100
+
+[crypto]
+identity_key_path = "/etc/prrr/keys/server_identity.key"
+pq_key_path = "/etc/prrr/keys/server_pq.key"
+
+[[transports]]
+name = "masque"
+enabled = true
+tls_cert = "/etc/letsencrypt/live/vpn.example.net/fullchain.pem"
+tls_key = "/etc/letsencrypt/live/vpn.example.net/privkey.pem"
+```
+
+Start and provision with the same endpoint flags:
+
+```sh
+prrr server --config /etc/prrr/server.toml \
+ --listen 0.0.0.0:443 --server-name vpn.example.net
+```
+
+| Setting | Behavior / default |
+| --- | --- |
+| `[server].data_dir` | Registry/state directory; default `/var/lib/prrr`. |
+| `[server].max_clients` | Default 100. |
+| `[network].subnet` | Default `10.66.66.0/24`. |
+| `[network].mtu` | Default 1100; chosen to fit tunnel and datagram overhead. |
+| `[crypto].identity_key_path` | Persistent X25519 identity key. |
+| `[crypto].pq_key_path` | Persistent ML-KEM key. |
+| `[[transports]].name` | `harp` or `masque`; `enabled = false` filters an entry. |
+| MASQUE `keep_alive` / `max_idle_timeout` | Defaults 25 / 300 seconds. |
+| HARP `websocket_enabled`, `polling_enabled`, `h2_streaming_enabled` | Default true when the transport is resolved. |
+| HARP `session_idle_timeout` | Default 300 seconds. |
+| Transport `tls_cert` / `tls_key` | Certificate chain and private-key paths; configure both for the real hostname. |
+
+**The defaults differ:** an absent/empty server transport list resolves to HARP, while an unqualified client and the provisioning fallback use `masque`. Configure the transport explicitly before provisioning clients. A generated config chooses the first enabled configured transport.
+
+## Client identity and connection
+
+The first `client add` output includes `[server]` public keys and an inline `[interface].private_key`. Keep that configuration private. This fragment illustrates operational settings without substituting fake public/private keys for the generated ones:
+
+```toml
+[interface]
+mtu = 1100
+transport_protocol = "masque"
+
+[transport]
+insecure_skip_verify = false
+reconnect_backoff_ms = 1000
+reconnect_max_backoff_ms = 30000
+```
+
+Merge fields into the existing sections; do not append duplicate TOML table headers.
+
+| Selection | Precedence |
+| --- | --- |
+| Client transport | `[interface].transport_protocol`, then `[transport].protocol`, then `masque`. |
+| Server name | Client CLI `--server-name`, then `[server].server_name`, then an error if absent. |
+| Server public keys | CLI key flags, then `[server].public_key` / `.pq_public_key`. |
+| Client private key | Inline `[interface].private_key`, then configured file fallback. |
+
+For HARP, `[transport].preferred_binding` selects `h2`, `stream` (WebSocket), or `poll`, subject to the negotiated capabilities and caller's fallback logic. `tls_profile` selects an approximate profile; it does not turn rustls into a browser TLS stack.
+
+## Routing policies
+
+Route IPv4 through the tunnel while preserving the detected local LAN:
+
+```toml
+[routing]
+all_traffic = true
+resources = []
+full_tunnel = false
+```
+
+Route only named resources:
+
+```toml
+[routing]
+all_traffic = false
+resources = ["example.net", "203.0.113.10"]
+full_tunnel = false
+```
+
+Resource names are resolved to IPv4 `/32` routes before activation. Names are exact entries; this does not recursively include subdomains or every address belonging to a service. Initial resolution failure prevents startup. Refresh happens separately, so a stalled resolver does not freeze the packet pump.
+
+`all_traffic` defaults to false. `full_tunnel` controls local-LAN auto-exclusion; it is a different setting from routing the default IPv4 route. The transport endpoint must keep a bypass to avoid routing the tunnel into itself. Default fwmark/table is 51820; `hook_script` defaults to `/usr/local/bin/prrr-route`.
+
+The current client path is IPv4-oriented. A full IPv4 route is not proof of IPv6 protection or a kill switch.
+
+## DNS and recovery
+
+Configured `[interface].dns` servers are pinned through the tunnel. The hook advertises responders when the DNS gate is healthy, withdraws the advertisement when necessary, and keeps pins in place for valid probing. Split mode scopes resolver domains to the configured resources; all-traffic mode can use the catch-all domain.
+
+Default recovery values are 60-second resource refresh, 20-second refresh budget, 15-second DNS probes, 2-second probe timeout, 45-second verdict lease, and three black-hole strikes at 5-second intervals. See [recovery](../how-to/recover.md) and the [routing animation](../explanation/mechanics.md#routing-and-recovery).
+
+## Admin listener
+
+`[web_admin].enabled` defaults to false. When enabled, the separate listener requires `admin_password_hash` and defaults to `0.0.0.0:8443`. Bind it to a private/loopback address and terminate TLS through a controlled proxy before exposing it. `run_web_server` serves HTTP; the existence of TLS-related fields in a configuration struct does not make that listener HTTPS.
+
+Sources: [schema and transport resolution](https://github.com/Mewplane/prrr/blob/191ebaf/src/config.rs), [active caller paths](https://github.com/Mewplane/prrr/blob/191ebaf/src/main.rs), [routing](https://github.com/Mewplane/prrr/blob/191ebaf/src/routing.rs), [reconnect](https://github.com/Mewplane/prrr/blob/191ebaf/src/reconnect.rs).
diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md
new file mode 100644
index 0000000..8a7926d
--- /dev/null
+++ b/docs/reference/glossary.md
@@ -0,0 +1,22 @@
+# Glossary
+
+| Term | Meaning in these guides |
+| --- | --- |
+| TUN | Virtual interface through which prrr receives and injects IP packets. |
+| HARP | prrr's HTTP-based relay transport, with HTTP/2, WebSocket, and polling bindings. |
+| MASQUE | prrr's QUIC/datagram transport and associated request/framing implementation. |
+| Noise IK | Authenticated two-message handshake whose initiator knows the responder's static public key. |
+| ML-KEM-768 | Key-encapsulation mechanism included in prrr's hybrid session setup. |
+| HKDF | Extract/expand key derivation; prrr's session KDF uses SHA-256. |
+| AEAD | Authenticated encryption: payload privacy plus integrity of authenticated fields. |
+| Counter | The monotonic per-direction value encoded into the encrypted channel's nonce and AAD. |
+| Replay window | Record of recently received counters, rejecting duplicates while allowing bounded reordering. |
+| Registry | Server-side identity and address records used during client authorization. |
+| fwmark | Linux socket/packet mark used to keep transport traffic out of its own tunnel route. |
+| Resource route | A selected hostname/IP resolved to exact IPv4 destination routes. |
+| DNS gate | Whether tunnel DNS responders are currently advertised to the host resolver. |
+| Verdict lease | Maximum age of a DNS health verdict before its advertisement is withdrawn. |
+| Black hole | An established-looking tunnel that consumes outbound packets without inbound progress. |
+| Kill switch | Policy that blocks ordinary egress when a tunnel is unavailable; do not infer this from prrr's reconnect behavior. |
+
+See [mechanics](../explanation/mechanics.md) for the relationships and [protocol](protocol.md) for exact fields.
diff --git a/docs/reference/protocol.md b/docs/reference/protocol.md
new file mode 100644
index 0000000..d77a2b9
--- /dev/null
+++ b/docs/reference/protocol.md
@@ -0,0 +1,67 @@
+# Protocol reference
+
+This page describes the inspected implementation, not a wire-compatibility commitment with every external MASQUE or Noise implementation. Message sizes below refer to the inner prrr layer unless stated otherwise.
+
+## Hybrid handshake
+
+The active client and server paths use Noise IK with ML-KEM-768. The initiator knows the server's X25519 static public key and 1184-byte ML-KEM encapsulation key. The client encapsulates a 32-byte KEM secret and puts the 1088-byte KEM ciphertext into the first Noise message's encrypted payload. The server decrypts, checks the initiator identity against its registry, decapsulates, and returns the second Noise message.
+
+The session KDF is **HKDF-SHA256**. The Noise handshake pattern is `Noise_IK_25519_ChaChaPoly_BLAKE2s`; these names refer to different layers.
+
+| KDF input/output | Value |
+| --- | --- |
+| Salt | Noise handshake hash |
+| Input keying material | ML-KEM shared secret |
+| Info | Literal `PhantomVPN v1`, then initiator static public key, then responder static public key |
+| Output | 96 bytes: three 32-byte keys |
+| First key | Initiator-to-responder encryption key |
+| Second key | Responder-to-initiator encryption key |
+| Third key | Derived header key |
+
+The responder reverses the send/receive use of the directional keys. Describing a derived header key does not imply the packet format below encrypts its counter.
+
+## Encrypted packet
+
+```text
++----------------------+-------------------------+------------------+
+| counter: 8 bytes BE | encrypted IP payload | Poly1305: 16 B |
++----------------------+-------------------------+------------------+
+```
+
+- Cipher: ChaCha20-Poly1305.
+- Nonce: four zero bytes followed by the 8-byte epoch-local counter, making 12 bytes. The wire counter stays absolute across rekey epochs; the channel derives the epoch and local counter from it.
+- Additional authenticated data: the encoded counter.
+- Minimum packet length: 24 bytes.
+- Replay window: 2048 counters by default; duplicates and sufficiently old packets are rejected, while limited reordering is supported.
+- Default channel rekey threshold: `2^32` sent packets. This differs from a parsed interval or session-info field measured in seconds; do not infer that an advertised seconds field drives a timer in every caller.
+
+The channel lives inside an outer transport. This diagram does not mean an ordinary observer outside outer TLS can read these fields.
+
+## HARP framing and bindings
+
+HARP frames have a 4-byte header:
+
+| Byte(s) | Contents |
+| --- | --- |
+| 0, high nibble | Version 1 |
+| 0, low nibble | Type: data `0`, keepalive `1`, close `2` |
+| 1 | Reserved zero |
+| 2–3 | Payload length, unsigned 16-bit big-endian |
+
+The maximum payload is 65535 bytes. Bindings carry these frames through HTTP/2 upload/download streams, WebSocket streaming, or HTTP polling. The HARP session response advertises supported capabilities. This is a prrr application protocol over HTTP; using HTTPS alone does not prove a browser-equivalent traffic fingerprint.
+
+## MASQUE datagrams
+
+The implementation frames payloads with QUIC variable integers for the Quarter Stream ID and Context ID zero before the encrypted-channel payload. The client uses its MASQUE connection layer and QUIC datagrams. UDP reachability and a sufficient datagram-size budget are necessary; a TCP-only firewall rule does not permit this path.
+
+The default TUN MTU is 1100. The client checks the payload plus encrypted-channel and MASQUE overhead against the connection's datagram budget; increasing MTU can make a connection unusable even when handshaking works.
+
+## Source map
+
+- [Hybrid handshake](https://github.com/Mewplane/prrr/blob/191ebaf/src/handshake/hybrid.rs)
+- [KDF implementation](https://github.com/Mewplane/prrr/blob/191ebaf/src/crypto/kdf.rs)
+- [Encrypted channel](https://github.com/Mewplane/prrr/blob/191ebaf/src/transport/encrypted_channel.rs)
+- [HARP framing](https://github.com/Mewplane/prrr/blob/191ebaf/src/transport/harp.rs)
+- [MASQUE framing](https://github.com/Mewplane/prrr/blob/191ebaf/src/transport/masque.rs)
+
+Watch the same layers in [the animated mechanics guide](../explanation/mechanics.md).
diff --git a/docs/stylesheets/prrr.css b/docs/stylesheets/prrr.css
new file mode 100644
index 0000000..554c1c9
--- /dev/null
+++ b/docs/stylesheets/prrr.css
@@ -0,0 +1,157 @@
+/* App palette: prrr-android/.../ui/theme/Color.kt. Gold sampled from assets/logo_app.png. */
+[data-md-color-scheme="prrr"] {
+ color-scheme: dark;
+ --sy-black: #000000;
+ --sy-surface: #111111;
+ --sy-border: #333333;
+ --sy-white: #ffffff;
+ --sy-dim: #a0a0a0;
+ --sy-success: #22c55e;
+ --sy-warning: #f59e0b;
+ --sy-danger: #ef4444;
+ --sy-key: #feda35;
+ --sy-paw: #ffe585;
+ --md-primary-fg-color: var(--sy-black);
+ --md-primary-bg-color: var(--sy-white);
+ --md-accent-fg-color: var(--sy-key);
+ --md-default-bg-color: var(--sy-black);
+ --md-default-fg-color: var(--sy-white);
+ --md-default-fg-color--light: #dddddd;
+ --md-default-fg-color--lighter: var(--sy-dim);
+ --md-default-fg-color--lightest: var(--sy-border);
+ --md-typeset-color: var(--sy-white);
+ --md-admonition-fg-color: var(--sy-white);
+ --md-code-bg-color: var(--sy-surface);
+ --md-code-fg-color: var(--sy-white);
+ --md-typeset-a-color: var(--sy-key);
+ --md-footer-bg-color: var(--sy-surface);
+ --md-footer-bg-color--dark: var(--sy-black);
+ --md-admonition-bg-color: var(--sy-surface);
+ --md-text-font: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ --md-code-font: ui-monospace, "Cascadia Code", "SFMono-Regular", monospace;
+}
+.md-header { border-bottom: 1px solid var(--sy-border); box-shadow: none; }
+.md-header__button.md-logo img { height: 2rem; width: 2rem; image-rendering: pixelated; }
+.md-typeset { font-size: .84rem; line-height: 1.7; }
+.md-typeset h1, .md-typeset h2 { color: var(--sy-white); font-weight: 750; letter-spacing: -.035em; }
+.md-typeset h1 { font-size: 2.1rem; }
+.md-typeset h2 { border-top: 1px solid var(--sy-border); padding-top: 1.3rem; }
+.md-typeset a:hover { text-decoration: underline; }
+.md-typeset code { border: 1px solid var(--sy-border); }
+.md-typeset .admonition, .md-typeset details { background: var(--sy-surface); font-size: .8rem; }
+.md-typeset table:not([class]) { border-color: var(--sy-border); background: var(--sy-surface); }
+.md-typeset table:not([class]) th { background: #1b1b1b; }
+.md-typeset .md-button { border-radius: 0; border-width: 1px; padding: .6em 1em; }
+.md-typeset .md-button:not(.md-button--primary) { color: var(--sy-white); border-color: var(--sy-dim); }
+.md-typeset .md-button--primary { background: var(--sy-key); border-color: var(--sy-key); color: var(--sy-black); }
+a:focus-visible, button:focus-visible, input:focus-visible { outline: 3px solid var(--sy-paw); outline-offset: 4px; }
+.sy-hero { display: grid; grid-template-columns: minmax(100px, .7fr) minmax(0, 1.7fr); gap: 1.5rem; align-items: center; padding: 1.5rem 0 2rem; border-bottom: 1px solid var(--sy-border); }
+.sy-hero img { width: 100%; max-width: 15rem; image-rendering: pixelated; }
+.md-typeset .sy-hero h1 { font-size: clamp(1.9rem, 4vw, 3.15rem); line-height: 1.13; margin: .3rem 0 1rem; }
+.sy-eyebrow { color: var(--sy-paw); font: 650 .64rem/1.6 var(--md-code-font); letter-spacing: .12em; }
+.sy-hero p { color: #ddd; }
+.sy-hero .sy-eyebrow { color: var(--sy-paw); }
+.sy-hero .md-button { margin: .35rem .35rem .35rem 0; }
+.sy-card-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; margin: 1.5rem 0 2rem; }
+.sy-card { border: 1px solid var(--sy-border); padding: 1rem 1.2rem; background: var(--sy-surface); }
+.md-typeset .sy-card h2, .md-typeset .sy-card h3 { margin-top: 0; padding-top: 0; border-top: 0; font-size: 1rem; }
+.sy-card p:last-child { margin-bottom: 0; }
+.sy-card a { font-weight: 650; }
+.sy-signal { display: inline-block; color: var(--sy-key); font: 650 .6rem/1.6 var(--md-code-font); letter-spacing: .08em; }
+
+/* Illustrated walkthroughs: a persistent system map, messages, and chapters. */
+.sy-mechanics:empty { display: none; }
+.sy-mechanics {
+ margin: 1.6rem 0 2rem;
+ border: 1px solid var(--sy-border);
+ border-radius: 12px;
+ overflow: hidden;
+ background: #0b0b0b;
+ color: var(--sy-white);
+}
+.sy-mechanics__top { display: flex; justify-content: space-between; flex-wrap: wrap; gap: .3rem; padding: .85rem 1rem 0; }
+.sy-story-label { color: var(--sy-paw); font: 650 .58rem/1.5 var(--md-code-font); letter-spacing: .13em; }
+.sy-story-sample { color: var(--sy-dim); font: .56rem/1.5 var(--md-code-font); }
+.sy-mechanics__title { margin: .3rem 1rem .7rem; font-size: 1.15rem; font-weight: 750; letter-spacing: -.025em; }
+.sy-mechanics__screen { background: #0b0b0b; border-block: 1px solid #252525; }
+.sy-scene { display: block; width: 100%; height: auto; overflow: hidden; font-family: var(--md-text-font); }
+.sy-scene[data-layout="portrait"] { max-width: 520px; margin-inline: auto; }
+.sy-scene text { fill: var(--sy-white); }
+.sy-svg-kicker { font: 600 14px var(--md-code-font); letter-spacing: .6px; fill: var(--sy-dim) !important; }
+.sy-svg-body { font-size: 16px; font-weight: 600; }
+.sy-svg-small { font-size: 14px; }
+.sy-svg-tiny { font-size: 14px; }
+.sy-svg-mono { font: 14px var(--md-code-font); }
+.sy-scene[data-layout="portrait"] .sy-svg-small,
+.sy-scene[data-layout="portrait"] .sy-svg-tiny,
+.sy-scene[data-layout="portrait"] .sy-svg-kicker,
+.sy-scene[data-layout="portrait"] .sy-svg-mono,
+.sy-scene[data-layout="portrait"] .sy-packet__text { font-size: 15px; }
+.sy-scene .sy-muted { fill: #b0b0b0; color: #b0b0b0; }
+.sy-scene .sy-gold { fill: var(--sy-key); color: var(--sy-key); }
+.sy-scene .sy-pink { fill: var(--sy-paw); color: var(--sy-paw); }
+.sy-scene .sy-good { fill: #71e7a1; color: #71e7a1; }
+.sy-grid-dot { fill: #2c2c2c; }
+.sy-boundary { fill: #0b0b0b; stroke: #555; stroke-width: 1; stroke-dasharray: 5 5; }
+.sy-device__body { fill: #111; stroke: #777; stroke-width: 1.5; }
+.sy-device__screen { fill: #171717; stroke: #303030; }
+.sy-device[data-active="true"] .sy-device__body { stroke: var(--sy-key); stroke-width: 2.5; }
+.sy-device[data-active="true"] .sy-device__screen { fill: #1a1810; }
+.sy-device__separator { fill: none; stroke: #404040; }
+.sy-icon { color: var(--sy-white); }
+.sy-icon__stroke { fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
+.sy-channel[data-visible="false"], .sy-verification[data-visible="false"] { display: none; }
+.sy-channel { color: #999; }
+.sy-channel__line { fill: none; stroke: #777; stroke-width: 1.5; }
+.sy-channel[data-active="true"] { color: var(--sy-key); }
+.sy-channel[data-active="true"] .sy-channel__line { stroke: var(--sy-key); stroke-width: 2.5; }
+.sy-channel text { fill: #c0c0c0; }
+.sy-channel[data-active="true"] text { fill: var(--sy-key); }
+.sy-arrowhead { fill: context-stroke; }
+.sy-channel__label-bg { fill: #0b0b0b; }
+.sy-packet__body { fill: var(--sy-key); stroke: #fff0b4; stroke-width: 1; }
+.sy-packet__text { fill: #000 !important; font: 650 12px var(--md-code-font); }
+.sy-packet__envelope { fill: none; stroke: #000; stroke-width: 1.2; stroke-linecap: round; stroke-linejoin: round; }
+.sy-frame__version { fill: #252525; stroke: #777; }
+.sy-frame__nonce { fill: #2d1c20; stroke: var(--sy-paw); }
+.sy-frame__mac { fill: #28220f; stroke: var(--sy-key); }
+.sy-mechanics__progress { height: 3px; background: #262626; }
+.sy-mechanics__progress span { display: block; width: 100%; height: 100%; background: var(--sy-key); transform-origin: left; }
+.sy-chapters { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1px; padding: 1px; background: #292929; }
+.sy-chapter { display: flex; align-items: baseline; gap: .4rem; padding: .55rem .6rem; min-height: 44px; background: #111; text-align: left; cursor: pointer; font: 500 .61rem/1.45 var(--md-text-font); color: #c7c7c7; }
+.sy-chapter__number { color: #aaa; font-family: var(--md-code-font); }
+.sy-chapter[aria-current="step"] { color: var(--sy-key); background: #29230e; box-shadow: inset 0 -2px var(--sy-key); }
+.sy-chapter[aria-current="step"] .sy-chapter__number { color: var(--sy-key); }
+.sy-chapter[data-complete="true"] .sy-chapter__number { color: #71e7a1; }
+.sy-mechanics__stage { padding: 1rem 1rem .7rem; min-height: 7.5rem; }
+.sy-mechanics__counter { color: var(--sy-paw); font: 600 .6rem/1.6 var(--md-code-font); text-transform: uppercase; letter-spacing: .07em; }
+.sy-mechanics__stage strong { display: block; margin: .25rem 0 .35rem; font-size: .95rem; }
+.sy-mechanics__stage p { margin: 0; color: #ddd; font-size: .78rem; }
+.sy-mechanics__controls { display: flex; align-items: center; flex-wrap: wrap; gap: .4rem; margin: 0 1rem; border-top: 1px solid var(--sy-border); padding-top: .8rem; }
+.sy-mechanics__controls button, .sy-speed select { min-height: 44px; min-width: 44px; color: var(--sy-white); background: #202020; border: 1px solid #777; padding: .3rem .6rem; font: 600 .65rem/1.5 var(--md-text-font); cursor: pointer; border-radius: 5px; }
+.sy-mechanics__controls .sy-play { color: #000; background: var(--sy-key); border-color: var(--sy-key); min-width: 65px; }
+.sy-mechanics__controls button:disabled { opacity: .45; cursor: default; }
+.sy-speed { display: flex; align-items: center; gap: .35rem; margin-left: auto; color: #bbb; font-size: .6rem; }
+.sy-speed select { padding: .3rem; }
+.sy-mechanics__motion-note { margin: .65rem 1rem .8rem; color: var(--sy-dim); font-size: .6rem; }
+@media (max-width: 600px) {
+ .sy-card-grid { grid-template-columns: 1fr; }
+ .sy-hero { grid-template-columns: 1fr; gap: 0; padding-top: 0; }
+ .sy-hero img { max-width: 8rem; justify-self: center; }
+ .md-typeset .sy-hero h1 { font-size: 2rem; }
+ .sy-mechanics__title { font-size: 1rem; }
+ .sy-story-sample { font-size: .5rem; }
+ .sy-chapters { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ .sy-chapter { font-size: .65rem; }
+ .sy-speed { margin-left: 0; width: 100%; }
+ .sy-mechanics__stage { min-height: 8rem; }
+}
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, *::after { scroll-behavior: auto !important; animation: none !important; transition: none !important; }
+}
+@media print {
+ .sy-mechanics, .sy-hero img { display: none; }
+ [data-md-color-scheme="prrr"] { color-scheme: light; --sy-white: #000; --sy-black: #fff; --sy-dim: #333; --sy-surface: #fff; --sy-border: #ccc; --sy-key: #000; --sy-paw: #000; --md-default-bg-color: #fff; --md-default-fg-color: #000; --md-typeset-color: #000; --md-code-fg-color: #000; --md-code-bg-color: #fff; --md-typeset-a-color: #000; }
+ .sy-hero p { color: #000; }
+ .md-typeset table:not([class]) th { color: #000; background: #fff; }
+}
diff --git a/docs/tutorials/first-tunnel.md b/docs/tutorials/first-tunnel.md
new file mode 100644
index 0000000..2d249d4
--- /dev/null
+++ b/docs/tutorials/first-tunnel.md
@@ -0,0 +1,86 @@
+# Make your first tunnel connection
+
+You will provision one client, connect it to a server, verify that traffic crosses the tunnel, and disconnect cleanly. Use two Linux hosts and an administrator-controlled server; this tutorial does not change the machine running the documentation checks.
+
+## Prerequisites
+
+Complete [installation](../how-to/install.md). The server needs a reachable endpoint, a certificate trusted by the client for its real DNS name, configured forwarding/NAT, and a permitted transport port. The client needs TUN support and administrative privileges. Keep another working connection to the host available.
+
+Select the same transport explicitly on both ends. This tutorial uses MASQUE on UDP 443. The minimal server transport entry is:
+
+```toml
+[[transports]]
+name = "masque"
+enabled = true
+tls_cert = "/etc/letsencrypt/live/vpn.example.net/fullchain.pem"
+tls_key = "/etc/letsencrypt/live/vpn.example.net/privkey.pem"
+```
+
+`vpn.example.net` is an example name: replace it with your server's domain and certificate paths. See [server configuration](../reference/configuration.md#server-configuration) for the accompanying server, network, and key settings.
+
+## 1. Save the first client configuration
+
+On the server, register a client using the same configuration and endpoint as the running server:
+
+```sh
+umask 077
+sudo prrr server --config /etc/prrr/server.toml \
+ --listen 0.0.0.0:443 --server-name vpn.example.net \
+ client add my-laptop > my-laptop.toml
+```
+
+The command writes a complete client TOML to standard output, including its private key. Save this first result securely; a later `client export` does not recover that private key. Transfer the file to your client through an authenticated private channel.
+
+## 2. Choose the traffic to carry
+
+For a first IPv4 egress check, add or edit the existing routing section in the client file:
+
+```toml
+[routing]
+all_traffic = true
+resources = []
+```
+
+This selects the VPN default route for IPv4. Detected private local-LAN networks remain excluded unless you also choose `full_tunnel = true`. It does not prove IPv6 traffic is tunneled. See [routing policies](../reference/configuration.md#routing-policies) before using a different mode.
+
+## 3. Install the client service
+
+From a current source checkout on the client:
+
+```sh
+cargo build --locked --release --bin prrr
+sudo ./deploy/client/install-client.sh ./my-laptop.toml
+sudo systemctl start prrr-client
+```
+
+The installer copies the built binary, routing hook, systemd service, and mode-600 configuration to their system paths. It also scopes NetworkManager's unmanaged-interface rule to `prrr*`. The service uses `/usr/local/bin/prrr`, not the copy installed by `cargo install` into your home directory.
+
+## 4. Verify the data plane
+
+```sh
+systemctl status prrr-client
+ip -4 addr show prrr0
+ip -4 rule
+resolvectl status
+curl -4 --fail https://api.ipify.org
+```
+
+Confirm that the tunnel has its assigned address, policy rules exist, DNS ownership matches the selected routing mode, and the final command reports your server's public egress address. A running service or a completed handshake alone does not prove packet forwarding works.
+
+Review logs with `journalctl -u prrr-client -n 100`. Once the checks pass, `sudo systemctl enable prrr-client` enables it for subsequent boots.
+
+## 5. Disconnect and verify recovery
+
+```sh
+sudo systemctl stop prrr-client
+ip -4 rule
+resolvectl status
+```
+
+The routing hook removes tunnel rules and DNS advertisements so the host's ordinary network can take over. This is availability-oriented recovery, not an Internet-blocking kill switch.
+
+## Next steps
+
+Watch the [handshake and packet walkthroughs](../explanation/mechanics.md), learn [resource routing](../reference/configuration.md#routing-policies), or use the [recovery guide](../how-to/recover.md).
+
+
diff --git a/mkdocs.yml b/mkdocs.yml
new file mode 100644
index 0000000..35b17da
--- /dev/null
+++ b/mkdocs.yml
@@ -0,0 +1,82 @@
+site_name: prrr
+site_url: https://mewplane.github.io/prrr/
+site_description: Understand, deploy, and operate the prrr encrypted tunnel.
+docs_dir: docs
+site_dir: target/docs-site
+strict: true
+exclude_docs: |
+ /api.md
+ /book.md
+ /cli.md
+ /client-recovery.md
+ /configuration.md
+ /crypto.md
+ /deployment.md
+ /ecosystem.md
+ /getting-started.md
+ /handshake.md
+ /ios-build-options.md
+ /messaging.md
+ /mobile-api.md
+ /mobile-build.md
+ /obfuscation.md
+ /overview.md
+ /security.md
+ /transport.md
+ /tunnel.md
+theme:
+ name: material
+ language: en
+ logo: assets/prrr.png
+ favicon: assets/prrr.png
+ font: false
+ palette:
+ scheme: prrr
+ features:
+ - navigation.sections
+ - navigation.top
+ - search.suggest
+ - search.highlight
+ - content.code.copy
+ - toc.follow
+plugins:
+ - search
+markdown_extensions:
+ - admonition
+ - attr_list
+ - md_in_html
+ - tables
+ - toc:
+ permalink: true
+ - pymdownx.details
+ - pymdownx.superfences
+extra_css:
+ - stylesheets/prrr.css
+extra_javascript:
+ - javascripts/mechanics.js
+extra:
+ generator: false
+ social:
+ - icon: fontawesome/brands/github
+ link: https://github.com/Mewplane/prrr
+ name: prrr on GitHub
+nav:
+ - Start here: index.md
+ - Tutorial:
+ - Your first tunnel: tutorials/first-tunnel.md
+ - How-to:
+ - Install: how-to/install.md
+ - Provision a client: how-to/provision-client.md
+ - Connect on Android: how-to/android.md
+ - Recover a connection: how-to/recover.md
+ - Reference:
+ - CLI: reference/cli.md
+ - Configuration: reference/configuration.md
+ - Protocol: reference/protocol.md
+ - REST API: reference/api.md
+ - Glossary: reference/glossary.md
+ - Explanation:
+ - How it works: explanation/mechanics.md
+ - Security: explanation/security.md
+ - Contributing:
+ - Documentation: contributing/documentation.md
diff --git a/requirements-docs.in b/requirements-docs.in
new file mode 100644
index 0000000..41f6512
--- /dev/null
+++ b/requirements-docs.in
@@ -0,0 +1,3 @@
+mkdocs==1.6.1
+mkdocs-material==9.7.7
+playwright==1.63.0
diff --git a/requirements-docs.txt b/requirements-docs.txt
new file mode 100644
index 0000000..05fffbf
--- /dev/null
+++ b/requirements-docs.txt
@@ -0,0 +1,83 @@
+# This file was autogenerated by uv via the following command:
+# uv pip compile requirements-docs.in -o requirements-docs.txt --python /usr/bin/python3.12
+babel==2.18.0
+ # via mkdocs-material
+backrefs==8.1
+ # via mkdocs-material
+certifi==2026.10.18
+ # via requests
+charset-normalizer==3.5.2
+ # via requests
+click==8.5.0
+ # via mkdocs
+colorama==0.4.6
+ # via mkdocs-material
+ghp-import==2.1.0
+ # via mkdocs
+greenlet==3.5.6
+ # via playwright
+idna==3.20
+ # via requests
+jinja2==3.1.6
+ # via
+ # mkdocs
+ # mkdocs-material
+markdown==3.11.2
+ # via
+ # mkdocs
+ # mkdocs-material
+ # pymdown-extensions
+markupsafe==3.0.4
+ # via
+ # jinja2
+ # mkdocs
+mergedeep==1.3.4
+ # via
+ # mkdocs
+ # mkdocs-get-deps
+mkdocs==1.6.1
+ # via
+ # -r requirements-docs.in
+ # mkdocs-material
+mkdocs-get-deps==0.2.2
+ # via mkdocs
+mkdocs-material==9.7.7
+ # via -r requirements-docs.in
+mkdocs-material-extensions==1.3.1
+ # via mkdocs-material
+packaging==26.3
+ # via mkdocs
+paginate==0.5.7
+ # via mkdocs-material
+pathspec==1.1.1
+ # via mkdocs
+platformdirs==4.13.5
+ # via mkdocs-get-deps
+playwright==1.63.0
+ # via -r requirements-docs.in
+pyee==13.0.1
+ # via playwright
+pygments==2.21.0
+ # via mkdocs-material
+pymdown-extensions==12.3
+ # via mkdocs-material
+python-dateutil==2.9.0.post0
+ # via ghp-import
+pyyaml==6.0.3
+ # via
+ # mkdocs
+ # mkdocs-get-deps
+ # pymdown-extensions
+ # pyyaml-env-tag
+pyyaml-env-tag==1.1
+ # via mkdocs
+requests==2.34.2
+ # via mkdocs-material
+six==1.17.0
+ # via python-dateutil
+typing-extensions==4.16.0
+ # via pyee
+urllib3==2.8.0
+ # via requests
+watchdog==6.0.0
+ # via mkdocs
diff --git a/scripts/docs-check.py b/scripts/docs-check.py
new file mode 100644
index 0000000..254383f
--- /dev/null
+++ b/scripts/docs-check.py
@@ -0,0 +1,527 @@
+#!/usr/bin/env python3
+"""Build and exercise the documentation as a reader.
+
+FRD: specs/frds/FRD-illustrated-documentation.md
+Run using the Python environment installed from requirements-docs.txt.
+"""
+from functools import partial
+from html.parser import HTMLParser
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from threading import Thread
+from urllib.parse import unquote, urlsplit
+import subprocess
+import sys
+
+from playwright.sync_api import expect, sync_playwright
+from yaml import safe_load
+
+ROOT = Path(__file__).resolve().parents[1]
+SITE = ROOT / "target" / "docs-site"
+SITE_PREFIX = urlsplit(safe_load((ROOT / "mkdocs.yml").read_text()).get("site_url", "")).path.rstrip("/")
+PREVIEW = ROOT / "target" / "docs-preview"
+MECHANICS = "explanation/mechanics/"
+LAST_STAGES = {
+ "handshake": "Tunnel ready",
+ "packets": "Reject a replay",
+ "routing": "Restore the session",
+}
+CHAPTER_COUNTS = {"handshake": 7, "packets": 8, "routing": 7}
+TOTAL_STEPS = sum(CHAPTER_COUNTS.values())
+
+
+class Links(HTMLParser):
+ """Collect local anchors for validation against the built output."""
+
+ def __init__(self):
+ super().__init__()
+ self.targets = []
+ self.ids = set()
+
+ def handle_starttag(self, tag, attrs):
+ attrs = dict(attrs)
+ if "id" in attrs:
+ self.ids.add(attrs["id"])
+ if tag == "a" and attrs.get("href"):
+ self.targets.append(attrs["href"])
+
+
+def check_links():
+ documents = {}
+ for path in SITE.rglob("*.html"):
+ parser = Links()
+ parser.feed(path.read_text())
+ documents[path.resolve()] = parser
+ for path, parser in documents.items():
+ for href in parser.targets:
+ link = urlsplit(href)
+ if link.scheme or link.netloc:
+ continue
+ target = (path.parent / unquote(link.path)).resolve() if link.path else path
+ if link.path.startswith("/"):
+ site_path = unquote(link.path)
+ if SITE_PREFIX and site_path.startswith(SITE_PREFIX + "/"):
+ site_path = site_path[len(SITE_PREFIX):]
+ target = (SITE / site_path.lstrip("/")).resolve()
+ if target.is_dir():
+ target /= "index.html"
+ assert target.is_relative_to(SITE), f"Link escapes site: {path}: {href}"
+ assert target.exists(), f"Broken link: {path}: {href}"
+ if link.fragment and target in documents:
+ assert unquote(link.fragment) in documents[target].ids, f"Missing anchor: {path}: {href}"
+ print(f"PASS local links and anchors ({len(documents)} HTML pages)")
+
+
+def no_overflow(page):
+ assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth"), "Horizontal page overflow"
+
+
+def check_rich_diagrams(page, base):
+ page.goto(base + MECHANICS)
+ wide_views = {}
+ for flow in LAST_STAGES:
+ widget = page.locator(f'.sy-mechanics[data-flow="{flow}"]')
+ scene = widget.locator("svg.sy-scene[role=img]")
+ expect(scene).to_be_visible()
+ expect(scene).to_have_attribute("data-layout", "landscape")
+ wide_views[flow] = scene.get_attribute("viewBox")
+ name = scene.get_attribute("aria-label") or scene.get_attribute("aria-labelledby")
+ assert name, "Illustrated scenes need an accessible description"
+ actor_names = {"handshake": ["client", "server"], "packets": ["application", "tun", "relay", "destination"], "routing": ["policy", "tunnel", "internet"]}[flow]
+ for actor in actor_names:
+ expect(scene.locator(f'[data-node="{actor}"]')).to_be_visible()
+ assert scene.locator("[data-channel]").count() >= 2, "Scenes need labeled message routes"
+ assert scene.locator('[data-channel][data-visible="false"]').count() >= 1, "Future message routes must be progressively revealed"
+ expect(widget).to_have_attribute("data-step", "0")
+ chapters = widget.locator(".sy-chapter")
+ expected_steps = CHAPTER_COUNTS[flow]
+ expect(chapters).to_have_count(expected_steps)
+ expect(chapters.first).to_have_attribute("aria-current", "step")
+ speed = widget.get_by_label("Playback speed", exact=True)
+ expect(speed).to_have_value("1")
+ assert set(speed.locator("option").evaluate_all("items => items.map(e => e.value)")) == {"0.75", "1", "1.5"}
+ print("PASS illustrated actors, accessible scenes, message routes, chapters and playback speeds")
+ return wide_views
+
+
+def check_flows(page, base):
+ page.goto(base + MECHANICS)
+ for name, last_stage in LAST_STAGES.items():
+ widget = page.locator(f'.sy-mechanics[data-flow="{name}"]')
+ expect(widget.get_by_role("button", name="Play", exact=True)).to_be_visible()
+ expect(widget.locator(".sy-mechanics__counter")).to_contain_text("Step 1 of")
+ next_step = widget.get_by_role("button", name="Next step", exact=True)
+ visited = 1
+ while next_step.is_enabled():
+ next_step.click()
+ visited += 1
+ assert visited <= 12, "Flow did not finish"
+ expect(widget.locator(".sy-mechanics__stage strong")).to_have_text(last_stage)
+ expect(widget.get_by_role("button", name="Play", exact=True)).to_be_disabled()
+ widget.get_by_role("button", name="Restart", exact=True).click()
+ expect(widget.locator(".sy-mechanics__counter")).to_contain_text("Step 1 of")
+ print(f"PASS {name}: {visited} readable steps, completion and restart")
+
+
+def contrast_ratio(first, second):
+ def luminance(values):
+ channels = [v / 255 for v in values[:3]]
+ linear = [v / 12.92 if v <= .04045 else ((v + .055) / 1.055) ** 2.4 for v in channels]
+ return sum(v * weight for v, weight in zip(linear, [.2126, .7152, .0722]))
+ foreground, background = luminance(first), luminance(second)
+ return (max(foreground, background) + .05) / (min(foreground, background) + .05)
+
+
+def check_contrast(page):
+ selectors = [".md-typeset", ".md-nav__link", ".sy-mechanics__title",
+ ".sy-mechanics__actor", ".sy-mechanics__stage strong",
+ ".sy-mechanics__controls button", ".sy-mechanics__motion-note",
+ ".sy-hero .md-button", ".sy-eyebrow",
+ "article h1", "article h2", "article > p", "article code", "article th", "article td"]
+ for selector in selectors:
+ for node in page.locator(selector).all():
+ if not node.is_visible():
+ continue
+ colors = node.evaluate(r"""e => {
+ const rgb = value => value.match(/[\d.]+/g).map(Number);
+ let background = e;
+ while (background.parentElement && getComputedStyle(background).backgroundColor === 'rgba(0, 0, 0, 0)') background = background.parentElement;
+ return {fg:rgb(getComputedStyle(e).color), bg:rgb(getComputedStyle(background).backgroundColor)};
+ }""")
+ ratio = contrast_ratio(colors["fg"], colors["bg"])
+ assert ratio >= 4.5, f"Unreadable text contrast {ratio:.2f}: {selector} {node.inner_text()}"
+ print("PASS representative navigation, explanation and control contrast")
+
+
+def check_svg_contrast(page):
+ for scene in page.locator("svg.sy-scene").all():
+ colors = scene.evaluate(r"""scene => {
+ const rgb=value => value.match(/[\d.]+/g)?.map(Number);
+ const visible=e => {
+ for(let n=e; n; n=n.parentElement) {
+ const s=getComputedStyle(n);
+ if(s.display==='none'||s.visibility==='hidden'||Number(s.opacity)<0.1) return false;
+ }
+ return true;
+ };
+ return Array.from(scene.querySelectorAll('text')).filter(visible).map(e => {
+ const box=e.getBoundingClientRect(), x=box.x+box.width/2,y=box.y+box.height/2;
+ const backgrounds=Array.from(scene.querySelectorAll('rect')).filter(r => {
+ const b=r.getBoundingClientRect(), f=getComputedStyle(r).fill;
+ return visible(r) && f.startsWith('rgb') && (r.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING) && b.x<=x && x<=b.right && b.y<=y && y<=b.bottom;
+ });
+ const background=backgrounds.at(-1);
+ return {label:e.textContent,fg:rgb(getComputedStyle(e).fill),bg:background?rgb(getComputedStyle(background).fill):[0,0,0]};
+ });
+ }""")
+ for label in colors:
+ assert label["fg"], f"SVG text needs a visible fill: {label['label']}"
+ ratio = contrast_ratio(label["fg"], label["bg"])
+ assert ratio >= 4.5, f"Unreadable diagram text contrast {ratio:.2f}: {label['label']}"
+ print("PASS painted SVG label contrast against device and packet surfaces")
+
+
+def scene_text(widget, text, exact=True):
+ label = widget.locator(".sy-scene").locator("text").get_by_text(text, exact=exact).first
+ expect(label).to_be_visible()
+ assert label.evaluate("""e => {
+ for (let n=e; n; n=n.parentElement) {
+ const style=getComputedStyle(n);
+ if (style.display==='none' || style.visibility==='hidden' || Number(style.opacity)<0.1) return false;
+ }
+ return true;
+ }"""), f"Illustrated label is hidden: {text}"
+
+
+def packet_position(widget):
+ packet = widget.locator("[data-packet]").first
+ expect(packet).to_be_visible()
+ return packet.evaluate("e => {const p=e.getBoundingClientRect(); return {x:p.x,y:p.y};}")
+
+
+def no_visual_motion(widget):
+ states = widget.evaluate("""e => e.getAnimations({subtree:true}).map(a => ({
+ state:a.playState, rate:a.playbackRate
+ }))""")
+ assert not any(a["state"] == "running" and a["rate"] != 0 for a in states), "Reduced motion must stop visual Web Animations and CSS animations"
+ movement = widget.evaluate("""async e => {
+ const packet=e.querySelector('[data-packet]');
+ if(!packet) return 0;
+ const first=packet.getBoundingClientRect();
+ await new Promise(resolve => setTimeout(resolve, 500));
+ const last=packet.getBoundingClientRect();
+ return Math.abs(last.x-first.x)+Math.abs(last.y-first.y);
+ }""")
+ assert movement < 1, "Reduced motion must also stop requestAnimationFrame packet movement"
+
+
+def seek(widget, index):
+ chapter = widget.locator(".sy-chapter").nth(index)
+ chapter.click()
+ expect(widget).to_have_attribute("data-step", str(index))
+ expect(chapter).to_have_attribute("aria-current", "step")
+ expect(widget.locator('.sy-chapter[aria-current="step"]')).to_have_count(1)
+
+
+def check_actor_labels(widget):
+ for actor in widget.locator("[data-node]").all():
+ body = actor.locator(".sy-device__body").bounding_box()
+ for label in actor.locator("text").all():
+ if not label.is_visible():
+ continue
+ bounds = label.bounding_box()
+ assert bounds["x"] >= body["x"]+4 and bounds["x"]+bounds["width"] <= body["x"]+body["width"]-4, f"Actor label touches its side: {label.text_content()}"
+ assert bounds["y"] >= body["y"]+4 and bounds["y"]+bounds["height"] <= body["y"]+body["height"]-4, f"Actor label touches its bottom: {label.text_content()}"
+
+
+def check_chapters_and_payloads(page):
+ for flow in LAST_STAGES:
+ widget = page.locator(f'.sy-mechanics[data-flow="{flow}"]')
+ for index in range(CHAPTER_COUNTS[flow]):
+ seek(widget, index)
+ stage = widget.locator(".sy-mechanics__stage")
+ assert len(stage.inner_text().strip()) > 40, "Every chapter needs a complete explanation"
+ check_actor_labels(widget)
+ check_svg_contrast(page)
+ widget.get_by_role("button", name="Previous step", exact=True).focus()
+ page.keyboard.press("Enter")
+ expect(widget).to_have_attribute("data-step", str(CHAPTER_COUNTS[flow]-2))
+ expect(widget.get_by_role("button", name="Previous step", exact=True)).to_be_focused()
+ chapter = widget.locator(".sy-chapter").nth(2)
+ chapter.focus()
+ page.keyboard.press("Space")
+ expect(widget).to_have_attribute("data-step", "2")
+ expect(chapter).to_be_focused()
+ widget.screenshot(path=str(PREVIEW / f"desktop-{flow}.png"), style=".md-header, .md-top { visibility: hidden !important; }")
+ widget.get_by_role("button", name="Restart", exact=True).click()
+ expect(widget.get_by_role("button", name="Previous step", exact=True)).to_be_disabled()
+ handshake = page.locator('.sy-mechanics[data-flow="handshake"]')
+ seek(handshake, 2)
+ scene_text(handshake, "ML-KEM-768 encapsulate")
+ scene_text(handshake, "Noise IK: e, es, s, ss")
+ seek(handshake, 5)
+ for label in ["HKDF-SHA256", "tx_key / rx_key"]:
+ scene_text(handshake, label)
+ packets = page.locator('.sy-mechanics[data-flow="packets"]')
+ seek(packets, 1)
+ for part in ["nonce", "ciphertext", "tag"]:
+ expect(packets.locator(f'[data-part="{part}"]')).to_be_visible()
+ scene_text(packets, "counter · 8 B")
+ scene_text(packets, "tag · 16 B")
+ seek(packets, 2)
+ scene_text(packets, "HARP · TCP/443", exact=False)
+ scene_text(packets, "MASQUE · UDP/443", exact=False)
+ seek(packets, 7)
+ scene_text(packets, "Replay rejected · duplicate counter 42")
+ routing = page.locator('.sy-mechanics[data-flow="routing"]')
+ seek(routing, 3)
+ scene_text(routing, "Host DNS retained")
+ seek(routing, 6)
+ scene_text(routing, "Fresh session keys")
+ scene_text(routing, "Same TUN device")
+ for widget in [handshake, packets, routing]:
+ widget.get_by_role("button", name="Restart", exact=True).click()
+ print(f"PASS all {TOTAL_STEPS} chapters, source-accurate payloads, routing gates, contrast, focus and keyboard seeking")
+
+
+def check_playback(page):
+ widget = page.locator('.sy-mechanics[data-flow="packets"]')
+ counter = widget.locator(".sy-mechanics__counter")
+ seek(widget, 3)
+ widget.get_by_label("Playback speed", exact=True).select_option("0.75")
+ widget.get_by_role("button", name="Play", exact=True).click()
+ expect(widget).to_have_attribute("data-playing", "true")
+ page.wait_for_timeout(300)
+ before = packet_position(widget)
+ page.wait_for_timeout(500)
+ after = packet_position(widget)
+ assert abs(after["x"]-before["x"]) + abs(after["y"]-before["y"]) > 2, "Playing must animate a real SVG message packet"
+ widget.get_by_role("button", name="Pause", exact=True).click()
+ expect(widget).to_have_attribute("data-playing", "false")
+ paused = counter.text_content()
+ frozen = packet_position(widget)
+ page.wait_for_timeout(600)
+ after_pause = packet_position(widget)
+ assert abs(after_pause["x"]-frozen["x"]) + abs(after_pause["y"]-frozen["y"]) < 1, "Pause must freeze packet movement"
+ page.wait_for_timeout(3100)
+ expect(counter).to_have_text(paused)
+ widget.get_by_role("button", name="Play", exact=True).click()
+ expect(counter).not_to_have_text(paused, timeout=9500)
+ widget.get_by_role("button", name="Pause", exact=True).click()
+ widget.get_by_role("button", name="Restart", exact=True).focus()
+ page.keyboard.press("Enter")
+ expect(counter).to_contain_text("Step 1 of")
+ widget.get_by_role("button", name="Next step", exact=True).focus()
+ page.keyboard.press("Space")
+ expect(counter).to_contain_text("Step 2 of")
+ widget.get_by_role("button", name="Play", exact=True).click()
+ page.emulate_media(reduced_motion="reduce")
+ expect(widget.get_by_role("button", name="Play", exact=True)).to_be_visible()
+ expect(widget.locator(".sy-mechanics__motion-note")).to_contain_text("Reduced motion")
+ no_visual_motion(widget)
+ page.emulate_media(reduced_motion="no-preference")
+ widget.get_by_role("button", name="Restart", exact=True).click()
+ widget.get_by_role("button", name="Play", exact=True).click()
+ # Chromium under automation reports every tab as visible here. Inject only
+ # the visibility signal; exercise the real component listener and timer.
+ page.evaluate("""() => {
+ Object.defineProperty(document, 'hidden', {configurable: true, get: () => true});
+ document.dispatchEvent(new Event('visibilitychange'));
+ }""")
+ expect(widget.get_by_role("button", name="Play", exact=True)).to_be_visible()
+ paused = counter.text_content()
+ page.wait_for_timeout(3100)
+ expect(counter).to_have_text(paused)
+ page.evaluate("delete document.hidden")
+ print("PASS SVG packet motion/freeze, playback, pause, keyboard, reduced motion and simulated hidden-document event")
+
+
+def check_final_delivery(page):
+ widget = page.locator('.sy-mechanics[data-flow="packets"]')
+ last = CHAPTER_COUNTS["packets"]-1
+ seek(widget, last-1)
+ widget.get_by_label("Playback speed", exact=True).select_option("1.5")
+ widget.get_by_role("button", name="Play", exact=True).click()
+ expect(widget).to_have_attribute("data-step", str(last), timeout=6500)
+ expect(widget.get_by_role("button", name="Pause", exact=True)).to_be_enabled()
+ expect(widget).to_have_attribute("data-playing", "true")
+ before = packet_position(widget)
+ page.wait_for_timeout(500)
+ after = packet_position(widget)
+ assert abs(after["x"]-before["x"]) + abs(after["y"]-before["y"]) > 1, "The final replay attempt must animate before playback completes"
+ expect(widget.get_by_role("button", name="Play", exact=True)).to_be_disabled(timeout=6500)
+ expect(widget).to_have_attribute("data-playing", "false")
+ expect(widget.locator(".sy-mechanics__stage strong")).to_have_text(LAST_STAGES["packets"])
+ widget.get_by_role("button", name="Restart", exact=True).click()
+ print("PASS final replay attempt animates before rejection and completion")
+
+
+def check_reduced(browser, base):
+ context = browser.new_context(reduced_motion="reduce")
+ page = context.new_page()
+ page.goto(base + MECHANICS)
+ widget = page.locator('.sy-mechanics[data-flow="routing"]')
+ expect(widget.get_by_role("button", name="Play", exact=True)).to_be_visible()
+ expect(widget).to_have_attribute("data-playing", "false")
+ seek(widget, 1)
+ widget.get_by_role("button", name="Play", exact=True).click()
+ no_visual_motion(widget)
+ expect(widget.locator(".sy-mechanics__motion-note")).to_contain_text("Reduced motion")
+ context.close()
+ print("PASS initial reduced motion and motion-free playback")
+
+
+def check_portrait_scene(scene, wide_view):
+ expect(scene).not_to_have_attribute("viewBox", wide_view)
+ geometry = scene.evaluate("""scene => {
+ const bounds=scene.getBoundingClientRect();
+ const labels=Array.from(scene.querySelectorAll('text')).map(e => {
+ let visible=true;
+ for(let n=e; n; n=n.parentElement) {
+ const s=getComputedStyle(n);
+ if(s.display==='none'||s.visibility==='hidden'||Number(s.opacity)<0.1) visible=false;
+ }
+ const m=e.getScreenCTM(),r=e.getBoundingClientRect();
+ return {label:e.textContent,visible,size:parseFloat(getComputedStyle(e).fontSize)*Math.hypot(m.a,m.b),x:r.x,y:r.y,width:r.width,height:r.height};
+ });
+ return {bounds:{x:bounds.x,y:bounds.y,width:bounds.width,height:bounds.height},labels};
+ }""")
+ bounds = geometry["bounds"]
+ assert bounds["height"] > bounds["width"], "Narrow screens need a portrait scene layout"
+ for label in geometry["labels"]:
+ if not label["visible"]:
+ continue
+ assert label["size"] >= 11.5, f"Narrow scene label is too small: {label['label']}"
+ assert label["x"] >= bounds["x"]-2 and label["x"]+label["width"] <= bounds["x"]+bounds["width"]+2, f"Clipped scene label: {label['label']}"
+ assert label["y"] >= bounds["y"]-2 and label["y"]+label["height"] <= bounds["y"]+bounds["height"]+2, f"Vertically clipped scene label: {label['label']}"
+
+
+def check_all_narrow_steps(page, wide_views):
+ for flow in LAST_STAGES:
+ widget = page.locator(f'.sy-mechanics[data-flow="{flow}"]')
+ for index in range(widget.locator(".sy-chapter").count()):
+ seek(widget, index)
+ check_portrait_scene(widget.locator("svg.sy-scene"), wide_views[flow])
+ check_actor_labels(widget)
+ widget.get_by_role("button", name="Restart", exact=True).click()
+
+
+def check_tablet(browser, base, wide_views):
+ context = browser.new_context(viewport={"width": 820, "height": 1180}, has_touch=True)
+ page = context.new_page()
+ page.goto(base + MECHANICS)
+ no_overflow(page)
+ check_all_narrow_steps(page, wide_views)
+ page.locator('.sy-mechanics[data-flow="packets"]').screenshot(path=str(PREVIEW / "tablet-packets.png"), style=".md-header, .md-top { visibility: hidden !important; }")
+ context.close()
+ print(f"PASS tablet portrait reflow, readable labels and unclipped scenes across all {TOTAL_STEPS} steps")
+
+
+def check_plain_and_mobile(browser, base, wide_views):
+ context = browser.new_context(java_script_enabled=False)
+ page = context.new_page()
+ page.goto(base + MECHANICS)
+ expect(page.locator("article")).to_contain_text("ML-KEM")
+ assert page.locator("article ol li").count() >= 10, "Complete numbered transcripts are required"
+ for widget in page.locator(".sy-mechanics").all():
+ expect(widget).to_be_hidden()
+ context.close()
+ context = browser.new_context(viewport={"width": 375, "height": 812}, is_mobile=True, has_touch=True)
+ page = context.new_page()
+ for path in ["", MECHANICS]:
+ page.goto(base + path)
+ no_overflow(page)
+ if not path:
+ page.screenshot(path=str(PREVIEW / "mobile-home.png"), full_page=True)
+ check_all_narrow_steps(page, wide_views)
+ widget = page.locator('.sy-mechanics[data-flow="handshake"]')
+ for button in widget.get_by_role("button").all() + [widget.get_by_label("Playback speed", exact=True)]:
+ bounds = button.bounding_box()
+ assert bounds["height"] >= 44 and bounds["width"] >= 44, "Mobile touch controls need 44px targets"
+ widget.get_by_role("button", name="Next step", exact=True).click()
+ expect(widget.locator(".sy-mechanics__counter")).to_contain_text("Step 2 of")
+ widget.screenshot(path=str(PREVIEW / "mobile-handshake.png"), style=".md-header, .md-top { visibility: hidden !important; }")
+ approval = page.locator('.sy-mechanics[data-flow="packets"]')
+ seek(approval, 2)
+ approval.screenshot(path=str(PREVIEW / "mobile-packets.png"), style=".md-header, .md-top { visibility: hidden !important; }")
+ page.screenshot(path=str(PREVIEW / "mobile-mechanics.png"), full_page=True)
+ context.close()
+ print("PASS script-free transcripts, hidden empty widgets and mobile layout")
+
+
+def check_search(page, base):
+ page.goto(base)
+ logo = page.locator(".sy-hero img")
+ expect(logo).to_be_visible()
+ assert logo.evaluate("image => image.complete && image.naturalWidth > 0"), "The project mascot must load on the landing page"
+ check_contrast(page)
+ page.locator("input.md-search__input").fill("ML-KEM")
+ expect(page.locator(".md-search-result__item").first).to_be_visible(timeout=10000)
+ print("PASS local search returns protocol results")
+
+
+class QuietHandler(SimpleHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+
+def main():
+ assert (ROOT / "mkdocs.yml").is_file(), "Documentation needs a MkDocs site configuration"
+ subprocess.run([sys.executable, "-m", "mkdocs", "build", "--strict"], cwd=ROOT, check=True)
+ check_links()
+ PREVIEW.mkdir(parents=True, exist_ok=True)
+ handler = partial(QuietHandler, directory=str(SITE))
+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ base = f"http://127.0.0.1:{server.server_port}/"
+ try:
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(args=["--disable-gpu"])
+ context = browser.new_context(viewport={"width": 1440, "height": 1000})
+ external = []
+ def local_only(route):
+ if route.request.url.startswith(base):
+ route.continue_()
+ else:
+ external.append(route.request.url)
+ route.abort()
+ context.route("**/*", local_only)
+ page = context.new_page()
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ wide_views = check_rich_diagrams(page, base)
+ check_flows(page, base)
+ check_chapters_and_payloads(page)
+ check_svg_contrast(page)
+ check_contrast(page)
+ assert not external, f"Unexpected external asset requests: {external}"
+ no_overflow(page)
+ check_playback(page)
+ check_final_delivery(page)
+ check_search(page, base)
+ page.keyboard.press("Escape")
+ page.screenshot(path=str(PREVIEW / "desktop-home.png"), full_page=True)
+ page.goto(base + MECHANICS)
+ page.screenshot(path=str(PREVIEW / "desktop-mechanics.png"), full_page=True)
+ check_reduced(browser, base)
+ check_plain_and_mobile(browser, base, wide_views)
+ check_tablet(browser, base, wide_views)
+ page.emulate_media(media="print")
+ check_contrast(page)
+ for widget in page.locator(".sy-mechanics").all():
+ expect(widget).to_be_hidden()
+ print("PASS print contrast and hidden illustrations with complete transcripts")
+ assert not external, f"Unexpected external asset requests: {external}"
+ assert not errors, f"Browser errors: {errors}"
+ context.close()
+ browser.close()
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+ print("Documentation checks passed")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/docs-examples-check.py b/scripts/docs-examples-check.py
new file mode 100644
index 0000000..cde3be7
--- /dev/null
+++ b/scripts/docs-examples-check.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python3
+"""Check documented CLI workflows without root, VPN connections, or existing credentials.
+
+FRD: specs/frds/FRD-illustrated-documentation.md
+Build `cargo build --locked --bin prrr`, then run with Python 3.11 or newer.
+Generated client credentials remain in a private temporary directory and are
+deleted at exit. No server or VPN session is started.
+"""
+
+import argparse
+import base64
+import os
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+import tomllib
+
+
+ROOT = Path(__file__).resolve().parents[1]
+CLIENT_NAME = "docs-client"
+SERVER_NAME = "vpn.example.net"
+SERVER_PORT = 1443
+KEY_BYTES = 32
+KEM_PUBLIC_KEY_BYTES = 1184
+DEFAULT_MTU = 1100
+TOML_FENCE = re.compile(r"^```toml[^\n]*\n(.*?)^```\s*$", re.MULTILINE | re.DOTALL)
+
+
+def check_toml_examples():
+ """Parse canonical site examples; legacy documents are not published."""
+ pages = [ROOT / "docs/index.md"]
+ for section in ("tutorials", "how-to", "reference", "explanation", "contributing"):
+ pages.extend(sorted((ROOT / "docs" / section).rglob("*.md")))
+ count = 0
+ for page in pages:
+ if not page.exists():
+ continue
+ for index, match in enumerate(TOML_FENCE.finditer(page.read_text()), 1):
+ try:
+ tomllib.loads(match.group(1))
+ except tomllib.TOMLDecodeError as error:
+ raise AssertionError(f"Invalid TOML example {page.relative_to(ROOT)} #{index}") from error
+ count += 1
+ return count
+
+
+def check_cli(binary):
+ """Exercise provisioning, import, routing edits, sharing and revocation."""
+ with tempfile.TemporaryDirectory(prefix="prrr-docs-") as temporary:
+ fixture = Path(temporary)
+ env = {key: value for key, value in os.environ.items() if not key.startswith("PRRR_")}
+ env.update(HOME=str(fixture), RUST_LOG="error")
+
+ def run(*arguments):
+ result = subprocess.run(
+ [str(binary), *map(str, arguments)], cwd=fixture, env=env,
+ capture_output=True, text=True, timeout=30, check=False,
+ )
+ # Never include captured config output in failure messages.
+ assert result.returncode == 0, f"CLI failed ({result.returncode}): {' '.join(map(str, arguments))}"
+ return result.stdout
+
+ helps = [(), ("server",), ("server", "client"), ("client",),
+ ("client", "route"), ("sharing",)]
+ for command in helps:
+ assert "Usage:" in run(*command, "--help"), f"Missing help for {command}"
+ for command in ("add", "list", "remove", "export"):
+ assert "Usage:" in run("server", "client", command, "--help")
+ for command in ("add", "list", "remove"):
+ assert "Usage:" in run("client", "route", command, "--help")
+ for command in ("enable", "disable", "status"):
+ assert "Usage:" in run("sharing", command, "--help")
+ assert "Usage:" in run("client", "import", "--help")
+
+ data = fixture / "data"
+ data.mkdir()
+ server_config = fixture / "server.toml"
+ basic_config = (
+ f'[server]\ndata_dir = "{data.as_posix()}"\n'
+ f'[crypto]\nidentity_key_path = "{fixture.as_posix()}/identity.key"\n'
+ f'pq_key_path = "{fixture.as_posix()}/pq.key"\n'
+ )
+ server_config.write_text(basic_config + '\n[[transports]]\nname = "harp"\nenabled = true\n')
+ server = ("server", "--config", server_config, "--server-name", SERVER_NAME,
+ "--listen", f"127.0.0.1:{SERVER_PORT}", "client")
+
+ generated_text = run(*server, "add", CLIENT_NAME)
+ generated = tomllib.loads(generated_text)
+ assert generated["server"]["endpoint"] == f"{SERVER_NAME}:{SERVER_PORT}"
+ assert generated["server"]["server_name"] == SERVER_NAME
+ for section, field, length in (
+ ("interface", "private_key", KEY_BYTES),
+ ("server", "public_key", KEY_BYTES),
+ ("server", "pq_public_key", KEM_PUBLIC_KEY_BYTES),
+ ):
+ assert len(base64.b64decode(generated[section][field], validate=True)) == length, field
+ assert generated["interface"]["mtu"] == DEFAULT_MTU
+ assert generated["interface"]["transport_protocol"] == "harp"
+ assert CLIENT_NAME in run(*server, "list")
+
+ private_config = fixture / "client.toml"
+ private_config.write_text(generated_text)
+ private_config.chmod(0o600)
+ run("client", "import", private_config)
+ imported_path = fixture / ".config/prrr/client.toml"
+ assert imported_path.read_text() == generated_text, "Import changed the generated config"
+
+ client = ("client", "--config", imported_path, "route")
+ run(*client, "add", "docs.example.net")
+ run(*client, "add", "192.0.2.10")
+ assert set(run(*client, "list").splitlines()) == {"docs.example.net", "192.0.2.10"}
+ run(*client, "add", "docs.example.net")
+ assert run(*client, "list").count("docs.example.net") == 1, "Duplicate route was stored"
+ run(*client, "remove", "docs.example.net")
+ assert run(*client, "list").strip() == "192.0.2.10"
+ assert tomllib.loads(imported_path.read_text())["interface"]["private_key"] == generated["interface"]["private_key"]
+
+ exported = tomllib.loads(run(*server, "export", CLIENT_NAME))
+ assert "private_key" not in exported.get("interface", {}), "Export unexpectedly contains a private key"
+ assert exported["server"]["public_key"] == generated["server"]["public_key"]
+ run(*server, "remove", CLIENT_NAME)
+ assert CLIENT_NAME not in run(*server, "list"), "Revoked client remains active"
+
+ # Capture the existing fallback explicitly so docs cannot silently
+ # assume a generated client uses the server's implicit HARP default.
+ server_config.write_text(basic_config)
+ fallback = tomllib.loads(run(*server, "add", "fallback-client"))
+ assert fallback["interface"]["transport_protocol"] == "masque"
+
+ assert "disabled" in run("sharing", "status")
+ run("sharing", "enable")
+ assert "enabled" in run("sharing", "status")
+ run("sharing", "disable")
+ assert "disabled" in run("sharing", "status")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", type=Path, default=ROOT / "target/debug/prrr")
+ args = parser.parse_args()
+ binary = args.binary.resolve()
+ if not binary.is_file():
+ parser.error(f"Missing {binary}; run cargo build --locked --bin prrr first")
+ toml_count = check_toml_examples()
+ check_cli(binary)
+ print(f"Documentation examples passed: {toml_count} TOML fences; real CLI help, provisioning, import, "
+ "route edits, public export, revocation, transport fallback and sharing state. "
+ "No VPN connection or system routing change.")
+
+
+if __name__ == "__main__":
+ main()