-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1320 lines (1086 loc) · 52.2 KB
/
app.py
File metadata and controls
1320 lines (1086 loc) · 52.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 os
import re
import subprocess
import sys
from enum import Enum
import objc
import rumps
from AppKit import (
NSWindowStyleMaskTitled,
NSWindowStyleMaskClosable,
NSBackingStoreBuffered,
NSFloatingWindowLevel
)
from Cocoa import (
NSPanel, NSTextField, NSMakeRect,
NSButton, NSApplication, NSDistributedNotificationCenter,
NSImageView, NSImage, NSFont, NSAttributedString, NSHTMLTextDocumentType,
NSFontAttributeName, NSMutableParagraphStyle, NSParagraphStyleAttributeName, NSTextAlignmentCenter,
NSForegroundColorAttributeName, NSColor, NSOnState, NSOffState,
NSSegmentedControl, NSSegmentSwitchTrackingSelectOne, NSRegularControlSize, NSImageScaleProportionallyDown,
NSSwitchButton, NSPopUpButton, NSComboBox, NSMenu, NSMenuItem
)
from Foundation import NSBundle, NSData, NSDictionary
from version import VERSION
class FieldType(Enum):
TEXT = "text"
COMBOBOX = "combobox"
class Appearance(Enum):
LIGHT = "LIGHT"
DARK = "DARK"
class ProcessState(Enum):
INITIAL = "INITIAL"
RUNNING = "RUNNING"
STOPPED_PARTIALLY = "STOPPED_PARTIALLY"
STOPPED = "STOPPED"
ERROR = "ERROR"
class LogoStyle(Enum):
GEAR = "GEAR"
COLORED_GLASSES = "COLORED_GLASSES"
COLORED_S = "COLORED_S"
DEFAULT_LOGO_STYLE = LogoStyle.COLORED_GLASSES
def get_appearance() -> Appearance:
app = NSApplication.sharedApplication()
appearance = app.effectiveAppearance().name()
return Appearance.DARK if Appearance.DARK.value.lower() in appearance.lower() else Appearance.LIGHT
def get_logo_style_image(style: LogoStyle, state: ProcessState = ProcessState.STOPPED_PARTIALLY,
appearance: Appearance = None) -> str:
appearance = appearance or get_appearance()
appearance = Appearance.LIGHT if appearance == Appearance.DARK else Appearance.DARK
return os.path.join("images", "icons", style.value.lower(), appearance.value.lower(), f"{state.value.lower()}.svg")
def alert_foreground(title, message, ok=None, cancel=None, other=None, icon_path=None) -> int:
NSApplication.sharedApplication().activateIgnoringOtherApps_(True)
return rumps.alert(title, message, ok, cancel, other, icon_path)
def bring_app_to_front(self: NSPanel):
NSApplication.sharedApplication().activateIgnoringOtherApps_(True)
self.center()
self.makeKeyAndOrderFront_(None)
def resource_path(rel_path):
# on macOS bundle, resources are in Contents/Resources
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
base = sys._MEIPASS
else:
# running normally: project root
base = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base, rel_path)
class FormValidator:
@staticmethod
# def validate_ip(ip: str) -> bool:
# parts = ip.split('.')
# if len(parts) != 4:
# return False
# for part in parts:
# if not part.isdigit() or not (0 <= int(part) <= 255):
# return False
# return True
@staticmethod
def validate_port(port) -> bool:
return port.isdigit() and 1 <= int(port) <= 65535
@staticmethod
def validate_port_with_alert(port, label: str):
if not FormValidator.validate_port(port):
alert_foreground("Error", f"{label} must be a valid port between 1 and 65535")
return False
return True
@staticmethod
def validate_empty_with_alert(value, label):
if not value:
alert_foreground("Error", f"{label} must not be empty")
return False
return True
class ConfigHelper:
yq_path = resource_path(os.path.join('bin', 'yq'))
workspace_path = os.path.expanduser("~/.susops")
config_path = os.path.join(workspace_path, "config.yaml")
@staticmethod
def get_connection_tags():
result = ConfigHelper.read_config(".connections[].tag", [])
return result.splitlines()
@staticmethod
def get_domains():
result = ConfigHelper.read_config(".connections[].pac_hosts[]", [])
split_result = result.splitlines()
return split_result
@staticmethod
def get_local_forwards():
result = ConfigHelper.read_config(".connections[].forwards.local[] | \"\\(.tag) (\\((.src_port // .src)) → \\((.dst_port // .dst)))\"", [])
# filter result items, remove all items equal to "( → )" (this is the case when no remote forwards are set)
result = [item for item in result.splitlines() if not item == "( → )"]
return result
@staticmethod
def get_remote_forwards():
result = ConfigHelper.read_config(".connections[].forwards.remote[] | \"\\(.tag) (\\((.src_port // .src)) → \\((.dst_port // .dst)))\"", [])
# filter result items, remove all items equal to "( → )" (this is the case when no remote forwards are set)
result = [item for item in result.splitlines() if not item == "( → )"]
return result
@staticmethod
def read_config(query: str, default):
try:
result = subprocess.check_output([ConfigHelper.yq_path, "e", query, ConfigHelper.config_path], encoding="utf-8").strip()
if result == "null":
result = default
except subprocess.CalledProcessError:
result = default
return result
@staticmethod
def update_config(query: str):
subprocess.run([ConfigHelper.yq_path, "e", "-i", query, ConfigHelper.config_path, ], check=True)
def add_bin_to_path():
os.environ['PATH'] = resource_path('bin') + os.pathsep + os.environ.get('PATH', '')
from pathlib import Path
from typing import List
def get_ssh_hosts(config_path: Path = None) -> List[str]:
if config_path is None:
config_path = Path(os.path.expanduser("~/.ssh/config"))
host_pattern = re.compile(r'^\s*Host\s+(.*)$', re.IGNORECASE)
hosts = []
try:
with config_path.open('r') as f:
for raw in f:
line = raw.strip()
# skip blanks and comments
if not line or line.startswith('#'):
continue
m = host_pattern.match(line)
if m:
# a Host line can list multiple names/patterns
for h in m.group(1).split():
hosts.append(h)
except FileNotFoundError:
raise FileNotFoundError(f"SSH config not found: {config_path!s}")
return hosts
def run_susops(command, show_alert=True):
susops_path = resource_path(os.path.join('bin', 'susops'))
result = subprocess.run(f"{susops_path} {command}", shell=True, capture_output=True, encoding="utf-8",
errors="ignore")
if result.returncode != 0 and show_alert:
alert_foreground("Error", result.stdout.strip())
return result.stdout.strip(), result.returncode
# Global instance of the app
susops_app = None # type: SusOpsApp|None
def add_edit_menu_item():
app = NSApplication.sharedApplication()
main_menu = app.mainMenu()
if main_menu is None:
main_menu = NSMenu.alloc().init()
app.setMainMenu_(main_menu)
# only initialize once
if main_menu.itemWithTitle_("Edit") is not None:
return
edit_menu = NSMenu.alloc().initWithTitle_("Edit")
edit_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Edit", None, "")
edit_item.setSubmenu_(edit_menu)
edit_menu.addItem_(NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Undo", "undo:", "z"))
edit_menu.addItem_(NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Redo", "redo:", "Z"))
edit_menu.addItem_(NSMenuItem.separatorItem())
edit_menu.addItem_(NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Cut", "cut:", "x"))
edit_menu.addItem_(NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Copy", "copy:", "c"))
edit_menu.addItem_(NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Paste", "paste:", "v"))
edit_menu.addItem_(NSMenuItem.separatorItem())
edit_menu.addItem_(NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Select All", "selectAll:", "a"))
main_menu.addItem_(edit_item)
def get_bind_addresses():
return ["localhost", "172.17.0.1", "0.0.0.0"]
class SusOpsApp(rumps.App):
def __init__(self, icon_dir=None):
global susops_app
susops_app = self
add_bin_to_path()
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.images_dir = icon_dir or os.path.join(self.base_dir, 'images')
self.process_state = ProcessState.INITIAL
super(SusOpsApp, self).__init__(name="SO", icon=None, quit_button=None)
# Observe theme changes
center = NSDistributedNotificationCenter.defaultCenter()
selector = objc.selector(
self.appearanceChanged_,
selector=b'appearanceChanged:',
signature=b'v@:@'
)
center.addObserver_selector_name_object_(
self,
selector,
'AppleInterfaceThemeChangedNotification',
None
)
# Set initial icon based on current appearance
self.config = self.load_config()
self.update_icon()
self._settings_panel = None
self._connection_panel = None
self._remove_connection_panel = None
self._add_host_panel = None
self._remove_host_panel = None
self._add_local_forward_panel = None
self._remove_local_forward_panel = None
self._add_remote_forward_panel = None
self._remove_remote_forward_panel = None
self._about_panel = None
self.menu = [
rumps.MenuItem("Status", callback=self.check_status),
None,
rumps.MenuItem("Settings…", callback=self.open_settings, key=","),
None,
(rumps.MenuItem("Add"), [
rumps.MenuItem("Add Connection", callback=self.add_connection),
rumps.MenuItem("Add Domain / IP / CIDR", callback=self.add_host),
rumps.MenuItem("Add Local Forward", callback=self.add_local_forward),
rumps.MenuItem("Add Remote Forward", callback=self.add_remote_forward),
]),
(rumps.MenuItem("Remove"), [
rumps.MenuItem("Remove Connection", callback=self.remove_connection),
rumps.MenuItem("Remove Domain / IP / CIDR", callback=self.remove_host),
rumps.MenuItem("Remove Local Forward", callback=self.remove_local_forward),
rumps.MenuItem("Remove Remote Forward", callback=self.remove_remote_forward),
]),
rumps.MenuItem("List All", callback=self.list_config),
rumps.MenuItem("Open Config File", callback=self.open_config_file),
None,
rumps.MenuItem("Start Proxy", callback=self.start_proxy),
rumps.MenuItem("Stop Proxy", callback=self.stop_proxy),
rumps.MenuItem("Restart Proxy", callback=self.restart_proxy, key="r"),
None,
("Test", [
rumps.MenuItem("Test Any", callback=self.test_any),
rumps.MenuItem("Test All", callback=self.test_all),
]),
("Launch Browser", [
("Chrome", [
rumps.MenuItem("Launch Chrome", callback=self.launch_chrome),
rumps.MenuItem("Open Chrome Proxy Settings", callback=self.launch_chrome_proxy_settings),
]),
("Firefox", [
rumps.MenuItem("Launch Firefox", callback=self.launch_firefox),
]),
]),
None,
rumps.MenuItem("Reset All", callback=self.reset),
None,
rumps.MenuItem("About SusOps", callback=self.open_about),
rumps.MenuItem("Quit", callback=self.quit_app, key="q")
]
self._check_timer = rumps.Timer(self.check_state_and_update_menu, 5)
self._startup_check_timer = rumps.Timer(self.async_startup_check, 0.1)
self._startup_check_timer.start()
def async_startup_check(self, _):
add_edit_menu_item()
status, output, returncode = self.check_state_and_update_menu()
# check if output has "no default connection found"
if status == ProcessState.ERROR and "no default connection found" in output:
# show welcome dialog for connection setup
alert_foreground("🎉 Welcome to SusOps 🎉",
"To get started, please follow these steps:\n\n"
"1. Add a connection\n"
"2. Start the proxy\n\n"
"If you need help, please check the documentation in 'About' → 'Github'.", )
self._startup_check_timer.stop()
self._check_timer.start()
def check_state_and_update_menu(self, _=None):
# runs every 5s
try:
output, returncode = run_susops("ps", False)
except subprocess.CalledProcessError:
output, returncode = "Error running command", -1
if not output:
returncode = -1
match returncode:
case 0:
new_state = ProcessState.RUNNING
case 2:
new_state = ProcessState.STOPPED_PARTIALLY
case 3:
new_state = ProcessState.STOPPED
case _:
new_state = ProcessState.ERROR
if new_state == self.process_state:
return
self.process_state = new_state
self.update_icon()
self.menu["Status"].title = f"Status: {self.process_state.value.lower().replace("_", " ")}"
self.menu["Status"].icon = os.path.join(self.images_dir, "status", self.process_state.value.lower() + ".svg")
match self.process_state:
case ProcessState.RUNNING:
self.menu["Start Proxy"].set_callback(None)
self.menu["Stop Proxy"].set_callback(self.stop_proxy)
self.menu["Restart Proxy"].set_callback(self.restart_proxy)
self.menu["Test"]["Test Any"].set_callback(self.test_any)
self.menu["Test"]["Test All"].set_callback(self.test_all)
case ProcessState.STOPPED_PARTIALLY:
self.menu["Start Proxy"].set_callback(self.start_proxy)
self.menu["Stop Proxy"].set_callback(self.stop_proxy)
self.menu["Restart Proxy"].set_callback(self.restart_proxy)
self.menu["Test"]["Test Any"].set_callback(self.test_any)
self.menu["Test"]["Test All"].set_callback(self.test_all)
case ProcessState.STOPPED:
self.menu["Start Proxy"].set_callback(self.start_proxy)
self.menu["Stop Proxy"].set_callback(None)
self.menu["Restart Proxy"].set_callback(None)
self.menu["Test"]["Test Any"].set_callback(None)
self.menu["Test"]["Test All"].set_callback(None)
case ProcessState.ERROR:
self.menu["Start Proxy"].set_callback(None)
self.menu["Stop Proxy"].set_callback(None)
self.menu["Restart Proxy"].set_callback(None)
self.menu["Test"]["Test Any"].set_callback(None)
self.menu["Test"]["Test All"].set_callback(None)
return self.process_state, output, returncode
def appearanceChanged_(self, _):
# Called when user switches between light/dark mode
self.update_icon()
if self._settings_panel:
self._settings_panel.update_appearance()
def update_icon(self, logo_style: LogoStyle = None):
logo_style = logo_style or LogoStyle[self.config['logo_style'].upper()]
state = ProcessState.STOPPED if self.process_state == ProcessState.INITIAL else self.process_state
self.icon = get_logo_style_image(logo_style, state)
@staticmethod
def load_config():
configs = {
"pac_server_port": ConfigHelper.read_config(".pac_server_port", "1081"),
"logo_style": ConfigHelper.read_config(".susops_app.logo_style", DEFAULT_LOGO_STYLE.value),
"stop_on_quit": ConfigHelper.read_config(".susops_app.stop_on_quit", '1') == '1',
"ephemeral_ports": ConfigHelper.read_config(".susops_app.ephemeral_ports", '1') == '1'
}
# check if logo_style is valid
if configs['logo_style'] not in LogoStyle.__members__:
configs['logo_style'] = DEFAULT_LOGO_STYLE.value
ConfigHelper.update_config(f".susops_app.logo_style = \"{configs['logo_style']}\"")
return configs
def open_settings(self, _):
if self._settings_panel is None:
frame = NSMakeRect(0, 0, 300, 240)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._settings_panel = SettingsPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self.config = self.load_config()
self._settings_panel.pac_port_field.setStringValue_(self.config['pac_server_port'])
app_path = os.path.basename(NSBundle.mainBundle().bundlePath())
app_name = os.path.splitext(os.path.basename(app_path))[0]
script = 'tell application "System Events" to get name of every login item'
try:
out = subprocess.check_output(["osascript", "-e", script])
launch_at_login = app_name in out.decode()
except:
launch_at_login = False
self._settings_panel.launch_at_login_checkbox.setState_(NSOnState if launch_at_login else NSOffState)
self._settings_panel.stop_on_quit_checkbox.setState_(NSOnState if self.config['stop_on_quit'] else NSOffState)
self._settings_panel.ephemeral_ports_checkbox.setState_(NSOnState if self.config['ephemeral_ports'] else NSOffState)
# get index of current logo style
logo_style = self.config['logo_style']
selected_index = list(LogoStyle).index(LogoStyle[logo_style.upper()])
self._settings_panel.segmented_icons.setSelectedSegment_(selected_index)
self._settings_panel.run()
def show_restart_dialog(self, title, message):
if self.process_state != ProcessState.RUNNING:
alert_foreground(title, message)
return
restart = alert_foreground(
title,
message,
ok="Restart Proxy", cancel="Skip"
)
if restart == 1:
self.restart_proxy(None)
def add_connection(self, sender, default_text=''):
frame_width = 440
frame_height = 195
if not self._connection_panel:
frame = NSMakeRect(0, 0, frame_width, frame_height)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._connection_panel = AddConnectionPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._connection_panel.setTitle_("Add Connection")
self._connection_panel.configure_fields([
('tag', "Connection Tag:", FieldType.TEXT),
('host', "SSH Host:", FieldType.COMBOBOX),
('socks_proxy_port', "SOCKS Proxy Port (optional):", FieldType.TEXT),
], label_width=170, input_start_x=190, input_width=230, hide_connection=True)
self._connection_panel.run()
def add_host(self, sender, default_text=''):
frame_width = 300
frame_height = 220
if not self._add_host_panel:
frame = NSMakeRect(0, 0, frame_width, frame_height)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._add_host_panel = AddHostPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._add_host_panel.setTitle_("Add Domain / IP / CIDR")
self._add_host_panel.configure_fields([
('host', "Host:", FieldType.TEXT),
], label_width=80, input_start_x=100)
self._add_host_panel.add_info_label("Host can be:\n"
"* Domain (subdomains & wildcards supported)\n"
"* IP address (CIDR notation supported)", frame_width, frame_height)
self._add_host_panel.run()
def add_local_forward(self, _):
if not self._add_local_forward_panel:
frame = NSMakeRect(0, 0, 340, 310)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._add_local_forward_panel = LocalForwardPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._add_local_forward_panel.setTitle_("Add Local Forward")
self._add_local_forward_panel.configure_fields([
('tag', 'Tag (optional):', FieldType.TEXT),
('local_port_field', 'Forward Local Port:', FieldType.TEXT),
('remote_port_field', 'To Remote Port:', FieldType.TEXT),
('local_addr_field', 'Local Bind (optional):', FieldType.COMBOBOX),
('remote_addr_field', 'Remote Bind (optional):', FieldType.COMBOBOX),
], label_width=140, input_start_x=160)
self._add_local_forward_panel.run()
def add_remote_forward(self, _):
if not self._add_remote_forward_panel:
frame = NSMakeRect(0, 0, 340, 310)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._add_remote_forward_panel = RemoteForwardPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._add_remote_forward_panel.setTitle_("Add Remote Forward")
self._add_remote_forward_panel.configure_fields([
('tag', 'Tag (optional):', FieldType.TEXT),
('remote_port_field', 'Forward Remote Port:', FieldType.TEXT),
('local_port_field', 'To Local Port:', FieldType.TEXT),
('remote_addr_field', 'Remote Bind (optional):', FieldType.COMBOBOX),
('local_addr_field', 'Local Bind (optional):', FieldType.COMBOBOX),
], label_width=140, input_start_x=160)
self._add_remote_forward_panel.run()
def remove_connection(self, _):
if not self._remove_connection_panel:
frame = NSMakeRect(0, 0, 300, 105)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._remove_connection_panel = RemoveConnectionPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._remove_connection_panel.setTitle_("Remove Connection")
self._remove_connection_panel.configure_field("Connection Tag:", label_width = 100, input_start_x = 120)
self._remove_connection_panel.update_items(ConfigHelper.get_connection_tags())
self._remove_connection_panel.run()
def remove_host(self, _):
if not self._remove_host_panel:
frame = NSMakeRect(0, 0, 255, 105)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._remove_host_panel = RemoveDomainPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._remove_host_panel.setTitle_("Remove Domain / IP / CIDR")
self._remove_host_panel.configure_field("Host:", label_width = 55, input_start_x = 75)
self._remove_host_panel.update_items(ConfigHelper.get_domains())
self._remove_host_panel.run()
def remove_local_forward(self, sender, default_text=''):
if not self._remove_local_forward_panel:
frame = NSMakeRect(0, 0, 290, 105)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._remove_local_forward_panel = RemoveLocalForwardPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._remove_local_forward_panel.setTitle_("Remove Local Forward")
self._remove_local_forward_panel.configure_field("Local Forward:", label_width=90, input_start_x=110)
self._remove_local_forward_panel.update_items(ConfigHelper.get_local_forwards())
self._remove_local_forward_panel.run()
def remove_remote_forward(self, sender, default_text=''):
if not self._remove_remote_forward_panel:
frame = NSMakeRect(0, 0, 310, 105)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._remove_remote_forward_panel = RemoveRemoteForwardPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._remove_remote_forward_panel.setTitle_("Remove Remote Forward")
self._remove_remote_forward_panel.configure_field("Remote Forward:", label_width=110, input_start_x=130)
self._remove_remote_forward_panel.update_items(ConfigHelper.get_remote_forwards())
self._remove_remote_forward_panel.run()
def list_config(self, _):
output, _ = run_susops("ls")
alert_foreground("Domains & Forwards", output)
def open_config_file(self, _):
run_susops("config")
def start_proxy(self, _):
output, _ = run_susops("start")
self.check_state_and_update_menu()
def stop_proxy(self, _):
ports_flag = "--keep-ports" if not self.config['ephemeral_ports'] else ""
output, _ = run_susops(f"stop {ports_flag}")
self.check_state_and_update_menu()
def restart_proxy(self, _):
self.config = self.load_config()
output, _ = run_susops("restart")
self.check_state_and_update_menu()
def check_status(self, _):
output, _ = run_susops("ps", False)
alert_foreground("SusOps Status", output)
def test_any(self, _):
host = rumps.Window("Enter domain or port to test: ", "Test Any",
ok="Test", cancel="Cancel", dimensions=(220, 20)).run().text
if host:
output, _ = run_susops(f"test {host}", False)
alert_foreground("SusOps Test", output)
def test_all(self, _):
output, _ = run_susops("test --all", False)
alert_foreground("SusOps Test All", output)
def launch_chrome(self, _):
output, _ = run_susops("chrome", False)
def launch_chrome_proxy_settings(self, _):
output, _ = run_susops("chrome-proxy-settings", False)
def launch_firefox(self, _):
output, _ = run_susops("firefox", False)
def reset(self, _):
result = alert_foreground(
"Reset Everything?",
"This will stop SusOps and remove all of its configs. You will have to reconfigure the ssh host as well as ports.\n\nAre you sure?",
ok="Reset Everything", cancel="Cancel"
)
if result == 1:
run_susops("reset --force", False)
self.config = self.load_config()
self.update_icon()
def open_about(self, _):
if self._about_panel is None:
frame = NSMakeRect(0, 0, 280, 190)
style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable)
self._about_panel = AboutPanel.alloc().initWithContentRect_styleMask_backing_defer_(
frame, style, NSBackingStoreBuffered, False
)
self._about_panel.run()
def quit_app(self, _):
if self.config['stop_on_quit']:
run_susops("stop --keep-ports", False)
rumps.quit_application()
class SettingsPanel(NSPanel):
"""A floating panel with SSH Host, SOCKS Port & PAC Port fields plus Save/Cancel."""
def initWithContentRect_styleMask_backing_defer_(
self, frame, style, backing, defer
):
self = objc.super(SettingsPanel, self).initWithContentRect_styleMask_backing_defer_(
frame, style, backing, defer
)
if not self:
return None
self.setHidesOnDeactivate_(False)
self.setTitle_("Settings")
self.setLevel_(NSFloatingWindowLevel)
content = self.contentView()
win_h = frame.size.height
label_margin_left = 20
label_width = 70
input_margin_left = 100
input_width = 180
element_height = 24
# --- Launch at Login Checkbox ---
y = win_h - 40
self.launch_at_login_checkbox = NSButton.alloc().initWithFrame_(NSMakeRect(input_margin_left, y, input_width, element_height))
self.launch_at_login_checkbox.setButtonType_(NSSwitchButton)
self.launch_at_login_checkbox.setTitle_("Launch at Login")
self.launch_at_login_checkbox.setTarget_(self)
# self.launch_at_login_checkbox.setAction_("toggleLaunchAtLogin:")
content.addSubview_(self.launch_at_login_checkbox)
# --- Stop On Close Checkbox ---
y -= 30
self.stop_on_quit_checkbox = NSButton.alloc().initWithFrame_(NSMakeRect(input_margin_left, y, input_width, element_height))
self.stop_on_quit_checkbox.setButtonType_(NSSwitchButton)
self.stop_on_quit_checkbox.setTitle_("Stop Proxy On Quit")
self.stop_on_quit_checkbox.setTarget_(self)
content.addSubview_(self.stop_on_quit_checkbox)
# --- Ephemeral Ports Checkbox ---
y -= 30
self.ephemeral_ports_checkbox = NSButton.alloc().initWithFrame_(NSMakeRect(input_margin_left, y, input_width, element_height))
self.ephemeral_ports_checkbox.setButtonType_(NSSwitchButton)
self.ephemeral_ports_checkbox.setTitle_("Random SSH Ports On Start")
self.ephemeral_ports_checkbox.setTarget_(self)
content.addSubview_(self.ephemeral_ports_checkbox)
# --- Logo Style ---
y -= 40
self.logo_label = NSTextField.alloc().initWithFrame_(NSMakeRect(label_margin_left, y - 4, label_width, element_height))
self.logo_label.setStringValue_("Logo Style:")
self.logo_label.setAlignment_(2)
self.logo_label.setBezeled_(False)
self.logo_label.setDrawsBackground_(False)
self.logo_label.setEditable_(False)
content.addSubview_(self.logo_label)
self.segmented_icons = NSSegmentedControl.alloc().initWithFrame_(NSMakeRect(input_margin_left, y, input_width, element_height))
self.segmented_icons.setSegmentCount_(len(LogoStyle))
self.segmented_icons.setTrackingMode_(NSSegmentSwitchTrackingSelectOne)
self.segmented_icons.setControlSize_(NSRegularControlSize)
self.update_appearance()
self.segmented_icons.setTarget_(self)
self.segmented_icons.setAction_("segmentedIconsChange:") # define this method to handle clicks
content.addSubview_(self.segmented_icons)
# --- PAC Port ---
y -= 40
self.pac_label = NSTextField.alloc().initWithFrame_(NSMakeRect(label_margin_left, y - 4, label_width, element_height))
self.pac_label.setStringValue_("PAC Port:")
self.pac_label.setAlignment_(2)
self.pac_label.setBezeled_(False)
self.pac_label.setDrawsBackground_(False)
self.pac_label.setEditable_(False)
content.addSubview_(self.pac_label)
self.pac_port_field = NSTextField.alloc().initWithFrame_(NSMakeRect(input_margin_left, y, input_width, element_height))
content.addSubview_(self.pac_port_field)
# --- Save/Cancel Buttons ---
button_x = input_margin_left - 5
button_width = 90
button_margin = 10
y -= 40
cancel_btn = NSButton.alloc().initWithFrame_(NSMakeRect(button_x, y, button_width, element_height))
cancel_btn.setTitle_("Cancel")
cancel_btn.setBezelStyle_(1)
cancel_btn.setTarget_(self)
cancel_btn.setAction_("cancelSettings:")
content.addSubview_(cancel_btn)
save_btn = NSButton.alloc().initWithFrame_(NSMakeRect(button_x + button_width + button_margin, y, button_width, element_height))
save_btn.setTitle_("Save")
save_btn.setBezelStyle_(1)
save_btn.setKeyEquivalent_("\r")
save_btn.setTarget_(self)
save_btn.setAction_("saveSettings:")
content.addSubview_(save_btn)
return self
def update_appearance(self):
# add / update logo segmented control
for idx, style in enumerate(LogoStyle):
icon = NSImage.alloc().initWithContentsOfFile_(get_logo_style_image(style))
icon.setSize_((24, 24))
self.segmented_icons.setImage_forSegment_(icon, idx)
self.segmented_icons.cell().setImageScaling_forSegment_(NSImageScaleProportionallyDown, idx)
def saveSettings_(self, _):
self.toggleLaunchAtLogin_(self.launch_at_login_checkbox)
ws = os.path.expanduser("~/.susops")
os.makedirs(ws, exist_ok=True)
pac_server_port = self.pac_port_field.stringValue().strip()
if not FormValidator.validate_port_with_alert(pac_server_port, self.pac_label.stringValue().rstrip(':')):
return
ConfigHelper.update_config(f".pac_server_port = {pac_server_port}")
stop_on_quit = self.stop_on_quit_checkbox.stringValue().strip()
if not FormValidator.validate_empty_with_alert(stop_on_quit, self.stop_on_quit_checkbox.stringValue().rstrip(':')):
return
ConfigHelper.update_config(f".susops_app.stop_on_quit = \"{stop_on_quit}\"")
ephemeral_ports = self.ephemeral_ports_checkbox.stringValue().strip()
if not FormValidator.validate_empty_with_alert(ephemeral_ports, self.ephemeral_ports_checkbox.stringValue().rstrip(':')):
return
ConfigHelper.update_config(f".susops_app.ephemeral_ports = \"{ephemeral_ports}\"")
selected_index = self.segmented_icons.selectedSegment()
selected_style = list(LogoStyle)[selected_index]
ConfigHelper.update_config(f".susops_app.logo_style = \"{selected_style.value}\"")
susops_app.config = susops_app.load_config()
susops_app.update_icon()
self.close()
susops_app.show_restart_dialog("Settings Saved", "Settings will be applied on next proxy start.")
def segmentedIconsChange_(self, sender):
selected_index = sender.selectedSegment()
selected_style = list(LogoStyle)[selected_index]
# temporarily set the icon to the selected style
susops_app.config['logo_style'] = selected_style.value
susops_app.update_icon(selected_style)
def toggleLaunchAtLogin_(self, sender):
enabled = (sender.state() == NSOnState)
bundle = NSBundle.mainBundle()
app_path = bundle.bundlePath()
bin_name = os.path.splitext(os.path.basename(app_path))[0]
if enabled:
applescript = '''
tell application "System Events"
make login item at end with properties {path:"%s", hidden:false}
end tell
''' % app_path
else:
applescript = '''
tell application "System Events"
delete login item "%s"
end tell
''' % bin_name
subprocess.call(["osascript", "-e", applescript])
def cancelSettings_(self, _):
# reset the logo style to the saved one
susops_app.config = susops_app.load_config()
susops_app.update_icon()
self.close()
def run(self):
bring_app_to_front(self)
class GenericFieldPanel(NSPanel):
def initWithContentRect_styleMask_backing_defer_(
self, frame, style, backing, defer
):
self = objc.super(GenericFieldPanel, self).initWithContentRect_styleMask_backing_defer_(
frame, style, backing, defer
)
if not self:
return None
self.setHidesOnDeactivate_(False)
self.setLevel_(NSFloatingWindowLevel)
return self
def configure_fields(self, field_defs, label_width: int = 150, input_start_x: int = 170, input_width: int = 160,
hide_connection: bool = False):
"""
field_defs = [(attr_name, label_text), ...] # order = top → bottom
Builds one label/field row per entry, 40 px vertical spacing.
"""
content = self.contentView()
y = 20 + 40 + len(field_defs) * 40
if not hide_connection:
# select for connections with NSPopUpButton
lbl = NSTextField.alloc().initWithFrame_(NSMakeRect(15, y - 2, label_width, 24))
lbl.setStringValue_("Connection:")
lbl.setAlignment_(2)
lbl.setBezeled_(False)
lbl.setDrawsBackground_(False)
lbl.setEditable_(False)
content.addSubview_(lbl)
self.connection = NSPopUpButton.alloc().initWithFrame_(NSMakeRect(input_start_x, y, input_width, 24))
self.connection.setPullsDown_(False)
self.connection.addItemsWithTitles_(ConfigHelper.get_connection_tags())
self.connection.selectItemAtIndex_(0)
content.addSubview_(self.connection)
y -= 40
for attr, label, type in field_defs:
lbl = NSTextField.alloc().initWithFrame_(NSMakeRect(15, y - 2, label_width, 24))
lbl.setStringValue_(label)
lbl.setAlignment_(2)
lbl.setBezeled_(False)
lbl.setDrawsBackground_(False)
lbl.setEditable_(False)
content.addSubview_(lbl)
if type == FieldType.COMBOBOX:
fld = NSComboBox.alloc().initWithFrame_(NSMakeRect(input_start_x, y, input_width + 3, 24))
else:
fld = NSTextField.alloc().initWithFrame_(NSMakeRect(input_start_x, y, input_width, 24))
content.addSubview_(fld)
setattr(self, attr, fld)
y -= 40
# --- Save/Cancel Buttons ---
button_width = 80
button_spacing = 7
cancel_btn = NSButton.alloc().initWithFrame_(NSMakeRect(input_start_x - 5, 16, button_width, 30))
cancel_btn.setTitle_("Cancel")
cancel_btn.setBezelStyle_(1)
cancel_btn.setTarget_(self)
cancel_btn.setAction_("cancel:")
content.addSubview_(cancel_btn)
add_btn = NSButton.alloc().initWithFrame_(NSMakeRect(input_start_x + input_width - button_width + button_spacing, 16, button_width, 30))
add_btn.setTitle_("Add")
add_btn.setBezelStyle_(1)
add_btn.setKeyEquivalent_("\r")
add_btn.setTarget_(self)
add_btn.setAction_("add:")
content.addSubview_(add_btn)
def run(self):
bring_app_to_front(self)
# reload connection tags
if hasattr(self, 'connection'):
self.connection.removeAllItems()
self.connection.addItemsWithTitles_(ConfigHelper.get_connection_tags())
def cancel_(self, _):
self.close()
class GenericSelectPanel(NSPanel):
"""A simple panel with a label, a dropdown, and Save/Cancel buttons."""
def initWithContentRect_styleMask_backing_defer_(
self, frame, style, backing, defer
):
self = objc.super(GenericSelectPanel, self).initWithContentRect_styleMask_backing_defer_(
frame, style, backing, defer
)
if not self:
return None
self.setHidesOnDeactivate_(False)
self.setLevel_(NSFloatingWindowLevel)
return self
def configure_field(self, label_text: str, label_width: int = 100, input_start_x: int = 120, input_width: int = 150, save_button_text: str = "Remove"):
"""
Configures the panel with a single label and NSPopUpButton.
:param label_text: The text for the label.
:param label_width: Width of the label.
:param input_start_x: X-coordinate for the NSPopUpButton.
:param input_width: Width of the NSPopUpButton.
"""
content = self.contentView()
# Label
y = 40 + 16
label = NSTextField.alloc().initWithFrame_(NSMakeRect(15, y - 2, label_width, 24))
label.setStringValue_(label_text)
label.setAlignment_(2)
label.setBezeled_(False)
label.setDrawsBackground_(False)
label.setEditable_(False)
content.addSubview_(label)
self.label = label
# NSPopUpButton
select = NSPopUpButton.alloc().initWithFrame_(NSMakeRect(input_start_x, y, input_width + 10, 24))
select.setPullsDown_(False)
# select.addItemsWithTitles_(options)
select.selectItemAtIndex_(0)
content.addSubview_(select)
self.select = select
# Save/Cancel Buttons
x = input_start_x - 5
cancel_btn = NSButton.alloc().initWithFrame_(NSMakeRect(x, 18, 80, 30))
cancel_btn.setTitle_("Cancel")
cancel_btn.setBezelStyle_(1)
cancel_btn.setTarget_(self)
cancel_btn.setAction_("cancel:")
content.addSubview_(cancel_btn)
save_btn = NSButton.alloc().initWithFrame_(NSMakeRect(x + 90, 18, 80, 30))
save_btn.setTitle_(save_button_text)
save_btn.setBezelStyle_(1)
save_btn.setKeyEquivalent_("\r")
save_btn.setTarget_(self)
save_btn.setAction_("save:")
content.addSubview_(save_btn)
def update_items(self, items: list):
"""Update the items in the NSPopUpButton."""