Files
chandra/remote/test_remote.py
T
nandiandClaude Opus 5.5 0356413bb2
CI / test (push) Failing after 1m7s
Remote: forward the physical keyboard and hide the phone OSK while typing
The web UI now sends key events without opening the KB bar, and releases
held keys on blur, hide or disconnect. The first remote keystroke (web or
VNC) turns the on-screen keyboard off; it comes back when the last typing
client disconnects, unless the user toggled it by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 14:27:17 -08:00

767 lines
31 KiB
Python

#!/usr/bin/env python3
"""End-to-end tests for chandra-remote (RFB 3.8 VNC + HTTP/WebSocket + Tailscale/Auth guardrails)."""
import base64
import hashlib
import http.client
import json
import mmap
import os
import shutil
import socket
import struct
import subprocess
import tempfile
import threading
import time
import unittest
import zlib
CHANDRA_FB_MAGIC = 0x43484642
CHANDRA_FB_VERSION = 1
CHANDRA_FB_HDR_BYTES = 4096
CHANDRA_FB_SLOT_BYTES = 34 * 1024 * 1024
CHANDRA_FB_TOTAL_BYTES = CHANDRA_FB_HDR_BYTES + 2 * CHANDRA_FB_SLOT_BYTES
def free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def decode_jpeg_rgb(jpg: bytes):
"""Return (w, h, bytes_rgb24) from JPEG bytes using cv2, PIL, djpeg, or ffmpeg."""
try:
import cv2
import numpy as np
arr = np.frombuffer(jpg, dtype=np.uint8)
bgr = cv2.imdecode(arr, cv2.IMREAD_COLOR)
if bgr is not None:
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
h, w, _ = rgb.shape
return w, h, rgb.tobytes()
except ImportError:
pass
try:
import io
from PIL import Image
im = Image.open(io.BytesIO(jpg)).convert("RGB")
return im.width, im.height, im.tobytes()
except ImportError:
pass
if shutil.which("djpeg"):
p = subprocess.run(["djpeg", "-rgb"], input=jpg, capture_output=True)
if p.returncode == 0 and p.stdout.startswith(b"P6"):
nl1 = p.stdout.find(b"\n")
nl2 = p.stdout.find(b"\n", nl1 + 1)
nl3 = p.stdout.find(b"\n", nl2 + 1)
dims = p.stdout[nl1 + 1 : nl2].decode().split()
return int(dims[0]), int(dims[1]), p.stdout[nl3 + 1 :]
if shutil.which("ffmpeg"):
# Probe size + decode rgb24
p = subprocess.run(
["ffmpeg", "-v", "error", "-f", "mjpeg", "-i", "pipe:0", "-f", "rawvideo", "-pix_fmt", "rgb24", "pipe:1"],
input=jpg,
capture_output=True,
)
if p.returncode == 0:
# Find SOF0/SOF2 dimensions in JPEG header
i = 2
w = h = 0
while i + 9 < len(jpg):
if jpg[i] != 0xFF:
break
m = jpg[i + 1]
if m in (0xC0, 0xC1, 0xC2):
h, w = struct.unpack(">HH", jpg[i + 5 : i + 9])
break
ln = struct.unpack(">H", jpg[i + 2 : i + 4])[0]
i += 2 + ln
return w, h, p.stdout
raise RuntimeError("No JPEG decoder available (cv2, PIL, djpeg, or ffmpeg)")
def vnc_des_encrypt_py(password: str, challenge: bytes) -> bytes:
"""Reference FIPS-46 DES for VNCAuth test client (pure Python)."""
IP = [58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8,
57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7]
FP = [40,8,48,16,56,24,64,32,39,7,47,15,55,23,63,31,38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29,
36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,34,2,42,10,50,18,58,26,33,1,41,9,49,17,57,25]
PC1 = [57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,
63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4]
PC2 = [14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,
41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32]
ROT = [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1]
E = [32,1,2,3,4,5,4,5,6,7,8,9,8,9,10,11,12,13,12,13,14,15,16,17,
16,17,18,19,20,21,20,21,22,23,24,25,24,25,26,27,28,29,28,29,30,31,32,1]
P = [16,7,20,21,29,12,28,17,1,15,23,26,5,18,31,10,2,8,24,14,32,27,3,9,19,13,30,6,22,11,4,25]
S = [
[14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8,
4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13],
[15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5,
0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9],
[10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1,
13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12],
[7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9,
10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14],
[2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6,
4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3],
[12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8,
9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13],
[4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6,
1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12],
[13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2,
7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11],
]
def perm(val, inb, tbl):
out = 0
for b in tbl:
out = (out << 1) | ((val >> (inb - b)) & 1)
return out
raw = password.encode("latin-1", "replace")[:8].ljust(8, b"\x00")
k64 = 0
for byte in raw:
rev = int(f"{byte:08b}"[::-1], 2)
k64 = (k64 << 8) | rev
cd = perm(k64, 64, PC1)
C, D = cd >> 28, cd & 0x0FFFFFFF
sk = []
for r in ROT:
C = ((C << r) | (C >> (28 - r))) & 0x0FFFFFFF
D = ((D << r) | (D >> (28 - r))) & 0x0FFFFFFF
sk.append(perm((C << 28) | D, 56, PC2))
def enc_block(blk):
ip = perm(int.from_bytes(blk, "big"), 64, IP)
L, R = ip >> 32, ip & 0xFFFFFFFF
for k in sk:
exp = perm(R, 32, E) ^ k
sout = 0
for i in range(8):
six = (exp >> ((7 - i) * 6)) & 0x3F
row = ((six & 0x20) >> 4) | (six & 1)
col = (six >> 1) & 0x0F
sout = (sout << 4) | S[i][row * 16 + col]
L, R = R, L ^ perm(sout, 32, P)
return perm((R << 32) | L, 64, FP).to_bytes(8, "big")
return enc_block(challenge[:8]) + enc_block(challenge[8:16])
class MockShm:
def __init__(self, path: str):
self.path = path
self.fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600)
os.ftruncate(self.fd, CHANDRA_FB_TOTAL_BYTES)
self.mm = mmap.mmap(self.fd, CHANDRA_FB_TOTAL_BYTES)
self.seq = 0
self.slot = 0
struct.pack_into("<IIIIIIiiiiQQQ", self.mm, 0,
CHANDRA_FB_MAGIC, CHANDRA_FB_VERSION, CHANDRA_FB_SLOT_BYTES,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
def write_frame(self, w: int, h: int, color_fn, dmg=None):
next_slot = 1 - self.slot
off = CHANDRA_FB_HDR_BYTES + next_slot * CHANDRA_FB_SLOT_BYTES
row = bytearray(w * 4)
for y in range(h):
for x in range(w):
r, g, b = color_fn(x, y)
row[x * 4 : x * 4 + 4] = bytes((r, g, b, 255))
self.mm[off + y * w * 4 : off + (y + 1) * w * 4] = row
x0, y0, x1, y1 = dmg if dmg else (0, 0, w, h)
self.slot = next_slot
self.seq += 1
now_ms = int(time.monotonic() * 1000)
struct.pack_into("<IIIiiii", self.mm, 12, self.slot, w, h, x0, y0, x1, y1)
struct.pack_into("<QQ", self.mm, 40, self.seq, now_ms)
def close(self):
self.mm.close()
os.close(self.fd)
class MockCtlServer:
def __init__(self, path: str):
self.path = path
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if os.path.exists(path):
os.unlink(path)
self.sock.bind(path)
self.sock.listen(8)
self.commands = []
self.running = True
self.w, self.h, self.rot = 540, 1170, 0
self.screen = "on"
self.brightness = 75
self.osk = 1
self.th = threading.Thread(target=self._serve, daemon=True)
self.th.start()
def _serve(self):
self.sock.settimeout(0.1)
while self.running:
try:
conn, _ = self.sock.accept()
except socket.timeout:
continue
except OSError:
break
threading.Thread(target=self._client, args=(conn,), daemon=True).start()
def _client(self, conn: socket.socket):
buf = b""
while self.running:
try:
data = conn.recv(4096)
except OSError:
break
if not data:
break
buf += data
while b"\n" in buf:
line, buf = buf.split(b"\n", 1)
cmd = line.decode("utf-8", "replace").strip()
self.commands.append(cmd)
if cmd == "status":
rep = f"ok {self.w}x{self.h} rot={self.rot} screen={self.screen} brightness={self.brightness} ptr=10,20 osk={self.osk}\n"
elif cmd == "rotate cw":
self.w, self.h = self.h, self.w
self.rot = (self.rot + 90) % 360
rep = "ok rotate cw\n"
elif cmd == "screen toggle":
self.screen = "off" if self.screen == "on" else "on"
rep = f"ok {self.screen}\n"
elif cmd == "osk status":
rep = f"ok {'on' if self.osk else 'off'}\n"
elif cmd == "osk off":
self.osk = 0
rep = "ok off\n"
elif cmd == "osk on":
self.osk = 1
rep = "ok on\n"
elif cmd == "osk toggle":
self.osk = 0 if self.osk else 1
rep = f"ok {'on' if self.osk else 'off'}\n"
else:
rep = "ok\n"
conn.sendall(rep.encode())
conn.close()
def close(self):
self.running = False
self.sock.close()
if os.path.exists(self.path):
os.unlink(self.path)
def recv_exact(s: socket.socket, n: int) -> bytes:
buf = bytearray()
while len(buf) < n:
c = s.recv(n - len(buf))
if not c:
raise EOFError("short read")
buf += c
return bytes(buf)
def ws_connect(host: str, port: int, path: str = "/ws", cookie: str = ""):
s = socket.create_connection((host, port), timeout=5)
key = base64.b64encode(os.urandom(16)).decode()
hdrs = [
f"GET {path} HTTP/1.1",
f"Host: {host}:{port}",
"Upgrade: websocket",
"Connection: Upgrade",
f"Sec-WebSocket-Key: {key}",
"Sec-WebSocket-Version: 13",
]
if cookie:
hdrs.append(f"Cookie: {cookie}")
s.sendall(("\r\n".join(hdrs) + "\r\n\r\n").encode())
raw = b""
while b"\r\n\r\n" not in raw:
chunk = s.recv(4096)
if not chunk:
raise EOFError("ws handshake closed")
raw += chunk
head, extra = raw.split(b"\r\n\r\n", 1)
status_line = head.split(b"\r\n", 1)[0].decode()
return s, status_line, head.decode("latin-1"), extra
def ws_send_text(s: socket.socket, text: str):
payload = text.encode("utf-8")
mask = os.urandom(4)
hdr = bytearray([0x81])
n = len(payload)
if n <= 125:
hdr.append(0x80 | n)
elif n <= 65535:
hdr.append(0x80 | 126)
hdr += struct.pack(">H", n)
else:
hdr.append(0x80 | 127)
hdr += struct.pack(">Q", n)
hdr += mask
masked = bytes(payload[i] ^ mask[i & 3] for i in range(n))
s.sendall(bytes(hdr) + masked)
def ws_read_frame(s: socket.socket, buf: bytearray):
while len(buf) < 2:
buf += s.recv(4096)
b0, b1 = buf[0], buf[1]
op = b0 & 0x0F
plen = b1 & 0x7F
pos = 2
if plen == 126:
while len(buf) < 4:
buf += s.recv(4096)
plen = struct.unpack(">H", buf[2:4])[0]
pos = 4
elif plen == 127:
while len(buf) < 10:
buf += s.recv(4096)
plen = struct.unpack(">Q", buf[2:10])[0]
pos = 10
while len(buf) < pos + plen:
buf += s.recv(65536)
payload = bytes(buf[pos : pos + plen])
del buf[: pos + plen]
return op, payload
def find_remote_bin() -> str:
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
cand = os.path.join(root, "build/chandra-remote")
if os.path.exists(cand):
return cand
if shutil.which("chandra-remote"):
return shutil.which("chandra-remote")
raise FileNotFoundError("build/chandra-remote not built")
class RemoteTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="chandra-remote-test-")
self.shm_path = os.path.join(self.tmp, "fb.shm")
self.sock_path = os.path.join(self.tmp, "wayland.sock")
self.cfg_path = os.path.join(self.tmp, "remote.conf")
self.web_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "web")
self.bin = find_remote_bin()
self.shm = MockShm(self.shm_path)
self.ctl = MockCtlServer(self.sock_path)
self.proc = None
def tearDown(self):
if self.proc:
if self.proc.poll() is None:
self.proc.terminate()
self.proc.wait(timeout=5)
if self.proc.stdout:
self.proc.stdout.close()
if self.proc.stderr:
self.proc.stderr.close()
self.ctl.close()
self.shm.close()
shutil.rmtree(self.tmp, ignore_errors=True)
def start_daemon(self, auth="none", password="", bind="127.0.0.1"):
with open(self.cfg_path, "w") as f:
f.write(
f"enabled=1\nbind={bind}\nbind_loopback=1\nauth={auth}\n"
f"jpeg_quality=88\nmax_fps=60\n"
)
if password:
f.write(f"password={password}\n")
self.vnc_port = free_port()
self.web_port = free_port()
self.proc = subprocess.Popen(
[
self.bin,
"--config", self.cfg_path,
"--socket", self.sock_path,
"--shm", self.shm_path,
"--web-dir", self.web_dir,
"--bind", bind,
"--vnc-port", str(self.vnc_port),
"--web-port", str(self.web_port),
],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
# Wait until web port accepts TCP
deadline = time.time() + 5.0
while time.time() < deadline:
if self.proc.poll() is not None:
raise RuntimeError(f"daemon exited early: {self.proc.stderr.read().decode()}")
try:
with socket.create_connection(("127.0.0.1", self.web_port), timeout=0.2):
return
except OSError:
time.sleep(0.05)
raise TimeoutError("daemon failed to listen")
def test_01_refuse_unauth_open_bind(self):
with open(self.cfg_path, "w") as f:
f.write("enabled=1\nbind=0.0.0.0\nauth=none\n")
r = subprocess.run(
[self.bin, "--config", self.cfg_path, "--vnc-port", str(free_port()), "--web-port", str(free_port())],
capture_output=True,
text=True,
)
self.assertNotEqual(r.returncode, 0)
self.assertIn("refusing", r.stderr)
def test_02_vnc_none_tight_zlib_raw_resize_and_input(self):
self.shm.write_frame(120, 80, lambda x, y: (220, 40, 30) if x < 60 else (20, 180, 60))
self.start_daemon(auth="none")
with socket.create_connection(("127.0.0.1", self.vnc_port), timeout=5) as s:
self.assertEqual(recv_exact(s, 12), b"RFB 003.008\n")
s.sendall(b"RFB 003.008\n")
nt = recv_exact(s, 1)[0]
types = recv_exact(s, nt)
self.assertIn(1, types)
s.sendall(b"\x01")
self.assertEqual(struct.unpack(">I", recv_exact(s, 4))[0], 0)
s.sendall(b"\x01") # ClientInit shared=1
sinit = recv_exact(s, 24)
w0, h0 = struct.unpack(">HH", sinit[:4])
self.assertGreater(w0, 0)
name_len = struct.unpack(">I", sinit[20:24])[0]
self.assertEqual(recv_exact(s, name_len), b"Chandra")
# Advertise Tight(7), JPEG quality -24, Zlib(6), Raw(0), ExtendedDesktopSize(-308)
encs = [7, -24, 6, 0, -308]
s.sendall(struct.pack(">BxH" + "i" * len(encs), 2, len(encs), *encs))
# Request full Tight JPEG frame
s.sendall(struct.pack(">BBHHHH", 3, 0, 0, 0, 120, 80))
msg = recv_exact(s, 4)
self.assertEqual(msg[0], 0)
nrects = struct.unpack(">H", msg[2:4])[0]
saw_pixel = False
for _ in range(nrects):
rx, ry, rw, rh, enc = struct.unpack(">HHHHi", recv_exact(s, 12))
if enc == -308:
nscr = recv_exact(s, 4)[0]
recv_exact(s, nscr * 16)
elif enc == 7:
ctrl = recv_exact(s, 1)[0]
self.assertEqual(ctrl, 0x90)
jlen = 0
for sh in (0, 7, 14):
b = recv_exact(s, 1)[0]
if sh < 14:
jlen |= (b & 0x7F) << sh
if not (b & 0x80):
break
else:
jlen |= b << sh
jpg = recv_exact(s, jlen)
jw, jh, rgb = decode_jpeg_rgb(jpg)
self.assertEqual((jw, jh), (120, 80))
# Left half red, right half green (verify no R/B swap!)
lr, lg, lb = rgb[(40 * jw + 20) * 3 : (40 * jw + 20) * 3 + 3]
rr, rg, rb = rgb[(40 * jw + 100) * 3 : (40 * jw + 100) * 3 + 3]
self.assertGreater(lr, 180)
self.assertLess(lb, 60)
self.assertGreater(rg, 140)
self.assertLess(rr, 60)
saw_pixel = True
self.assertTrue(saw_pixel)
# Rotate SHM dimensions 120x80 -> 80x120 and verify ExtendedDesktopSize(-308)
self.shm.write_frame(80, 120, lambda x, y: (30, 50, 230))
s.sendall(struct.pack(">BBHHHH", 3, 1, 0, 0, 120, 80))
msg = recv_exact(s, 4)
nrects = struct.unpack(">H", msg[2:4])[0]
got_ext = False
for _ in range(nrects):
rx, ry, rw, rh, enc = struct.unpack(">HHHHi", recv_exact(s, 12))
if enc == -308:
self.assertEqual((rw, rh), (80, 120))
nscr = recv_exact(s, 4)[0]
recv_exact(s, nscr * 16)
got_ext = True
elif enc == 7:
recv_exact(s, 1)
jlen = 0
for sh in (0, 7, 14):
b = recv_exact(s, 1)[0]
if sh < 14:
jlen |= (b & 0x7F) << sh
if not (b & 0x80):
break
else:
jlen |= b << sh
jw, jh, rgb = decode_jpeg_rgb(recv_exact(s, jlen))
self.assertEqual((jw, jh), (80, 120))
br, bg, bb = rgb[(60 * jw + 40) * 3 : (60 * jw + 40) * 3 + 3]
self.assertGreater(bb, 190)
self.assertLess(br, 60)
self.assertTrue(got_ext)
# Pointer, scroll, Shift+'A', Unicode é, CutText
s.sendall(struct.pack(">BBHH", 5, 1, 25, 35))
s.sendall(struct.pack(">BBHH", 5, 8, 25, 35)) # scroll up bit
s.sendall(struct.pack(">BBxxI", 4, 1, 0x0041)) # 'A' down
s.sendall(struct.pack(">BBxxI", 4, 0, 0x0041)) # 'A' up
s.sendall(struct.pack(">BBxxI", 4, 1, 0x00E9)) # Latin-1 e-acute
cut = b"hello-vnc"
s.sendall(struct.pack(">BxxxI", 6, len(cut)) + cut)
time.sleep(0.15)
cmds = "\n".join(self.ctl.commands)
self.assertIn("input-ptr 25 35", cmds)
self.assertIn("input-btn 272 1", cmds)
self.assertIn("input-scroll 0 -30 -1", cmds)
self.assertIn("input-key 30 1", cmds)
self.assertIn("input-text c3a9", cmds)
self.assertIn("clipboard-set " + cut.hex(), cmds)
def test_03_vnc_password_and_zlib(self):
self.shm.write_frame(64, 48, lambda x, y: (10, 200, 220))
self.start_daemon(auth="password", password="TestPass99")
# Bad password fails
with socket.create_connection(("127.0.0.1", self.vnc_port), timeout=5) as s:
recv_exact(s, 12)
s.sendall(b"RFB 003.008\n")
nt = recv_exact(s, 1)[0]
types = recv_exact(s, nt)
self.assertEqual(types, b"\x02")
s.sendall(b"\x02")
chal = recv_exact(s, 16)
s.sendall(vnc_des_encrypt_py("WrongPass", chal))
self.assertEqual(struct.unpack(">I", recv_exact(s, 4))[0], 1)
# Good password + Zlib frame
with socket.create_connection(("127.0.0.1", self.vnc_port), timeout=5) as s:
recv_exact(s, 12)
s.sendall(b"RFB 003.008\n")
recv_exact(s, 2)
s.sendall(b"\x02")
chal = recv_exact(s, 16)
s.sendall(vnc_des_encrypt_py("TestPass99", chal))
self.assertEqual(struct.unpack(">I", recv_exact(s, 4))[0], 0)
s.sendall(b"\x01")
sinit = recv_exact(s, 24)
recv_exact(s, struct.unpack(">I", sinit[20:24])[0])
s.sendall(struct.pack(">BxHii", 2, 2, 6, 0)) # Zlib, Raw
s.sendall(struct.pack(">BBHHHH", 3, 0, 0, 0, 64, 48))
msg = recv_exact(s, 4)
nrects = struct.unpack(">H", msg[2:4])[0]
self.assertEqual(nrects, 1)
_, _, rw, rh, enc = struct.unpack(">HHHHi", recv_exact(s, 12))
self.assertEqual((rw, rh, enc), (64, 48, 6))
zlen = struct.unpack(">I", recv_exact(s, 4))[0]
px = zlib.decompressobj().decompress(recv_exact(s, zlen))
self.assertEqual(len(px), 64 * 48 * 4)
self.assertEqual(tuple(px[:3]), (10, 200, 220))
def test_04_web_no_auth_stream_ack_and_ctl(self):
self.shm.write_frame(160, 120, lambda x, y: (240, 120, 15))
self.start_daemon(auth="none")
c = http.client.HTTPConnection("127.0.0.1", self.web_port, timeout=5)
c.request("GET", "/api/info")
r = c.getresponse()
self.assertEqual(r.status, 200)
info = json.loads(r.read())
self.assertFalse(info["auth_required"])
c.request("GET", "/")
r = c.getresponse()
self.assertEqual(r.status, 200)
self.assertIn(b"Chandra Remote", r.read())
c.close()
ws, status_line, _, extra = ws_connect("127.0.0.1", self.web_port)
self.assertIn("101", status_line)
buf = bytearray(extra)
frames = []
statuses = []
deadline = time.time() + 4.0
while time.time() < deadline and (len(frames) < 1 or len(statuses) < 1):
op, payload = ws_read_frame(ws, buf)
if op == 1:
statuses.append(json.loads(payload))
elif op == 2:
frames.append(payload)
self.assertGreaterEqual(len(statuses), 1)
self.assertEqual(statuses[0]["t"], "status")
hdr = struct.unpack(">BBHHHHHHI", frames[0][:18])
ftype, flags, x, y, w, h, fbw, fbh, fid = hdr
self.assertEqual((ftype, fbw, fbh), (1, 160, 120))
jw, jh, rgb = decode_jpeg_rgb(frames[0][18:])
self.assertEqual((jw, jh), (160, 120))
pr, pg, pb = rgb[:3]
self.assertGreater(pr, 200)
self.assertGreater(pg, 90)
self.assertLess(pb, 50)
ws_send_text(ws, json.dumps({"t": "ack", "id": fid}))
ws_send_text(ws, json.dumps({"t": "tap", "x": 50, "y": 60, "b": 1}))
ws_send_text(ws, json.dumps({"t": "text", "s": "hi!"}))
ws_send_text(ws, json.dumps({"t": "ctl", "cmd": "rotate cw"}))
deadline = time.time() + 3.0
saw_rot = False
while time.time() < deadline and not saw_rot:
op, payload = ws_read_frame(ws, buf)
if op == 1:
st = json.loads(payload)
if st.get("rot") == 90:
saw_rot = True
self.assertTrue(saw_rot)
cmds = "\n".join(self.ctl.commands)
self.assertIn("input-ptr 50 60", cmds)
self.assertIn("input-btn 272 1", cmds)
self.assertIn("input-key-tap 2 1", cmds) # '!' shifted (KEY_1)
self.assertIn("rotate cw", cmds)
ws.close()
def test_05_web_password_auth_gate(self):
self.shm.write_frame(96, 96, lambda x, y: (40, 90, 210))
self.start_daemon(auth="password", password="Secret42")
ws0, status_line0, _, _ = ws_connect("127.0.0.1", self.web_port)
self.assertIn("401", status_line0)
ws0.close()
c = http.client.HTTPConnection("127.0.0.1", self.web_port, timeout=5)
c.request("POST", "/api/login", body=json.dumps({"password": "bad"}))
self.assertEqual(c.getresponse().status, 401)
c.request("POST", "/api/login", body=json.dumps({"password": "Secret42"}))
r = c.getresponse()
self.assertEqual(r.status, 200)
tok = json.loads(r.read())["token"]
self.assertTrue(len(tok) > 10)
c.close()
ws, status_line, _, _ = ws_connect("127.0.0.1", self.web_port, path=f"/ws?token={tok}")
self.assertIn("101", status_line)
ws.close()
def test_06_web_keyboard_forwarding_release_and_osk_autosuppress(self):
self.shm.write_frame(160, 120, lambda x, y: (30, 80, 180))
self.start_daemon(auth="none")
c = http.client.HTTPConnection("127.0.0.1", self.web_port, timeout=5)
c.request("GET", "/")
r = c.getresponse()
self.assertEqual(r.status, 200)
html = r.read().decode("utf-8")
self.assertIn("window.addEventListener('keydown'", html)
c.close()
# Connect WebSocket and wait for initial status (osk=1)
ws, status_line, _, extra = ws_connect("127.0.0.1", self.web_port)
self.assertIn("101", status_line)
buf = bytearray(extra)
def read_next_status(sock, rxbuf, timeout=3.0):
deadline = time.time() + timeout
while time.time() < deadline:
op, payload = ws_read_frame(sock, rxbuf)
if op == 1:
return json.loads(payload)
raise TimeoutError("timed out waiting for status")
st0 = read_next_status(ws, buf)
self.assertEqual(st0["osk"], 1)
# Shifted letter, Ctrl+C, F5, Super, CapsLock, non-ASCII Unicode, and release
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFE1, "d": 1})) # Shift_L
ws_send_text(ws, json.dumps({"t": "key", "k": 0x0041, "d": 1})) # 'A'
ws_send_text(ws, json.dumps({"t": "key", "k": 0x0041, "d": 0}))
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFE1, "d": 0}))
# OSK should auto-suppress to 0 on first keystroke and push updated status
st1 = read_next_status(ws, buf)
self.assertEqual(st1["osk"], 0)
self.assertEqual(self.ctl.osk, 0)
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFE3, "d": 1})) # Control_L
ws_send_text(ws, json.dumps({"t": "key", "k": 0x0063, "d": 1})) # 'c'
ws_send_text(ws, json.dumps({"t": "key", "k": 0x0063, "d": 0}))
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFE3, "d": 0}))
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFC2, "d": 1})) # F5 (evdev 63)
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFC2, "d": 0}))
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFEB, "d": 1})) # Super_L (evdev 125, mod 64)
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFEB, "d": 0}))
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFE5, "d": 1})) # CapsLock (evdev 58, no depressed mod)
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFE5, "d": 0}))
ws_send_text(ws, json.dumps({"t": "key", "k": 0x00E9, "d": 1})) # Unicode 'é'
ws_send_text(ws, json.dumps({"t": "key", "k": 0x00E9, "d": 0}))
# Hold Shift_L + 'b' (evdev 48) and test release clearing both
ws_send_text(ws, json.dumps({"t": "key", "k": 0xFFE1, "d": 1}))
ws_send_text(ws, json.dumps({"t": "key", "k": 0x0062, "d": 1}))
ws_send_text(ws, json.dumps({"t": "release"}))
time.sleep(0.2)
cmds = self.ctl.commands
joined = "\n".join(cmds)
self.assertIn("osk status", joined)
self.assertIn("osk off", joined)
self.assertIn("input-mods 1 0 0 0", joined)
self.assertIn("input-key 30 1", joined)
self.assertIn("input-mods 4 0 0 0", joined)
self.assertIn("input-key 46 1", joined)
self.assertIn("input-key 63 1", joined)
self.assertIn("input-mods 64 0 0 0", joined)
self.assertIn("input-key 125 1", joined)
self.assertIn("input-key 58 1", joined)
self.assertIn("input-key 58 0", joined)
self.assertNotIn("input-mods 2 0 0 0", joined)
self.assertIn("input-text c3a9", joined)
# Release cleared stuck 'b' (48), Shift_L (42), and depressed mods
rel_idx = len(cmds) - 1 - cmds[::-1].index("input-key 48 0")
tail = "\n".join(cmds[rel_idx:])
self.assertIn("input-key 48 0", tail)
self.assertIn("input-key 42 0", tail)
self.assertIn("input-mods 0 0 0 0", tail)
ws.close()
deadline = time.time() + 3.0
while time.time() < deadline and self.ctl.osk != 1:
time.sleep(0.05)
self.assertEqual(self.ctl.osk, 1)
# Manual override: explicit `ctl: "osk on"` stays on across later keystrokes & disconnect
ws2, status_line2, _, extra2 = ws_connect("127.0.0.1", self.web_port)
self.assertIn("101", status_line2)
buf2 = bytearray(extra2)
_ = read_next_status(ws2, buf2)
ws_send_text(ws2, json.dumps({"t": "key", "k": 0x0061, "d": 1}))
ws_send_text(ws2, json.dumps({"t": "key", "k": 0x0061, "d": 0}))
self.assertEqual(read_next_status(ws2, buf2)["osk"], 0)
self.assertEqual(self.ctl.osk, 0)
ws_send_text(ws2, json.dumps({"t": "ctl", "cmd": "osk on"}))
self.assertEqual(read_next_status(ws2, buf2)["osk"], 1)
self.assertEqual(self.ctl.osk, 1)
ws_send_text(ws2, json.dumps({"t": "key", "k": 0x0062, "d": 1}))
ws_send_text(ws2, json.dumps({"t": "key", "k": 0x0062, "d": 0}))
time.sleep(0.15)
self.assertEqual(self.ctl.osk, 1)
ws2.close()
time.sleep(0.15)
self.assertEqual(self.ctl.osk, 1)
if __name__ == "__main__":
unittest.main()