Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
1395 lines (1175 loc) · 47.2 KB
/
Copy pathserver.py
File metadata and controls
1395 lines (1175 loc) · 47.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import subprocess
import platform
import logging
from logging.handlers import RotatingFileHandler
import threading
import time
import base64
import io
import os
import socket
import warnings
import re
import hmac
import hashlib
import csv
import sys
warnings.filterwarnings(
'ignore',
message='.*Eventlet is deprecated.*',
)
warnings.filterwarnings(
'ignore',
category=Warning,
module=r'engineio\.async_drivers\.eventlet',
)
from flask import Flask, jsonify, redirect, render_template, request, send_from_directory, url_for
from flask_socketio import SocketIO, emit
try:
import pyautogui
except Exception:
pyautogui = None
else:
pyautogui.FAILSAFE = False
pyautogui.PAUSE = 0
if hasattr(pyautogui, 'MINIMUM_DURATION'):
pyautogui.MINIMUM_DURATION = 0
if hasattr(pyautogui, 'MINIMUM_SLEEP'):
pyautogui.MINIMUM_SLEEP = 0
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_DIR = os.path.join(BASE_DIR, 'logs')
LOG_FILE = os.path.join(LOG_DIR, 'remote.log')
DEVICE_LOG_FILE = os.path.join(LOG_DIR, 'device.csv')
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
CERT_DIR = os.path.join(BASE_DIR, 'certs')
CA_CERT_FILE = os.path.join(CERT_DIR, 'ca.pem')
CA_KEY_FILE = os.path.join(CERT_DIR, 'ca-key.pem')
CERT_FILE = os.path.join(CERT_DIR, 'cert.pem')
KEY_FILE = os.path.join(CERT_DIR, 'key.pem')
os.makedirs(LOG_DIR, exist_ok=True)
device_log_lock = threading.Lock()
REMOTE_LOGGER = logging.getLogger('remote_mac_controller')
if not REMOTE_LOGGER.handlers:
REMOTE_LOGGER.setLevel(logging.INFO)
REMOTE_LOGGER.propagate = False
file_handler = RotatingFileHandler(
LOG_FILE,
maxBytes=1_000_000,
backupCount=3,
encoding='utf-8',
delay=True,
)
file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
REMOTE_LOGGER.addHandler(file_handler)
console_handler = logging.StreamHandler(sys.stderr)
console_handler.setLevel(logging.ERROR)
console_handler.setFormatter(logging.Formatter('%(levelname)s %(message)s'))
REMOTE_LOGGER.addHandler(console_handler)
werkzeug_log = logging.getLogger('werkzeug')
werkzeug_log.setLevel(logging.WARNING)
app = Flask(__name__)
app.config['SECRET_KEY'] = 'remote-mac-phase4'
socketio = SocketIO(app, cors_allowed_origins="*", logger=False, engineio_logger=False,
max_http_buffer_size=5 * 1024 * 1024)
IS_MAC = platform.system() == 'Darwin'
SERVER_PORT = 5001
HTTP_REDIRECT_PORT = 5002
REMOTE_PIN = os.environ.get('REMOTE_PIN', '1234')
PIN_AUTH_TTL_SECONDS = 24 * 60 * 60
# ── Screen streaming state ────────────────────────────────────────────────────
streaming_clients = set()
terminal_announced_devices = set()
stream_thread = None
stream_lock = threading.Lock()
STREAM_FPS = 10 # frames per second
STREAM_QUALITY = 35 # JPEG quality (lower = faster, smaller)
STREAM_SCALE = 0.35 # scale factor for screenshot (0.35 = ~35% of native res)
MOBILE_UA_HINTS = (
'iphone', 'ipad', 'ipod', 'android', 'mobile',
'blackberry', 'opera mini', 'windows phone'
)
VIEW_ALIASES = {
'': 'auto',
'auto': 'auto',
'index': 'controller',
'controller': 'controller',
'mobile': 'controller',
'remote': 'controller',
'desktop': 'desktop',
'notice': 'desktop',
'apps': 'apps',
'app': 'apps',
'remote-preview': 'remote-preview',
'preview': 'remote-preview',
'trackpad': 'trackpad',
'remote-trackpad': 'trackpad',
'remote-preview-trackpad': 'trackpad',
}
def sanitize_device_name(value: str, fallback: str = 'Unknown device') -> str:
"""Keep device labels log-friendly while preserving useful names."""
cleaned = re.sub(r'\s+', ' ', str(value or '').strip())
cleaned = ''.join(ch for ch in cleaned if ch.isprintable())
return cleaned[:80] or fallback
def request_device_name(payload=None) -> str:
"""Resolve the friendly device name sent by the browser."""
source = payload or {}
if not source:
source = request.args
return sanitize_device_name(source.get('deviceName') or source.get('device') or '')
def write_device_csv(device_name: str, ip_address: str):
"""Record a unique device/IP pair in logs/device.csv."""
row = [sanitize_device_name(device_name), str(ip_address or '')]
with device_log_lock:
existing = set()
if os.path.exists(DEVICE_LOG_FILE):
try:
with open(DEVICE_LOG_FILE, newline='', encoding='utf-8') as csv_file:
reader = csv.reader(csv_file)
next(reader, None)
existing = {tuple(item[:2]) for item in reader if len(item) >= 2}
except Exception:
REMOTE_LOGGER.exception("Could not read device CSV")
if tuple(row) in existing:
return
needs_header = not os.path.exists(DEVICE_LOG_FILE) or os.path.getsize(DEVICE_LOG_FILE) == 0
with open(DEVICE_LOG_FILE, 'a', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file)
if needs_header:
writer.writerow(['device_name', 'ip_address'])
writer.writerow(row)
def signed_auth_token(device_name: str, expires_at: int) -> str:
message = f'{device_name}|{expires_at}'.encode('utf-8')
secret = app.config['SECRET_KEY'].encode('utf-8')
return hmac.new(secret, message, hashlib.sha256).hexdigest()
def request_has_valid_pin_auth() -> bool:
device_name = request_device_name()
try:
expires_at = int(request.args.get('authExpiresAt', '0'))
except (TypeError, ValueError):
return False
auth_token = str(request.args.get('authToken', ''))
if expires_at <= int(time.time() * 1000):
return False
expected = signed_auth_token(device_name, expires_at)
return hmac.compare_digest(auth_token, expected)
def announce_device_connected(device_name: str, ip_address: str):
key = (device_name, ip_address)
if key in terminal_announced_devices:
return
terminal_announced_devices.add(key)
print(f' New device connected: {device_name} ({ip_address})', flush=True)
# ── AppleScript helpers ───────────────────────────────────────────────────────
def run_applescript(script: str):
try:
result = subprocess.run(
['osascript', '-e', script],
capture_output=True, text=True, timeout=5
)
return result.returncode == 0, result.stdout.strip()
except Exception as e:
REMOTE_LOGGER.exception("AppleScript execution failed")
return False, ''
def press_key(key_code: int, modifiers: list = None):
"""Press a key with optional modifier keys."""
if not modifiers:
script = f'tell application "System Events" to key code {key_code}'
else:
mod_str = ', '.join(f'{m} down' for m in modifiers)
script = f'tell application "System Events" to key code {key_code} using {{{mod_str}}}'
ok, _ = run_applescript(script)
return ok
def press_key_string(key: str, modifiers: list = None):
"""Press a key by character string."""
safe = key.replace('"', '\\"').replace('\\', '\\\\')
if not modifiers:
script = f'tell application "System Events" to keystroke "{safe}"'
else:
mod_str = ', '.join(f'{m} down' for m in modifiers)
script = f'tell application "System Events" to keystroke "{safe}" using {{{mod_str}}}'
ok, _ = run_applescript(script)
return ok
def get_screen_size():
"""Return (width, height) of the primary display."""
if pyautogui is not None:
try:
size = pyautogui.size()
if size.width > 0 and size.height > 0:
return int(size.width), int(size.height)
except Exception:
pass
try:
ok, out = run_applescript(
'tell application "Finder" to get bounds of window of desktop'
)
if ok and out:
parts = [int(x.strip()) for x in out.split(',')]
return parts[2], parts[3] # right, bottom = width, height
except Exception:
pass
return 1920, 1080 # fallback
def get_mouse_position():
"""Return the current mouse cursor position."""
if pyautogui is not None:
try:
point = pyautogui.position()
return int(point.x), int(point.y)
except Exception:
pass
try:
ok, out = run_applescript(
'tell application "System Events" to get the position of the mouse cursor'
)
if ok and out:
parts = [int(float(value.strip())) for value in out.split(',')]
if len(parts) >= 2:
return parts[0], parts[1]
except Exception:
pass
sw, sh = get_screen_size()
return sw // 2, sh // 2
# ── Phase 0 — Key action map ──────────────────────────────────────────────────
KEY_ACTIONS = {
'arrow_left': lambda: press_key(123),
'arrow_right': lambda: press_key(124),
'arrow_up': lambda: press_key(126),
'arrow_down': lambda: press_key(125),
'volume_up': lambda: run_applescript('set volume output volume (output volume of (get volume settings) + 10)')[0],
'volume_down': lambda: run_applescript('set volume output volume (output volume of (get volume settings) - 10)')[0],
'mute': lambda: run_applescript('set volume with output muted')[0],
'unmute': lambda: run_applescript('set volume without output muted')[0],
'play_pause': lambda: press_key(179),
'next_track': lambda: press_key(171),
'prev_track': lambda: press_key(172),
'space': lambda: press_key(49),
'escape': lambda: press_key(53),
'return': lambda: press_key(36),
'tab': lambda: press_key(48),
'delete': lambda: press_key(51),
'brightness_up': lambda: press_key(144),
'brightness_down': lambda: press_key(145),
'sleep': lambda: run_applescript('tell application "System Events" to sleep')[0],
}
# ── Phase 1 — Modifier map ────────────────────────────────────────────────────
MODIFIER_MAP = {
'cmd': 'command key',
'command': 'command key',
'shift': 'shift key',
'option': 'option key',
'alt': 'option key',
'ctrl': 'control key',
'control': 'control key',
}
# Common shortcut presets (action_name -> [key_code, [modifiers]])
SHORTCUT_PRESETS = {
'cmd_c': (8, ['command key']), # Copy
'cmd_v': (9, ['command key']), # Paste
'cmd_x': (7, ['command key']), # Cut
'cmd_z': (6, ['command key']), # Undo
'cmd_a': (0, ['command key']), # Select All
'cmd_s': (1, ['command key']), # Save
'cmd_w': (13, ['command key']), # Close window
'cmd_q': (12, ['command key']), # Quit
'cmd_t': (17, ['command key']), # New tab
'cmd_tab': (48, ['command key']), # App switch
'cmd_space':(49, ['command key']), # Spotlight
'cmd_shift_3': (20, ['command key', 'shift key']), # Screenshot
'cmd_shift_4': (21, ['command key', 'shift key']), # Screenshot area
'mission_control': (160, []), # Mission Control (F9 key code)
'show_desktop': (103, ['command key']), # cmd+F3
}
APP_LAUNCHERS = {
'hotstar': {
'label': 'JioHotstar',
'subtitle': 'Start JioHotstar on your Mac',
'emoji': 'HS',
'image': 'jiohotstar.png',
'candidates': ['JioHotstar', 'Hotstar', 'Disney+ Hotstar'],
},
'youtube': {
'label': 'YouTube',
'subtitle': 'Open the YouTube app on your Mac',
'emoji': 'YT',
'image': 'youtube.png',
'candidates': ['YouTube'],
},
'primevideo': {
'label': 'Prime Video',
'subtitle': 'Launch Prime Video on your Mac',
'emoji': 'PV',
'image': 'primevideos.png',
'candidates': ['Prime Video', 'PrimeVideo'],
},
}
# ── Phase 2 — Screen streaming ────────────────────────────────────────────────
def capture_screen_jpeg() -> bytes | None:
"""Capture screen as JPEG bytes using Quartz (fast, no temp file)."""
try:
import Quartz
from PIL import Image
# Capture the main display
display = Quartz.CGMainDisplayID()
image_ref = Quartz.CGDisplayCreateImage(display)
if image_ref is None:
return None
width = Quartz.CGImageGetWidth(image_ref)
height = Quartz.CGImageGetHeight(image_ref)
# Convert to PIL Image via raw pixel data
color_space = Quartz.CGColorSpaceCreateDeviceRGB()
ctx_data = bytearray(height * width * 4)
ctx = Quartz.CGBitmapContextCreate(
ctx_data, width, height, 8, width * 4,
color_space,
Quartz.kCGImageAlphaPremultipliedLast | Quartz.kCGBitmapByteOrder32Big
)
Quartz.CGContextDrawImage(ctx, Quartz.CGRectMake(0, 0, width, height), image_ref)
img = Image.frombytes('RGBA', (width, height), bytes(ctx_data))
img = img.convert('RGB')
# Scale down
new_w = int(width * STREAM_SCALE)
new_h = int(height * STREAM_SCALE)
img = img.resize((new_w, new_h), Image.BILINEAR)
buf = io.BytesIO()
img.save(buf, format='JPEG', quality=STREAM_QUALITY, optimize=False)
return buf.getvalue()
except Exception as e:
# Fallback: use screencapture CLI
return capture_screen_fallback()
def capture_screen_fallback() -> bytes | None:
"""Fallback capture using screencapture command."""
try:
from PIL import Image
import tempfile, os
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as f:
tmp = f.name
subprocess.run(
['screencapture', '-x', '-t', 'jpg', tmp],
timeout=2, capture_output=True
)
img = Image.open(tmp)
new_w = int(img.width * STREAM_SCALE)
new_h = int(img.height * STREAM_SCALE)
img = img.resize((new_w, new_h), Image.BILINEAR)
buf = io.BytesIO()
img.save(buf, format='JPEG', quality=STREAM_QUALITY)
os.unlink(tmp)
return buf.getvalue()
except Exception as e:
REMOTE_LOGGER.exception("Screen capture fallback failed")
return None
def stream_loop():
"""Background thread: capture & broadcast frames to streaming clients."""
interval = 1.0 / STREAM_FPS
while True:
with stream_lock:
clients = set(streaming_clients)
if not clients:
time.sleep(0.2)
continue
frame = capture_screen_jpeg()
if frame:
b64 = base64.b64encode(frame).decode('ascii')
socketio.emit('screen_frame', {'data': b64})
time.sleep(interval)
def ensure_stream_thread():
global stream_thread
if stream_thread is None or not stream_thread.is_alive():
stream_thread = threading.Thread(target=stream_loop, daemon=True)
stream_thread.start()
# ── Phase 3/4 — Mouse helpers ─────────────────────────────────────────────────
def clamp_norm(value, default: float = 0.5) -> float:
"""Clamp a normalised coordinate to the 0..1 range."""
try:
number = float(value)
except (TypeError, ValueError):
number = default
return max(0.0, min(1.0, number))
def resolve_mouse_coords(data, *, allow_current: bool = False):
"""Resolve socket payload coordinates to absolute screen pixels."""
payload = data or {}
if payload.get('use_current_position'):
return get_mouse_position()
if 'norm_x' in payload or 'norm_y' in payload:
return scale_coords(
clamp_norm(payload.get('norm_x', 0.5)),
clamp_norm(payload.get('norm_y', 0.5)),
)
if allow_current:
return get_mouse_position()
return scale_coords(0.5, 0.5)
def mouse_move(x: int, y: int) -> bool:
"""Move mouse cursor to absolute screen position."""
if pyautogui is not None:
try:
pyautogui.moveTo(int(x), int(y), duration=0)
return True
except Exception:
pass
ok, _ = run_applescript(
f'tell application "System Events" to set the position of the mouse cursor to {{{x}, {y}}}'
)
return ok
def mouse_click(x: int, y: int, button: str = 'left') -> bool:
"""Click at screen coordinates using native mouse APIs when available."""
target_button = 'right' if button == 'right' else 'left'
if pyautogui is not None:
try:
pyautogui.click(x=int(x), y=int(y), button=target_button)
return True
except Exception:
pass
try:
if target_button == 'right':
result = subprocess.run(
['cliclick', f'rc:{x},{y}'],
capture_output=True, timeout=3
)
else:
result = subprocess.run(
['cliclick', f'c:{x},{y}'],
capture_output=True, timeout=3
)
return result.returncode == 0
except FileNotFoundError:
pass
return False
def mouse_double_click(x: int, y: int) -> bool:
if pyautogui is not None:
try:
pyautogui.doubleClick(x=int(x), y=int(y), button='left')
return True
except Exception:
pass
try:
result = subprocess.run(
['cliclick', f'dc:{x},{y}'],
capture_output=True, timeout=3
)
return result.returncode == 0
except FileNotFoundError:
return False
def mouse_drag(x1: int, y1: int, x2: int, y2: int) -> bool:
"""Click-drag from (x1,y1) to (x2,y2)."""
if pyautogui is not None:
try:
pyautogui.moveTo(int(x1), int(y1), duration=0)
pyautogui.dragTo(int(x2), int(y2), duration=0, button='left')
return True
except Exception:
pass
try:
result = subprocess.run(
['cliclick', f'm:{x1},{y1}', f'dd:{x1},{y1}', f'du:{x2},{y2}'],
capture_output=True, timeout=5
)
return result.returncode == 0
except FileNotFoundError:
pass
return False
def mouse_scroll(x: int, y: int, dx: int, dy: int) -> bool:
"""Scroll at position (x,y) by (dx, dy) lines."""
if pyautogui is not None:
try:
pyautogui.moveTo(int(x), int(y), duration=0)
if dx and hasattr(pyautogui, 'hscroll'):
pyautogui.hscroll(int(dx))
if dy:
pyautogui.scroll(int(dy))
return True
except Exception:
pass
try:
result = subprocess.run(
['python3', '-c',
f'''
import Quartz
ev = Quartz.CGEventCreateScrollWheelEvent(None, Quartz.kCGScrollEventUnitLine, 2, {dy}, {dx})
Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)
'''],
capture_output=True, timeout=3
)
return result.returncode == 0
except Exception:
pass
# AppleScript scroll fallback
direction = 'up' if dy > 0 else 'down'
steps = abs(dy)
key_code = 126 if direction == 'up' else 125
ok, _ = run_applescript(
f'tell application "System Events" to repeat {steps} times\n'
f' key code {key_code}\n'
f'end repeat'
)
return ok
def scale_coords(norm_x: float, norm_y: float):
"""Convert normalised 0-1 coordinates to screen pixels."""
sw, sh = get_screen_size()
return int(norm_x * sw), int(norm_y * sh)
def is_mobile_client(user_agent: str) -> bool:
"""Detect whether a request likely came from a phone or tablet."""
ua = (user_agent or '').lower()
return any(hint in ua for hint in MOBILE_UA_HINTS)
def requested_root_view() -> str:
"""Normalise the requested root view."""
raw = str(request.args.get('view', '')).strip().lower()
return VIEW_ALIASES.get(raw, 'auto')
def get_local_ip_address() -> str:
"""Return the best LAN IP we can determine for this machine."""
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect(('10.255.255.255', 1))
candidate = sock.getsockname()[0]
if candidate:
return candidate
except OSError:
pass
try:
hostname = socket.gethostname()
candidate = socket.gethostbyname(hostname)
if candidate:
return candidate
except OSError:
pass
return '127.0.0.1'
def is_ip_address(value: str) -> bool:
try:
socket.inet_pton(socket.AF_INET, value)
return True
except OSError:
return False
def normalize_local_hostname(value: str) -> str | None:
"""Convert a macOS local hostname into the Bonjour .local form."""
raw = str(value or '').strip().rstrip('.')
if not raw or is_ip_address(raw):
return None
if raw.lower().endswith('.local'):
host = raw
else:
host = f'{raw}.local'
host = re.sub(r'\s+', '-', host)
host = re.sub(r'[^A-Za-z0-9.-]', '', host)
return host or None
def get_local_hostname() -> str | None:
"""Return the stable Bonjour hostname for this Mac, if one is available."""
configured = os.environ.get('REMOTE_LOCAL_HOSTNAME', '')
hostname = normalize_local_hostname(configured)
if hostname:
return hostname
candidates = []
if IS_MAC:
try:
result = subprocess.run(
['scutil', '--get', 'LocalHostName'],
capture_output=True,
text=True,
timeout=2,
)
if result.returncode == 0:
candidates.append(result.stdout)
except Exception:
REMOTE_LOGGER.exception("Could not read macOS LocalHostName")
candidates.append(socket.gethostname())
for candidate in candidates:
hostname = normalize_local_hostname(candidate)
if hostname:
return hostname
return None
def build_certificate_sans(local_ip: str, local_hostname: str | None):
dns_names = ['localhost']
if local_hostname:
dns_names.extend([local_hostname, local_hostname.lower()])
ip_addresses = ['127.0.0.1']
if local_ip and local_ip not in ip_addresses:
ip_addresses.append(local_ip)
dns_names = list(dict.fromkeys(dns_names))
ip_addresses = list(dict.fromkeys(ip_addresses))
return dns_names, ip_addresses
def certificate_text() -> str:
try:
result = subprocess.run(
['openssl', 'x509', '-in', CERT_FILE, '-noout', '-text'],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0:
return result.stdout
except Exception:
REMOTE_LOGGER.exception("Could not inspect TLS certificate")
return ''
def certificate_has_sans(dns_names: list[str], ip_addresses: list[str]) -> bool:
text = certificate_text()
if not text:
return False
for dns_name in dns_names:
pattern = rf'DNS:{re.escape(dns_name)}(?=,|\s|$)'
if not re.search(pattern, text, re.IGNORECASE):
return False
for ip_address in ip_addresses:
pattern = rf'IP Address:{re.escape(ip_address)}(?=,|\s|$)'
if not re.search(pattern, text):
return False
return True
def certificate_is_signed_by_ca() -> bool:
if not (os.path.exists(CA_CERT_FILE) and os.path.exists(CERT_FILE)):
return False
try:
result = subprocess.run(
['openssl', 'verify', '-CAfile', CA_CERT_FILE, CERT_FILE],
capture_output=True,
text=True,
timeout=5,
)
return result.returncode == 0
except Exception:
REMOTE_LOGGER.exception("Could not verify TLS certificate")
return False
def certificate_is_fresh() -> bool:
if not os.path.exists(CERT_FILE):
return False
try:
result = subprocess.run(
[
'openssl', 'x509',
'-checkend', str(30 * 24 * 60 * 60),
'-noout',
'-in', CERT_FILE,
],
capture_output=True,
text=True,
timeout=5,
)
return result.returncode == 0
except Exception:
REMOTE_LOGGER.exception("Could not check TLS certificate expiry")
return False
def ensure_certificate_authority():
"""Create the local root CA if this checkout does not have one yet."""
os.makedirs(CERT_DIR, exist_ok=True)
if os.path.exists(CA_CERT_FILE) and os.path.exists(CA_KEY_FILE):
try:
os.chmod(CA_KEY_FILE, 0o600)
except OSError:
pass
return
print(" Generating local root CA for HTTPS ...")
subprocess.run([
'openssl', 'req', '-x509', '-newkey', 'rsa:4096',
'-keyout', CA_KEY_FILE, '-out', CA_CERT_FILE,
'-days', '1825', '-nodes',
'-subj', '/CN=Remote Mac Controller/O=Pratik Kabade',
], check=True, capture_output=True, text=True)
os.chmod(CA_KEY_FILE, 0o600)
def generate_server_certificate(dns_names: list[str], ip_addresses: list[str]):
"""Generate a server cert signed by the trusted local CA."""
os.makedirs(CERT_DIR, exist_ok=True)
csr_file = os.path.join(CERT_DIR, 'server.csr')
ext_file = os.path.join(CERT_DIR, 'server.ext')
serial_file = os.path.join(CERT_DIR, 'ca.srl')
san_entries = [f'DNS:{name}' for name in dns_names]
san_entries.extend(f'IP:{ip_address}' for ip_address in ip_addresses)
with open(ext_file, 'w', encoding='utf-8') as file:
file.write('basicConstraints=CA:FALSE\n')
file.write('keyUsage=digitalSignature,keyEncipherment\n')
file.write('extendedKeyUsage=serverAuth\n')
file.write(f'subjectAltName={",".join(san_entries)}\n')
try:
subprocess.run([
'openssl', 'req', '-newkey', 'rsa:2048',
'-keyout', KEY_FILE, '-out', csr_file, '-nodes',
'-subj', '/CN=Remote Mac Controller',
], check=True, capture_output=True, text=True)
subprocess.run([
'openssl', 'x509', '-req',
'-in', csr_file,
'-CA', CA_CERT_FILE,
'-CAkey', CA_KEY_FILE,
'-CAcreateserial',
'-out', CERT_FILE,
'-days', '825',
'-extfile', ext_file,
], check=True, capture_output=True, text=True)
os.chmod(KEY_FILE, 0o600)
finally:
for path in (csr_file, ext_file, serial_file):
try:
os.remove(path)
except FileNotFoundError:
pass
def ensure_tls_certificate(local_ip: str, local_hostname: str | None):
ensure_certificate_authority()
dns_names, ip_addresses = build_certificate_sans(local_ip, local_hostname)
needs_refresh = (
not os.path.exists(CERT_FILE)
or not os.path.exists(KEY_FILE)
or not certificate_is_signed_by_ca()
or not certificate_is_fresh()
or not certificate_has_sans(dns_names, ip_addresses)
)
if not needs_refresh:
return
names = ', '.join([*dns_names, *ip_addresses])
print(f" Generating HTTPS certificate for {names} ...")
generate_server_certificate(dns_names, ip_addresses)
def preferred_control_host(local_hostname: str | None, local_ip: str) -> str:
return local_hostname or local_ip
def copy_text_to_clipboard(text: str) -> bool:
"""Copy text to the OS clipboard when supported."""
platform_name = platform.system()
clipboard_commands = {
'Darwin': [['pbcopy']],
'Linux': [['wl-copy'], ['xclip', '-selection', 'clipboard'], ['xsel', '--clipboard', '--input']],
'Windows': [['clip']],
}
for command in clipboard_commands.get(platform_name, []):
try:
subprocess.run(
command,
input=text,
text=True,
capture_output=True,
timeout=2,
check=True,
)
return True
except FileNotFoundError:
continue
except Exception:
REMOTE_LOGGER.exception("Clipboard copy failed via %s", command[0])
return False
return False
def print_startup_banner(control_url: str, fallback_url: str, copied_to_clipboard: bool):
"""Print a concise startup summary to the terminal."""
print("=" * 58)
print(" Remote Mac Controller")
print("=" * 58)
print(f" URL: {control_url}")
if fallback_url != control_url:
print(f" Fallback URL: {fallback_url}")
print(f" Clipboard: {'copied' if copied_to_clipboard else 'unavailable'}")
print(" Press Ctrl+C to stop")
print("=" * 58)
def render_root_view(view_name: str):
"""Render the requested view for the root URL."""
if view_name == 'controller':
return render_template('index.html')
if view_name == 'desktop':
return redirect(url_for('desktop_notice'))
if view_name == 'apps':
return redirect(url_for('app_launcher'))
if view_name == 'remote-preview':
return redirect(url_for('remote_preview'))
if view_name == 'trackpad':
return redirect(url_for('remote_trackpad'))
return render_template('index.html')
def launch_app(app_key: str):
"""Open a configured macOS app by a friendly key."""
app_config = APP_LAUNCHERS.get(app_key)
if not app_config:
return False, 'Unknown app requested.'
label = app_config['label']
if not IS_MAC:
REMOTE_LOGGER.info("SIM launch_app %s", app_key)
return True, f'{label} launch simulated.'
for candidate in app_config['candidates']:
try:
result = subprocess.run(
['open', '-a', candidate],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
REMOTE_LOGGER.info("APP launch success %s via %s", label, candidate)
return True, f'{label} opened on your Mac.'
except Exception:
continue
for candidate in app_config['candidates']:
app_paths = [
os.path.expanduser(f'~/Applications/{candidate}.app'),
f'/Applications/{candidate}.app',
]
for app_path in app_paths:
if not os.path.exists(app_path):
continue
try:
result = subprocess.run(
['open', app_path],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
REMOTE_LOGGER.info("APP launch success %s via %s", label, app_path)
return True, f'{label} opened on your Mac.'
except Exception:
continue
for candidate in app_config['candidates']:
try:
search = subprocess.run(
['mdfind', f'kMDItemFSName == "{candidate}.app"c'],
capture_output=True, text=True, timeout=5
)
matches = [
line.strip() for line in search.stdout.splitlines()
if line.strip().endswith('.app')
]
for match in matches:
result = subprocess.run(
['open', match],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
REMOTE_LOGGER.info("APP launch success %s via %s", label, match)
return True, f'{label} opened on your Mac.'
except Exception:
continue
REMOTE_LOGGER.warning("APP launch failed %s not found", label)
return False, f'{label} was not found. Update APP_LAUNCHERS in server.py if your installed app uses a different name.'
# ── Routes ────────────────────────────────────────────────────────────────────
@app.route('/index.html')
@app.route('/')
def index():
return render_root_view(requested_root_view())
@app.route('/desktop')
def desktop_notice():
return render_template(
'desktop_notice.html',
control_url=request.url_root.rstrip('/')
)
@app.route('/apps')
def app_launcher():
return render_template('apps.html', apps=APP_LAUNCHERS)
@app.route('/media/<path:filename>')
def media_file(filename):
return send_from_directory(MEDIA_DIR, filename)