@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
swift 382 lines 14.8 KB
Raw
1 import ExpoModulesCore
2 import Network
3 import WebKit
4
5 /// A webview whose loopback is another environment's: `localhost` requests go to a SOCKS
6 /// listener in this process, which carries each connection over the environment's tunnel.
7 final class T3TunnelWebView: ExpoView, WKNavigationDelegate {
8 let onAccessRequest = EventDispatcher()
9 let onNavigationChange = EventDispatcher()
10 let onLoadError = EventDispatcher()
11 let onPageScroll = EventDispatcher()
12
13 private var webView: WKWebView?
14 private var proxyPort: UInt16?
15 private var environmentId: String?
16 private var pendingUrl: String?
17 private var requestedUrl: URL?
18 /// A link that failed before its page committed leaves the old page current, so retry it.
19 private var failedUrl: URL?
20 private var observations: [NSKeyValueObservation] = []
21 private var reportedScrollY: CGFloat = 0
22 private var scrolledDistance: CGFloat = 0
23 private var lastOffsetY: CGFloat = 0
24 private var topInset: CGFloat = 0
25
26 /// JavaScript remounts the view for another environment, so only the first one counts.
27 func setEnvironment(_ environmentId: String) {
28 guard self.environmentId == nil else { return }
29 self.environmentId = environmentId
30 T3EnvironmentProxy.forEnvironment(environmentId).attach(self) { [weak self] port in
31 self?.proxyPort = port
32 self?.attachWebView()
33 }
34 }
35
36 private func attachWebView() {
37 guard webView == nil, let proxyPort, let environmentId else { return }
38 let configuration = WKWebViewConfiguration()
39 configuration.websiteDataStore = T3EnvironmentProxy.forEnvironment(environmentId)
40 .store(proxyPort: proxyPort)
41 let webView = WKWebView(frame: bounds, configuration: configuration)
42 webView.navigationDelegate = self
43 webView.allowsBackForwardNavigationGestures = true
44 // The page scrolls under the browser bar, like Safari; `topInset` keeps its top clear.
45 webView.scrollView.contentInsetAdjustmentBehavior = .never
46 webView.isOpaque = false
47 applyTopInset(to: webView)
48 webView.isInspectable = true
49 addSubview(webView)
50 self.webView = webView
51 observations = [
52 webView.observe(\.url) { [weak self] _, _ in self?.reportNavigation() },
53 webView.observe(\.title) { [weak self] _, _ in self?.reportNavigation() },
54 webView.observe(\.isLoading) { [weak self] _, _ in self?.reportNavigation() },
55 webView.observe(\.canGoBack) { [weak self] _, _ in self?.reportNavigation() },
56 webView.observe(\.canGoForward) { [weak self] _, _ in self?.reportNavigation() },
57 webView.observe(\.themeColor) { [weak self] _, _ in self?.reportNavigation() },
58 webView.observe(\.underPageBackgroundColor) { [weak self] _, _ in self?.reportNavigation() },
59 webView.scrollView.observe(\.contentOffset) { [weak self] scrollView, _ in
60 self?.reportScroll(scrollView)
61 },
62 ]
63 if let pendingUrl { load(pendingUrl) }
64 }
65
66 override func layoutSubviews() {
67 super.layoutSubviews()
68 webView?.frame = bounds
69 if let webView { applyIndicatorInsets(to: webView) }
70 }
71
72 override func safeAreaInsetsDidChange() {
73 super.safeAreaInsetsDidChange()
74 if let webView { applyIndicatorInsets(to: webView) }
75 }
76
77 /// The scroll indicator runs from under the bar to above the home indicator.
78 private func applyIndicatorInsets(to webView: WKWebView) {
79 let insets = UIEdgeInsets(top: topInset, left: 0, bottom: safeAreaInsets.bottom, right: 0)
80 if webView.scrollView.verticalScrollIndicatorInsets != insets {
81 webView.scrollView.verticalScrollIndicatorInsets = insets
82 }
83 }
84
85 func load(_ url: String) {
86 guard let webView else {
87 pendingUrl = url
88 return
89 }
90 pendingUrl = nil
91 guard let target = URL(string: url).map(T3Loopback.standIn), webView.url != target else {
92 return
93 }
94 requestedUrl = target
95 webView.load(URLRequest(url: target))
96 }
97
98 /// Opens `url`, even when it is the address already showing.
99 func navigate(_ url: String) {
100 guard let webView else {
101 pendingUrl = url
102 return
103 }
104 guard let target = URL(string: url).map(T3Loopback.standIn) else { return }
105 requestedUrl = target
106 webView.load(URLRequest(url: target))
107 }
108
109 func setTopInset(_ inset: CGFloat) {
110 guard inset != topInset else { return }
111 topInset = inset
112 if let webView { applyTopInset(to: webView) }
113 }
114
115 /// A page resting at its top stays there when the bar grows or shrinks.
116 private func applyTopInset(to webView: WKWebView) {
117 let scrollView = webView.scrollView
118 let atTop = scrollView.contentOffset.y <= -scrollView.contentInset.top + 1
119 scrollView.contentInset.top = topInset
120 applyIndicatorInsets(to: webView)
121 if atTop { scrollView.contentOffset.y = -topInset }
122 }
123
124 func goBack() { webView?.goBack() }
125 func goForward() { webView?.goForward() }
126 // After a failed load the webview may show no page or the previous one, so retry what failed.
127 func reload() {
128 guard let environmentId else { return reloadPage() }
129 T3EnvironmentProxy.forEnvironment(environmentId).ensureListening { [weak self] _ in
130 self?.reloadPage()
131 }
132 }
133
134 private func reloadPage() {
135 guard let webView else { return }
136 if let target = failedUrl ?? (webView.url == nil ? requestedUrl : nil) {
137 failedUrl = nil
138 webView.load(URLRequest(url: target))
139 } else {
140 webView.reload()
141 }
142 }
143
144 /// Reports how far the user has scrolled, in steps, enough for the bar to follow its direction.
145 private func reportScroll(_ scrollView: UIScrollView) {
146 // Rubber-banding past either end isn't scrolling, or the bounce back would flip the bar.
147 let top = -scrollView.adjustedContentInset.top
148 let bottom = max(
149 top,
150 scrollView.contentSize.height - scrollView.bounds.height
151 + scrollView.adjustedContentInset.bottom
152 )
153 let offset = min(max(scrollView.contentOffset.y, top), bottom)
154 defer { lastOffsetY = offset }
155 // WebKit's own offset changes while loading aren't the user scrolling.
156 let userScrolling = scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating
157 if userScrolling { scrolledDistance = max(0, scrolledDistance + offset - lastOffsetY) }
158 if offset <= top + 1 { scrolledDistance = 0 }
159 let y = scrolledDistance
160 guard abs(y - reportedScrollY) >= 24 || (y == 0 && reportedScrollY != 0) else { return }
161 reportedScrollY = y
162 onPageScroll(["y": y])
163 }
164
165 private func reportNavigation() {
166 guard let webView else { return }
167 onNavigationChange([
168 "url": webView.url.map(T3Loopback.shown)?.absoluteString ?? "",
169 "title": webView.title ?? "",
170 "loading": webView.isLoading,
171 "canGoBack": webView.canGoBack,
172 "canGoForward": webView.canGoForward,
173 // What Safari tints its bar with: the page's theme-color, else its background.
174 "pageColor": Self.hex(webView.themeColor ?? webView.underPageBackgroundColor) ?? "",
175 ])
176 }
177
178 private static func hex(_ color: UIColor?) -> String? {
179 var (red, green, blue, alpha): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0)
180 guard let color, color.getRed(&red, green: &green, blue: &blue, alpha: &alpha), alpha > 0
181 else { return nil }
182 let byte = { (value: CGFloat) in Int((min(max(value, 0), 1) * 255).rounded()) }
183 return String(format: "#%02x%02x%02x", byte(red), byte(green), byte(blue))
184 }
185
186 func webView(
187 _ webView: WKWebView,
188 didFailProvisionalNavigation navigation: WKNavigation!,
189 withError error: Error
190 ) {
191 let nsError = error as NSError
192 if !(nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled) {
193 let failing = nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String
194 failedUrl = failing.flatMap(URL.init(string:)) ?? requestedUrl
195 }
196 reportError(error)
197 }
198
199 /// Links and redirects to loopback go to the stand-in host, which is the one the proxy carries.
200 func webView(
201 _ webView: WKWebView,
202 decidePolicyFor navigationAction: WKNavigationAction,
203 decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void
204 ) {
205 let url = navigationAction.request.url
206 guard let url, navigationAction.targetFrame?.isMainFrame ?? true,
207 T3Loopback.standIn(url) != url
208 else { return decisionHandler(.allow) }
209 decisionHandler(.cancel)
210 // The same request at the stand-in host, so a form keeps its method, headers and body.
211 var request = navigationAction.request
212 let target = T3Loopback.standIn(url)
213 request.url = target
214 requestedUrl = target
215 webView.load(request)
216 }
217
218 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
219 failedUrl = nil
220 }
221
222 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
223 reportError(error)
224 }
225
226 private func reportError(_ error: Error) {
227 let error = error as NSError
228 if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { return }
229 let failingUrl = (error.userInfo[NSURLErrorFailingURLStringErrorKey] as? String)
230 .flatMap(URL.init(string:)).map(T3Loopback.shown)?.absoluteString
231 onLoadError([
232 "code": error.code,
233 "description": error.localizedDescription,
234 "url": failingUrl ?? "",
235 "debug": "\(error.domain) \(error.code), port \(proxyPort.map(String.init) ?? "none"), " + T3TunnelDiagnostics.shared.summary,
236 "cause": environmentId
237 .flatMap { T3EnvironmentProxy.forEnvironment($0).lastFailure?.rawValue } ?? "",
238 ])
239 }
240 }
241
242 /// Each environment keeps one listener on one port for the app's life, restarted there if iOS tore
243 /// it down, and one in-memory data store pointed at it, so cookies survive closing or maximizing a
244 /// page and never reach another environment's pages. A store saved on disk kept an old launch's
245 /// proxy port on devices. Access requests go to the newest live view. Main thread only.
246 private final class T3EnvironmentProxy {
247 nonisolated(unsafe) private static var proxies: [String: T3EnvironmentProxy] = [:]
248
249 nonisolated(unsafe) private static var foregroundObserver: NSObjectProtocol?
250
251 static func forEnvironment(_ environmentId: String) -> T3EnvironmentProxy {
252 if let proxy = proxies[environmentId] { return proxy }
253 // A real device can drop listening sockets while the app is suspended; the simulator never does.
254 foregroundObserver = foregroundObserver ?? NotificationCenter.default.addObserver(
255 forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main
256 ) { _ in
257 for proxy in proxies.values { proxy.ensureListening { _ in } }
258 }
259 let proxy = T3EnvironmentProxy()
260 proxies[environmentId] = proxy
261 return proxy
262 }
263
264 private var views: [WeakView] = []
265 private var listener: T3SocksListener?
266 private var port: UInt16?
267 private var waiting: [(UInt16) -> Void] = []
268 private var dataStore: WKWebsiteDataStore?
269
270 func store(proxyPort: UInt16) -> WKWebsiteDataStore {
271 if let dataStore { return dataStore }
272 let store = WKWebsiteDataStore.nonPersistent()
273 var proxy = ProxyConfiguration(
274 socksv5Proxy: .hostPort(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: proxyPort)!)
275 )
276 // Only the stand-in host belongs to the environment; everything else loads directly.
277 proxy.matchDomains = [T3Loopback.standInHost]
278 proxy.allowFailover = false
279 store.proxyConfigurations = [proxy]
280 dataStore = store
281 return store
282 }
283
284 func attach(_ view: T3TunnelWebView, onReady: @escaping (UInt16) -> Void) {
285 views = views.filter { $0.view != nil } + [WeakView(view: view)]
286 ensureListening(onReady)
287 }
288
289 /// Starts the listener, or restarts it on its port if iOS tore it down.
290 func ensureListening(_ onReady: @escaping (UInt16) -> Void) {
291 if let port, listener?.isListening == true { return onReady(port) }
292 waiting.append(onReady)
293 guard waiting.count == 1 else { return }
294 startListener(attempt: 0)
295 }
296
297 private func startListener(attempt: Int) {
298 listener?.stop()
299 let listener = T3SocksListener { [weak self] completion in
300 T3TunnelAccess.shared.request(
301 ask: { requestId in
302 DispatchQueue.main.async {
303 guard let view = self?.views.last(where: { $0.view != nil })?.view else {
304 return T3TunnelAccess.shared.resolve(requestId: requestId, url: nil)
305 }
306 view.onAccessRequest(["requestId": requestId])
307 }
308 },
309 completion: completion
310 )
311 }
312 self.listener = listener
313 listener.start(
314 port: port,
315 onReady: { [weak self] port in DispatchQueue.main.async { self?.ready(port) } },
316 onFailed: { [weak self, weak listener] in
317 DispatchQueue.main.async {
318 guard let self, let listener, self.listener === listener else { return }
319 if self.waiting.isEmpty { return self.ensureListening { _ in } }
320 // Startup failed before it was ready: try again shortly, then give the waiters up so
321 // a later reload starts over instead of queueing behind a listener that never came.
322 guard attempt < 4 else {
323 self.listener = nil
324 self.waiting = []
325 return
326 }
327 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
328 guard self.listener === listener, !self.waiting.isEmpty else { return }
329 self.startListener(attempt: attempt + 1)
330 }
331 }
332 }
333 )
334 }
335
336 var lastFailure: T3TunnelFailure? { listener?.lastFailure }
337
338 private func ready(_ port: UInt16) {
339 self.port = port
340 let waiting = self.waiting
341 self.waiting = []
342 for onReady in waiting { onReady(port) }
343 }
344 }
345
346 private struct WeakView {
347 weak var view: T3TunnelWebView?
348 }
349
350 /// Real iPhones never send loopback addresses to a webview's proxy (the simulator does), so the
351 /// view loads them under a stand-in host the proxy does carry, and shows `localhost` instead.
352 /// It is as long as `localhost`, so the proxy can swap the two in plain HTTP without
353 /// changing a message's length.
354 enum T3Loopback {
355 static let standInHost = "t3lo.test"
356
357 static func isLoopbackHost(_ host: String) -> Bool {
358 let host = host.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
359 if host == "localhost" || host.hasSuffix(".localhost") { return true }
360 if let address = IPv4Address(host) { return address.rawValue.first == 127 }
361 if let address = IPv6Address(host) { return address.isLoopback }
362 return false
363 }
364
365 static func standIn(_ url: URL) -> URL {
366 guard let host = url.host(percentEncoded: false), isLoopbackHost(host) else { return url }
367 return replacingHost(url, with: standInHost)
368 }
369
370 static func shown(_ url: URL) -> URL {
371 guard url.host(percentEncoded: false)?.lowercased() == standInHost else { return url }
372 return replacingHost(url, with: "localhost")
373 }
374
375 private static func replacingHost(_ url: URL, with host: String) -> URL {
376 guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
377 return url
378 }
379 components.host = host
380 return components.url ?? url
381 }
382 }