提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
+83
View File
@@ -0,0 +1,83 @@
---
layout: default
title: Automation (Tasker / MacroDroid)
---
# Automation (Tasker / MacroDroid)
Drive Haven from your phone's automation apps. Haven ships a native Tasker /
Locale / MacroDroid **plugin action** — "Run command on a Haven server" — and
exposes the same capability over its local [MCP HTTP endpoint](../mcp-tools.md)
for hosts that prefer raw HTTP requests.
## Run command on a Haven server (plugin action)
A Locale-protocol plugin action, discoverable directly in Tasker's and
MacroDroid's "add action → plugin" list — there's no separate plugin APK, it's
built into Haven. Add the action, tap to configure, and set:
- **Haven server** — a dropdown of your saved SSH connections.
- **Command** — a shell command, run in the login shell. The host substitutes
its own variables into it *before* it fires, so a one-liner like
`cd {lv=project_dir} && git pull origin {lv=branch}`
works with your MacroDroid/Tasker variables inline.
- **Wait until the command finishes** — hold the macro until the command exits
(Tasker/MacroDroid's "wait for action"). Off = fire-and-forget.
- **Show the command in a live terminal** — bring Haven to the front and stream
the command into a visible terminal tab so you can watch it run.
When the command finishes it posts a result notification (exit code + a snippet
of the output).
### Result variables
In **wait** mode the action returns the command's output to the host as local
variables, for use in later macro steps:
| Variable | Contents |
|---|---|
| `%hstdout` | the command's standard output |
| `%hstderr` | the command's standard error |
| `%hexit` | the exit code (`-1` if the connection failed) |
The action declares these variables to the host so they appear in its variable
list. Passback only happens in wait mode — a fire-and-forget host has already
moved on by the time the command finishes.
### Watching it run (live terminal)
Android's background-activity-launch rules don't let a plugin's broadcast
receiver bring an app to the foreground on its own, so "show the command in a
live terminal" posts a **"Watch <server>" notification**; tapping it foregrounds
Haven, connects (or reuses) the profile's terminal, and types the command in.
One tap, then you watch the output live.
### Firing it as a raw intent
The action also accepts its config as **flat intent extras**, so it works from a
generic "Send Intent" step (or `adb`) as well as the plugin flow — broadcast
`com.twofortyfouram.locale.intent.action.FIRE_SETTING` to
`sh.haven.app/.tasker.TaskerFireReceiver` with string extras
`sh.haven.tasker.PROFILE_ID`, `sh.haven.tasker.COMMAND`, and boolean extras
`sh.haven.tasker.BLOCK`, `sh.haven.tasker.OVERLAY`.
### How it runs
The command runs over SSH through Haven's headless exec path: it reuses a live
session for the profile if one is connected, otherwise it connects headlessly.
Headless connect needs a stored password or an unencrypted key — FIDO2/encrypted
keys, and port-knock / SPA / tunnel-routed profiles, must be connected
interactively in Haven at least once first, after which the reuse path serves
them. No extra setup beyond having the SSH connection saved.
## HTTP / MCP endpoint
The same "run a command on a server" capability is available over Haven's local
agent endpoint (`http://127.0.0.1:8730/mcp`) via the `run_command` tool — pair
once (an approve-on-device prompt mints a token), then drive it with a single
authenticated POST per action from MacroDroid's/Tasker's **HTTP Request** action.
See [Agent transport (MCP)](../mcp-tools.md).
---
[← All features](../FEATURES.md)
@@ -0,0 +1,33 @@
---
layout: default
title: Connections & networking
---
# Connections & networking
Saved connection profiles, the transports they ride, the firewall front-doors
that open before a connect, and on-device SSH key management.
## Connections
Saved profiles with transport selection (SSH, Mosh, Eternal Terminal, VNC, RDP, SMB, Email, Cloud Storage, Reticulum, and [Bluetooth / BLE / USB serial consoles](terminal.md#serial-consoles-bluetooth-ble-usb)), host key TOFU verification, fingerprint change detection, auto-reconnect with backoff, password fallback, local/remote/**dynamic** port forwarding (-L/-R/-D — the dynamic type runs a built-in SOCKS5 proxy that tunnels traffic through the SSH session), ProxyJump multi-hop tunneling (-J) with tree view, SOCKS5/SOCKS4/HTTP proxy support (Tor .onion compatible), RDP-over-SSH tunnel profiles, DNS resolution with 5s timeout, and connection error safety nets (20s UI watchdog, post-connect shell verification, session manager detection).
**Per-app WireGuard and Tailscale tunnels** — each profile can route its connection through its own userspace tunnel, with no system VPN slot taken, so other apps keep using the direct network.
## Port knocking
Optional per-profile knock sequence sent immediately before the real socket open. Format is whitespace- or comma-separated `port[/proto]` tokens — e.g. `7000 8000 9000` (all TCP) or `7000/tcp 8000/udp 9000/tcp` for mixed sequences that match a `knockd`/`fwknop`-style configuration. The sequence is fired from the device using ordinary TCP `Socket.connect()` and `DatagramSocket.send()` calls (no root, no raw sockets), with a configurable inter-knock delay (default 100 ms) and a fixed 200 ms post-knock settle so the firewall has time to install its rule before SSH/VNC/RDP/SMB connects. Wired into all direct-dial paths; skipped on SSH-tunneled, WireGuard/Tailscale, and SOCKS-routed paths since the knock packet wouldn't reach the right firewall from the device. Each knock attempt — success or failure — appears in the Connection Log entry's verbose output as a `[knock] ... -> ok in Nms` line so post-hoc debugging is possible. The connection-edit dialog includes a **Test knock** button that runs the sequence once without committing or connecting, returning the result inline.
## Single Packet Authorization (fwknop)
The cryptographic alternative to port knocking, interoperable with [fwknop](https://github.com/mrash/fwknop)/`fwknopd`. Where a knock sequence is a series of cleartext SYNs that a passive observer can record and replay in order, SPA is a single encrypted, HMAC-authenticated UDP packet — it can't be read, and the per-packet HMAC plus random/timestamp fields defeat replay. Haven builds the packet itself, natively in Kotlin (no `fwknop` binary), and sends it on the same pre-connect hook as the knock; if both are configured the SPA goes first.
The implementation follows the fwknop wire format: an SHA-256-digested message encrypted with AES-256-CBC (OpenSSL `Salted__` / EVP-BytesToKey-MD5 key derivation) and authenticated with encrypt-then-MAC HMAC-SHA256 — the modern fwknop defaults. The Kotlin builder is verified byte-for-byte against `fwknop 2.6.11`, and a live `fwknopd` accepts Haven's packets and opens the firewall. Per profile you set the Rijndael key and (recommended) HMAC key — each as a passphrase or base64 (`--key-base64-rijndael` / `--key-base64-hmac`) — the access spec (`tcp/22`, or comma-separated for multiple ports), the destination UDP port (default 62201), and the allow-IP mode: **Source IP** (sends `0.0.0.0`, so `fwknopd` opens for the packet's own source IP — the right default for a phone behind changing/CGNAT addresses, with no extra round-trip), **Resolve public IP** (looks up the egress IP first, like `fwknop -R`), or **Explicit IP**. Like the knock it runs only on direct-dial paths, logs a `[spa] ... -> sent NB in Nms` line to the Connection Log, and has a **Test SPA** button that sends one packet without committing or connecting. Keys are stored encrypted at rest (Android Keystore-backed AEAD), and the `set_spa`/`test_spa` MCP tools never echo key material back. v1 is AES-CBC + HMAC-SHA256 over UDP only — no GPG mode, alternate cipher/digest modes, or NAT-access.
## SSH Keys
Generate Ed25519, RSA, and ECDSA keys on-device. Import keys from file (PEM/OpenSSH/Dropbear format) or paste from clipboard. FIDO2/SK hardware key support (ed25519-sk, ecdsa-sk) via NFC or USB security keys — and a phone-hosted security key can be forwarded to a remote host (see [USB device forwarding](usb.md)). One-tap public key copy and deploy key dialog for `authorized_keys` setup. Assign specific keys to individual connections.
---
[← All features](../FEATURES.md)
+47
View File
@@ -0,0 +1,47 @@
---
layout: default
title: Desktops
---
# Desktops
Remote and on-device desktops: a VNC viewer, an RDP client, a SPICE client, a
GPU-accelerated native Wayland compositor that runs inside Haven, and a
multi-distro manager for full Linux desktops on the phone. For the local *shell*
side of the on-device distros, see [Local Linux](local-linux.md).
## Desktop (VNC)
Remote desktop viewer with RFB 3.8 protocol support. Pinch-to-zoom, two-finger pan and scroll, single-finger drag for window management, soft keyboard with X11 KeySym mapping. Fullscreen mode with NoMachine-style corner hotspot for session controls. Connect directly or tunnel through SSH. Supports Raw, CopyRect, RRE, Hextile, and ZLib encodings. Security types: **None**, classic **VncAuth** (DES), and **VeNCrypt** (security type 19) with TLSPlain/X509Plain/TLSVnc/X509Vnc/TLSNone/X509None/Plain sub-types — connects to wayvnc, TigerVNC, libvncserver, x11vnc and other servers that require a username alongside a password, wrapping the socket in TLS after sub-type negotiation.
## Desktop (RDP)
Remote Desktop Protocol client built on [IronRDP](https://github.com/Devolutions/IronRDP) via UniFFI Kotlin bindings. Connects to Windows Remote Desktop, xrdp (Linux), and GNOME Remote Desktop. **EGFX (MS-RDPEGFX) graphics-pipeline support** — ClearCodec and RemoteFX Progressive decoders light up the fast graphics path on modern Windows (verified against Windows Server 2025), with a slow-path fallback for servers that don't negotiate it. Pinch-to-zoom, pan, keyboard with scancode mapping, mouse input. SSH tunnel support with auto-connect through saved SSH profiles. Saved connection profiles with optional stored password.
## Desktop (SPICE)
[SPICE](https://www.spice-space.org/) client for QEMU/KVM and libvirt virtual machines, built on a vendored Rust SPICE core exposed through UniFFI Kotlin bindings (the same approach as the RDP client). The display channel decodes the SPICE image codecs — raw bitmap, **LZ**, **GLZ** and **ZLIB-GLZ** dictionary compression, and **QUIC** (SFALIC), plus the image cache — alongside server draw operations, hardware-cursor shape and position, and multiple display surfaces. Input covers the keyboard (scancodes), an absolute pointer, mouse buttons and the scroll wheel. The viewer shares the VNC/RDP gestures: two-finger pinch-zoom and pan, and a soft keyboard. SSH tunnelling is supported — the SPICE core dials its own TCP socket, so Haven opens a local `-L` forward through a saved SSH profile and points the client at `127.0.0.1`. Decoding is verified pixel-correct against QEMU and Windows Server 2025 guests (the GLZ and QUIC paths). Configure SPICE connections in the Connections tab or via the agent (MCP).
## Native Wayland Desktop
GPU-accelerated Wayland compositor (labwc) running natively inside Haven. Full interactive terminal with keyboard input, mouse interaction, server-side window decorations, pinch-to-zoom, and fullscreen mode with corner overlay menu. The GPU pipeline renders via GLES2 on the device's GPU (AHardwareBuffer allocator, ASurfaceControl zero-copy presentation). Native Wayland clients can render 3D content — includes a built-in GLES2 benchmark (rotating lit cube at 60fps on Mali-G715). **Display-scale / resolution control** — pick the compositor's output resolution from the toolbar or fullscreen menu; it reflows windows at the new resolution rather than just visually zooming. Configurable shell (/bin/sh, bash, zsh, fish) and shared keyboard toolbar (Esc, Tab, Ctrl, Alt, arrows, function keys, plus a Super/Mod4 key for compositor keybinds). External Wayland clients can connect via Shizuku (symlinks the socket to `/data/local/tmp/haven-wayland/`). No root required — runs in PRoot with an Alpine Linux rootfs.
## GPU-accelerated Linux GL apps
A single Linux GUI app can run in a **cage** (single-app kiosk compositor) with the device GPU passed through — no `/dev/dri`, no root. A host-side [virglrenderer](https://gitlab.freedesktop.org/virgl/virglrenderer) broker hands the **Mali** GPU to the guest:
- **virgl** (default) translates the guest's OpenGL onto the host GPU — OpenGL 2.1, on by default for cage apps (`GL_RENDERER = virgl (Mali-G715)`).
- **venus + zink** (experimental, toggled in Settings) routes the guest's Vulkan straight to the GPU and runs **zink** on top for modern OpenGL (~3.2 core), for apps that need newer GL than virgl exposes. Needs `mesa-vulkan-drivers` in the guest; off falls back to virgl. Verified on Mali-G715 with vkcube and a geometry-animating GL demo (the clip on the [landing page](../index.md)) running accelerated.
## Local Desktops (multi-distro manager)
A **Desktop → Manage** view installs and runs full Linux desktops on-device via PRoot, with no root. Pick a distro — **Alpine** (APK), **Debian 12** (APT), **Arch Linux ARM** (PACMAN), or **Void** (XBPS) — and install them side-by-side; each carries its native package manager. For each installed distro you can install, start, and stop desktop environments, open a shell into it, and read a Room-backed install log that names the layer that broke if a package install fails.
Desktop environments:
- **X11 (via Xvnc)** — Xfce4 or Openbox, each on its own VNC port, viewed through the in-app VNC client.
- **Nested Wayland (via wayvnc)** — a headless wlroots compositor inside the rootfs, surfaced over VNC. **Sway** is the supported, working option. Hyprland and niri are offered but GPU-limited: their renderers (aquamarine / smithay) are GLES-only with no software fallback, and the Android GPU isn't driveable by Mesa inside PRoot, so they can't currently initialise a backend (tracked on #162). For a GPU-accelerated local desktop, use the Native Wayland Desktop above; for a single GPU-accelerated app, use the cage path above.
---
[← All features](../FEATURES.md)
+30
View File
@@ -0,0 +1,30 @@
---
layout: default
title: Email & Mail Rules
---
# Email & Mail Rules
An in-app mail client — read and send without leaving Haven — plus inbound
automation that runs against new mail.
## Email
Two engines sit behind one `MailClient` abstraction (`Map<MailEngine, MailClient>`), so a new provider drops in without touching the UI:
- **ProtonMail** — read mail via the Proton bridge protocol (the path the desktop Proton Bridge speaks), decrypted in the Go mailbridge.
- **Generic IMAP/SMTP** — any standard mailbox: read **and** send.
A folder and message list, a reader, and **compose / reply / forward** over IMAP/SMTP. **Multi-account** — a From-row account picker, with the message list and reader showing the active account. **Attachments** — save an attachment to, or attach a file from, any filesystem Haven already browses (local, SFTP, SMB, rclone) plus the Android document picker (SAF). Proton *send* is a follow-up; Proton is read-only today.
**Supported providers.** The generic engine works with any mailbox reachable over standard IMAP + SMTP with a username and password — Gmail, Outlook / Microsoft 365, Fastmail, Yahoo, iCloud, and self-hosted servers (Dovecot, etc.). Providers that require an app-specific password when 2-factor is on (e.g. Gmail, Yahoo, iCloud) work once you generate one. Authentication is username/password only — there is no OAuth / SSO sign-in flow yet, so mailboxes that *only* allow OAuth (some corporate/Google-Workspace tenants) aren't reachable. ProtonMail is the one non-IMAP engine, spoken over the Proton bridge protocol (read-only for now).
## Mail Rules — inbound automation
Rules that run against new mail. Each rule combines **match conditions** (from / to / subject / unread / has-attachment / body / header, with contains / equals / regex / glob) under ALL or ANY, with an ordered list of **actions** — mark read/unread, set/clear flag, move to folder, delete, notify, plus advanced actions an agent can author (run a command, save attachments, send to the agent, invoke an MCP tool). A **master switch** keeps automation inert until you enable it; a **firing history** logs what ran; and **destructive actions matched while Haven is backgrounded are held in a pending-approval queue** — approve to run them on the message, or reject to discard. Rules are authorable over MCP and managed in-app from the Mail screen's overflow menu; the in-app editor builds the human-friendly subset and opens agent-authored advanced rules read-only so it can't corrupt them.
Mail is also exposed to the agent: `list_mail_folders`, `list_mail_messages`, `read_mail_message`, and `send_mail`, plus the Mail Rules tools (`create_mail_rule`, `list_mail_rules`, `delete_mail_rule`).
---
[← All features](../FEATURES.md)
@@ -0,0 +1,29 @@
---
layout: default
title: Files & cloud storage
---
# Files & cloud storage
A unified file browser across SFTP/SCP, SMB, 60+ cloud providers, and Reticulum
mesh, plus on-device media transcoding and streaming.
## Files
Unified file browser with SFTP, SMB, and cloud storage tabs. Browse remote directories, upload files or entire folders, download, delete, rename, create directories, copy path, toggle hidden files, sort by name/size/date. **Multi-select** — long-press or tap **Select** to enter selection mode with a contextual action bar (copy, cut, permissions, delete). **Permissions editor** — octal field plus a 3×3 rwx checkbox grid, supported on SFTP/SCP/local (not SMB/rclone). **Built-in text editor** with syntax highlighting, find/replace, and terminal-matched theme. **Image tools** — view, crop, rotate, perspective-correct. **Cross-filesystem copy/move** — copy files between any backends (e.g. Google Drive → SFTP server) with clipboard model: long-press → Copy/Cut, switch tab, Paste. Conflict resolution (skip/replace) for existing files. Path preserved when switching between tabs.
## SMB
Browse Windows/Samba file shares with optional SSH tunneling for secure access over the internet.
## Cloud Storage
Browse, upload, download, and manage files on 60+ cloud providers via [rclone](https://rclone.org) — Google Drive, Dropbox, OneDrive, Amazon S3, Backblaze B2, and more. OAuth authentication with automatic browser flow. Server-side copy between cloud remotes (no temp file needed). **Share link** — generate public URLs for files on supported backends. **Folder size** — fast recursive size calculation. **Folder sync** — copy, mirror, or move between remotes with include/exclude filters, size limits, bandwidth throttling, and dry-run preview. **Media streaming** — stream audio/video to VLC or any player via local HTTP server with M3U playlists and seeking. **DLNA server** — stream cloud media to smart TVs and Chromecast on the local network.
## Media Convert
Convert media files between formats directly on-device using a custom [FFmpeg 8.0](https://ffmpeg.org) build with the full codec/format/filter set. Long-press any media file and tap Convert. Separate dropdown selectors for container format (MP4, MKV, WebM, MOV, AVI, MPEG-TS, MP3, WAV, OGG, Opus, FLAC, M4A), video encoder (H.264, H.265, VP9, VP8, MPEG-4, stream copy), and audio encoder (AAC, MP3, Opus, Vorbis, FLAC, PCM, FLAC, stream copy). **Copy-remux by default** — container auto-matches the source extension so tapping Convert on most files gives an instant lossless remux. **Frame preview** — see filter effects on a single frame before committing, with seek slider and tap-to-fullscreen. **Audio preview** — play a 5-second clip with current filters applied. Video filters: brightness, contrast, saturation, gamma, sharpen, denoise, stabilize (deshake), auto color correction, speed, rotation. Audio filters: volume, loudness normalization (EBU R128). One-tap presets (Stabilize, Fix Colors, Enhance, Normalize Audio). Live CLI preview shows the exact ffmpeg command being built. Audio-only files auto-detected — video UI hidden, only audio formats shown. **Save to** picker: Downloads folder or back to the source folder (uploads to cloud/SFTP/SMB with live progress). **Works on cloud files without downloading** — for rclone profiles, ffmpeg streams the source over HTTP via the rclone VFS so transcode starts in seconds regardless of file size (falls back to full download for offline/reliability via a toggle). **HLS streaming** — stream any local or rclone media file to other devices on the network via an HTML5 player; URL auto-copied to clipboard and opened at the device's LAN IP for easy sharing.
---
[← All features](../FEATURES.md)
+29
View File
@@ -0,0 +1,29 @@
---
layout: default
title: Languages & translation
---
# Languages & translation
Haven's interface is translated into **12 languages** — English, Chinese (Simplified), Spanish, Hindi, Arabic (with right-to-left layout), Portuguese, Bengali, Russian, Japanese, Korean, French, and German. By default the UI follows your device language; you can override it under **Settings → Language**, which uses Android's per-app locale API so the switch is instant and doesn't restart the app. Pick **System default** to go back to tracking the device.
## Contribute a translation
The translations began as machine-generated drafts, so corrections — and new languages — are genuinely welcome. The **[translation page](../translate.html)** lets you help without cloning the repo or hand-editing XML:
- **Browse every string.** All ~1,800 in-app strings across the app are listed with the developer's context comment, and you can see, per language, exactly what's translated and what's still missing.
- **Fill the gaps inline.** Filter to just the untranslated strings, type your translations, and the page tracks your changes. Format placeholders like `%1$s` are flagged so they survive translation.
- **Propose as a pull request.** When you're done, the page builds the updated resource file and hands off to GitHub's own editor — GitHub handles sign-in and forking, so there's **no account to create here and no backend to trust**. Your changes arrive as a normal pull request.
- **Start a new language** the same way — pick a locale code and fill in what you can.
Contributions are reviewed before they ship. The string list is regenerated from the app's resources on every change, so it always reflects the current release.
**[🌍 Open the translation page →](../translate.html)**
## The site is translated too
This documentation site's landing page is available in all 12 languages — use the language bar at the top of any page to switch.
---
[← All features](../FEATURES.md)
@@ -0,0 +1,28 @@
---
layout: default
title: Local Linux on-device
---
# Local Linux on-device
Run a real Linux userland directly on the phone, no root required — a shell, a
package manager, and (via the [Desktops](desktops.md) manager) full desktop
environments, all side-by-side.
## Local Shell (PRoot)
Run a real Linux terminal directly on your phone, no root required. Select "Local Shell (PRoot)" when creating a connection and Haven downloads a minimal [Alpine Linux](https://alpinelinux.org/) rootfs (~4 MB) on first use, giving you a full `apk` package manager — install Python, Node.js, git, build tools, or anything in Alpine's [package repository](https://pkgs.alpinelinux.org/packages). Beyond Alpine, the Desktop → Manage view can install **Debian 12** (`apt`), **Arch Linux ARM** (`pacman`), and **Void** (`xbps`) rootfs side-by-side, each with its own package manager and a one-tap shell.
PRoot works by intercepting system calls in userspace (no kernel modifications), so it runs on **any unrooted Android device**. It does not require or use root access — the name "PRoot" stands for "ptrace-based root", meaning it *emulates* a root filesystem without actual superuser privileges. Think of it as a lightweight container that runs entirely within Haven's app sandbox.
How it compares to alternatives:
- **Rooted phones (Magisk/su)**: Root gives full system access. PRoot is sandboxed — it can't modify your system, but it also doesn't need root to work.
- **[Android Terminal VM](https://developer.android.com/studio/run/managing-avds)** (Pixel 8+): Google's official Linux VM runs a full kernel via [pKVM](https://source.android.com/docs/core/virtualization). It's more capable but only available on Pixel 8 and newer. PRoot runs on any device back to Android 8. Haven can SSH into an Android Terminal VM if you have one — see the connection settings.
- **[Termux](https://termux.dev/)**: A standalone terminal emulator with its own package ecosystem. PRoot is lighter (4 MB vs ~100 MB) and integrated into Haven alongside your SSH/cloud sessions.
See [PRoot documentation](https://proot-me.github.io/) for technical details. For desktop environments on top of these distros, see [Desktops → Local Desktops](desktops.md).
---
[← All features](../FEATURES.md)
+19
View File
@@ -0,0 +1,19 @@
---
layout: default
title: Reticulum mesh
---
# Reticulum mesh
Connect over [Reticulum](https://reticulum.network) mesh networks with native Kotlin transport (reticulum-kt + rnsh-kt). Two-way terminal sessions over IFAC-protected TCP gateways, announce-based rnsh node discovery via scan button, configurable IFAC network name and passphrase. No Python runtime or Chaquopy dependency — pure Kotlin implementation with Flow-based I/O.
Beyond the shell, the mesh carries files and tunnels — the same surface area SSH has, layered on the rnsh remote command-exec substrate (each operation runs one busybox-portable command over its own Reticulum Link):
- **File transfer** — the unified file browser lists, downloads, and uploads files on an rnsh destination, plus mkdir/rename/delete. Directory listings parse `ls -la` (no GNU `stat`/`find` assumed, so it works against a busybox OpenWRT router as well as a full Linux host). Uploads stream over a **single Link**: the bytes are octal-encoded and fed as `printf` commands to one interactive `sh` over stdin, device-verified byte-identical (all 256 byte values, including NUL and high bytes). Small-file oriented — one command per directory op and a stdin stream per upload, well suited to configs, keys, and scripts rather than large media over a low-bandwidth mesh.
- **Tunnelable port** — `-L` local forwarding and `-D` SOCKS5 dynamic forwarding tunnel TCP across the mesh (one Link per connection, bridged to a remote `nc`), so you can reach a LAN host behind a Reticulum gateway.
Reticulum is the only transport in Haven that survives full internet loss, so anything routed through it is a uniquely offline-capable path, not a duplicate of SSH.
---
[← All features](../FEATURES.md)
+14
View File
@@ -0,0 +1,14 @@
---
layout: default
title: Security & privacy
---
# Security & privacy
Screen lock with biometric or device PIN/password/pattern, configurable timeout (immediate/30s/1m/5m/never), no telemetry or analytics, local storage only. Keyboard security: all credential fields set `IME_FLAG_NO_PERSONALIZED_LEARNING` to prevent keyboard apps from recording passwords, with a warning when the active keyboard has internet access. Encrypted backup/restore with AES-256-GCM. See the [privacy policy](../privacy-policy.html).
The encrypted backup wire format (PBKDF2/AES-GCM envelope) and a Python recipe for manual decryption are documented in [Backup file format](../backup-format.md).
---
[← All features](../FEATURES.md)
+38
View File
@@ -0,0 +1,38 @@
---
layout: default
title: Terminal
---
# Terminal
VT100/xterm emulator with multi-tab sessions, [Mosh](https://mosh.org) (Mobile Shell) for roaming connections and [Eternal Terminal](https://eternalterminal.dev) (ET) for persistent sessions — both with pure Kotlin protocol implementations (no native binaries), tmux/zellij/screen auto-attach with **session restore** (remembers previously open sessions and offers to reopen them), tab reordering via long-press menu, color-coded tabs matching connection profiles, mouse mode for TUI apps, configurable keyboard toolbar (Esc, Tab, Ctrl, Alt, AltGr, arrows, Delete, Insert, Home/End/PgUp/PgDn, F1–F12, custom macro keys with presets for common combos like Ctrl+C/D/Z and Ctrl+Alt+Delete), text selection with copy and Open URL, OSC 133 shell integration with one-tap "copy last command output", configurable font size, and six color schemes. The bundled Hack Nerd Font Mono renders Powerline / Devicons / Font Awesome / Material Design glyphs in shell prompts out of the box.
## Serial consoles (Bluetooth, BLE, USB)
Haven speaks serial as well as network transports, so a microcontroller or an embedded board gets a full terminal — the same tabs, keyboard toolbar, text selection and colour schemes as SSH. Each is an ordinary saved connection profile, so reconnect, workspace capture and agent control all apply.
- **USB serial** — plug a USB-serial device into the phone over OTG: an Arduino, a Duet3D G-code board, an ESP32, or a USB-TTL adapter. Pick the attached device by its `vendor:product` id, set the baud rate and, if needed, the line format — data bits, parity, stop bits, flow control (default 8N1, no flow control). Android asks for USB permission on first connect. Common chipsets work: CDC-ACM, CH34x, FTDI, CP21xx, Prolific. DTR and RTS are asserted on open, so a device that stays silent until the port is "opened" (many Arduino sketches that wait on `while (!Serial)`) starts streaming right away.
- **Bluetooth serial (Classic SPP)** — a console over a paired Bluetooth-to-serial adapter (RFCOMM / Serial Port Profile). Pair the adapter in Android Settings → Bluetooth first, then pick it by its Bluetooth address.
- **Bluetooth LE serial (GATT UART)** — for BLE-only peripherals like an nRF board or an HM-10 module that Classic SPP can't reach. No pairing needed: add a connection, tap **Scan**, and pick the advertising device. The GATT service is auto-detected (Nordic UART Service, then HM-10), or you can supply explicit service/characteristic UUIDs.
## Serial-to-TCP bridge
A live serial session — Bluetooth, BLE, or USB — can be exposed as a raw TCP port on the phone's loopback interface, so a physically-attached device joins the rest of Haven's routing fabric. Pair that with an SSH remote-forward or a [tunnel](connections.md) and the serial device is reachable *off* the phone: read a sensor, or drive a board, from anywhere your phone can reach. The terminal tab keeps working while it's bridged, and bytes pass raw in both directions. The bridge is driven through Haven's [agent/MCP interface](../mcp-tools.md) — `bridge_serial_to_tcp` opens it and returns the port, `list_serial_bridges` shows what's active, `stop_serial_bridge` tears it down.
## OSC escape sequences
Remote programs can interact with Android through standard terminal escape sequences:
| OSC | Function | Example |
|-----|----------|---------|
| 52 | Set clipboard | `printf '\e]52;c;%s\a' "$(echo -n text \| base64)"` |
| 8 | Hyperlinks | `printf '\e]8;;https://example.com\aClick\e]8;;\a'` |
| 9 | Notification | `printf '\e]9;Build complete\a'` |
| 777 | Notification (with title) | `printf '\e]777;notify;CI;Pipeline green\a'` |
| 7 | Working directory | `printf '\e]7;file:///home/user\a'` |
Notifications appear as a toast in the foreground or as an Android notification in the background.
---
[← All features](../FEATURES.md)
+190
View File
@@ -0,0 +1,190 @@
---
layout: default
title: Reading USB drives
---
# Reading USB drives (flash drives, SSDs, memory cards)
**The short version:** plug a USB drive into your phone, and Haven can show you
its files — even drives formatted for Linux that your phone normally can't read.
Tap once, wait a minute, and the drive's folders appear in Haven's file browser
like any other connection.
This page assumes no background knowledge. If you just want the steps, jump to
[How to use it](#how-to-use-it). If you're curious *why* a phone struggles with
some drives, read [Why this is hard](#why-this-is-hard) at the end.
## The problem this solves
You plug a USB flash drive or portable SSD into your phone (with a USB-C or
USB-OTG adapter). Sometimes the phone shows the files straight away — great. But
often it shows **nothing**, even though the drive is fine and full of files.
That usually means the drive is formatted in a way your phone's built-in file
support doesn't understand. The most common cases:
- The drive was **formatted on a Linux PC** (a format called *ext4*). Android
can read the simple formats cameras and Windows use (FAT32, exFAT), but not the
Linux ones.
- The drive is **partitioned** in a layout (called *GPT*) the phone won't open.
- It's an **internal disk pulled out of a computer**, a Raspberry Pi SD card, a
NAS disk, and so on.
In all of these, the files are perfectly readable — your phone just doesn't have
the right "driver" built in, and on a normal (un-rooted) phone you can't add one.
## What Haven does
Haven runs a **tiny, throwaway Linux computer inside the app** (a *virtual
machine*) that *does* have those drivers. It hands the USB drive to that little
Linux, which reads the drive and shares the files back to Haven. To you it just
looks like a new connection named after your drive — open it in **Files** and
browse, copy things off, or open a terminal into it.
Nothing is written to your drive (it's mounted **read-only** by default), nothing
leaves your phone, and the little Linux is deleted as soon as you eject the drive.
> You don't need to know anything about virtual machines to use this — that's the
> whole point. The word "QEMU" you might see elsewhere is just the engine doing
> the work behind the scenes.
## How to use it
There's nothing to turn on first — just open the drive when you want it.
**1. Plug in the drive.** Connect your USB drive to the phone with a USB-C or OTG
adapter. (If nothing happens at all, try a different adapter or cable — a flaky
adapter is the most common reason a drive isn't detected.)
**2. Open it.** Go to the **Desktop** tab → **Manage** → the menu next to the
distro picker → **"Open USB drive…"**. (Opening a drive is always a deliberate
tap like this, so it never happens behind your back.) Haven shows *"Opening the
USB drive in a Linux VM — this can take a few minutes…"*
**3. Wait.** The **first** time, this takes a few minutes: Haven downloads a
small Linux image once and builds a little helper system from it. That helper is
**kept**, so every open after the first skips all of that and just boots it —
much quicker. A **live progress line** under Manage shows what it's doing —
*"Building the USB helper Linux…"* (first time only), then *"Booting the USB
helper…", "Setting up the VM and mounting your drive…"* — so you can see it's
working, not stuck.
**4. Browse.** When it's ready, Haven **opens the drive in Files for you**,
showing its contents (your drive's partitions live under `/mnt`, e.g.
`/mnt/sda1`). It also stays saved as a **"USB: …"** connection in **Connections**
— copy files off, preview them, or open a terminal into the drive.
**5. Eject when done.** Back in **Desktop → Manage**, the same menu now says
**"Eject USB drive"** — tap it to shut the little Linux down and free the drive.
(It also closes by itself if you don't.) The **"USB: …"** connection stays put —
it's a bookmark to the drive, not a live session. **Tap it again any time** (with
the drive still plugged in) and Haven reopens the little Linux and reconnects
automatically — you don't need to go back through "Open USB drive…". If the
drive isn't plugged in when you tap it, Haven tells you to plug it back in
first. The helper system itself stays installed between opens; if you'd rather
have the ~280 MB back, the same Manage menu has **"Delete USB helper Linux"** —
it just rebuilds itself, once, the next time you open a drive.
## What works, and what doesn't
**Works:**
- **Linux drives** — ext4, and most partition layouts including GPT.
- **Ordinary drives** — FAT32 / exFAT work here too (though your phone can
usually read those directly without this feature).
- A full **terminal into the drive**, if you want to poke around with Linux
commands — it comes free with the connection.
- **Recovery and forensics tooling, pre-installed** — the VM ships `testdisk`
(partition-table + deleted-file recovery, bundles `photorec`), `gdisk`/
`sgdisk` (GPT repair), `parted` (MBR/GPT editing), `smartctl` (drive
health), `ddrescue` (imaging a failing drive), and `fsck.ext4`/`ntfsfix`/
`fsck.vfat` — because this is a *real* Linux kernel with real block-device
access, not proot. Run them from the terminal like you would on any Linux
box; open the drive **writable** first if a repair needs to write.
**Also works:**
- **Encrypted drives (LUKS)** — a locked partition mounts read-only-locked
alongside any plain ones; the Desktop → Manage card shows an "Unlock…"
action per locked partition (or the `unlock_usb_drive_partition` MCP verb)
once you enter its passphrase. Runs against the already-booted VM, no reboot.
- **Writing to the drive** — "Open USB drive (writable)" mounts read-write
instead of the default read-only, with a confirmation first. Writes are
flushed immediately (mounted with `sync`) rather than cached, and ejecting
explicitly syncs + unmounts before the VM powers off — both specifically to
limit what an unexpected kill (app backgrounded under memory pressure,
crash, battery pull) can corrupt. Read-only stays the safer default.
**Also works: multiple drives at once** — open a second (or third, up to a
phone-resource limit) drive without ejecting the first. They share one
running VM rather than each getting their own (the small helper Linux is
booted once; every additional drive is just another attach inside it),
each with independent files, mounts, and its own Eject.
**Doesn't work (and never will):**
- **Webcams and USB microphones** — these can *never* work through any of Haven's
USB features, due to a hard limit in Android's USB support (see
[USB device forwarding](usb.md) for the details).
## Trade-offs and limits
Because your phone isn't "rooted," the little Linux can't use the phone's CPU
directly — it has to be *emulated*, which is **slow**. That's fine for what this
feature is for: **getting files off a drive**. It is *not* meant to be a fast,
everyday Linux desktop. Expect the **first** open to take a few minutes (it
builds the helper once); later opens are quicker, and file copies are unhurried
either way.
If all you need is a normal Linux *desktop* on your phone (not a USB drive),
Haven has a much faster option that doesn't involve a virtual machine — see
[Local Linux on-device](local-linux.md).
## For the agent (MCP)
If you drive Haven with the built-in AI-agent bridge, these tools cover this.
There's no setting to enable first — `open_usb_drive` is consent-gated per
session (approve it once, since it mounts your disk):
- `open_usb_drive` — start the VM for an attached drive (returns immediately;
the boot continues in the background).
- `list_usb_drives` — list attached USB drives and the VM's progress. While it's
booting, `vm.stage` carries a human-readable line ("Building the USB helper
Linux…", "Booting the USB helper…", etc.) you can relay; poll until
`vm.phase: ready`, which includes the loopback **`profileId`** and the mounted
paths. `applianceProvisioned` tells you whether the one-time setup is already
done (so the next open is quick).
- `close_usb_drive` — eject and tear everything down.
- `delete_usb_appliance` — delete the kept helper Linux (reclaims ~280 MB); the
next `open_usb_drive` re-provisions it once.
Once it's ready, browse the drive with the normal file tools (`list_directory`,
`serve_file`) using the returned `profileId`, exactly like any SFTP connection.
## Why this is hard
*(Optional — skip this unless you're curious.)*
Reading a drive like an ext4 disk needs a piece of software called a **kernel
driver**, which only a real operating-system **kernel** can load. A normal phone
app — including Haven's lightweight "Linux on the phone" mode
([proot](local-linux.md)) — has no kernel of its own, so it can never grow that
ability, no matter what you install.
A **virtual machine** is different: it's a complete, real (if pretend) computer,
*with its own kernel*. So it can load the driver and read the drive. The catch is
that running a whole computer-inside-a-computer is expensive, which is why it's
slow on a phone.
Haven already knew how to lend a phone's USB device to a *real* Linux machine over
the network (the [USB/IP feature](usb.md#to-a-remote-host-over-usbip)). This
feature reuses exactly that — except the "real Linux machine" is the little one
running on your own phone, a few inches from the drive. Same plumbing, no network.
Originally requested in
[issue #287](https://github.com/GlassHaven/Haven/issues/287).
---
[← All features](../FEATURES.md) · [USB device forwarding](usb.md) ·
[Local Linux on-device](local-linux.md)
+201
View File
@@ -0,0 +1,201 @@
---
layout: default
title: USB device forwarding
---
# USB device forwarding
On an unrooted Android phone, only the app holding the runtime USB permission can
open a device — `/dev/bus/usb` is denied to both the proot guest and the adb
shell. Haven turns that into a feature: it **brokers** the attached USB/OTG
device through Android's `UsbManager` and re-exposes it three ways, with no root.
This is the same pattern as the rest of Haven's bridge work — when something
downstream can't reach a capability directly, Haven brokers the Android privilege
and re-exposes it (see [Vision](https://github.com/GlassHaven/Haven/blob/main/VISION.md)).
The spark was a **YubiKey**: plug it into the phone and use it for SSH/FIDO on a
machine that has no key of its own, with the **touch happening on the phone**.
> **Just want a serial terminal?** For a USB-serial adapter — an Arduino, an ESP32,
> a USB-TTL cable, a Duet3D G-code board — you don't need forwarding at all: add a
> **USB-serial console** connection and you get a terminal straight to the device
> (see [Serial consoles](terminal.md#serial-consoles-bluetooth-ble-usb)), which can
> also be exposed off-phone via the [serial-to-TCP bridge](terminal.md#serial-to-tcp-bridge).
> The forwarding below is for handing a USB device to the *Linux guest* or a *remote host*.
## Device-class support
What reaches each consumer depends on the device class. **Guest** = the local
proot Linux guest, via the `haven-usb` shim; **Remote** = a Linux host over
USB/IP. (✅ works · ⚠️ feasible but not yet built · ❌ not feasible by this route.)
| Device class | Guest (proot) | Remote (USB/IP) | Notes |
|---|:---:|:---:|---|
| HID — keyboards, FIDO/CTAPHID security keys | ✅ `hidraw` shim | ✅ | Verified: YubiKey FIDO/SSH |
| CDC-ACM serial — USB-serial, ESP32 | ✅ serial shim | ✅ | Verified: ESP32-S3 `esptool` |
| Other bulk/control — printers, scanners, SDR, MTP/PTP cameras, `fastboot` | ⚠️ needs a libusb/usbfs shim | ✅ | Userspace-driven; see [Extending guest support](#extending-guest-support) |
| Mass storage — flash drives | ❌ no block layer | ✅ real kernel | Guest: read files via Android mount + `/storage` |
| Network — RNDIS / CDC-ECM / NCM | ❌ no netdev | ✅ | |
| Webcam (UVC) / Audio (UAC) | ❌ | ❌ | **Isochronous** — no Android `UsbDeviceConnection` API |
### Why these limits
The broker moves **control and bulk/interrupt** transfers over Android's
`UsbDeviceConnection` — that's all the Android API exposes. Two hard walls follow:
- **Kernel-object classes.** Mass storage (`/dev/sd*` + `mount`), network
(a netdev), webcams (`/dev/video`), and audio (ALSA) need a kernel **class
driver** to materialise a kernel object. proot has no kernel, so they can't
appear in the guest. The **remote USB/IP** path sidesteps this — it attaches
the device to a *real* Linux kernel, so any non-isochronous class works there.
For mass storage specifically, the **on-device VM** route does the same thing
locally — see [Reading USB drives](usb-drives.md).
- **Isochronous transfers.** `UsbDeviceConnection` has no isochronous API, so
UVC webcams and UAC audio — which live on isochronous endpoints — can't be
bridged on *either* path, guest or remote.
### Extending guest support
Today the guest shim emulates two specific char devices (`hidraw`, serial). The
general next step is a **libusb / usbfs shim** — emulate `/dev/bus/usb/*` (or
interpose libusb) and route its URBs over the same proxy. `UsbDeviceConnection`
already provides exactly libusb's primitives (descriptors, `claimInterface`,
control, bulk), so one shim would unlock **any userspace-driven class** —
printers (CUPS), scanners (SANE), SDR, MTP/PTP (libgphoto2/libmtp), `fastboot` —
with no per-class code. It does **not** move the two walls above: kernel-object
classes still need the remote path, and isochronous still has no Android API.
## To the agent (MCP)
`list_usb_devices`, `request_usb_permission`, `usb_control_transfer`, and
`usb_bulk_transfer` let an AI agent enumerate the attached USB/OTG devices and run
raw control/bulk transfers. Each device-open and transfer asks for consent.
## To the local Linux guest
With **Settings → "Expose USB devices to the Linux guest"** turned on (off by
default), `usb_attach_to_guest` opens the device and binds a small userspace USB
proxy on a socket the proot guest can reach. A bundled `haven-usb` shim then makes
the device appear inside the guest as a **character** device — for a HID-class
device, a normal `/dev/hidraw*` node (CDC-serial devices surface as a serial
endpoint instead):
- **native Linux apps** via `LD_PRELOAD` (the shim interposes
`open`/`ioctl`/`read`/`write`);
- **Mono / .NET apps** (anything built on HidSharp) via a Mono **DllMap** config —
the shim fakes the `libudev` enumeration and a non-crashing hotplug monitor and
routes the HID I/O over the proxy. `usb_attach_to_guest` returns the
ready-to-use config to drop beside the app's `HidSharp.dll`.
All USB I/O stays in the Android layer (`UsbDeviceConnection`), so the guest never
needs a real device node or root. The shim is built for both glibc and musl, so it
works the same on every distro Haven offers.
> **Not block storage.** A USB drive (mass-storage class) can't appear as a disk
> here, and `fdisk` isn't possible — see [Device-class support](#device-class-support)
> for why. To use a drive's *files*, either let Android mount it (USB-OTG storage)
> and read/write them under `/storage` (bound into every guest), or — for a
> Linux-formatted drive (ext4/GPT) Android can't open — use
> [Reading USB drives](usb-drives.md), which mounts it in a small on-device VM
> that *does* have a kernel. Partitioning is still host-side.
## To a remote host over USB/IP
Haven can also export a phone-attached USB device over the network with a
**userspace USB/IP server**, so a stock `usbip attach` on a remote Linux host
imports it as a real local device node. Every program there (`ssh`, `libfido2`,
browsers) sees an ordinary USB device; the **touch still happens on the phone**.
> Why a *userspace* server, and why remote-only: the Android kernel ships no
> `usbip-host`/`vhci-hcd` modules, so Haven can't use the stock `usbipd` daemon
> and the proot guest can't be a USB/IP *client*. Haven reimplements the USB/IP
> server in userspace and bridges each URB onto `UsbDeviceConnection` transfers.
> The remote host (a normal Linux box with `vhci-hcd` + `usbip`) is the client.
### Use case — a phone-hosted YubiKey for a remote host
Forward the phone's YubiKey to a server and mint a hardware-backed SSH key there:
```bash
# on the remote host, with the key forwarded and attached (see below):
ssh-keygen -t ed25519-sk -O device=/dev/hidraw14 -O application=ssh:example
```
The `makeCredential` and assertion run on the phone's key; you press the gold
contact on the phone to authorise.
### Auto-forward on connect (per profile)
In an SSH connection's editor there's a **"USB device forwarding"** picker
(below *Post-login command*). Pick the device — it's pinned by VID:PID, so it
survives a replug — and Haven, every time that profile connects:
1. resolves the VID:PID to the live device and opens it (USB permission prompt
the first time),
2. starts the USB/IP server on the phone's loopback,
3. binds a remote `-R 3240` port-forward so the host reaches the phone's server
at its own `127.0.0.1:3240`, and
4. best-effort runs `usbip attach` on the host so the device comes up as a real
node (e.g. `/dev/hidraw14`).
On disconnect it tears the forward down (which detaches the remote device as the
socket closes), stops the server, and closes the device.
### Hands-off attach (host sudoers)
Step 4 runs `sudo usbip attach` on the host, so for a fully automatic attach the
host needs passwordless sudo for just those commands. Drop this in
`/etc/sudoers.d/haven-usbip` (replace `ian` with your user; validate with
`sudo visudo -cf <file>` before installing):
```
Cmnd_Alias HAVEN_USBIP = /usr/sbin/modprobe vhci_hcd, \
/usr/bin/usbip attach *, \
/usr/bin/usbip detach *, \
/usr/bin/usbip port
ian ALL=(root) NOPASSWD: HAVEN_USBIP
```
It grants passwordless sudo for **only** those four commands — not general root.
`usbip` and `modprobe vhci_hcd` have a small blast radius (attach a remote USB
device / load one fixed module). Paths may differ on your distro (`command -v
usbip modprobe`).
### Without the sudoers — manual attach
If the host has no passwordless sudo for `usbip`, the connect still brings the
export and the tunnel up; it just can't attach for you. Haven logs the exact
command to run on the host:
```bash
sudo bash -c 'modprobe vhci_hcd; usbip attach -r 127.0.0.1 -b <busid>'
```
(`<busid>` is shown in the log, e.g. `1-2`.) Detach again with `sudo usbip detach
-p <port>`, or just disconnect the Haven profile.
### Caveats
- **`ssh-keygen` needs `-O device=/dev/hidrawN`.** OpenSSH's `sk-helper` does a
multi-device "touch to select" probe when no device is named, and that probe
stalls over the bridge. Naming the device skips it. `fido2-cred -M
/dev/hidrawN` and `fido2-token` work without the flag.
- **Verified for FIDO/CTAPHID (YubiKey) and CDC serial (ESP32-S3
USB-Serial/JTAG).** A composite FIDO key exports interface 0 only — its CCID
interface would starve FIDO on Android's serialized connection — but every
other device exports all its interfaces, so a USB-serial adapter binds
`cdc_acm` on the host and `esptool flash_id` connects, uploads the stub, and
reads flash over the bridge. Other device classes are still untested.
- **Remote-only.** This path needs the host's `vhci-hcd` kernel module; it's not
a proot-guest path (the guest uses the broker above).
### Security
Every device-open is consent-gated, and the sudoers grant is narrowly scoped to
the attach/detach/port/modprobe commands — never general root. Nothing in the
USB/IP path bypasses Android's USB-permission model.
---
[← All features](../FEATURES.md) · [Vision](https://github.com/GlassHaven/Haven/blob/main/VISION.md)