Files
VoiceStudio/backend/services/network_share.py
T
Palash DebnathandClaude Opus 4.8 fa1503c4eb feat: network sharing (PIN-gated LAN + QR) & Tailscale remote access (#125) (#159)
* docs(spec): network sharing + Tailscale remote access design

Same-state LAN sharing via a second in-process uvicorn listener on a
dedicated share port (no restart, model/jobs preserved), PIN-gated for
non-loopback clients, with QR + all-LAN-addresses panel. Tailscale serve
for private remote access. Supersedes the raw 0.0.0.0 default-flip in #125.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(spec): control endpoints reuse existing require_loopback gate

Security review of #157 confirmed the /system router is already loopback-gated
via Depends(require_loopback) (non-spoofable request.client.host). The network
control endpoints inherit it and /system/set-env is auto-protected from the
LAN listener — no new guard needed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(network): share-listener module — LAN enumeration + PIN + lifecycle

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(network): loopback-only control endpoints + /system/info sharing fields

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(cjk): scan git-tracked files only, not untracked vendored dirs

The no-hardcoded-CJK guard walked the filesystem, so local untracked
vendored experiments (research/voice-pro etc. with JP issue templates)
caused false local failures while CI (committed files) passed. Scan via
git ls-files so local-only and CI behavior match.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(network): PIN middleware — gate non-loopback API access when sharing on

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(network): inject X-OmniVoice-Pin globally + capture ?pin= from QR URL

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(network): remote PIN gate on 401

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(network): add qrcode dep for share QR

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(network): footer Local/Network toggle with LAN addresses, QR, copy/open

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(tailscale): CLI status + serve enable/disable + endpoints

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(network): Settings → Sharing & Remote Access panel (LAN + Tailscale)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(network): sharing & remote access guide (LAN PIN/QR + Tailscale)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(network): enable() tears down and raises if the share listener never binds

Defensive guard (spec §7): if the second uvicorn server doesn't reach
'started' (e.g. the share port was taken in the race after the free-port
probe), cancel the task, reset state, and raise — so the API surfaces the
failure and the UI stays Local rather than reporting a dead 'Network' state.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(network): use globalThis (not Node global) in client.test.ts for tsc

CI runs 'tsc --noEmit --checkJs false', which type-checks .ts files; Node's
'global' isn't typed there (TS2304). vitest (esbuild) tolerated it locally.
Use globalThis (standard, typed) + cast the mock.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(network): apiFetch leaves opts untouched when no PIN set

The unconditional headers merge changed the request shape for callers with
no headers (e.g. FormData posts), breaking the legacy 'apiPost passes
FormData without Content-Type override' node test. Only spread opts +
inject X-OmniVoice-Pin when a PIN is actually present; otherwise pass opts
through unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 11:26:16 +05:30

110 lines
3.3 KiB
Python

"""Same-process LAN share listener + access PIN.
Enabling starts a SECOND uvicorn.Server bound to 0.0.0.0 on a dedicated port,
serving the SAME FastAPI app object — so the loaded model and in-flight jobs
are untouched (no restart). Disabling stops it, closing the 0.0.0.0 socket.
Loopback-only by default: nothing binds 0.0.0.0 until enable() is called.
"""
import asyncio
import secrets
import socket
from dataclasses import dataclass, field
from typing import Optional
import psutil
import uvicorn
BACKEND_PORT = 3900 # must match backend/main.py uvicorn.run(port=...)
@dataclass
class ShareState:
enabled: bool = False
share_port: Optional[int] = None
pin: Optional[str] = None
lan_addresses: list = field(default_factory=list)
_state = ShareState()
_server: Optional["uvicorn.Server"] = None
_task: Optional["asyncio.Task"] = None
def lan_ipv4_addresses() -> list:
out, seen = [], set()
for _name, addrs in psutil.net_if_addrs().items():
for a in addrs:
if a.family == socket.AF_INET:
ip = a.address
if ip.startswith("127.") or ip.startswith("169.254."):
continue
if ip not in seen:
seen.add(ip)
out.append(ip)
return out
def _gen_pin() -> str:
return f"{secrets.randbelow(900000) + 100000}" # 100000-999999
def _find_free_port(base: int, tries: int = 20) -> int:
for p in range(base, base + tries):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(("0.0.0.0", p))
return p
except OSError:
continue
raise RuntimeError("no free share port available")
def get_state() -> ShareState:
return _state
async def enable(app) -> ShareState:
global _server, _task, _state
if _state.enabled:
return _state
port = _find_free_port(BACKEND_PORT + 1)
pin = _gen_pin()
config = uvicorn.Config(app, host="0.0.0.0", port=port, log_level="warning")
server = uvicorn.Server(config)
server.install_signal_handlers = lambda: None # never hijack signals in-process
_task = asyncio.create_task(server.serve())
for _ in range(100): # ~5s for the socket to bind
if getattr(server, "started", False):
break
await asyncio.sleep(0.05)
if not getattr(server, "started", False):
# Bind failed (e.g. the port was taken in the race after the
# free-port probe). Tear down and stay Local — never report enabled
# with a listener that isn't actually up (spec §7).
server.should_exit = True
try:
await asyncio.wait_for(_task, timeout=2)
except Exception:
pass
_task = None
raise RuntimeError("share listener failed to start")
_server = server
_state = ShareState(True, port, pin, lan_ipv4_addresses())
app.state.network_share = _state
return _state
async def disable(app) -> ShareState:
global _server, _task, _state
if _server is not None:
_server.should_exit = True
if _task is not None:
try:
await asyncio.wait_for(_task, timeout=5)
except Exception:
pass
_server = _task = None
_state = ShareState()
app.state.network_share = _state
return _state