| 1 | |
| 2 | """Attach an authenticated phone view to the desktop application's display.""" |
| 3 | import fcntl |
| 4 | import json |
| 5 | import math |
| 6 | import os |
| 7 | from pathlib import Path |
| 8 | import pwd |
| 9 | import re |
| 10 | import socket |
| 11 | import subprocess |
| 12 | import sys |
| 13 | |
| 14 | STATE = Path('/run/cage-phone-desktop-owner') |
| 15 | RUNTIME = Path('/run/cage-phone-desktop') |
| 16 | TOOLS = '/usr/local/lib/cage-phone-desktop' |
| 17 | UNIT = 'cage-phone-desktop.service' |
| 18 | |
| 19 | |
| 20 | class Failure(Exception): |
| 21 | def __init__(self, status): |
| 22 | self.status = status |
| 23 | |
| 24 | |
| 25 | def command(*args, timeout=10): |
| 26 | return subprocess.run(args, check=True, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, |
| 27 | stderr=subprocess.DEVNULL, timeout=timeout).stdout |
| 28 | |
| 29 | |
| 30 | def unit_state(): |
| 31 | return command('systemctl', 'show', UNIT, '-p', 'ActiveState', '--value').strip() |
| 32 | |
| 33 | |
| 34 | def stop(): |
| 35 | if unit_state() not in (b'inactive', b'failed'): |
| 36 | command('systemctl', 'stop', UNIT, timeout=20) |
| 37 | |
| 38 | if unit_state() == b'failed': |
| 39 | command('systemctl', 'reset-failed', UNIT) |
| 40 | |
| 41 | |
| 42 | def launch(request, record): |
| 43 | if not Path('/usr/bin/claude-desktop').is_file(): |
| 44 | raise Failure(501) |
| 45 | ident = request['id'] |
| 46 | w, h = request['width'], request['height'] |
| 47 | pixel_ratio = request.get('pixel_ratio', 0) |
| 48 | if type(pixel_ratio) not in (int, float) or not math.isfinite(pixel_ratio) or (pixel_ratio != 0 and not 1 <= pixel_ratio <= 8): |
| 49 | raise Failure(400) |
| 50 | if type(w) is not int or type(h) is not int or not (240 <= w <= 1440 and 160 <= h <= 1600): |
| 51 | raise Failure(400) |
| 52 | desktop = command('systemctl', 'show', 'cage-claude-desktop.service', '-p', 'ActiveState', '--value').strip() |
| 53 | if desktop != b'active' or not Path('/run/cage-desktop/keyring-ready').exists(): |
| 54 | raise Failure(412) |
| 55 | owner = {'id': ident, 'mode': 'shared'} |
| 56 | state = unit_state() |
| 57 | if record.exists() and json.loads(record.read_bytes()) == owner and state in (b'active', b'activating'): |
| 58 | return |
| 59 | stop() |
| 60 | user = pwd.getpwnam('cage') |
| 61 | args = ['systemd-run', '--quiet', '--collect', '--unit=' + UNIT, '--service-type=exec', |
| 62 | '--working-directory=' + user.pw_dir, '--uid=' + user.pw_name, '--gid=' + str(user.pw_gid)] |
| 63 | |
| 64 | for prop in ['RuntimeDirectory=cage-phone-desktop', |
| 65 | 'RuntimeDirectoryMode=0700', 'UMask=0077', 'KillMode=control-group', 'TimeoutStopSec=8', |
| 66 | 'ProtectSystem=strict', 'ProtectHome=read-only', |
| 67 | 'ReadWritePaths=/run/cage-desktop', |
| 68 | 'ExecStopPost=' + TOOLS + '/session.sh --restore', |
| 69 | 'BindsTo=cage-claude-desktop.service', 'After=cage-claude-desktop.service', |
| 70 | 'StandardOutput=null', 'StandardError=null']: |
| 71 | args.append('--property=' + prop) |
| 72 | for name, value in [('HOME', user.pw_dir), ('CAGE_PHONE_ID', ident), ('CAGE_PHONE_WIDTH', w), ('CAGE_PHONE_HEIGHT', h), |
| 73 | ('CAGE_PHONE_PIXEL_RATIO', pixel_ratio)]: |
| 74 | args.append('--setenv=' + name + '=' + str(value)) |
| 75 | command(*args, TOOLS + '/session.sh') |
| 76 | temporary = record.with_suffix('.new') |
| 77 | temporary.write_text(json.dumps(owner)) |
| 78 | os.replace(temporary, record) |
| 79 | |
| 80 | |
| 81 | def main(): |
| 82 | os.umask(0o077) |
| 83 | if os.geteuid() or len(sys.argv) != 1: |
| 84 | raise Failure(403) |
| 85 | raw = sys.stdin.buffer.readline(65537) |
| 86 | if len(raw) > 65536: |
| 87 | raise Failure(400) |
| 88 | req = json.loads(raw) |
| 89 | if not re.fullmatch('[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}', req.get('id', '')): |
| 90 | raise Failure(400) |
| 91 | if req.get('op') not in ('open', 'frame', 'action', 'close'): |
| 92 | raise Failure(400) |
| 93 | STATE.mkdir(mode=0o700, exist_ok=True) |
| 94 | record = STATE / 'owner' |
| 95 | with open(STATE / 'lock', 'a+b') as lock: |
| 96 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 97 | if req['op'] == 'open': |
| 98 | launch(req, record) |
| 99 | return {'id': req['id']} |
| 100 | owner = json.loads(record.read_bytes()) if record.exists() else {} |
| 101 | if owner.get('id') != req['id'] or owner.get('mode') != 'shared': |
| 102 | raise Failure(410) |
| 103 | if req['op'] == 'close': |
| 104 | stop() |
| 105 | record.unlink(missing_ok=True) |
| 106 | return {'id': req['id']} |
| 107 | if unit_state() not in (b'active', b'activating'): |
| 108 | raise Failure(503) |
| 109 | user = pwd.getpwnam('cage') |
| 110 | os.setgroups([]) |
| 111 | os.setgid(user.pw_gid) |
| 112 | os.setuid(user.pw_uid) |
| 113 | with socket.socket(socket.AF_UNIX) as channel: |
| 114 | channel.settimeout(8) |
| 115 | try: |
| 116 | channel.connect(str(RUNTIME / 'view.sock')) |
| 117 | except (FileNotFoundError, ConnectionRefusedError): |
| 118 | raise Failure(409) |
| 119 | channel.sendall(raw) |
| 120 | reply = channel.makefile('rb').readline(3600001) |
| 121 | if not reply or len(reply) > 3600000: |
| 122 | raise Failure(503) |
| 123 | return json.loads(reply) |
| 124 | |
| 125 | |
| 126 | if __name__ == '__main__': |
| 127 | try: |
| 128 | print(json.dumps(main(), separators=(',', ':'))) |
| 129 | except Failure as error: |
| 130 | print(json.dumps({'status': error.status})) |
| 131 | except Exception: |
| 132 | print('{"status":503}') |