-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClaudeRootHelper.swift
More file actions
1152 lines (991 loc) · 44.9 KB
/
ClaudeRootHelper.swift
File metadata and controls
1152 lines (991 loc) · 44.9 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 Cocoa
// MARK: - Root Server (runs as root when invoked with --server)
class RootServer {
let socketPath = "/var/run/claude-root-helper.sock"
let pidPath = "/var/run/claude-root-helper.pid"
let logPath = "/var/log/claude-root-helper.log"
let clientInstallPath = "/usr/local/bin/claude-root-cmd"
let allowedGID: gid_t = 20 // staff group
var appPidPath: String
var homePath: String?
var allowedUID: uid_t?
var allowRules: [String] = []
var blockRules: [String] = []
var startTime = Date()
var cmdCount = 0
var logHandle: FileHandle?
var watchdogFileSource: DispatchSourceFileSystemObject?
var watchdogTimerSource: DispatchSourceTimer?
var acceptSource: DispatchSourceRead?
var termSignalSource: DispatchSourceSignal?
var intSignalSource: DispatchSourceSignal?
init(home: String?) {
self.homePath = home
if let home = home {
appPidPath = "\(home)/.claude-root-helper.pid"
} else {
appPidPath = "/tmp/claude-root-helper-app.pid"
}
}
func loadConfig() {
guard let home = homePath else {
allowRules = []
blockRules = []
return
}
let configPath = "\(home)/.claude-root-helper-filters.json"
guard let data = FileManager.default.contents(atPath: configPath),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
allowRules = []
blockRules = []
log("No command filter config found")
return
}
allowRules = json["allow"] as? [String] ?? []
blockRules = json["block"] as? [String] ?? []
log("Loaded filter config: \(allowRules.count) allow, \(blockRules.count) block rules")
}
func commandAllowed(_ cmd: String) -> (allowed: Bool, reason: String?) {
// Check allowlist first — if non-empty, first token must match
if !allowRules.isEmpty {
let firstToken = String(cmd.split(separator: " ", maxSplits: 1).first ?? Substring(cmd))
if !allowRules.contains(firstToken) {
return (false, "Command not in allowlist")
}
}
// Check blocklist — if any rule is a substring of cmd, reject
for rule in blockRules {
if cmd.contains(rule) {
return (false, "Blocked by rule: \"\(rule)\"")
}
}
return (true, nil)
}
private let logDateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss,SSS"
return df
}()
func log(_ message: String, level: String = "INFO") {
let line = "\(logDateFormatter.string(from: Date())) [\(level)] \(message)\n"
if let data = line.data(using: .utf8) {
logHandle?.write(data)
}
}
func installClient() {
let exe = Bundle.main.executablePath ?? CommandLine.arguments[0]
let candidates = [
(exe as NSString).deletingLastPathComponent + "/../Resources/claude-root-cmd",
(exe as NSString).deletingLastPathComponent + "/claude-root-cmd",
(Bundle.main.bundlePath as NSString).deletingLastPathComponent + "/claude-root-cmd"
]
for src in candidates {
if FileManager.default.fileExists(atPath: src) {
try? FileManager.default.removeItem(atPath: clientInstallPath)
try? FileManager.default.copyItem(atPath: src, toPath: clientInstallPath)
chmod(clientInstallPath, 0o755)
log("Installed client to \(clientInstallPath)")
return
}
}
}
func getPeerUID(_ fd: Int32) -> uid_t? {
// struct xucred { u_int cr_version; uid_t cr_uid; short cr_ngroups; gid_t cr_groups[16]; }
let xucredSize = 4 + 4 + 2 + 2 + (16 * 4) // 76 bytes
var buf = [UInt8](repeating: 0, count: xucredSize)
var len = socklen_t(xucredSize)
let ret = getsockopt(fd, 0 /* SOL_LOCAL */, 0x001 /* LOCAL_PEERCRED */, &buf, &len)
guard ret == 0 else { return nil }
return buf.withUnsafeBufferPointer { ptr -> uid_t in
ptr.baseAddress!.advanced(by: 4).withMemoryRebound(to: uid_t.self, capacity: 1) { $0.pointee }
}
}
func sendResponse(_ fd: Int32, exitCode: Int, stdout: String, stderr: String) {
let response: [String: Any] = ["exit_code": exitCode, "stdout": stdout, "stderr": stderr]
if let data = try? JSONSerialization.data(withJSONObject: response),
var str = String(data: data, encoding: .utf8) {
str += "\n"
let result = str.withCString { send(fd, $0, strlen($0), 0) }
if result < 0 && errno != EPIPE && errno != ECONNRESET {
log("Send failed (fd=\(fd)): \(String(cString: strerror(errno)))", level: "ERROR")
}
}
}
func handleClient(_ clientFd: Int32) {
defer { close(clientFd) }
// Check peer UID
if let peerUID = getPeerUID(clientFd), let allowed = allowedUID {
if peerUID != allowed && peerUID != 0 {
log("Rejected connection from UID \(peerUID) (allowed: \(allowed))", level: "WARNING")
return
}
}
// Read request
var data = Data()
var buf = [UInt8](repeating: 0, count: 65536)
while true {
let n = recv(clientFd, &buf, buf.count, 0)
if n <= 0 { break }
data.append(contentsOf: buf[0..<n])
if data.contains(UInt8(ascii: "\n")) { break }
}
guard let str = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),
let json = try? JSONSerialization.jsonObject(with: Data(str.utf8)) as? [String: Any],
let cmd = json["command"] as? String else {
return
}
let timeout = json["timeout"] as? Int ?? 120
let cwd = json["cwd"] as? String ?? "/"
if cmd == "__ping__" {
sendResponse(clientFd, exitCode: 0, stdout: "pong\n", stderr: "")
return
}
if cmd == "__quit__" {
sendResponse(clientFd, exitCode: 0, stdout: "Shutting down\n", stderr: "")
log("Quit command received, shutting down")
cleanup()
exit(0)
}
if cmd == "__status__" {
let uptime = Int(Date().timeIntervalSince(startTime))
let info = "{\"uptime\":\(uptime),\"commands\":\(cmdCount),\"pid\":\(getpid())}"
sendResponse(clientFd, exitCode: 0, stdout: info + "\n", stderr: "")
return
}
if cmd == "__reload__" {
loadConfig()
sendResponse(clientFd, exitCode: 0, stdout: "Config reloaded\n", stderr: "")
return
}
// Command filtering
let filterResult = commandAllowed(cmd)
if !filterResult.allowed {
let reason = filterResult.reason ?? "Blocked by filter"
log("BLOCKED: \(cmd) — \(reason)", level: "WARNING")
sendResponse(clientFd, exitCode: 1, stdout: "", stderr: "claude-root-helper: \(reason)\n")
return
}
cmdCount += 1
log("CMD: \(cmd) (cwd=\(cwd), timeout=\(timeout))")
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/sh")
process.arguments = ["-c", cmd]
process.currentDirectoryURL = URL(fileURLWithPath: cwd)
var env = ProcessInfo.processInfo.environment
env["PATH"] = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
process.environment = env
let outPipe = Pipe()
let errPipe = Pipe()
process.standardOutput = outPipe
process.standardError = errPipe
do {
try process.run()
// Read stdout/stderr concurrently to avoid pipe buffer deadlock
var stdoutStr = ""
var stderrStr = ""
let group = DispatchGroup()
group.enter()
DispatchQueue.global().async {
let d = outPipe.fileHandleForReading.readDataToEndOfFile()
stdoutStr = String(data: d, encoding: .utf8) ?? ""
group.leave()
}
group.enter()
DispatchQueue.global().async {
let d = errPipe.fileHandleForReading.readDataToEndOfFile()
stderrStr = String(data: d, encoding: .utf8) ?? ""
group.leave()
}
// Timeout
var timedOut = false
let timer = DispatchSource.makeTimerSource(queue: .global())
timer.schedule(deadline: .now() + .seconds(timeout))
timer.setEventHandler {
if process.isRunning {
timedOut = true
process.terminate()
}
}
timer.resume()
process.waitUntilExit()
timer.cancel()
group.wait()
if timedOut {
log("EXIT: timeout")
sendResponse(clientFd, exitCode: 124, stdout: stdoutStr, stderr: "Command timed out after \(timeout)s\n")
} else {
log("EXIT: \(process.terminationStatus)")
sendResponse(clientFd, exitCode: Int(process.terminationStatus), stdout: stdoutStr, stderr: stderrStr)
}
} catch {
log("Error running command: \(error.localizedDescription)", level: "ERROR")
sendResponse(clientFd, exitCode: 1, stdout: "", stderr: error.localizedDescription)
}
}
func cleanup() {
for path in [socketPath, pidPath, "/Library/LaunchDaemons/com.claude.root-helper.plist"] {
unlink(path)
}
}
func appPidAlive(_ pid: pid_t) -> Bool {
let ret = kill(pid, 0)
if ret == 0 { return true }
return errno == EPERM
}
func startWatchdog() {
// Watch the app PID file for deletion (app quit removes it)
let fd = Darwin.open(appPidPath, O_RDONLY | O_EVTONLY)
if fd >= 0 {
let fileSource = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: fd, eventMask: .delete, queue: .global(qos: .utility)
)
fileSource.setEventHandler { [weak self] in
self?.log("App PID file deleted, shutting down")
self?.cleanup()
exit(0)
}
fileSource.setCancelHandler {
Darwin.close(fd)
}
fileSource.resume()
watchdogFileSource = fileSource
}
// Fallback timer every 30s — catches edge cases where file persists but process died
let timer = DispatchSource.makeTimerSource(queue: .global(qos: .utility))
timer.schedule(deadline: .now() + .seconds(30), repeating: .seconds(30), leeway: .seconds(30))
timer.setEventHandler { [weak self] in
guard let self = self else { return }
guard FileManager.default.fileExists(atPath: self.appPidPath) else {
self.log("App PID file gone (fallback check), shutting down")
self.cleanup()
exit(0)
}
guard let pidStr = try? String(contentsOfFile: self.appPidPath, encoding: .utf8)
.trimmingCharacters(in: .whitespacesAndNewlines),
let pid = pid_t(pidStr) else {
return
}
if !self.appPidAlive(pid) {
self.log("App (PID \(pid)) is no longer running (fallback check), shutting down")
self.cleanup()
exit(0)
}
}
timer.resume()
watchdogTimerSource = timer
}
func run() -> Never {
// Ignore SIGPIPE — sending to a disconnected client must not kill the server
signal(SIGPIPE, SIG_IGN)
// Ignore SIGHUP — survive the osascript shell's exit
signal(SIGHUP, SIG_IGN)
// Set up logging
FileManager.default.createFile(atPath: logPath, contents: nil)
logHandle = FileHandle(forWritingAtPath: logPath)
logHandle?.seekToEndOfFile()
installClient()
loadConfig()
// Determine allowed UID from PID file owner
if let attrs = try? FileManager.default.attributesOfItem(atPath: appPidPath),
let uid = attrs[.ownerAccountID] as? NSNumber {
allowedUID = uid.uint32Value
log("Restricting access to UID \(allowedUID!)")
} else {
log("App PID file not found, allowing any staff-group user", level: "WARNING")
}
// Clean up old socket
unlink(socketPath)
// Write PID file
try? "\(getpid())".write(toFile: pidPath, atomically: true, encoding: .utf8)
// Create and bind socket
let serverFd = Darwin.socket(AF_UNIX, SOCK_STREAM, 0)
guard serverFd >= 0 else {
log("Failed to create socket", level: "ERROR")
exit(1)
}
var addr = sockaddr_un()
addr.sun_family = sa_family_t(AF_UNIX)
withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in
socketPath.withCString { strcpy(ptr, $0) }
}
let bindResult = withUnsafePointer(to: &addr) { ptr in
ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) {
bind(serverFd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
}
}
guard bindResult == 0 else {
log("Failed to bind socket: \(String(cString: strerror(errno)))", level: "ERROR")
exit(1)
}
chmod(socketPath, 0o660)
chown(socketPath, 0, allowedGID)
listen(serverFd, 5)
startWatchdog()
// Use sigaction with SA_SIGINFO to capture sender PID
var termAction = sigaction()
termAction.sa_flags = Int32(SA_SIGINFO)
termAction.__sigaction_u = unsafeBitCast(
{ (_: Int32, info: UnsafeMutablePointer<__siginfo>?, _: UnsafeMutableRawPointer?) in
let senderPID = info?.pointee.si_pid ?? -1
let senderUID = info?.pointee.si_uid ?? UInt32.max
var pathBuf = [CChar](repeating: 0, count: 4096)
proc_pidpath(senderPID, &pathBuf, UInt32(pathBuf.count))
let senderPath = String(cString: pathBuf)
let msg = "SIGTERM from PID \(senderPID) (UID \(senderUID), path: \(senderPath))\n"
// Write directly to log file (signal-safe via fd)
let logFd = Darwin.open("/var/log/claude-root-helper.log", O_WRONLY | O_APPEND)
if logFd >= 0 {
msg.withCString { Darwin.write(logFd, $0, Int(strlen($0))) }
Darwin.close(logFd)
}
unlink("/var/run/claude-root-helper.sock")
unlink("/var/run/claude-root-helper.pid")
_exit(0)
} as @convention(c) (Int32, UnsafeMutablePointer<__siginfo>?, UnsafeMutableRawPointer?) -> Void,
to: type(of: termAction.__sigaction_u)
)
sigaction(SIGTERM, &termAction, nil)
signal(SIGINT, SIG_IGN)
let intSource = DispatchSource.makeSignalSource(signal: SIGINT, queue: .global(qos: .utility))
intSource.setEventHandler { [weak self] in
self?.log("SIGINT received, shutting down")
self?.cleanup()
exit(0)
}
intSource.resume()
intSignalSource = intSource
log("Root helper started (PID \(getpid()))")
let clientQueue = DispatchQueue(label: "claude-root-helper.clients", attributes: .concurrent)
let source = DispatchSource.makeReadSource(fileDescriptor: serverFd, queue: .global(qos: .utility))
source.setEventHandler { [weak self] in
let clientFd = accept(serverFd, nil, nil)
if clientFd >= 0 {
clientQueue.async { self?.handleClient(clientFd) }
}
}
source.resume()
acceptSource = source
dispatchMain()
}
}
// MARK: - Log text view (kills cursor blink timer)
class LogTextView: NSTextView {
override func updateInsertionPointStateAndRestartTimer(_ flag: Bool) {
super.updateInsertionPointStateAndRestartTimer(false)
}
}
// MARK: - Click-through placeholder label
class PlaceholderLabel: NSTextField {
override func hitTest(_ point: NSPoint) -> NSView? { nil }
}
// MARK: - GUI App
class AppDelegate: NSObject, NSApplicationDelegate, NSTextViewDelegate {
var window: NSWindow!
var statusDot: NSTextField!
var statusText: NSTextField!
var scrollView: NSScrollView!
var textView: NSTextView!
var logSource: DispatchSourceFileSystemObject?
var logFd: Int32 = -1
var lastLogOffset: UInt64 = 0
let maxLogLines = 2000
var logLineCount = 0
var helperRunning = false
let appPidPath = NSHomeDirectory() + "/.claude-root-helper.pid"
let configPath = NSHomeDirectory() + "/.claude-root-helper-filters.json"
// Filter panel (bottom of main window)
var filterToggle: NSButton!
var filterContainer: NSView!
var allowTextView: NSTextView!
var blockTextView: NSTextView!
var allowPlaceholder: PlaceholderLabel!
var blockPlaceholder: PlaceholderLabel!
var filterSaveTimer: Timer?
var toggleBottomCollapsed: NSLayoutConstraint!
var filterBottomExpanded: NSLayoutConstraint!
var filtersExpanded = false
var logMonitorSuspended = false
// Menu bar mode
let menuBarPrefKey = "minimizeToMenuBar"
var minimizeMenuItem: NSMenuItem!
var statusItem: NSStatusItem?
var minimizeToMenuBar: Bool {
get { UserDefaults.standard.bool(forKey: menuBarPrefKey) }
set { UserDefaults.standard.set(newValue, forKey: menuBarPrefKey) }
}
private let logDateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "HH:mm:ss"
return df
}()
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.setActivationPolicy(.regular)
writeAppPid()
setupMenuBar()
setupWindow()
NotificationCenter.default.addObserver(
self, selector: #selector(windowOcclusionChanged(_:)),
name: NSWindow.didChangeOcclusionStateNotification, object: window
)
loadFilterConfig()
updatePlaceholders()
if pingHelper() {
helperRunning = true
setStatus(running: true, text: "Connected to existing helper")
appendLog("Connected to already-running root helper", color: .systemGreen)
startLogMonitor()
} else {
DispatchQueue.main.async { self.startHelper() }
}
}
func writeAppPid() {
try? "\(ProcessInfo.processInfo.processIdentifier)".write(
toFile: appPidPath, atomically: true, encoding: .utf8)
}
// MARK: - UI Setup
func setupMenuBar() {
let menuBar = NSMenu()
let appMenuItem = NSMenuItem()
menuBar.addItem(appMenuItem)
let appMenu = NSMenu(title: "Claude Root Helper")
minimizeMenuItem = NSMenuItem(title: "Minimize to Menu Bar",
action: #selector(toggleMinimizeToMenuBar(_:)), keyEquivalent: "")
minimizeMenuItem.target = self
minimizeMenuItem.state = minimizeToMenuBar ? .on : .off
appMenu.addItem(minimizeMenuItem)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(withTitle: "Quit Claude Root Helper", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
appMenuItem.submenu = appMenu
NSApp.mainMenu = menuBar
}
func makeFilterTextView() -> (NSScrollView, NSTextView, PlaceholderLabel) {
let sv = NSScrollView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.hasVerticalScroller = true
sv.borderType = .bezelBorder
sv.autohidesScrollers = true
let tv = NSTextView()
tv.isEditable = true
tv.isSelectable = true
tv.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
tv.backgroundColor = NSColor(white: 0.12, alpha: 1.0)
tv.textColor = NSColor(white: 0.85, alpha: 1.0)
tv.insertionPointColor = NSColor(white: 0.85, alpha: 1.0)
tv.textContainerInset = NSSize(width: 4, height: 4)
tv.delegate = self
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
tv.isContinuousSpellCheckingEnabled = false
tv.isGrammarCheckingEnabled = false
tv.isAutomaticSpellingCorrectionEnabled = false
tv.isAutomaticTextCompletionEnabled = false
tv.isAutomaticLinkDetectionEnabled = false
sv.documentView = tv
let ph = PlaceholderLabel(labelWithString: "one rule per line")
ph.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
ph.textColor = NSColor(white: 0.35, alpha: 1.0)
ph.backgroundColor = .clear
ph.translatesAutoresizingMaskIntoConstraints = false
return (sv, tv, ph)
}
func setupWindow() {
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 620, height: 440),
styleMask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered, defer: false
)
window.title = "Claude Root Helper"
window.center()
window.minSize = NSSize(width: 480, height: 300)
let cv = window.contentView!
// Status bar
statusDot = NSTextField(labelWithString: "\u{25CF}")
statusDot.font = .systemFont(ofSize: 16)
statusDot.textColor = .systemGray
statusDot.translatesAutoresizingMaskIntoConstraints = false
cv.addSubview(statusDot)
statusText = NSTextField(labelWithString: "Starting\u{2026}")
statusText.font = .systemFont(ofSize: 13, weight: .medium)
statusText.translatesAutoresizingMaskIntoConstraints = false
cv.addSubview(statusText)
// Log view
scrollView = NSScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.hasVerticalScroller = true
scrollView.borderType = .bezelBorder
scrollView.autohidesScrollers = false
textView = LogTextView()
textView.isEditable = false
textView.isSelectable = true
textView.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
textView.backgroundColor = NSColor(white: 0.08, alpha: 1.0)
textView.textColor = NSColor(white: 0.7, alpha: 1.0)
textView.textContainerInset = NSSize(width: 6, height: 6)
textView.isAutomaticQuoteSubstitutionEnabled = false
textView.isAutomaticDashSubstitutionEnabled = false
textView.isAutomaticTextReplacementEnabled = false
textView.isContinuousSpellCheckingEnabled = false
textView.isGrammarCheckingEnabled = false
textView.isAutomaticSpellingCorrectionEnabled = false
textView.isAutomaticTextCompletionEnabled = false
textView.isAutomaticLinkDetectionEnabled = false
textView.insertionPointColor = .clear
textView.allowsUndo = false
scrollView.documentView = textView
cv.addSubview(scrollView)
// Layer-back views with on-demand redraw to eliminate speculative redraws
cv.wantsLayer = true
cv.layerContentsRedrawPolicy = .onSetNeedsDisplay
scrollView.layerContentsRedrawPolicy = .onSetNeedsDisplay
textView.layerContentsRedrawPolicy = .onSetNeedsDisplay
// Filter toggle bar at the bottom
filterToggle = NSButton(title: "Command Filters \u{25B8}", target: self, action: #selector(toggleFilters(_:)))
filterToggle.bezelStyle = .inline
filterToggle.translatesAutoresizingMaskIntoConstraints = false
cv.addSubview(filterToggle)
// Intercept the standard miniaturize button so we can route to the menu bar when enabled
if let miniBtn = window.standardWindowButton(.miniaturizeButton) {
miniBtn.target = self
miniBtn.action = #selector(customMinimize(_:))
}
// Filter container (hidden by default)
filterContainer = NSView()
filterContainer.translatesAutoresizingMaskIntoConstraints = false
filterContainer.isHidden = true
cv.addSubview(filterContainer)
let allowLabel = NSTextField(labelWithString: "Allowed Commands")
allowLabel.font = .systemFont(ofSize: 11, weight: .semibold)
allowLabel.translatesAutoresizingMaskIntoConstraints = false
filterContainer.addSubview(allowLabel)
let allowHint = NSTextField(labelWithString: "first word must match")
allowHint.font = .systemFont(ofSize: 9)
allowHint.textColor = .secondaryLabelColor
allowHint.translatesAutoresizingMaskIntoConstraints = false
filterContainer.addSubview(allowHint)
let blockLabel = NSTextField(labelWithString: "Blocked Commands")
blockLabel.font = .systemFont(ofSize: 11, weight: .semibold)
blockLabel.translatesAutoresizingMaskIntoConstraints = false
filterContainer.addSubview(blockLabel)
let blockHint = NSTextField(labelWithString: "blocked if command contains rule")
blockHint.font = .systemFont(ofSize: 9)
blockHint.textColor = .secondaryLabelColor
blockHint.translatesAutoresizingMaskIntoConstraints = false
filterContainer.addSubview(blockHint)
let (allowSV, allowTV, allowPH) = makeFilterTextView()
let (blockSV, blockTV, blockPH) = makeFilterTextView()
allowTextView = allowTV
blockTextView = blockTV
allowPlaceholder = allowPH
blockPlaceholder = blockPH
filterContainer.addSubview(allowSV)
filterContainer.addSubview(blockSV)
cv.addSubview(allowPH)
cv.addSubview(blockPH)
// Switchable constraints
toggleBottomCollapsed = filterToggle.bottomAnchor.constraint(equalTo: cv.bottomAnchor, constant: -14)
filterBottomExpanded = filterContainer.bottomAnchor.constraint(equalTo: cv.bottomAnchor, constant: -14)
toggleBottomCollapsed.isActive = true
NSLayoutConstraint.activate([
// Status bar
statusDot.leadingAnchor.constraint(equalTo: cv.leadingAnchor, constant: 14),
statusDot.topAnchor.constraint(equalTo: cv.topAnchor, constant: 10),
statusText.leadingAnchor.constraint(equalTo: statusDot.trailingAnchor, constant: 6),
statusText.centerYAnchor.constraint(equalTo: statusDot.centerYAnchor),
statusText.trailingAnchor.constraint(lessThanOrEqualTo: cv.trailingAnchor, constant: -14),
// Log view — bottom tied to filter toggle
scrollView.topAnchor.constraint(equalTo: statusDot.bottomAnchor, constant: 10),
scrollView.leadingAnchor.constraint(equalTo: cv.leadingAnchor, constant: 14),
scrollView.trailingAnchor.constraint(equalTo: cv.trailingAnchor, constant: -14),
scrollView.bottomAnchor.constraint(equalTo: filterToggle.topAnchor, constant: -8),
// Toggle bar
filterToggle.leadingAnchor.constraint(equalTo: cv.leadingAnchor, constant: 14),
// Filter container
filterContainer.topAnchor.constraint(equalTo: filterToggle.bottomAnchor, constant: 6),
filterContainer.leadingAnchor.constraint(equalTo: cv.leadingAnchor, constant: 14),
filterContainer.trailingAnchor.constraint(equalTo: cv.trailingAnchor, constant: -14),
filterContainer.heightAnchor.constraint(equalToConstant: 130),
// Labels and hints inside container
allowLabel.topAnchor.constraint(equalTo: filterContainer.topAnchor),
allowLabel.leadingAnchor.constraint(equalTo: filterContainer.leadingAnchor),
allowHint.leadingAnchor.constraint(equalTo: allowLabel.trailingAnchor, constant: 4),
allowHint.lastBaselineAnchor.constraint(equalTo: allowLabel.lastBaselineAnchor),
blockLabel.topAnchor.constraint(equalTo: filterContainer.topAnchor),
blockLabel.leadingAnchor.constraint(equalTo: filterContainer.centerXAnchor, constant: 6),
blockHint.leadingAnchor.constraint(equalTo: blockLabel.trailingAnchor, constant: 4),
blockHint.lastBaselineAnchor.constraint(equalTo: blockLabel.lastBaselineAnchor),
// Text view scroll views
allowSV.topAnchor.constraint(equalTo: allowLabel.bottomAnchor, constant: 4),
allowSV.leadingAnchor.constraint(equalTo: filterContainer.leadingAnchor),
allowSV.trailingAnchor.constraint(equalTo: filterContainer.centerXAnchor, constant: -6),
allowSV.bottomAnchor.constraint(equalTo: filterContainer.bottomAnchor),
blockSV.topAnchor.constraint(equalTo: blockLabel.bottomAnchor, constant: 4),
blockSV.leadingAnchor.constraint(equalTo: filterContainer.centerXAnchor, constant: 6),
blockSV.trailingAnchor.constraint(equalTo: filterContainer.trailingAnchor),
blockSV.bottomAnchor.constraint(equalTo: filterContainer.bottomAnchor),
// Placeholders positioned over text views
allowPH.leadingAnchor.constraint(equalTo: allowSV.leadingAnchor, constant: 8),
allowPH.topAnchor.constraint(equalTo: allowSV.topAnchor, constant: 6),
blockPH.leadingAnchor.constraint(equalTo: blockSV.leadingAnchor, constant: 8),
blockPH.topAnchor.constraint(equalTo: blockSV.topAnchor, constant: 6),
])
window.makeKeyAndOrderFront(nil)
window.makeFirstResponder(nil)
NSApp.activate(ignoringOtherApps: true)
}
@objc func toggleFilters(_ sender: Any?) {
filtersExpanded = !filtersExpanded
filterContainer.isHidden = !filtersExpanded
filterToggle.title = filtersExpanded ? "Command Filters \u{25BE}" : "Command Filters \u{25B8}"
if filtersExpanded {
toggleBottomCollapsed.isActive = false
filterBottomExpanded.isActive = true
} else {
filterBottomExpanded.isActive = false
toggleBottomCollapsed.isActive = true
}
updatePlaceholders()
}
// MARK: - Menu Bar Mode
@objc func toggleMinimizeToMenuBar(_ sender: Any?) {
minimizeToMenuBar.toggle()
minimizeMenuItem.state = minimizeToMenuBar ? .on : .off
}
@objc func customMinimize(_ sender: Any?) {
if minimizeToMenuBar {
hideToMenuBar()
} else {
window.miniaturize(sender)
}
}
func createStatusItem() {
guard statusItem == nil else { return }
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
if let button = item.button {
if let img = NSImage(systemSymbolName: "lock.shield",
accessibilityDescription: "Claude Root Helper") {
let cfg = NSImage.SymbolConfiguration(pointSize: 18, weight: .regular)
button.image = img.withSymbolConfiguration(cfg) ?? img
} else {
button.title = "RH"
}
button.toolTip = "Claude Root Helper"
button.target = self
button.action = #selector(showFromMenuBar(_:))
}
statusItem = item
}
func removeStatusItem() {
if let item = statusItem {
NSStatusBar.system.removeStatusItem(item)
statusItem = nil
}
}
func hideToMenuBar() {
window.orderOut(nil)
NSApp.setActivationPolicy(.accessory)
// Defer creation so the menu bar finishes rebuilding for the new policy
DispatchQueue.main.async { [weak self] in
self?.createStatusItem()
}
}
@objc func showFromMenuBar(_ sender: Any?) {
removeStatusItem()
NSApp.setActivationPolicy(.regular)
DispatchQueue.main.async { [weak self] in
self?.window.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
}
}
func setStatus(running: Bool, text: String) {
statusDot.textColor = running ? .systemGreen : .systemRed
statusText.stringValue = text
}
@objc func windowOcclusionChanged(_ note: Notification) {
if window.occlusionState.contains(.visible) {
window.contentView?.layer?.speed = 1.0
if logMonitorSuspended {
logMonitorSuspended = false
logSource?.resume()
readNewLogData()
}
} else {
window.contentView?.layer?.speed = 0
if !logMonitorSuspended, logSource != nil {
logMonitorSuspended = true
logSource?.suspend()
}
}
}
func appendLog(_ text: String, color: NSColor = NSColor(white: 0.7, alpha: 1.0)) {
let line = "[\(logDateFormatter.string(from: Date()))] \(text)\n"
textView.textStorage?.append(NSAttributedString(
string: line,
attributes: [
.font: NSFont.monospacedSystemFont(ofSize: 11, weight: .regular),
.foregroundColor: color
]
))
textView.scrollToEndOfDocument(nil)
}
// MARK: - Filter Config
func loadFilterConfig() {
guard FileManager.default.fileExists(atPath: configPath),
let data = FileManager.default.contents(atPath: configPath),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
allowTextView.string = ""
blockTextView.string = ""
return
}
allowTextView.string = (json["allow"] as? [String] ?? []).joined(separator: "\n")
blockTextView.string = (json["block"] as? [String] ?? []).joined(separator: "\n")
}
func saveFilterConfig() {
let allow = allowTextView.string.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
let block = blockTextView.string.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
if allow.isEmpty && block.isEmpty {
try? FileManager.default.removeItem(atPath: configPath)
} else {
let config: [String: Any] = ["allow": allow, "block": block]
if let data = try? JSONSerialization.data(withJSONObject: config, options: .prettyPrinted) {
try? data.write(to: URL(fileURLWithPath: configPath))
}
}
sendSocketCommand("__reload__")
}
func updatePlaceholders() {
allowPlaceholder?.isHidden = !allowTextView.string.isEmpty || !filtersExpanded
blockPlaceholder?.isHidden = !blockTextView.string.isEmpty || !filtersExpanded
}
func textDidChange(_ notification: Notification) {
guard let tv = notification.object as? NSTextView,
tv === allowTextView || tv === blockTextView else { return }
updatePlaceholders()
filterSaveTimer?.invalidate()
filterSaveTimer = Timer.scheduledTimer(withTimeInterval: 0.8, repeats: false) { [weak self] _ in
self?.saveFilterConfig()
}
}
// MARK: - Helper Management
let launchdLabel = "com.claude.root-helper"
let launchdPlistPath = "/Library/LaunchDaemons/com.claude.root-helper.plist"
func startHelper() {
appendLog("Requesting administrator privileges\u{2026}", color: .systemYellow)
let exe = Bundle.main.executablePath!
let home = NSHomeDirectory()
// Build a launchd plist so the server is a proper managed daemon
let plist: [String: Any] = [
"Label": launchdLabel,
"ProgramArguments": [exe, "--server", "--home", home],
"RunAtLoad": true,
"KeepAlive": false,
"StandardOutPath": "/dev/null",
"StandardErrorPath": "/dev/null",
]
DispatchQueue.global().async { [weak self] in
guard let self = self else { return }
// Write plist to a temp file, then use osascript to move it into place and bootstrap
let tmpPlist = NSTemporaryDirectory() + "com.claude.root-helper.plist"
let plistData = try? PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
guard let plistData = plistData else {
DispatchQueue.main.async {
self.setStatus(running: false, text: "Failed to create plist")
}
return
}
try? plistData.write(to: URL(fileURLWithPath: tmpPlist))
// Use osascript to: stop old daemon if loaded, install plist, bootstrap it
let script = """
do shell script "\
launchctl bootout system/\(self.launchdLabel) 2>/dev/null; \
cp '\(tmpPlist)' '\(self.launchdPlistPath)'; \
chmod 644 '\(self.launchdPlistPath)'; \
chown root:wheel '\(self.launchdPlistPath)'; \
launchctl bootstrap system '\(self.launchdPlistPath)'\
" with administrator privileges
"""
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")
process.arguments = ["-e", script]
let errPipe = Pipe()
process.standardError = errPipe
process.standardOutput = Pipe()
do {
try process.run()
process.waitUntilExit()
} catch {
DispatchQueue.main.async {
self.setStatus(running: false, text: "Failed to start")
self.appendLog("Error launching osascript: \(error.localizedDescription)", color: .systemRed)
}
return
}
let errData = errPipe.fileHandleForReading.readDataToEndOfFile()
let errStr = String(data: errData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
try? FileManager.default.removeItem(atPath: tmpPlist)
Thread.sleep(forTimeInterval: 1.5)
DispatchQueue.main.async {
if self.pingHelper() {
self.helperRunning = true
self.setStatus(running: true, text: "Running")
self.appendLog("Root helper is running (launchd managed)", color: .systemGreen)
self.startLogMonitor()
} else {
self.setStatus(running: false, text: "Failed to start")
if !errStr.isEmpty {
self.appendLog("Error: \(errStr)", color: .systemRed)
} else {
self.appendLog("Helper did not respond. Check /var/log/claude-root-helper.log", color: .systemRed)
}
}
}
}
}
func pingHelper() -> Bool {
let sock = Darwin.socket(AF_UNIX, SOCK_STREAM, 0)
guard sock >= 0 else { return false }
defer { Darwin.close(sock) }
var addr = sockaddr_un()
addr.sun_family = sa_family_t(AF_UNIX)
withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in
"/var/run/claude-root-helper.sock".withCString { strcpy(ptr, $0) }
}
let ok = withUnsafePointer(to: &addr) { ptr in
ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) {
Darwin.connect(sock, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
}
}