Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-06-21 13:23:06 +03:00
1 parent fb46b5e6a1
commit 067f5289b2
26 files changed
+4189 -3033

No files matched your search

View File
Whitespace-only changes.
+794
View File
@@ -0,0 +1,794 @@
"""
dashboard/server.py — JARVIS Local HTTP Dashboard
Plain HTTP on port 8000 (no SSL warnings, no firewall issues).
Security at the application layer: AES-256-CBC with session-key-derived key.
CryptoJS is auto-downloaded once and served locally — no CDN needed after that.
Install deps: pip install fastapi "uvicorn[standard]" cryptography
"""
import asyncio
import base64
import hashlib
import re
import secrets
import socket
import string
import time
from pathlib import Path
_DEPS_OK = False
try:
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
import uvicorn
_DEPS_OK = True
except ImportError:
pass
# python-multipart is required for file uploads — optional dependency
_UPLOAD_OK = False
try:
from fastapi import UploadFile, File as FastAPIFile
_UPLOAD_OK = True
except Exception:
pass
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_DIR = Path(__file__).parent / "static"
PORT = 8000
MAX_UPLOAD_MB = 500
def _make_uploads_dir() -> Path:
"""Return (and create) the cross-platform uploads folder."""
for candidate in [
Path.home() / "Downloads" / "JARVIS Uploads",
Path.home() / "Documents" / "JARVIS Uploads",
BASE_DIR / "uploads",
]:
try:
candidate.mkdir(parents=True, exist_ok=True)
return candidate
except Exception:
pass
return BASE_DIR / "uploads"
UPLOADS_DIR = _make_uploads_dir()
def _get_gemini_key() -> str | None:
try:
import json as _json
with open(BASE_DIR / "config" / "api_keys.json", "r", encoding="utf-8") as f:
return _json.load(f).get("gemini_api_key")
except Exception:
return None
_KEY_CHARS = [c for c in (string.ascii_uppercase + string.digits)
if c not in ('O', 'I', 'L', '0', '1')]
# ── AES-256-CBC ───────────────────────────────────────────────────────────────
_AES_SALT = b'JARVIS-DASHBOARD-v1'
def _derive_key(session_key: str) -> bytes:
"""SHA-256(sessionKey‖salt) → 32-byte AES-256 key (microseconds, no PBKDF2 needed)."""
return hashlib.sha256(session_key.encode('utf-8') + _AES_SALT).digest()
def _decrypt_cbc(aes_key: bytes, enc_b64: str) -> str:
"""Decrypt base64(IV[16] ‖ ciphertext) with AES-256-CBC + PKCS7."""
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding as sym_pad
raw = base64.b64decode(enc_b64)
iv, ct = raw[:16], raw[16:]
dec = Cipher(algorithms.AES(aes_key), modes.CBC(iv)).decryptor()
padded = dec.update(ct) + dec.finalize()
unpadder = sym_pad.PKCS7(128).unpadder()
return (unpadder.update(padded) + unpadder.finalize()).decode('utf-8')
# ── CryptoJS (auto-download once, served locally) ─────────────────────────────
_CRYPTOJS_CDN = ("https://cdnjs.cloudflare.com/ajax/libs/"
"crypto-js/4.2.0/crypto-js.min.js")
_CRYPTOJS_FILE = STATIC_DIR / "crypto-js.min.js"
def _ensure_network_access(port: int) -> None:
"""Cross-platform, best-effort: open port in the OS firewall for LAN access.
Runs in a background thread — never blocks uvicorn startup.
Windows : writes a .bat file, runs it elevated via Windows ShellExecuteW
(native UAC dialog, guaranteed to appear). One-time setup.
macOS : osascript admin dialog if the Application Firewall is on.
Linux : pkexec GUI → sudo -n → prints manual command as fallback.
"""
import sys, subprocess, os, tempfile, threading
# ── Windows ──────────────────────────────────────────────────────────────
if sys.platform == "win32":
import ctypes, time
port_rule = f"JARVIS Dashboard Port {port}"
prog_rule = "JARVIS Dashboard Python"
py_exe = sys.executable
def _netsh_rule_exists(name: str) -> bool:
try:
r = subprocess.run(
["netsh", "advfirewall", "firewall", "show", "rule", f"name={name}"],
capture_output=True, text=True, timeout=5,
)
return r.returncode == 0 and "No rules match" not in r.stdout
except Exception:
return False
def _network_is_public() -> bool:
try:
r = subprocess.run(
["powershell", "-NoProfile", "-NonInteractive", "-Command",
"(Get-NetConnectionProfile | "
"Where-Object {$_.NetworkCategory -eq 'Public'} | "
"Measure-Object).Count"],
capture_output=True, text=True, timeout=6,
)
return r.stdout.strip() not in ("", "0")
except Exception:
return False
need_port = not _netsh_rule_exists(port_rule)
need_prog = not _netsh_rule_exists(prog_rule)
need_private = _network_is_public()
if not need_port and not need_prog and not need_private:
return # already fully configured
# Build a .bat file — netsh + powershell, runs fast when elevated
bat_lines = ["@echo off"]
if need_private:
bat_lines.append(
'powershell -NoProfile -NonInteractive -Command "'
'Get-NetConnectionProfile | '
"Where-Object {$_.NetworkCategory -eq 'Public'} | "
'Set-NetConnectionProfile -NetworkCategory Private"'
)
if need_port:
bat_lines.append(
f'netsh advfirewall firewall add rule '
f'name="{port_rule}" protocol=TCP dir=in '
f'localport={port} action=allow'
)
if need_prog:
bat_lines.append(
f'netsh advfirewall firewall add rule '
f'name="{prog_rule}" dir=in action=allow '
f'program="{py_exe}" enable=yes'
)
bat_body = "\r\n".join(bat_lines) + "\r\n"
fd, bat_path = tempfile.mkstemp(suffix=".bat", prefix="jarvis_fw_")
try:
os.write(fd, bat_body.encode("mbcs")) # Windows cmd.exe expects ANSI
os.close(fd)
except Exception:
try:
os.close(fd)
except Exception:
pass
return
# ── Try running directly (succeeds when already admin) ────────────────
try:
r = subprocess.run(
[bat_path], capture_output=True, timeout=8, shell=True
)
if r.returncode == 0:
print(f"[Dashboard] Firewall configured for port {port}.")
try:
os.unlink(bat_path)
except Exception:
pass
return
except Exception:
pass
# ── ShellExecuteW: native UAC elevation (most reliable on Windows) ────
# ShellExecuteW with verb "runas" always shows the UAC dialog regardless
# of UAC level settings. Non-blocking — uvicorn is already running.
print("[Dashboard] One-time network setup required.")
print("[Dashboard] >>> A Windows security dialog will appear — click 'Yes' <<<")
try:
ret = ctypes.windll.shell32.ShellExecuteW(
None, # hwnd (no parent window)
"runas", # verb (request elevation)
bat_path, # file (our .bat)
None, # params
None, # working dir
0, # SW_HIDE (run without a visible cmd window)
)
if int(ret) > 32:
# ShellExecuteW returns immediately; bat finishes in ~1 second.
# Sleep briefly so the rules are in place before the first retry.
time.sleep(2)
print(f"[Dashboard] Network setup complete — port {port} is open.")
print("[Dashboard] Refresh your phone browser to connect.")
else:
print("[Dashboard] Setup was not allowed.")
print("[Dashboard] Phone connections may fail until JARVIS is run as Administrator.")
except Exception as e:
print(f"[Dashboard] Firewall setup error: {e}")
finally:
# Cleanup after the bat has had time to run
def _cleanup(path: str) -> None:
time.sleep(5)
try:
os.unlink(path)
except Exception:
pass
threading.Thread(target=_cleanup, args=(bat_path,), daemon=True).start()
return
# ── macOS ─────────────────────────────────────────────────────────────────
if sys.platform == "darwin":
fw_ctl = "/usr/libexec/ApplicationFirewall/socketfilterfw"
try:
r = subprocess.run(
[fw_ctl, "--getglobalstate"], capture_output=True, text=True, timeout=5,
)
if "disabled" in r.stdout.lower():
return # firewall off — nothing to do
py = sys.executable
listed = subprocess.run(
[fw_ctl, "--listapps"], capture_output=True, text=True, timeout=5,
)
if py in listed.stdout:
return # already allowed
print("[Dashboard] One-time network setup — enter your password in the macOS dialog.")
subprocess.run(
["osascript", "-e",
f'do shell script "{fw_ctl} --add {py} && {fw_ctl} --unblockapp {py}"'
f' with administrator privileges'],
timeout=60,
)
except Exception:
pass # macOS firewall is off by default — silent failure is fine
return
# ── Linux ─────────────────────────────────────────────────────────────────
def _privileged(cmd: list[str]) -> bool:
for prefix in (["pkexec"], ["sudo", "-n"]):
try:
r = subprocess.run(prefix + cmd, capture_output=True, timeout=30)
if r.returncode == 0:
return True
except Exception:
pass
return False
try: # ufw
r = subprocess.run(["ufw", "status"], capture_output=True, text=True, timeout=5)
if "active" in r.stdout.lower():
if _privileged(["ufw", "allow", f"{port}/tcp"]):
print(f"[Dashboard] ufw: port {port} allowed.")
else:
print(f"[Dashboard] Run manually: sudo ufw allow {port}/tcp")
return
except FileNotFoundError:
pass
try: # firewalld
r = subprocess.run(
["firewall-cmd", "--state"], capture_output=True, text=True, timeout=5,
)
if "running" in r.stdout.lower():
ok = (_privileged(["firewall-cmd", "--add-port", f"{port}/tcp", "--permanent"])
and _privileged(["firewall-cmd", "--reload"]))
if ok:
print(f"[Dashboard] firewalld: port {port} allowed.")
else:
print(f"[Dashboard] Run manually: sudo firewall-cmd --add-port={port}/tcp --permanent && sudo firewall-cmd --reload")
return
except FileNotFoundError:
pass
try: # iptables (not persistent but works until reboot)
r = subprocess.run(["iptables", "-L", "INPUT", "-n"], capture_output=True, timeout=5)
if r.returncode == 0:
if _privileged(["iptables", "-A", "INPUT", "-p", "tcp", "--dport", str(port), "-j", "ACCEPT"]):
print(f"[Dashboard] iptables: port {port} opened.")
else:
print(f"[Dashboard] Run manually: sudo iptables -A INPUT -p tcp --dport {port} -j ACCEPT")
except FileNotFoundError:
pass # no iptables means firewall is probably off — nothing to do
def _ensure_crypto_js() -> None:
if _CRYPTOJS_FILE.exists():
return
try:
import urllib.request
print("[Dashboard] Downloading CryptoJS (one-time setup)…")
urllib.request.urlretrieve(_CRYPTOJS_CDN, str(_CRYPTOJS_FILE))
print("[Dashboard] CryptoJS cached — will serve locally from now on.")
except Exception as e:
print(f"[Dashboard] CryptoJS download failed: {e}")
print(f"[Dashboard] Encryption will fall back to CDN load on client.")
_ensure_crypto_js()
# ── helpers ───────────────────────────────────────────────────────────────────
def _local_ip() -> str:
"""Return the best LAN-facing IPv4 address, no internet required."""
# Method 1: route trick (fast, works when internet is available)
for probe in ("8.8.8.8", "1.1.1.1", "192.168.1.1"):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0.5)
s.connect((probe, 80))
ip = s.getsockname()[0]
s.close()
if not ip.startswith("127."):
return ip
except Exception:
pass
# Method 2: hostname resolution (works offline on most systems)
try:
ip = socket.gethostbyname(socket.gethostname())
if not ip.startswith("127."):
return ip
except Exception:
pass
# Method 3: enumerate all interfaces (fully offline, no external deps)
try:
for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):
ip = info[4][0]
if not ip.startswith("127.") and not ip.startswith("169.254."):
return ip
except Exception:
pass
return "127.0.0.1"
def _read(name: str) -> str:
return (STATIC_DIR / name).read_text(encoding="utf-8")
# ── DashboardServer ───────────────────────────────────────────────────────────
class DashboardServer:
def __init__(self):
self._ip = _local_ip()
self._tokens: set[str] = set()
self._token_keys: dict[str, str] = {} # auth_token → session_key
self._aes_cache: dict[str, bytes]= {} # session_key → AES bytes
self._clients: set[WebSocket] = set()
self._history: list[dict] = []
self._command_queue = asyncio.Queue()
self._wake_callback = None
self._connect_callback = None
self._pending_keys: dict[str, float] = {}
self._device_sessions: dict[str, dict] = {} # device_token → {session_key}
self._phone_audio_queue: asyncio.Queue = asyncio.Queue(maxsize=200)
self._uploads_dir = UPLOADS_DIR
self._login_html = _read("login.html")
self._app_html = _read("app.html")
self.app = self._build_app()
# ── one-time key management ───────────────────────────────────────────
def new_key(self, expiry_secs: int = 600) -> str:
now = time.time()
self._pending_keys = {k: v for k, v in self._pending_keys.items() if v > now}
key = ''.join(secrets.choice(_KEY_CHARS) for _ in range(6))
self._pending_keys[key] = now + expiry_secs
return key
@staticmethod
def _ssl_enabled() -> bool:
certs = BASE_DIR / "config" / "certs"
return (certs / "jarvis.key").exists() and (certs / "jarvis.crt").exists()
def get_url(self) -> str:
proto = "https" if self._ssl_enabled() else "http"
return f"{proto}://{self._ip}:{PORT}"
def get_manual_url(self) -> str:
"""URL for manual browser entry. When HTTPS active, points to alias port (also HTTPS)."""
if self._ssl_enabled():
return f"{self._ip}:{PORT + 1}"
return f"{self._ip}:{PORT}"
def _aes_key(self, session_key: str) -> bytes:
if session_key not in self._aes_cache:
self._aes_cache[session_key] = _derive_key(session_key)
return self._aes_cache[session_key]
def _decrypt(self, token: str, enc_b64: str) -> str | None:
sk = self._token_keys.get(token)
if not sk:
return None
try:
return _decrypt_cbc(self._aes_key(sk), enc_b64)
except Exception:
return None
# ── callbacks ────────────────────────────────────────────────────────
def set_wake_callback(self, fn) -> None:
self._wake_callback = fn
def set_connect_callback(self, fn) -> None:
self._connect_callback = fn
# ── broadcast ────────────────────────────────────────────────────────
async def broadcast(self, msg: dict) -> None:
self._history.append(msg)
if len(self._history) > 300:
self._history = self._history[-300:]
dead: set[WebSocket] = set()
for ws in list(self._clients):
try:
await ws.send_json(msg)
except Exception:
dead.add(ws)
self._clients -= dead
# ── FastAPI app ───────────────────────────────────────────────────────
def _build_app(self) -> "FastAPI":
app = FastAPI(docs_url=None, redoc_url=None)
def _auth(req: Request) -> bool:
tok = req.headers.get("authorization", "").removeprefix("Bearer ").strip()
return bool(tok) and tok in self._tokens
# serve CryptoJS from local cache, fallback to CDN redirect
@app.get("/static/crypto.js")
async def serve_crypto():
if _CRYPTOJS_FILE.exists():
return FileResponse(str(_CRYPTOJS_FILE),
media_type="application/javascript")
from fastapi.responses import RedirectResponse
return RedirectResponse(_CRYPTOJS_CDN)
@app.get("/login", response_class=HTMLResponse)
async def login_page():
return HTMLResponse(self._login_html)
@app.get("/", response_class=HTMLResponse)
async def index():
# Auth is handled client-side via sessionStorage bearer token.
# Server-side header auth can't work here because browser navigations
# don't send custom headers (location.href doesn't carry Authorization).
html = (self._app_html
.replace("__IP__", self._ip)
.replace("__PORT__", str(PORT)))
return HTMLResponse(html)
@app.post("/login")
async def login(req: Request):
body = await req.json()
entered = str(body.get("pin", "")).strip().upper()
now = time.time()
if entered in self._pending_keys and self._pending_keys[entered] > now:
del self._pending_keys[entered] # one-time use
tok = secrets.token_urlsafe(32)
self._tokens.add(tok)
self._token_keys[tok] = entered
self._aes_key(entered) # pre-derive & cache
if self._connect_callback:
self._connect_callback()
asyncio.create_task(self.broadcast(
{"type": "sys", "text": "Remote connection established."}
))
# Bearer token in response body — no cookies needed (works on any browser/HTTP)
return JSONResponse({"ok": True, "token": tok})
return JSONResponse({"ok": False, "error": "Invalid or expired key"},
status_code=401)
@app.get("/auto-login")
async def auto_login(key: str = ""):
"""QR code target — validates one-time key, creates session, redirects phone."""
now = time.time()
if not key or key not in self._pending_keys or self._pending_keys[key] <= now:
return HTMLResponse("""<!DOCTYPE html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width">
<style>
body{background:#07090f;color:#dde3ed;font-family:sans-serif;
display:flex;align-items:center;justify-content:center;height:100vh;margin:0;text-align:center}
h2{color:#f87171;margin-bottom:12px}p{color:#5e6a7e;font-size:14px}
</style></head>
<body><div><h2>Link Expired</h2>
<p>Press <strong style="color:#dde3ed">Remote Control</strong> in JARVIS to get a new QR code.</p>
</div></body></html>""")
del self._pending_keys[key]
tok = secrets.token_urlsafe(32)
dev_tok = secrets.token_urlsafe(32)
self._tokens.add(tok)
self._token_keys[tok] = key
self._aes_key(key)
self._device_sessions[dev_tok] = {"session_key": key}
if self._connect_callback:
self._connect_callback()
asyncio.create_task(self.broadcast(
{"type": "sys", "text": "Remote connection established via QR code."}
))
return HTMLResponse(f"""<!DOCTYPE html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width">
<style>
body{{background:#07090f;color:#dde3ed;font-family:sans-serif;
display:flex;align-items:center;justify-content:center;height:100vh;margin:0;text-align:center}}
p{{color:#5e6a7e;font-size:14px}}
</style></head>
<body>
<script>
sessionStorage.setItem('jarvis_token','{tok}');
sessionStorage.setItem('jarvis_key','{key}');
localStorage.setItem('jarvis_device_token','{dev_tok}');
setTimeout(function(){{location.replace('/')}},400);
</script>
<p>Connecting to JARVIS…</p>
</body></html>""")
@app.post("/api/device-login")
async def device_login_ep(req: Request):
"""Return a fresh auth token for a previously paired device token."""
try:
body = await req.json()
except Exception:
return JSONResponse({"ok": False}, status_code=400)
dev_tok = (body.get("device_token") or "").strip()
if not dev_tok or dev_tok not in self._device_sessions:
return JSONResponse({"ok": False}, status_code=401)
session_key = self._device_sessions[dev_tok]["session_key"]
tok = secrets.token_urlsafe(32)
self._tokens.add(tok)
self._token_keys[tok] = session_key
self._aes_key(session_key)
if self._connect_callback:
self._connect_callback()
asyncio.create_task(self.broadcast(
{"type": "sys", "text": "Known device reconnected automatically."}
))
return JSONResponse({"ok": True, "token": tok, "key": session_key})
@app.post("/api/revoke-devices")
async def revoke_devices(req: Request):
"""Invalidate all persistent device tokens (admin action)."""
if not _auth(req):
return JSONResponse({"error": "Unauthorized"}, status_code=401)
count = len(self._device_sessions)
self._device_sessions.clear()
return JSONResponse({"ok": True, "revoked": count})
@app.post("/api/command")
async def command(req: Request):
if not _auth(req):
return JSONResponse({"error": "Unauthorized"}, status_code=401)
body = await req.json()
token = req.headers.get("authorization", "").removeprefix("Bearer ").strip()
enc = body.get("enc", "")
if enc:
text = self._decrypt(token, enc)
if text is None:
return JSONResponse({"error": "Decryption failed"}, status_code=400)
else:
text = (body.get("text") or "").strip()
if text:
await self._command_queue.put(text)
if self._wake_callback:
self._wake_callback()
return JSONResponse({"ok": True})
@app.post("/api/wake")
async def wake_ep(req: Request):
if not _auth(req):
return JSONResponse({"error": "Unauthorized"}, status_code=401)
if self._wake_callback:
self._wake_callback()
return JSONResponse({"ok": True})
# ── Phone mic real-time audio → Gemini Live ──────────────────────────
@app.websocket("/ws/phone-audio")
async def phone_audio_ws(websocket: WebSocket, token: str = ""):
tok = token.strip()
if not tok or tok not in self._tokens:
await websocket.close(code=4001)
return
await websocket.accept()
asyncio.create_task(self.broadcast(
{"type": "sys", "text": "Phone microphone live."}
))
try:
while True:
data = await websocket.receive_bytes()
try:
self._phone_audio_queue.put_nowait(
{"data": data, "mime_type": "audio/pcm"}
)
except asyncio.QueueFull:
pass # drop frame rather than block
except WebSocketDisconnect:
pass
finally:
asyncio.create_task(self.broadcast(
{"type": "sys", "text": "Phone microphone stopped."}
))
# ── File sharing ──────────────────────────────────────────────────────
def _safe_filename(raw: str) -> str:
name = Path(raw).name # strip path components
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', name).strip(". ")
return name or "upload"
if _UPLOAD_OK:
@app.post("/api/upload")
async def upload_file(req: Request, file: UploadFile = FastAPIFile(...)):
if not _auth(req):
return JSONResponse({"error": "Unauthorized"}, status_code=401)
safe = _safe_filename(file.filename or "upload")
dest = self._uploads_dir / safe
stem, suffix = Path(safe).stem, Path(safe).suffix
counter = 1
while dest.exists():
dest = self._uploads_dir / f"{stem}_{counter}{suffix}"
counter += 1
size = 0
max_bytes = MAX_UPLOAD_MB * 1024 * 1024
try:
with open(dest, "wb") as fout:
while True:
chunk = await file.read(65536)
if not chunk:
break
size += len(chunk)
if size > max_bytes:
fout.close()
dest.unlink(missing_ok=True)
return JSONResponse(
{"error": f"File too large (max {MAX_UPLOAD_MB} MB)"},
status_code=413,
)
fout.write(chunk)
except Exception as exc:
try:
dest.unlink(missing_ok=True)
except Exception:
pass
return JSONResponse({"error": str(exc)}, status_code=500)
asyncio.create_task(self.broadcast({
"type": "file_received",
"name": dest.name,
"size": size,
"saved_to": str(self._uploads_dir),
}))
return JSONResponse({"ok": True, "name": dest.name, "size": size})
else:
@app.post("/api/upload")
async def upload_unavailable(req: Request):
return JSONResponse(
{"error": "File uploads require: pip install python-multipart"},
status_code=503,
)
@app.get("/api/files")
async def list_files(req: Request):
if not _auth(req):
return JSONResponse({"error": "Unauthorized"}, status_code=401)
files = []
try:
for f in sorted(
(p for p in self._uploads_dir.iterdir() if p.is_file()),
key=lambda p: p.stat().st_mtime,
reverse=True,
):
files.append({"name": f.name, "size": f.stat().st_size})
except Exception:
pass
return JSONResponse({"files": files})
@app.get("/uploads/{filename}")
async def download_file(filename: str, token: str = ""):
# Auth via query param — browser <a download> can't send custom headers
tok = token.strip()
if not tok or tok not in self._tokens:
return JSONResponse({"error": "Unauthorized"}, status_code=401)
safe = re.sub(r'[/\\]', '', filename)
path = self._uploads_dir / safe
if not path.exists() or not path.is_file():
return JSONResponse({"error": "Not found"}, status_code=404)
return FileResponse(str(path), filename=safe)
@app.websocket("/ws")
async def ws_ep(websocket: WebSocket, token: str = ""):
tok = token.strip()
if not tok or tok not in self._tokens:
await websocket.close(code=4001)
return
await websocket.accept()
self._clients.add(websocket)
for entry in self._history[-50:]:
try:
await websocket.send_json(entry)
except Exception:
break
try:
while True:
data = await websocket.receive_json()
if data.get("type") == "command":
enc = data.get("enc", "")
t = self._decrypt(tok, enc) if enc else (data.get("text") or "").strip()
if t:
await self._command_queue.put(t)
if self._wake_callback:
self._wake_callback()
except WebSocketDisconnect:
pass
finally:
self._clients.discard(websocket)
return app
# ── serve ─────────────────────────────────────────────────────────────
async def _serve_alias(self) -> None:
"""Second HTTPS server on PORT+1 sharing the same app and in-memory state.
Chrome HTTPS-upgrades any bare IP:PORT the user types, so this port also needs TLS.
User types IP:8001 → Chrome tries https → self-signed cert warning → accept once → done."""
ssl_key = BASE_DIR / "config" / "certs" / "jarvis.key"
ssl_cert = BASE_DIR / "config" / "certs" / "jarvis.crt"
asyncio.get_event_loop().run_in_executor(None, _ensure_network_access, PORT + 1)
cfg = uvicorn.Config(
self.app, host="0.0.0.0", port=PORT + 1, log_level="warning",
ssl_keyfile=str(ssl_key), ssl_certfile=str(ssl_cert),
)
print(f"[Dashboard] Manual entry: {self._ip}:{PORT + 1} (type in browser, accept cert once)")
await uvicorn.Server(cfg).serve()
async def serve(self) -> None:
if not _DEPS_OK:
print("[Dashboard] fastapi/uvicorn not installed — dashboard disabled.")
print("[Dashboard] Run: pip install fastapi 'uvicorn[standard]' cryptography")
return
# Firewall setup runs in a thread — uvicorn starts immediately,
# no waiting for UAC dialogs or subprocess timeouts.
asyncio.get_event_loop().run_in_executor(None, _ensure_network_access, PORT)
use_ssl = self._ssl_enabled()
ssl_key = BASE_DIR / "config" / "certs" / "jarvis.key"
ssl_cert = BASE_DIR / "config" / "certs" / "jarvis.crt"
if use_ssl:
asyncio.create_task(self._serve_alias())
cfg = uvicorn.Config(
self.app, host="0.0.0.0", port=PORT, log_level="warning",
**({"ssl_keyfile": str(ssl_key), "ssl_certfile": str(ssl_cert)} if use_ssl else {}),
)
proto = "https" if use_ssl else "http"
print(f"[Dashboard] {proto}://{self._ip}:{PORT}")
print("[Dashboard] Press 'Remote Control' in JARVIS UI to get the QR code.")
await uvicorn.Server(cfg).serve()
+559
View File
@@ -0,0 +1,559 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JARVIS Dashboard</title>
<script src="/static/crypto.js"></script>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #07090f;
--surface: rgba(255,255,255,0.04);
--border: rgba(255,255,255,0.07);
--accent: #6366f1;
--adim: rgba(99,102,241,0.14);
--text: #dde3ed;
--muted: #5e6a7e;
--green: #22c55e;
--gdim: rgba(34,197,94,0.14);
}
html, body {
height: 100%; background: var(--bg); color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
display: flex; flex-direction: column; overflow: hidden;
}
/* ── HEADER ── */
header {
flex-shrink: 0; display: flex; align-items: center; gap: 10px;
padding: 12px 16px; border-bottom: 1px solid var(--border);
background: rgba(7,9,15,0.95);
}
.logo { font-size: 15px; font-weight: 700; letter-spacing: 6px; }
.logo em { color: var(--accent); font-style: normal; }
.pill {
display: flex; align-items: center; gap: 6px; padding: 4px 11px;
border-radius: 99px; background: var(--surface); border: 1px solid var(--border);
font-size: 10px; font-weight: 700; letter-spacing: 1.5px; text-transform: uppercase;
color: var(--muted); transition: all 0.3s;
}
.pill.on { background: var(--gdim); border-color: rgba(34,197,94,0.3); color: var(--green); }
.dot { width: 6px; height: 6px; border-radius: 50%; background: var(--muted); transition: background 0.3s; }
.pill.on .dot { background: var(--green); animation: blink 2s infinite; }
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.4} }
.spacer { flex: 1; }
.enc-badge {
font-size: 9px; font-weight: 700; letter-spacing: 1.5px; padding: 3px 8px;
border-radius: 4px; display: none;
}
.enc-badge.on { display: block; background: rgba(34,197,94,0.1); border: 1px solid rgba(34,197,94,0.25); color: var(--green); }
.enc-badge.off { display: block; background: rgba(255,100,100,0.08); border: 1px solid rgba(255,100,100,0.2); color: #f87171; }
.url { font-size: 10px; font-family: monospace; color: var(--muted); padding: 4px 9px; background: var(--surface); border: 1px solid var(--border); border-radius: 6px; }
/* ── FEED ── */
main { flex: 1; overflow-y: auto; padding: 14px 16px 8px; display: flex; flex-direction: column; gap: 10px; }
main::-webkit-scrollbar { width: 3px; }
main::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
.msg { max-width: 82%; padding: 10px 14px; border-radius: 14px; font-size: 14px; line-height: 1.55; animation: pop 0.18s ease; }
@keyframes pop { from { opacity:0; transform:translateY(4px); } }
.msg-j { align-self:flex-start; background:var(--adim); border:1px solid rgba(99,102,241,0.18); border-bottom-left-radius:4px; }
.msg-u { align-self:flex-end; background:var(--surface); border:1px solid var(--border); border-bottom-right-radius:4px; }
.msg-sys { align-self:center; font-size:11px; color:var(--muted); padding:2px 0; background:transparent; border:none; letter-spacing:0.3px; }
.lbl { font-size:9px; font-weight:700; letter-spacing:2px; text-transform:uppercase; opacity:0.45; margin-bottom:4px; }
.msg-j .lbl { color:var(--accent); }
.msg-u .lbl { color:var(--muted); text-align:right; }
/* ── FILE CARD ── */
.msg-file {
align-self: flex-end;
background: var(--surface); border: 1px solid var(--border);
border-radius: 14px; border-bottom-right-radius: 4px;
padding: 11px 14px; display: flex; align-items: center; gap: 12px;
max-width: 82%; animation: pop 0.18s ease;
}
.fc-icon { font-size: 26px; flex-shrink: 0; }
.fc-meta { flex: 1; min-width: 0; }
.fc-lbl { font-size:9px; font-weight:700; letter-spacing:2px; text-transform:uppercase; opacity:0.45; color:var(--muted); margin-bottom:4px; }
.fc-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fc-size { font-size: 11px; color: var(--muted); margin-top: 2px; }
.fc-bar-wrap { height: 3px; background: var(--border); border-radius: 2px; margin-top: 7px; overflow: hidden; }
.fc-bar { height: 100%; width: 0%; background: var(--accent); border-radius: 2px; transition: width 0.12s linear; }
.fc-status { font-size: 10px; font-weight: 700; letter-spacing: 1px; flex-shrink: 0; color: var(--muted); }
.fc-status.done { color: var(--green); }
.fc-status.err { color: #f87171; }
.fc-dl { display:block; margin-top:6px; font-size:11px; color:var(--accent); text-decoration:none; font-weight:600; }
.fc-dl:hover { opacity: 0.8; }
/* ── FOOTER ── */
footer { flex-shrink:0; padding:10px 14px; border-top:1px solid var(--border); background:rgba(7,9,15,0.95); display:flex; gap:8px; align-items:center; }
#inp { flex:1; padding:11px 14px; background:var(--surface); border:1.5px solid var(--border); border-radius:12px; color:var(--text); font-size:14px; outline:none; transition:border-color 0.15s; }
#inp:focus { border-color: var(--accent); }
#inp::placeholder { color: var(--muted); }
.btn { padding:11px 15px; border:none; border-radius:12px; font-size:11px; font-weight:700; letter-spacing:1.5px; cursor:pointer; transition:opacity 0.15s,transform 0.1s; }
.btn:active { transform: scale(0.96); }
.btn:hover { opacity: 0.82; }
.btn-send { background: var(--accent); color: #fff; }
.btn-wake { background:var(--surface); border:1px solid var(--border); color:var(--muted); display:none; }
.btn-wake.show { display:block; color:var(--green); border-color:rgba(34,197,94,0.35); }
.btn-attach {
background: var(--surface); border: 1px solid var(--border); color: var(--muted);
padding: 11px 13px; font-size: 16px; line-height: 1; border-radius: 12px;
cursor: pointer; transition: opacity 0.15s, transform 0.1s; display: flex;
align-items: center; justify-content: center; flex-shrink: 0;
}
.btn-attach:hover { opacity: 0.82; border-color: var(--accent); color: var(--accent); }
.btn-attach:active { transform: scale(0.96); }
/* ── MIC BUTTON ── */
#mic-btn {
background: var(--surface); border: 1px solid var(--border); color: var(--muted);
padding: 11px 13px; font-size: 16px; line-height: 1; border-radius: 12px;
cursor: pointer; transition: opacity 0.15s, transform 0.1s, background 0.2s, border-color 0.2s;
display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
#mic-btn:hover { opacity: 0.82; border-color: var(--accent); color: var(--accent); }
#mic-btn:active { transform: scale(0.96); }
#mic-btn.recording {
background: rgba(239,68,68,0.15); border-color: rgba(239,68,68,0.45); color: #ef4444;
animation: mic-pulse 1s ease-in-out infinite;
}
#mic-btn.unsupported { opacity: 0.3; cursor: not-allowed; }
@keyframes mic-pulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:0.65;transform:scale(0.97)} }
/* ── TOAST ── */
#toast {
position:fixed; top:66px; left:50%; transform:translateX(-50%) translateY(-8px);
background:rgba(34,197,94,0.16); border:1px solid rgba(34,197,94,0.4);
color:var(--green); font-size:12px; font-weight:700; letter-spacing:1px;
padding:7px 18px; border-radius:99px;
opacity:0; transition:opacity 0.22s,transform 0.22s;
pointer-events:none; white-space:nowrap;
}
#toast.show { opacity:1; transform:translateX(-50%) translateY(0); }
</style>
</head>
<body>
<div id="toast"></div>
<header>
<div class="logo"><em>J</em>ARVIS</div>
<div class="pill" id="pill"><span class="dot"></span><span id="st">Connecting</span></div>
<div class="enc-badge" id="enc">AES-256</div>
<div class="spacer"></div>
<div class="url">__IP__:__PORT__</div>
</header>
<main id="feed"></main>
<footer>
<input id="inp" placeholder="Send a command to JARVIS…" autocomplete="off">
<label class="btn-attach" for="file-inp" title="Send file">📎</label>
<input type="file" id="file-inp" multiple accept="*/*" style="display:none">
<button id="mic-btn" onclick="doMic()" title="Voice command">🎤</button>
<button class="btn btn-wake" id="wake" onclick="doWake()">WAKE</button>
<button class="btn btn-send" onclick="doSend()">SEND</button>
</footer>
<script>
// ── Auth — bearer token ───────────────────────────────────────────────────
const _authToken = sessionStorage.getItem('jarvis_token');
const _sessionKey = sessionStorage.getItem('jarvis_key');
if (!_authToken) {
location.replace('/login');
}
function _authHeader() { return { 'Authorization': `Bearer ${_authToken}` }; }
function _authFetch(url, opts = {}) {
opts.headers = Object.assign({}, opts.headers, _authHeader());
return fetch(url, opts);
}
// ── AES-256-CBC encryption (CryptoJS) ────────────────────────────────────
const _AES_SALT = 'JARVIS-DASHBOARD-v1';
let _aesKey = null;
function _initCrypto(key) {
if (typeof CryptoJS === 'undefined') return false;
_aesKey = CryptoJS.SHA256(key + _AES_SALT);
return true;
}
function _encrypt(plaintext) {
if (!_aesKey || typeof CryptoJS === 'undefined') return null;
try {
const iv = CryptoJS.lib.WordArray.random(16);
const enc = CryptoJS.AES.encrypt(
CryptoJS.enc.Utf8.parse(plaintext), _aesKey,
{ iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
);
const ivHex = iv.toString(CryptoJS.enc.Hex);
const ctHex = enc.ciphertext.toString(CryptoJS.enc.Hex);
const hex = ivHex + ctHex;
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < bytes.length; i++)
bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
return btoa(String.fromCharCode(...bytes));
} catch { return null; }
}
const _encReady = _sessionKey ? _initCrypto(_sessionKey) : false;
const encBadge = document.getElementById('enc');
if (_encReady) { encBadge.className = 'enc-badge on'; }
else { encBadge.className = 'enc-badge off'; encBadge.textContent = 'NO ENC'; }
// ── WebSocket ─────────────────────────────────────────────────────────────
const feed = document.getElementById('feed');
const pill = document.getElementById('pill');
const stTxt = document.getElementById('st');
const wake = document.getElementById('wake');
const _wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
const _wsUrl = `${_wsProto}://${location.host}/ws?token=${encodeURIComponent(_authToken)}`;
const ws = new WebSocket(_wsUrl);
ws.onopen = () => { sys('Remote session active.'); toast('Connected to JARVIS'); };
ws.onclose = () => sys('Connection lost — refresh to reconnect.');
ws.onerror = () => sys('Connection error.');
ws.onmessage = (e) => {
const m = JSON.parse(e.data);
if (m.type === 'log') append(m.speaker, m.text);
if (m.type === 'status') setStatus(m.state);
if (m.type === 'wake') sys('Wake word detected — connecting…');
if (m.type === 'sys') sys(m.text);
if (m.type === 'file_received') _onFileReceived(m);
};
function setStatus(s) {
if (s === 'active') {
pill.className = 'pill on'; stTxt.textContent = 'Active'; wake.classList.remove('show');
} else {
pill.className = 'pill'; stTxt.textContent = 'Sleeping'; wake.classList.add('show');
}
}
function append(speaker, text) {
const d = document.createElement('div');
if (speaker === 'jarvis') {
d.className = 'msg msg-j';
d.innerHTML = `<div class="lbl">Jarvis</div>${esc(text)}`;
} else {
d.className = 'msg msg-u';
d.innerHTML = `<div class="lbl">You</div>${esc(text)}`;
}
feed.appendChild(d);
feed.scrollTop = feed.scrollHeight;
}
function sys(text) {
const d = document.createElement('div');
d.className = 'msg msg-sys'; d.textContent = text;
feed.appendChild(d); feed.scrollTop = feed.scrollHeight;
}
function esc(s) {
return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
// ── File helpers ──────────────────────────────────────────────────────────
function _fileIcon(name) {
const ext = (name.split('.').pop() || '').toLowerCase();
if (['jpg','jpeg','png','gif','webp','heic','heif','avif','bmp','svg'].includes(ext)) return '🖼️';
if (['mp4','mov','avi','mkv','webm','m4v','3gp'].includes(ext)) return '🎬';
if (['mp3','m4a','wav','flac','aac','ogg','opus'].includes(ext)) return '🎵';
if (['pdf'].includes(ext)) return '📋';
if (['doc','docx','txt','md','rtf','odt'].includes(ext)) return '📝';
if (['xls','xlsx','csv','ods'].includes(ext)) return '📊';
if (['ppt','pptx','odp'].includes(ext)) return '📑';
if (['zip','rar','7z','tar','gz','bz2','xz'].includes(ext)) return '📦';
if (['apk','exe','dmg','deb','rpm','msi'].includes(ext)) return '⚙️';
return '📎';
}
function _fmtSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
if (bytes < 1024 ** 3) return (bytes / 1024 / 1024).toFixed(1) + ' MB';
return (bytes / 1024 ** 3).toFixed(2) + ' GB';
}
// ── File upload (phone → computer) ────────────────────────────────────────
function _uploadFile(file) {
const id = 'fc_' + Date.now() + '_' + Math.random().toString(36).slice(2);
// Create file card in feed
const card = document.createElement('div');
card.className = 'msg-file';
card.id = id;
card.innerHTML = `
<div class="fc-icon">${_fileIcon(file.name)}</div>
<div class="fc-meta">
<div class="fc-lbl">Sending</div>
<div class="fc-name">${esc(file.name)}</div>
<div class="fc-size">${_fmtSize(file.size)}</div>
<div class="fc-bar-wrap"><div class="fc-bar" id="${id}_bar"></div></div>
</div>
<div class="fc-status" id="${id}_st">0%</div>
`;
feed.appendChild(card);
feed.scrollTop = feed.scrollHeight;
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload');
xhr.setRequestHeader('Authorization', `Bearer ${_authToken}`);
xhr.upload.onprogress = (e) => {
if (!e.lengthComputable) return;
const pct = Math.round(e.loaded / e.total * 100);
const bar = document.getElementById(`${id}_bar`);
const st = document.getElementById(`${id}_st`);
if (bar) bar.style.width = pct + '%';
if (st) st.textContent = pct + '%';
};
xhr.onload = () => {
const bar = document.getElementById(`${id}_bar`);
const st = document.getElementById(`${id}_st`);
const meta = card.querySelector('.fc-meta');
const lbl = card.querySelector('.fc-lbl');
if (xhr.status === 200) {
let savedName = file.name;
try { savedName = JSON.parse(xhr.responseText).name || file.name; } catch {}
const dlUrl = `/uploads/${encodeURIComponent(savedName)}?token=${encodeURIComponent(_authToken)}`;
if (bar) { bar.style.width = '100%'; bar.style.background = 'var(--green)'; }
if (st) { st.textContent = '✓'; st.className = 'fc-status done'; }
if (lbl) lbl.textContent = 'Sent';
if (meta) meta.insertAdjacentHTML('beforeend',
`<a class="fc-dl" href="${dlUrl}" download="${esc(savedName)}">⬇ Download back</a>`);
toast('File sent!');
} else {
let errMsg = 'Upload failed';
try { errMsg = JSON.parse(xhr.responseText).error || errMsg; } catch {}
if (bar) bar.style.background = '#f87171';
if (st) { st.textContent = 'ERR'; st.className = 'fc-status err'; }
if (lbl) lbl.textContent = errMsg;
}
};
xhr.onerror = () => {
const st = document.getElementById(`${id}_st`);
const lbl = card.querySelector('.fc-lbl');
if (st) { st.textContent = 'ERR'; st.className = 'fc-status err'; }
if (lbl) lbl.textContent = 'Connection error';
};
const fd = new FormData();
fd.append('file', file);
xhr.send(fd);
}
// File received by another WebSocket client (e.g., second open tab)
function _onFileReceived(m) {
const dlUrl = `/uploads/${encodeURIComponent(m.name)}?token=${encodeURIComponent(_authToken)}`;
const card = document.createElement('div');
card.className = 'msg-file';
card.innerHTML = `
<div class="fc-icon">${_fileIcon(m.name)}</div>
<div class="fc-meta">
<div class="fc-lbl">Received</div>
<div class="fc-name">${esc(m.name)}</div>
<div class="fc-size">${_fmtSize(m.size)}</div>
<a class="fc-dl" href="${dlUrl}" download="${esc(m.name)}">⬇ Download</a>
</div>
<div class="fc-status done">✓</div>
`;
feed.appendChild(card);
feed.scrollTop = feed.scrollHeight;
toast('File received on computer!');
}
// File input change handler
document.getElementById('file-inp').addEventListener('change', function () {
Array.from(this.files).forEach(_uploadFile);
this.value = ''; // reset so the same file can be re-sent
});
// ── Commands ──────────────────────────────────────────────────────────────
function doSend() {
const inp = document.getElementById('inp');
const txt = inp.value.trim();
if (!txt) return;
inp.value = '';
append('user', txt);
const enc = _encrypt(txt);
const body = enc ? { enc } : { text: txt };
_authFetch('/api/command', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
}
function doWake() {
sys('Sending wake signal…');
_authFetch('/api/wake', { method: 'POST' });
}
document.getElementById('inp').addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); doSend(); }
});
// ── Toast ─────────────────────────────────────────────────────────────────
let _toastTimer;
function toast(msg) {
const t = document.getElementById('toast');
t.textContent = msg; t.classList.add('show');
clearTimeout(_toastTimer);
_toastTimer = setTimeout(() => t.classList.remove('show'), 2800);
}
// ── Real-time Voice — PCM16 WebSocket → Gemini Live ──────────────────────
const micBtn = document.getElementById('mic-btn');
let _voiceWs = null;
let _audioCtx = null;
let _micStm = null;
let _audioNd = null;
function _micIdle() {
micBtn.innerHTML = '🎤';
micBtn.title = 'Voice — tap to speak';
micBtn.classList.remove('recording');
}
// Float32 PCM → resample to 16 kHz + convert to Int16
function _f32toPcm16(f32, srcRate) {
let s = f32;
if (srcRate !== 16000) {
const ratio = srcRate / 16000;
const len = Math.round(f32.length / ratio);
s = new Float32Array(len);
for (let i = 0; i < len; i++)
s[i] = f32[Math.min(Math.round(i * ratio), f32.length - 1)];
}
const out = new Int16Array(s.length);
for (let i = 0; i < s.length; i++)
out[i] = Math.max(-32768, Math.min(32767, Math.round(s[i] * 32768)));
return out.buffer;
}
function _showVoiceSetup() {
if (document.getElementById('voice-setup')) return; // show once
const origin = location.origin;
const card = document.createElement('div');
card.id = 'voice-setup';
card.style.cssText = [
'align-self:stretch', 'background:rgba(99,102,241,0.07)',
'border:1px solid rgba(99,102,241,0.22)', 'border-radius:14px',
'padding:16px 18px', 'font-size:13px', 'line-height:1.8',
'animation:pop 0.18s ease'
].join(';');
card.innerHTML =
'<div style="font-weight:700;color:#818cf8;letter-spacing:.5px;margin-bottom:10px">🎤 One-time voice setup</div>' +
'<ol style="padding-left:18px;color:#8899aa;margin:0;display:flex;flex-direction:column;gap:4px">' +
'<li>Open a new tab → go to <span style="background:rgba(255,255,255,0.07);padding:1px 6px;border-radius:4px;font-family:monospace;font-size:12px">chrome://flags</span></li>' +
'<li>Search: <strong style="color:#dde3ed">Insecure origins treated as secure</strong></li>' +
'<li>Paste this URL into the box:<br><span id="flags-url" style="background:rgba(255,255,255,0.07);padding:2px 8px;border-radius:4px;font-family:monospace;font-size:11px;user-select:all;cursor:pointer">' + esc(origin) + '</span></li>' +
'<li>Set to <strong style="color:#22c55e">Enabled</strong> → tap <strong style="color:#dde3ed">Relaunch</strong></li>' +
'<li>Return here and tap 🎤</li>' +
'</ol>';
feed.appendChild(card);
feed.scrollTop = feed.scrollHeight;
// tap to copy
card.querySelector('#flags-url').addEventListener('click', () => {
navigator.clipboard?.writeText(origin).then(() => toast('URL copied!')).catch(() => {});
});
}
async function doMic() {
if (_voiceWs) { _stopVoice(); return; }
if (!navigator.mediaDevices?.getUserMedia) {
_showVoiceSetup();
return;
}
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
});
} catch (e) {
sys(e.name === 'NotAllowedError'
? 'Microphone denied — tap the address bar lock and allow microphone.'
: 'Mic error: ' + e.message);
return;
}
// 16 kHz context (fall back to native rate — _f32toPcm16 resamples)
let ctx;
try { ctx = new AudioContext({ sampleRate: 16000 }); }
catch (_) { ctx = new AudioContext(); }
if (ctx.state === 'suspended') await ctx.resume();
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
const ws = new WebSocket(
`${wsProto}://${location.host}/ws/phone-audio?token=${encodeURIComponent(_authToken)}`
);
ws.binaryType = 'arraybuffer';
ws.onopen = async () => {
const rate = ctx.sampleRate;
const src = ctx.createMediaStreamSource(stream);
// AudioWorklet (modern) — runs in dedicated audio thread
const wCode = `class J extends AudioWorkletProcessor{process(i){const c=i[0]?.[0];if(c)this.port.postMessage(c.slice());return true;}}registerProcessor('j',J);`;
try {
const burl = URL.createObjectURL(new Blob([wCode], { type: 'application/javascript' }));
await ctx.audioWorklet.addModule(burl);
URL.revokeObjectURL(burl);
const nd = new AudioWorkletNode(ctx, 'j');
// Buffer to 1024 samples (64 ms at 16 kHz) before sending —
// matches PC mic chunk size, prevents queue flooding on the server.
let _pbuf = [], _plen = 0;
nd.port.onmessage = e => {
const chunk = new Int16Array(_f32toPcm16(e.data, rate));
_pbuf.push(chunk); _plen += chunk.length;
if (_plen >= 1024) {
const out = new Int16Array(_plen); let off = 0;
for (const c of _pbuf) { out.set(c, off); off += c.length; }
if (ws.readyState === 1) ws.send(out.buffer);
_pbuf = []; _plen = 0;
}
};
src.connect(nd);
_audioNd = nd;
} catch (_) {
// ScriptProcessor fallback (deprecated, still works everywhere)
const sp = ctx.createScriptProcessor(4096, 1, 1);
sp.onaudioprocess = e => {
if (ws.readyState === 1) ws.send(_f32toPcm16(e.inputBuffer.getChannelData(0), rate));
};
src.connect(sp); sp.connect(ctx.destination);
_audioNd = sp;
}
micBtn.innerHTML = '⏹';
micBtn.title = 'Tap to stop';
micBtn.classList.add('recording');
sys('Voice live — speak now');
toast('🎤 Live');
};
ws.onclose = () => { _stopVoice(); };
ws.onerror = () => { sys('Voice connection failed.'); _stopVoice(); };
_voiceWs = ws;
_audioCtx = ctx;
_micStm = stream;
}
function _stopVoice() {
if (_audioNd) { try { _audioNd.disconnect(); } catch (_) {}; _audioNd = null; }
if (_audioCtx) { try { _audioCtx.close(); } catch (_) {}; _audioCtx = null; }
if (_micStm) { _micStm.getTracks().forEach(t => t.stop()); _micStm = null; }
if (_voiceWs) {
const w = _voiceWs; _voiceWs = null;
if (w.readyState < 2) w.close();
}
_micIdle();
}
</script>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
!function(t,e){"object"==typeof exports?module.exports=exports=e():"function"==typeof define&&define.amd?define([],e):t.CryptoJS=e()}(this,function(){var W,O,I,U,K,X,L,l,j,T,t,N,q,e,Z,V,G,J,Q,Y,$,t1,e1,r1,i1,o1,n1,s,s1,c1,a1,h1,l1,o,f1,r,d1,u1,n,c,a,h,f,d,i=function(h){var i;if("undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),!(i=!(i=!(i="undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:i)&&"undefined"!=typeof window&&window.msCrypto?window.msCrypto:i)&&"undefined"!=typeof global&&global.crypto?global.crypto:i)&&"function"==typeof require)try{i=require("crypto")}catch(t){}var r=Object.create||function(t){return e.prototype=t,t=new e,e.prototype=null,t};function e(){}var t={},o=t.lib={},n=o.Base={extend:function(t){var e=r(this);return t&&e.mixIn(t),e.hasOwnProperty("init")&&this.init!==e.init||(e.init=function(){e.$super.init.apply(this,arguments)}),(e.init.prototype=e).$super=this,e},create:function(){var t=this.extend();return t.init.apply(t,arguments),t},init:function(){},mixIn:function(t){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e]);t.hasOwnProperty("toString")&&(this.toString=t.toString)},clone:function(){return this.init.prototype.extend(this)}},l=o.WordArray=n.extend({init:function(t,e){t=this.words=t||[],this.sigBytes=null!=e?e:4*t.length},toString:function(t){return(t||c).stringify(this)},concat:function(t){var e=this.words,r=t.words,i=this.sigBytes,o=t.sigBytes;if(this.clamp(),i%4)for(var n=0;n<o;n++){var s=r[n>>>2]>>>24-n%4*8&255;e[i+n>>>2]|=s<<24-(i+n)%4*8}else for(var c=0;c<o;c+=4)e[i+c>>>2]=r[c>>>2];return this.sigBytes+=o,this},clamp:function(){var t=this.words,e=this.sigBytes;t[e>>>2]&=4294967295<<32-e%4*8,t.length=h.ceil(e/4)},clone:function(){var t=n.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var e=[],r=0;r<t;r+=4)e.push(function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")}());return new l.init(e,t)}}),s=t.enc={},c=s.Hex={stringify:function(t){for(var e=t.words,r=t.sigBytes,i=[],o=0;o<r;o++){var n=e[o>>>2]>>>24-o%4*8&255;i.push((n>>>4).toString(16)),i.push((15&n).toString(16))}return i.join("")},parse:function(t){for(var e=t.length,r=[],i=0;i<e;i+=2)r[i>>>3]|=parseInt(t.substr(i,2),16)<<24-i%8*4;return new l.init(r,e/2)}},a=s.Latin1={stringify:function(t){for(var e=t.words,r=t.sigBytes,i=[],o=0;o<r;o++){var n=e[o>>>2]>>>24-o%4*8&255;i.push(String.fromCharCode(n))}return i.join("")},parse:function(t){for(var e=t.length,r=[],i=0;i<e;i++)r[i>>>2]|=(255&t.charCodeAt(i))<<24-i%4*8;return new l.init(r,e)}},f=s.Utf8={stringify:function(t){try{return decodeURIComponent(escape(a.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return a.parse(unescape(encodeURIComponent(t)))}},d=o.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=new l.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=f.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(t){var e,r=this._data,i=r.words,o=r.sigBytes,n=this.blockSize,s=o/(4*n),c=(s=t?h.ceil(s):h.max((0|s)-this._minBufferSize,0))*n,t=h.min(4*c,o);if(c){for(var a=0;a<c;a+=n)this._doProcessBlock(i,a);e=i.splice(0,c),r.sigBytes-=t}return new l.init(e,t)},clone:function(){var t=n.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0}),u=(o.Hasher=d.extend({cfg:n.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){d.reset.call(this),this._doReset()},update:function(t){return this._append(t),this._process(),this},finalize:function(t){return t&&this._append(t),this._doFinalize()},blockSize:16,_createHelper:function(r){return function(t,e){return new r.init(e).finalize(t)}},_createHmacHelper:function(r){return function(t,e){return new u.HMAC.init(r,e).finalize(t)}}}),t.algo={});return t}(Math),u=(u=(p=i).lib,W=u.Base,O=u.WordArray,(u=p.x64={}).Word=W.extend({init:function(t,e){this.high=t,this.low=e}}),u.WordArray=W.extend({init:function(t,e){t=this.words=t||[],this.sigBytes=null!=e?e:8*t.length},toX32:function(){for(var t=this.words,e=t.length,r=[],i=0;i<e;i++){var o=t[i];r.push(o.high),r.push(o.low)}return O.create(r,this.sigBytes)},clone:function(){for(var t=W.clone.call(this),e=t.words=this.words.slice(0),r=e.length,i=0;i<r;i++)e[i]=e[i].clone();return t}}),"function"==typeof ArrayBuffer&&(p=i.lib.WordArray,I=p.init,(p.init=function(t){if((t=(t=t instanceof ArrayBuffer?new Uint8Array(t):t)instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array?new Uint8Array(t.buffer,t.byteOffset,t.byLine truncated
+224
View File
@@ -0,0 +1,224 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>JARVIS</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #07090f;
--card: rgba(255,255,255,0.04);
--border: rgba(255,255,255,0.08);
--accent: #6366f1;
--adim: rgba(99,102,241,0.15);
--text: #dde3ed;
--muted: #5e6a7e;
}
html, body {
height: 100%;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
display: flex;
align-items: center;
justify-content: center;
}
.card {
width: 340px;
padding: 44px 36px;
background: var(--card);
border: 1px solid var(--border);
border-radius: 22px;
text-align: center;
}
.logo {
font-size: 28px;
font-weight: 700;
letter-spacing: 10px;
margin-bottom: 6px;
}
.logo em { color: var(--accent); font-style: normal; }
.sub {
font-size: 11px;
color: var(--muted);
letter-spacing: 3px;
text-transform: uppercase;
margin-bottom: 10px;
}
.hint {
font-size: 12px;
color: var(--muted);
line-height: 1.55;
margin-bottom: 28px;
}
.key-wrap {
position: relative;
margin-bottom: 16px;
}
.key-input {
width: 100%;
padding: 18px 14px;
background: rgba(255,255,255,0.05);
border: 1.5px solid var(--border);
border-radius: 14px;
color: var(--text);
font-size: 30px;
font-weight: 700;
font-family: 'Courier New', monospace;
text-align: center;
letter-spacing: 10px;
text-transform: uppercase;
outline: none;
transition: border-color 0.15s, background 0.15s, box-shadow 0.15s;
caret-color: var(--accent);
}
.key-input::placeholder {
color: rgba(94,106,126,0.5);
letter-spacing: 6px;
font-size: 20px;
}
.key-input:focus {
border-color: var(--accent);
background: var(--adim);
box-shadow: 0 0 0 3px rgba(99,102,241,0.12);
}
.err {
font-size: 12px;
color: #f87171;
min-height: 18px;
margin-bottom: 14px;
}
.btn {
width: 100%;
padding: 14px;
background: var(--accent);
color: #fff;
font-size: 12px;
font-weight: 700;
letter-spacing: 3px;
border: none;
border-radius: 12px;
cursor: pointer;
transition: opacity 0.15s, transform 0.1s;
}
.btn:hover { opacity: 0.88; }
.btn:active { transform: scale(0.98); }
@keyframes shake {
0%,100% { transform: translateX(0); }
20%,60% { transform: translateX(-7px); }
40%,80% { transform: translateX(7px); }
}
.shake { animation: shake 0.35s ease; }
.voice-note {
font-size: 10px;
color: var(--muted);
margin-top: 20px;
line-height: 1.6;
text-align: left;
}
.voice-note code {
background: rgba(255,255,255,0.07);
padding: 1px 4px;
border-radius: 3px;
font-family: 'Courier New', monospace;
font-size: 9px;
}
#reconnecting {
display: none;
color: var(--muted);
font-size: 12px;
margin-bottom: 16px;
}
</style>
</head>
<body>
<div class="card" id="card">
<div class="logo"><em>J</em>ARVIS</div>
<div class="sub">Remote Access</div>
<p id="reconnecting">Reconnecting…</p>
<p class="hint">Press <strong style="color:var(--text)">Remote Control</strong> in the JARVIS desktop app to get a QR code or session key.</p>
<div class="key-wrap">
<input class="key-input" id="key" type="text" maxlength="6"
autocomplete="off" autocorrect="off" spellcheck="false"
placeholder="· · · · · ·">
</div>
<div class="err" id="err"></div>
<button class="btn" onclick="doLogin()">CONNECT</button>
<p class="voice-note">
🎤 <strong style="color:var(--text)">Voice commands:</strong> open
<code>chrome://flags</code> on your phone, search
<code>Insecure origins treated as secure</code>, add your JARVIS URL, tap Relaunch.
</p>
</div>
<script>
// Try auto-reconnect with stored device token (set on first QR login)
(async function() {
const devTok = localStorage.getItem('jarvis_device_token');
if (!devTok) return;
document.getElementById('reconnecting').style.display = 'block';
try {
const r = await fetch('/api/device-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_token: devTok }),
});
const d = await r.json();
if (d.ok && d.token) {
sessionStorage.setItem('jarvis_key', d.key);
sessionStorage.setItem('jarvis_token', d.token);
location.replace('/');
return;
}
} catch (_) {}
// Device token rejected (server restarted) — clear it and show normal form
localStorage.removeItem('jarvis_device_token');
document.getElementById('reconnecting').style.display = 'none';
})();
const inp = document.getElementById('key');
inp.focus();
inp.addEventListener('input', () => {
inp.value = inp.value.toUpperCase().replace(/[^A-Z2-9]/g, '');
if (inp.value.length === 6) doLogin();
});
inp.addEventListener('keydown', e => { if (e.key === 'Enter') doLogin(); });
async function doLogin() {
const key = inp.value.trim();
if (key.length < 6) { shake(); return; }
let data;
try {
const r = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pin: key })
});
data = await r.json();
} catch (e) {
document.getElementById('err').textContent = 'Connection error';
shake(); return;
}
if (data.ok && data.token) {
sessionStorage.setItem('jarvis_key', key);
sessionStorage.setItem('jarvis_token', data.token);
location.href = '/';
} else {
inp.value = '';
inp.focus();
document.getElementById('err').textContent = 'Invalid or expired key';
shake();
}
}
function shake() {
const c = document.getElementById('card');
c.classList.remove('shake');
void c.offsetWidth;
c.classList.add('shake');
}
</script>
</body>
</html>