-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathBrowserPanel.swift
More file actions
11595 lines (10509 loc) · 475 KB
/
Copy pathBrowserPanel.swift
File metadata and controls
11595 lines (10509 loc) · 475 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 Foundation
import CMUXMobileCore
import CmuxCore
import CmuxBrowser
import CmuxFoundation
import CmuxSettings
import Combine
import CmuxAppKitSupportUI
import WebKit
import AppKit
import Bonsplit
import CmuxTerminalCore
import Network
import CFNetwork
import SQLite3
import CryptoKit
import Darwin
import CmuxTerminal
#if canImport(CommonCrypto)
import CommonCrypto
#endif
#if canImport(Security)
import Security
#endif
fileprivate func dedupedCanonicalURLs(_ urls: [URL]) -> [URL] {
var seen = Set<String>()
var result: [URL] = []
for url in urls {
let canonical = url.standardizedFileURL.resolvingSymlinksInPath().path
if seen.insert(canonical).inserted {
result.append(url)
}
}
return result
}
private struct BrowserFocusModePlainEscapeEventFingerprint: Equatable {
let type: NSEvent.EventType
let timestamp: TimeInterval
let windowNumber: Int
let keyCode: UInt16
let modifierFlags: NSEvent.ModifierFlags.RawValue
init(_ event: NSEvent) {
self.type = event.type
self.timestamp = event.timestamp
self.windowNumber = event.windowNumber
self.keyCode = event.keyCode
self.modifierFlags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
.subtracting([.numericPad, .function, .capsLock])
.rawValue
}
}
enum GhosttyBackgroundTheme {
static func clampedOpacity(_ opacity: Double) -> CGFloat {
WindowAppearanceSnapshot.clampedOpacity(opacity)
}
static func color(backgroundColor: NSColor, opacity: Double) -> NSColor {
WindowAppearanceSnapshot.compositedTerminalColor(
backgroundColor: backgroundColor,
opacity: opacity
)
}
static func color(
from notification: Notification?,
fallbackColor: NSColor,
fallbackOpacity: Double
) -> NSColor {
let userInfo = notification?.userInfo
let backgroundColor =
(userInfo?[GhosttyNotificationKey.backgroundColor] as? NSColor)
?? fallbackColor
let opacity: Double
if let value = userInfo?[GhosttyNotificationKey.backgroundOpacity] as? Double {
opacity = value
} else if let value = userInfo?[GhosttyNotificationKey.backgroundOpacity] as? NSNumber {
opacity = value.doubleValue
} else {
opacity = fallbackOpacity
}
return color(backgroundColor: backgroundColor, opacity: opacity)
}
static func color(from notification: Notification?) -> NSColor {
color(
from: notification,
fallbackColor: GhosttyApp.shared.defaultBackgroundColor,
fallbackOpacity: GhosttyApp.shared.defaultBackgroundOpacity
)
}
/// Resolves a live background notification against the terminal theme's
/// concrete light/dark base. This is the variant used by detached browser
/// and Dock chrome; the legacy `color(from:)` helper remains available for
/// callers that explicitly need the window ambient composition.
static func resolvedColor(from notification: Notification?) -> NSColor {
let userInfo = notification?.userInfo
let backgroundColor =
(userInfo?[GhosttyNotificationKey.backgroundColor] as? NSColor)
?? GhosttyApp.shared.defaultBackgroundColor
let opacity: Double
if let value = userInfo?[GhosttyNotificationKey.backgroundOpacity] as? Double {
opacity = value
} else if let value = userInfo?[GhosttyNotificationKey.backgroundOpacity] as? NSNumber {
opacity = value.doubleValue
} else {
opacity = GhosttyApp.shared.defaultBackgroundOpacity
}
return WindowAppearanceSnapshot.resolvedChromeBackgroundColor(
backgroundColor: backgroundColor,
opacity: opacity,
colorScheme: GhosttyApp.shared.effectiveTerminalColorSchemePreference == .dark ? .dark : .light
)
}
static func currentColor() -> NSColor {
WindowAppearanceSnapshot.resolvedChromeBackgroundColor(
backgroundColor: GhosttyApp.shared.defaultBackgroundColor,
opacity: GhosttyApp.shared.defaultBackgroundOpacity,
colorScheme: GhosttyApp.shared.effectiveTerminalColorSchemePreference == .dark ? .dark : .light
)
}
}
enum BrowserThemeMode: String, CaseIterable, Identifiable {
case system
case light
case dark
var id: String { rawValue }
var displayName: String {
switch self {
case .system:
return String(localized: "theme.system", defaultValue: "System")
case .light:
return String(localized: "theme.light", defaultValue: "Light")
case .dark:
return String(localized: "theme.dark", defaultValue: "Dark")
}
}
var iconName: String {
switch self {
case .system:
return "circle.lefthalf.filled"
case .light:
return "sun.max"
case .dark:
return "moon"
}
}
}
enum BrowserThemeSettings {
static let modeKey = "browserThemeMode"
static let legacyForcedDarkModeEnabledKey = "browserForcedDarkModeEnabled"
static let defaultMode: BrowserThemeMode = .system
static func mode(for rawValue: String?) -> BrowserThemeMode {
guard let rawValue, let mode = BrowserThemeMode(rawValue: rawValue) else {
return defaultMode
}
return mode
}
static func mode(defaults: UserDefaults = .standard) -> BrowserThemeMode {
let resolvedMode = mode(for: defaults.string(forKey: modeKey))
if defaults.string(forKey: modeKey) != nil {
return resolvedMode
}
// Migrate the legacy bool toggle only when the new mode key is unset.
if defaults.object(forKey: legacyForcedDarkModeEnabledKey) != nil {
let migratedMode: BrowserThemeMode = defaults.bool(forKey: legacyForcedDarkModeEnabledKey) ? .dark : .system
defaults.set(migratedMode.rawValue, forKey: modeKey)
return migratedMode
}
return defaultMode
}
static func apply(_ mode: BrowserThemeMode, to webView: WKWebView) {
switch mode {
case .system:
webView.appearance = nil
case .light:
webView.appearance = NSAppearance(named: .aqua)
case .dark:
webView.appearance = NSAppearance(named: .darkAqua)
}
}
}
enum BrowserImportHintVariant: String, CaseIterable, Identifiable {
case inlineStrip
case floatingCard
case toolbarChip
case settingsOnly
var id: String { rawValue }
}
enum BrowserImportHintBlankTabPlacement: Equatable {
case hidden
case inlineStrip
case floatingCard
case toolbarChip
}
enum BrowserImportHintSettingsStatus: Equatable {
case visible
case hidden
case settingsOnly
}
struct BrowserImportHintPresentation: Equatable {
let blankTabPlacement: BrowserImportHintBlankTabPlacement
let settingsStatus: BrowserImportHintSettingsStatus
init(
variant: BrowserImportHintVariant,
showOnBlankTabs: Bool,
isDismissed: Bool
) {
if variant == .settingsOnly {
blankTabPlacement = .hidden
settingsStatus = .settingsOnly
return
}
if !showOnBlankTabs || isDismissed {
blankTabPlacement = .hidden
settingsStatus = .hidden
return
}
switch variant {
case .inlineStrip:
blankTabPlacement = .inlineStrip
case .floatingCard:
blankTabPlacement = .floatingCard
case .toolbarChip:
blankTabPlacement = .toolbarChip
case .settingsOnly:
blankTabPlacement = .hidden
}
settingsStatus = .visible
}
}
enum BrowserImportHintSettings {
static let variantKey = "browserImportHintVariant"
static let showOnBlankTabsKey = "browserImportHintShowOnBlankTabs"
static let dismissedKey = "browserImportHintDismissed"
static let defaultVariant: BrowserImportHintVariant = .toolbarChip
static let defaultShowOnBlankTabs = true
static let defaultDismissed = false
static func variant(for rawValue: String?) -> BrowserImportHintVariant {
guard let rawValue, let variant = BrowserImportHintVariant(rawValue: rawValue) else {
return defaultVariant
}
return variant
}
static func variant(defaults: UserDefaults = .standard) -> BrowserImportHintVariant {
variant(for: defaults.string(forKey: variantKey))
}
static func showOnBlankTabs(defaults: UserDefaults = .standard) -> Bool {
if defaults.object(forKey: showOnBlankTabsKey) == nil {
return defaultShowOnBlankTabs
}
return defaults.bool(forKey: showOnBlankTabsKey)
}
static func isDismissed(defaults: UserDefaults = .standard) -> Bool {
if defaults.object(forKey: dismissedKey) == nil {
return defaultDismissed
}
return defaults.bool(forKey: dismissedKey)
}
static func presentation(defaults: UserDefaults = .standard) -> BrowserImportHintPresentation {
BrowserImportHintPresentation(
variant: variant(defaults: defaults),
showOnBlankTabs: showOnBlankTabs(defaults: defaults),
isDismissed: isDismissed(defaults: defaults)
)
}
static func reset(defaults: UserDefaults = .standard) {
defaults.set(defaultVariant.rawValue, forKey: variantKey)
defaults.set(defaultShowOnBlankTabs, forKey: showOnBlankTabsKey)
defaults.set(defaultDismissed, forKey: dismissedKey)
}
}
// `BrowserProfileDefinition` and `BrowserProfileClearOutcome` now live in the
// `CmuxBrowser` package (imported above); the call sites reference them
// unqualified through that import.
// Adapts `BrowserHistoryStore` to the `CmuxBrowser` history seams so the
// profile repository can manage per-profile history stores without depending on
// the app-target `BrowserHistoryStore` type.
extension BrowserHistoryStore: BrowserProfileHistoryStore {}
@MainActor
private final class BrowserProfileHistoryAdapter: BrowserProfileHistoryProviding {
var sharedHistoryStore: any BrowserProfileHistoryStore { BrowserHistoryStore.shared }
func makeHistoryStore(fileURL: URL?) -> any BrowserProfileHistoryStore {
BrowserHistoryStore(fileURL: fileURL)
}
func defaultHistoryFileURLForCurrentBundle() -> URL? {
BrowserHistoryStore.defaultHistoryFileURLForCurrentBundle()
}
func normalizedBrowserHistoryNamespace(forBundleIdentifier bundleIdentifier: String) -> String {
BrowserHistoryStore.normalizedBrowserHistoryNamespaceForBundleIdentifier(bundleIdentifier)
}
func flushSharedHistoryPendingSaves() {
BrowserHistoryStore.shared.flushPendingSaves()
}
}
// Adapts WebKit's `WKWebsiteDataStore` to the `CmuxBrowser` data-store
// seam, mapping the built-in default profile to the default store and bridging
// the legacy completion-handler wipe to `async`/`await` at this one boundary.
@MainActor
private final class BrowserProfileWebsiteDataStoreAdapter: BrowserProfileWebsiteDataStoreProviding {
var defaultWebsiteDataStore: AnyObject { WKWebsiteDataStore.default() }
func makeWebsiteDataStore(forProfileID profileID: UUID) -> AnyObject {
WKWebsiteDataStore(forIdentifier: profileID)
}
var allWebsiteDataTypes: [String] { Array(WKWebsiteDataStore.allWebsiteDataTypes()) }
func removeAllData(ofTypes dataTypes: [String], from store: AnyObject) async {
guard let store = store as? WKWebsiteDataStore else { return }
let types = Set(dataTypes)
await withCheckedContinuation { continuation in
store.removeData(ofTypes: types, modifiedSince: .distantPast) {
continuation.resume()
}
}
}
}
// Removes profile-owned files via a detached utility task, matching the original
// best-effort, ignore-errors deletion behavior.
private struct BrowserProfileFileRemover: BrowserProfileFileRemoving {
func removeItemIfExists(at url: URL) async {
await Task.detached(priority: .utility) {
try? FileManager.default.removeItem(at: url)
}.value
}
}
@MainActor
final class BrowserProfileStore: ObservableObject {
static let shared = BrowserProfileStore()
@Published private(set) var profiles: [BrowserProfileDefinition] = []
@Published private(set) var lastUsedProfileID: UUID = BrowserProfileRepository.builtInDefaultProfileID
private let repository: BrowserProfileRepository
init(defaults: UserDefaults = .standard) {
repository = BrowserProfileRepository(
defaults: defaults,
historyProvider: BrowserProfileHistoryAdapter(),
websiteDataStoreProvider: BrowserProfileWebsiteDataStoreAdapter(),
fileRemover: BrowserProfileFileRemover(),
bundleIdentifier: Bundle.main.bundleIdentifier ?? "cmux",
defaultProfileDisplayName: String(localized: "browser.profile.default", defaultValue: "Default")
)
mirrorPublishedState()
}
private func mirrorPublishedState() {
profiles = repository.profiles
lastUsedProfileID = repository.lastUsedProfileID
}
var builtInDefaultProfileID: UUID {
repository.builtInDefaultProfileID
}
var effectiveLastUsedProfileID: UUID {
repository.effectiveLastUsedProfileID
}
func profileDefinition(id: UUID) -> BrowserProfileDefinition? {
repository.profileDefinition(id: id)
}
func resolveProfileSelection(_ selector: String) -> BrowserProfileSelectionResolution {
repository.resolveProfileSelection(selector)
}
func displayName(for id: UUID) -> String {
repository.displayName(for: id)
}
func createProfile(named rawName: String) -> BrowserProfileDefinition? {
let result = repository.createProfile(named: rawName)
mirrorPublishedState()
return result
}
func renameProfile(id: UUID, to rawName: String) -> Bool {
let result = repository.renameProfile(id: id, to: rawName)
mirrorPublishedState()
return result
}
func canRenameProfile(id: UUID) -> Bool {
repository.canRenameProfile(id: id)
}
func deleteProfile(id: UUID) -> BrowserProfileDefinition? {
let result = repository.deleteProfile(id: id)
mirrorPublishedState()
return result
}
func clearProfileData(id: UUID) async -> BrowserProfileClearOutcome? {
let result = await repository.clearProfileData(id: id)
mirrorPublishedState()
return result
}
func noteUsed(_ id: UUID) {
repository.noteUsed(id)
mirrorPublishedState()
}
func websiteDataStore(for profileID: UUID) -> WKWebsiteDataStore {
// Safe force-cast: the adapter only ever vends `WKWebsiteDataStore` handles.
repository.websiteDataStore(for: profileID) as! WKWebsiteDataStore
}
func historyStore(for profileID: UUID) -> BrowserHistoryStore {
// Safe force-cast: the adapter only ever vends `BrowserHistoryStore` handles.
repository.historyStore(for: profileID) as! BrowserHistoryStore
}
func historyFileURL(for profileID: UUID) -> URL? {
repository.historyFileURL(for: profileID)
}
func flushPendingSaves() {
repository.flushPendingSaves()
}
}
enum BrowserLinkOpenSettings {
static let openTerminalLinksInCmuxBrowserKey = "browserOpenTerminalLinksInCmuxBrowser"
static let defaultOpenTerminalLinksInCmuxBrowser: Bool = true
static let openSidebarPullRequestLinksInCmuxBrowserKey = "browserOpenSidebarPullRequestLinksInCmuxBrowser"
static let defaultOpenSidebarPullRequestLinksInCmuxBrowser: Bool = true
static let openSidebarPortLinksInCmuxBrowserKey = "browserOpenSidebarPortLinksInCmuxBrowser"
static let defaultOpenSidebarPortLinksInCmuxBrowser: Bool = true
static let interceptTerminalOpenCommandInCmuxBrowserKey = "browserInterceptTerminalOpenCommandInCmuxBrowser"
static let defaultInterceptTerminalOpenCommandInCmuxBrowser: Bool = true
static let browserHostWhitelistKey = "browserHostWhitelist"
static let defaultBrowserHostWhitelist: String = ""
static let browserExternalOpenPatternsKey = BrowserExternalURLPolicy.userDefaultsKey
static func openTerminalLinksInCmuxBrowser(defaults: UserDefaults = .standard) -> Bool {
guard BrowserAvailabilitySettings.isEnabled(defaults: defaults) else { return false }
if defaults.object(forKey: openTerminalLinksInCmuxBrowserKey) == nil {
return defaultOpenTerminalLinksInCmuxBrowser
}
return defaults.bool(forKey: openTerminalLinksInCmuxBrowserKey)
}
static func openSidebarPullRequestLinksInCmuxBrowser(defaults: UserDefaults = .standard) -> Bool {
guard BrowserAvailabilitySettings.isEnabled(defaults: defaults) else { return false }
if defaults.object(forKey: openSidebarPullRequestLinksInCmuxBrowserKey) == nil {
return defaultOpenSidebarPullRequestLinksInCmuxBrowser
}
return defaults.bool(forKey: openSidebarPullRequestLinksInCmuxBrowserKey)
}
static func openSidebarPortLinksInCmuxBrowser(defaults: UserDefaults = .standard) -> Bool {
guard BrowserAvailabilitySettings.isEnabled(defaults: defaults) else { return false }
if defaults.object(forKey: openSidebarPortLinksInCmuxBrowserKey) == nil {
return defaultOpenSidebarPortLinksInCmuxBrowser
}
return defaults.bool(forKey: openSidebarPortLinksInCmuxBrowserKey)
}
static func interceptTerminalOpenCommandInCmuxBrowser(defaults: UserDefaults = .standard) -> Bool {
guard BrowserAvailabilitySettings.isEnabled(defaults: defaults) else { return false }
if defaults.object(forKey: interceptTerminalOpenCommandInCmuxBrowserKey) != nil {
return defaults.bool(forKey: interceptTerminalOpenCommandInCmuxBrowserKey)
}
// Migrate existing behavior for users who only had the link-click toggle.
if defaults.object(forKey: openTerminalLinksInCmuxBrowserKey) != nil {
return defaults.bool(forKey: openTerminalLinksInCmuxBrowserKey)
}
return defaultInterceptTerminalOpenCommandInCmuxBrowser
}
static func initialInterceptTerminalOpenCommandInCmuxBrowserValue(defaults: UserDefaults = .standard) -> Bool {
interceptTerminalOpenCommandInCmuxBrowser(defaults: defaults)
}
static func hostWhitelist(defaults: UserDefaults = .standard) -> [String] {
let raw = defaults.string(forKey: browserHostWhitelistKey) ?? defaultBrowserHostWhitelist
return raw
.components(separatedBy: .newlines)
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
}
/// Check whether a hostname matches the configured whitelist.
/// Empty whitelist means "allow all" (no filtering).
/// Supports exact match and wildcard prefix (`*.example.com`).
static func hostMatchesWhitelist(_ host: String, defaults: UserDefaults = .standard) -> Bool {
let rawPatterns = hostWhitelist(defaults: defaults)
if rawPatterns.isEmpty { return true }
guard let normalizedHost = BrowserInsecureHTTPSettings.normalizeHost(host) else { return false }
for rawPattern in rawPatterns {
guard let pattern = normalizeWhitelistPattern(rawPattern) else { continue }
if hostMatchesPattern(normalizedHost, pattern: pattern) {
return true
}
}
return false
}
private static func normalizeWhitelistPattern(_ rawPattern: String) -> String? {
let trimmed = rawPattern
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased()
guard !trimmed.isEmpty else { return nil }
if trimmed.hasPrefix("*.") {
let suffixRaw = String(trimmed.dropFirst(2))
guard let suffix = BrowserInsecureHTTPSettings.normalizeHost(suffixRaw) else { return nil }
return "*.\(suffix)"
}
return BrowserInsecureHTTPSettings.normalizeHost(trimmed)
}
private static func hostMatchesPattern(_ host: String, pattern: String) -> Bool {
if pattern.hasPrefix("*.") {
let suffix = String(pattern.dropFirst(2))
return host == suffix || host.hasSuffix(".\(suffix)")
}
return host == pattern
}
}
enum BrowserAvailabilitySettings {
static let disabledKey = "browserDisabledOverride"
static let didChangeNotification = Notification.Name("cmux.browserAvailabilityDidChange")
static let defaultDisabled = false
static func isDisabled(defaults: UserDefaults = .standard) -> Bool {
// An MDM configuration profile (DisableEmbeddedBrowser) wins over
// every user-level source and cannot be overridden from the app.
if isManagedByPolicy {
return true
}
// No synchronize() on read: it forces a blocking prefs-plist reload on a path hit from link-open/pane-create; UserDefaults stays coherent in-process and via cfprefsd.
if defaults.object(forKey: disabledKey) == nil {
return defaultDisabled
}
return defaults.bool(forKey: disabledKey)
}
static func isEnabled(defaults: UserDefaults = .standard) -> Bool {
!isDisabled(defaults: defaults)
}
static func setDisabled(_ disabled: Bool, defaults: UserDefaults = .standard) {
// `set` already persists; `synchronize()` is a deprecated no-op-style fsync.
defaults.set(disabled, forKey: disabledKey)
NotificationCenter.default.post(name: didChangeNotification, object: nil)
}
}
enum BrowserInsecureHTTPSettings {
static let allowlistKey = "browserInsecureHTTPAllowlist"
static let defaultAllowlistPatterns = [
"localhost",
"*.localhost",
"127.0.0.1",
"::1",
"0.0.0.0",
"*.localtest.me",
]
static let defaultAllowlistText = defaultAllowlistPatterns.joined(separator: "\n")
static func normalizedAllowlistPatterns(defaults: UserDefaults = .standard) -> [String] {
guard defaults.object(forKey: allowlistKey) != nil else {
return defaultAllowlistPatterns
}
return normalizedAllowlistPatterns(rawValue: defaults.string(forKey: allowlistKey))
}
static func normalizedAllowlistPatterns(rawValue: String?) -> [String] {
// `nil` means no user override, so retain the safe loopback defaults.
// An explicitly empty string is a real override and intentionally
// removes every default entry.
guard let rawValue else { return defaultAllowlistPatterns }
return parsePatterns(from: rawValue)
}
static func isHostAllowed(_ host: String, defaults: UserDefaults = .standard) -> Bool {
isHostAllowed(host, rawAllowlist: defaults.string(forKey: allowlistKey))
}
static func isHostAllowed(_ host: String, rawAllowlist: String?) -> Bool {
guard let normalizedHost = normalizeHost(host) else { return false }
// Private-network addresses skip the warning outright: the modal's
// rationale — "traffic can be read or modified on the network" — is
// about the public Internet, and traffic to these ranges never crosses
// it. cmux Cloud machines live here (their VPC addresses, reached
// through the user's WireGuard tunnel, which encrypts the path anyway),
// so warning on every http://10.x panel would train people to click
// through the one dialog that matters on public sites.
if isPrivateNetworkHost(normalizedHost) { return true }
return normalizedAllowlistPatterns(rawValue: rawAllowlist).contains { pattern in
hostMatchesPattern(normalizedHost, pattern: pattern)
}
}
/// Whether the (normalized) host is a literal address in a range that is
/// not publicly routable: RFC 1918 IPv4, IPv4 link-local, IPv6 unique-local
/// (`fc00::/7` — cmux VPC addresses are here) and IPv6 link-local. Names
/// are never matched — only literals, so DNS can't smuggle a public host in.
static func isPrivateNetworkHost(_ normalizedHost: String) -> Bool {
// IPv6 literal (normalizeHost strips brackets and lowercases).
if normalizedHost.contains(":") {
var addr = in6_addr()
guard inet_pton(AF_INET6, normalizedHost, &addr) == 1 else { return false }
let bytes = withUnsafeBytes(of: addr) { Array($0) }
let first = bytes[0]
if first == 0xfc || first == 0xfd { return true } // fc00::/7 unique-local
if first == 0xfe, (bytes[1] & 0xc0) == 0x80 { return true } // fe80::/10 link-local
return false
}
// IPv4 literal.
var addr4 = in_addr()
guard inet_pton(AF_INET, normalizedHost, &addr4) == 1 else { return false }
let value = UInt32(bigEndian: addr4.s_addr)
let octet1 = UInt8(truncatingIfNeeded: value >> 24)
let octet2 = UInt8(truncatingIfNeeded: value >> 16)
switch octet1 {
case 10: return true // 10.0.0.0/8
case 172: return (16...31).contains(octet2) // 172.16.0.0/12
case 192: return octet2 == 168 // 192.168.0.0/16
case 169: return octet2 == 254 // 169.254.0.0/16 link-local
default: return false
}
}
static func addAllowedHost(_ host: String, defaults: UserDefaults = .standard) {
guard let normalizedHost = normalizeHost(host) else { return }
var patterns = normalizedAllowlistPatterns(defaults: defaults)
guard !patterns.contains(normalizedHost) else { return }
patterns.append(normalizedHost)
defaults.set(patterns.joined(separator: "\n"), forKey: allowlistKey)
}
// Single source of truth: the host normalizer moved to CmuxCore with the
// loopback alias lift; this forwards so allowlist semantics stay identical.
static func normalizeHost(_ rawHost: String) -> String? {
RemoteLoopbackProxyAlias.normalizeHost(rawHost)
}
private static func parsePatterns(from rawValue: String) -> [String] {
let separators = CharacterSet(charactersIn: ",;\n\r\t")
var out: [String] = []
var seen = Set<String>()
for token in rawValue.components(separatedBy: separators) {
guard let normalized = normalizePattern(token) else { continue }
guard seen.insert(normalized).inserted else { continue }
out.append(normalized)
}
return out
}
private static func normalizePattern(_ rawPattern: String) -> String? {
let trimmed = rawPattern
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased()
guard !trimmed.isEmpty else { return nil }
if trimmed.hasPrefix("*.") {
let suffixRaw = String(trimmed.dropFirst(2))
guard let suffix = normalizeHost(suffixRaw) else { return nil }
return "*.\(suffix)"
}
return normalizeHost(trimmed)
}
private static func hostMatchesPattern(_ host: String, pattern: String) -> Bool {
if pattern.hasPrefix("*.") {
let suffix = String(pattern.dropFirst(2))
return host == suffix || host.hasSuffix(".\(suffix)")
}
return host == pattern
}
}
/// Carries the request and one-shot HTTP bypass needed to seed a retargeted tab.
struct BrowserNewTabNavigationSeed {
let url: URL
let initialRequest: URLRequest
let bypassInsecureHTTPHostOnce: String?
}
/// Preserves the original request metadata for a retargeted new-tab navigation.
func browserNewTabNavigationSeed(
from request: URLRequest,
bypassInsecureHTTPHostOnce: String? = nil
) -> BrowserNewTabNavigationSeed? {
guard let url = request.url else { return nil }
return BrowserNewTabNavigationSeed(
url: url,
initialRequest: request,
bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce
)
}
/// Mirrors the opener's WebKit browsing context for popup windows.
struct BrowserPopupBrowserContext {
let websiteDataStore: WKWebsiteDataStore
}
enum BrowserFileSystemAccessBridge {
static let scriptSource = """
(() => {
if (typeof window.showOpenFilePicker === "function") {
return true;
}
if (window.__cmuxFileSystemAccessBridgeInstalled) {
return true;
}
window.__cmuxFileSystemAccessBridgeInstalled = true;
const makeDOMException = (name, message) => {
try {
return new DOMException(message, name);
} catch (_) {
const error = new Error(message);
error.name = name;
return error;
}
};
const normalizeAcceptToken = (value) => {
if (typeof value !== "string") {
return null;
}
const token = value.trim();
return token.length > 0 ? token : null;
};
const acceptStringFromTypes = (types) => {
if (!Array.isArray(types)) {
return "";
}
const seen = new Set();
const tokens = [];
const pushToken = (value) => {
const token = normalizeAcceptToken(value);
if (token && !seen.has(token)) {
seen.add(token);
tokens.push(token);
}
};
for (const type of types) {
const accept = type && type.accept;
if (!accept || typeof accept !== "object") {
continue;
}
for (const [mimeType, extensions] of Object.entries(accept)) {
pushToken(mimeType);
if (Array.isArray(extensions)) {
for (const extension of extensions) {
pushToken(extension);
}
} else {
pushToken(extensions);
}
}
}
return tokens.join(",");
};
const FileSystemHandleShim = window.FileSystemHandle || function FileSystemHandle() {};
const FileSystemFileHandleShim = window.FileSystemFileHandle || function FileSystemFileHandle() {};
if (typeof window.FileSystemHandle !== "function") {
Object.defineProperty(window, "FileSystemHandle", {
value: FileSystemHandleShim,
configurable: true,
writable: true,
});
}
if (typeof window.FileSystemFileHandle !== "function") {
FileSystemFileHandleShim.prototype = Object.create(FileSystemHandleShim.prototype);
Object.defineProperty(FileSystemFileHandleShim.prototype, "constructor", {
value: FileSystemFileHandleShim,
configurable: true,
writable: true,
});
Object.defineProperty(window, "FileSystemFileHandle", {
value: FileSystemFileHandleShim,
configurable: true,
writable: true,
});
}
const makeFileHandle = (file) => {
const handle = Object.create(window.FileSystemFileHandle.prototype);
Object.defineProperties(handle, {
kind: {
value: "file",
enumerable: true,
},
name: {
value: file.name,
enumerable: true,
},
getFile: {
value: () => Promise.resolve(file),
},
isSameEntry: {
value: (other) => Promise.resolve(other === handle),
},
queryPermission: {
value: () => Promise.resolve("granted"),
},
requestPermission: {
value: () => Promise.resolve("granted"),
},
});
return handle;
};
const filePickerDismissedError = () => makeDOMException(
"AbortError",
"The file picker was dismissed."
);
const cleanupInput = (input) => {
if (input && input.parentNode) {
input.parentNode.removeChild(input);
}
};
const showOpenFilePicker = (options = {}) => new Promise((resolve, reject) => {
const input = document.createElement("input");
input.type = "file";
input.multiple = options && options.multiple === true;
const accept = acceptStringFromTypes(options && options.types);
if (accept) {
input.accept = accept;
}
input.style.position = "fixed";
input.style.left = "-10000px";
input.style.top = "0";
input.style.width = "1px";
input.style.height = "1px";
input.style.opacity = "0";
input.tabIndex = -1;
let settled = false;
let focusFallbackScheduled = false;
let focusFallbackTimer = null;
const currentFiles = () => Array.from(input.files || []);
const cleanup = () => {
if (focusFallbackTimer !== null) {
clearTimeout(focusFallbackTimer);
focusFallbackTimer = null;
}
input.removeEventListener("change", handleChange);
input.removeEventListener("cancel", handleCancel);
window.removeEventListener("focus", handleWindowFocus);
cleanupInput(input);
};
const settle = (callback) => {
if (settled) {
return;
}
settled = true;
cleanup();
callback();
};
const resolveFiles = () => {
const files = currentFiles();
settle(() => resolve(files.map(makeFileHandle)));
};
const dismissPicker = () => {
settle(() => reject(filePickerDismissedError()));
};
function handleChange() {
resolveFiles();
}
function handleCancel() {
dismissPicker();
}
function handleWindowFocus() {
if (settled || focusFallbackScheduled) {
return;
}
focusFallbackScheduled = true;
// Defer one turn so a selection-triggered change event can settle first.
focusFallbackTimer = setTimeout(() => {
focusFallbackTimer = null;
if (settled) {
return;
}
if (currentFiles().length > 0) {
resolveFiles();
} else {
dismissPicker();
}
}, 0);
}
input.addEventListener("change", handleChange);
input.addEventListener("cancel", handleCancel);
window.addEventListener("focus", handleWindowFocus);
try {
(document.body || document.documentElement).appendChild(input);
input.click();
} catch (error) {
settle(() => reject(error));
}
});
Object.defineProperty(window, "showOpenFilePicker", {
value: showOpenFilePicker,
configurable: true,
writable: true,
});
return true;
})();
"""
}
func browserReadAccessURL(forLocalFileURL fileURL: URL, fileManager: FileManager = .default) -> URL? {
guard fileURL.isFileURL, fileURL.path.hasPrefix("/") else { return nil }
let path = fileURL.path
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue {
return fileURL
}
let parent = fileURL.deletingLastPathComponent()
guard !parent.path.isEmpty, parent.path.hasPrefix("/") else { return nil }
return parent
}
@MainActor
@discardableResult
func browserLoadRequest(
_ request: URLRequest,
in webView: WKWebView,
trustedInternalNavigation: Bool = false
) -> WKNavigation? {