import Cocoa import Security import FlutterMacOS import ServiceManagement import UniformTypeIdentifiers import AVFoundation import Vision import ImageIO import OSLog class MainFlutterWindow: NSWindow { private let runtimeLogger = Logger(subsystem: "com.example.meshportLab", category: "Runtime") private var vpnChannel: FlutterMethodChannel? private var qrScanner: MeshQRScanner? private var importing = false private let profileStore = LocalProfileStore() private let profileQueue = DispatchQueue(label: "com.meshport.local-profiles") override func close() { // Hiding keeps the Flutter engine, drafts and active network sessions alive. // Only the explicit Quit action terminates the application. qrScanner?.cancelScan() orderOut(nil) } override func awakeFromNib() { let flutterViewController = FlutterViewController() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) RegisterGeneratedPlugins(registry: flutterViewController) vpnChannel = FlutterMethodChannel(name: "meshport/system_vpn", binaryMessenger: flutterViewController.engine.binaryMessenger) vpnChannel?.setMethodCallHandler { [weak self] call, result in guard let self = self else { result(FlutterError(code:"WINDOW_CLOSED",message:"Window closed",details:nil)); return } if self.handleCapabilities(call, result:result) { return } let profileMethod = call.method.replacingOccurrences(of: "_proxy_profile", with: "_profile") if ["save_profile", "load_profile", "delete_profile", "profile_storage_status", "migrate_profiles"].contains(profileMethod) { let kind: StoredProfile = call.method.contains("_proxy_profile") ? .proxy : .network self.profileQueue.async { do { let value: Any? switch profileMethod { case "save_profile": guard let text = call.arguments as? String else { throw NSError(domain: "MeshPort.LocalProfile", code: 1) } try self.profileStore.save(text, kind: kind) value = nil case "load_profile": value = try self.profileStore.load(kind) case "delete_profile": try self.profileStore.delete(kind); value = nil case "migrate_profiles": try self.profileStore.migratePending(); value = nil default: value = ["path": self.profileStore.root.path, "migration_pending": try self.profileStore.migrationPending()] } DispatchQueue.main.async { result(value) } } catch { DispatchQueue.main.async { result(FlutterError(code: "PROFILE_STORAGE", message: "Could not read, save or migrate local configuration", details: (error as NSError).code)) } } } return } guard call.method == "launch", let args = call.arguments as? [String: Any], let socket = args["socket"] as? String, let uid = args["uid"] as? Int, uid == Int(getuid()), uid != 0, socket.hasPrefix("/tmp/meshport-vpn-"), socket.hasSuffix("/control.sock"), let helper = Bundle.main.path(forAuxiliaryExecutable: "meshport-vpn-helper") else { result(FlutterError(code: "VPN_UNAVAILABLE", message: "VPN helper missing or invalid launch request", details: nil)) return } func quoteShell(_ value: String) -> String { "'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'" } let command = quoteShell(helper) + " --socket " + quoteShell(socket) + " --uid " + String(uid) + " /dev/null 2>&1 &" let literal = command.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") DispatchQueue.global(qos: .userInitiated).async { var error: NSDictionary? let script = NSAppleScript(source: "do shell script \"" + literal + "\" with administrator privileges") let output = script?.executeAndReturnError(&error) DispatchQueue.main.async { if output == nil || error != nil { result(FlutterError(code: "VPN_AUTHORIZATION", message: "Administrator authorization cancelled or helper launch failed", details: nil)) } else { result(nil) } } } } super.awakeFromNib() } private func startupStatus() -> [String: Any] { var status = "unsupported" if #available(macOS 13.0, *) { switch SMAppService.mainApp.status { case .enabled: status = "enabled" case .requiresApproval: status = "requires_approval" case .notRegistered: status = "disabled" case .notFound: status = "not_found" @unknown default: status = "unknown" } } return ["login_status":status,"auto_connect":UserDefaults.standard.bool(forKey:"MeshPort.autoConnect")] } private func handleCapabilities(_ call: FlutterMethodCall, result: @escaping FlutterResult) -> Bool { if call.method == "runtime_log" { guard let message = call.arguments as? String, message.utf8.count <= 8192 else { result(FlutterError(code: "BAD_LOG", message: "Invalid diagnostic event", details: nil)); return true } // Flutter sends only credential-redacted diagnostic events, never profiles. runtimeLogger.notice("\(message, privacy: .public)") result(nil); return true } if call.method == "startup_status" { result(startupStatus()); return true } if call.method == "set_startup" { guard let args = call.arguments as? [String:Any] else { result(FlutterError(code:"BAD_ARGUMENT",message:"Invalid preferences",details:nil));return true } do { if let login = args["login"] as? Bool { if #available(macOS 13.0, *) { if login { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() } } else { throw NSError(domain:"MeshPort",code:13) } } if let connect = args["auto_connect"] as? Bool { UserDefaults.standard.set(connect,forKey:"MeshPort.autoConnect") } result(startupStatus()) } catch { result(FlutterError(code:"STARTUP_SETTINGS",message:"Unable to update login preferences; install the app in Applications and check System Settings",details:nil)) } return true } if call.method == "open_login_settings" { if #available(macOS 13.0, *) { SMAppService.openSystemSettingsLoginItems() } result(nil); return true } if call.method == "import_file" || call.method == "import_qr_image" { guard !importing && qrScanner == nil else { result(FlutterError(code:"IMPORT_BUSY",message:"Import already open",details:nil));return true } importing = true let panel = NSOpenPanel() panel.allowsMultipleSelection = false; panel.canChooseDirectories = false if #available(macOS 11.0, *) { panel.allowedContentTypes = call.method == "import_qr_image" ? [.image] : [.text,.json,.data] } panel.beginSheetModal(for:self) { [weak self] response in self?.importing = false guard response == .OK, let url = panel.url else { result(nil); return } let access = url.startAccessingSecurityScopedResource() defer { if access { url.stopAccessingSecurityScopedResource() } } do { let size = try url.resourceValues(forKeys:[.fileSizeKey]).fileSize ?? Int.max let isImage = call.method == "import_qr_image" guard size <= (isImage ? 20*1024*1024 : 1024*1024) else { throw NSError(domain:"MeshPort",code:1) } if isImage { guard let source = CGImageSourceCreateWithURL(url as CFURL,nil), let properties = CGImageSourceCopyPropertiesAtIndex(source,0,nil) as? [CFString:Any], let width = properties[kCGImagePropertyPixelWidth] as? Int, let height = properties[kCGImagePropertyPixelHeight] as? Int, width > 0 && height > 0 && width <= 20000000 / height else { throw NSError(domain:"MeshPort",code:2) } let request = VNDetectBarcodesRequest(); request.symbologies = [.qr] try VNImageRequestHandler(url:url,options:[:]).perform([request]) let codes = Set((request.results ?? []).compactMap { $0.payloadStringValue }) guard codes.count == 1, let code = codes.first, code.utf8.count <= 1024*1024 else { throw NSError(domain:"MeshPort",code:3) } result(code) } else { let data = try Data(contentsOf:url) guard data.count <= 1024*1024, let text = String(data:data,encoding:.utf8) else { throw NSError(domain:"MeshPort",code:4) } result(text) } } catch { result(FlutterError(code:"IMPORT_FAILED",message:"Invalid, oversized file or no unique QR code",details:nil)) } } return true } if call.method == "scan_qr" { guard !importing && qrScanner == nil else { result(FlutterError(code:"IMPORT_BUSY",message:"Import already open",details:nil));return true } importing = true AVCaptureDevice.requestAccess(for:.video) { [weak self] granted in DispatchQueue.main.async { guard let self = self else { result(nil);return } self.importing = false guard granted else { result(FlutterError(code:"CAMERA_PERMISSION",message:"Allow camera access in System Settings",details:nil));return } let scanner = MeshQRScanner { [weak self] text, failed in self?.qrScanner = nil if failed { result(FlutterError(code:"CAMERA_FAILED",message:"Camera unavailable",details:nil)) } else { result(text) } } self.qrScanner = scanner scanner.show(on:self) } } return true } return false } } // Only the native capture/panel lifetime lives here; Flutter owns imported drafts. private final class MeshQRPreview: NSView { let preview: AVCaptureVideoPreviewLayer init(session:AVCaptureSession) { preview = AVCaptureVideoPreviewLayer(session:session) super.init(frame:NSRect(x:0,y:0,width:640,height:400)) wantsLayer = true; preview.videoGravity = .resizeAspectFill layer?.addSublayer(preview) } required init?(coder:NSCoder) { fatalError("init(coder:) unsupported") } override func layout() { super.layout(); preview.frame = bounds } } private final class MeshQRScanner: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate, NSWindowDelegate { let session = AVCaptureSession() let queue = DispatchQueue(label:"MeshPort.qrCapture") let completion: (String?,Bool) -> Void var panel:NSPanel? weak var parent:NSWindow? var finished = false, lastFrame = Date.distantPast init(completion:@escaping (String?,Bool) -> Void) { self.completion = completion } func show(on window:NSWindow) { parent = window let panel = NSPanel(contentRect:NSRect(x:0,y:0,width:640,height:450),styleMask:[.titled,.closable],backing:.buffered,defer:false) panel.title = "扫描配置二维码"; panel.delegate = self; self.panel = panel let preview = MeshQRPreview(session:session) let cancel = NSButton(title:"取消",target:self,action:#selector(cancelScan)) let stack = NSStackView(views:[preview,cancel]); stack.orientation = .vertical; stack.spacing = 8 panel.contentView = stack preview.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([preview.widthAnchor.constraint(equalToConstant:640),preview.heightAnchor.constraint(equalToConstant:400)]) window.beginSheet(panel) queue.async { [weak self] in guard let self = self else { return } do { guard let device = AVCaptureDevice.default(for:.video) else { throw NSError(domain:"MeshPort",code:1) } let input = try AVCaptureDeviceInput(device:device), output = AVCaptureVideoDataOutput() output.alwaysDiscardsLateVideoFrames = true output.setSampleBufferDelegate(self,queue:self.queue) self.session.beginConfiguration() guard self.session.canAddInput(input), self.session.canAddOutput(output) else { self.session.commitConfiguration(); throw NSError(domain:"MeshPort",code:2) } self.session.addInput(input);self.session.addOutput(output);self.session.commitConfiguration() self.session.startRunning() } catch { DispatchQueue.main.async { self.finish(nil,failed:true) } } } } @objc func cancelScan() { finish(nil,failed:false) } func windowShouldClose(_ sender:NSWindow) -> Bool { cancelScan();return false } func finish(_ text:String?,failed:Bool) { guard !finished else { return }; finished = true if let panel = panel { parent?.endSheet(panel);panel.orderOut(nil) } queue.async { [self] in session.stopRunning() } completion(text,failed) } func captureOutput(_ output:AVCaptureOutput,didOutput buffer:CMSampleBuffer,from connection:AVCaptureConnection) { guard Date().timeIntervalSince(lastFrame) > 0.4 else { return };lastFrame=Date() let request = VNDetectBarcodesRequest();request.symbologies=[.qr] do { guard let image = CMSampleBufferGetImageBuffer(buffer) else { return } try VNImageRequestHandler(cvPixelBuffer:image,orientation:.up,options:[:]).perform([request]) let codes = Set((request.results ?? []).compactMap { $0.payloadStringValue }) if codes.count == 1, let text = codes.first, text.utf8.count <= 1024*1024 { DispatchQueue.main.async { [weak self] in self?.finish(text,failed:false) } } } catch { /* A frame may be temporarily unreadable; the user can cancel. */ } } }