Repository Public
1// Small platform services: the expiring clipboard, content-free notifications and the live-event stream.2import Foundation3import SharedVaultKit4import UniformTypeIdentifiers5import UserNotifications6import os7#if os(macOS)8import AppKit9#else10import UIKit11#endif1213// ── clipboard ──1415/// Copies text and removes it again after a delay.16/// macOS: the entry is marked `org.nspasteboard.ConcealedType` (clipboard managers that honour the convention do17/// not record it) and cleared after the delay only if the clipboard still holds it (change count unchanged).18/// iOS: the entry is local-only (never offered to Universal Clipboard) and carries a system-enforced expiration.19@MainActor20enum SecureClipboard {21 #if os(macOS)22 private static var clearTask: Task<Void, Never>?23 #endif2425 static func copy(_ value: String, secret: Bool, clearAfter seconds: Int) {26 #if os(macOS)27 let pb = NSPasteboard.general28 pb.clearContents()29 pb.setString(value, forType: .string)30 if secret { pb.setString("", forType: NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")) }31 let count = pb.changeCount32 clearTask?.cancel()33 guard secret, seconds > 0 else { return }34 clearTask = Task {35 try? await Task.sleep(for: .seconds(seconds))36 if !Task.isCancelled, NSPasteboard.general.changeCount == count { NSPasteboard.general.clearContents() }37 }38 #else39 var options: [UIPasteboard.OptionsKey: Any] = [:]40 if secret {41 options[.localOnly] = true42 if seconds > 0 { options[.expirationDate] = Date().addingTimeInterval(TimeInterval(seconds)) }43 }44 UIPasteboard.general.setItems([[UTType.utf8PlainText.identifier: value]], options: options)45 #endif46 }47}4849// ── notifications (never any content of the vault) ──5051enum Notifier {52 enum Kind: String, Sendable { case pairing, approval, shares, pendingSaved }5354 static func requestAuthorization() async {55 _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound])56 }5758 static func post(_ kind: Kind) async {59 let center = UNUserNotificationCenter.current()60 let settings = await center.notificationSettings()61 guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else { return }62 let c = UNMutableNotificationContent()63 c.title = "SP Vault"64 c.body = switch kind {65 case .pairing: "A device is asking to join your vault. Open SP Vault to review the request."66 case .approval: "An agent is waiting for your approval. Open SP Vault to review the request."67 case .shares: "Something was shared with you. Open SP Vault to see it."68 case .pendingSaved: "Items created from AutoFill were saved to your vault."69 }70 c.sound = .default71 try? await center.add(UNNotificationRequest(identifier: "spv.\(kind.rawValue)", content: c, trigger: nil))72 }73}7475// ── live events (SSE pokes: types only, never content) ──7677/// Server-sent events from `/api/v1/events`. Reconnects with backoff; stops when cancelled.78struct LiveEvents: Sendable {79 enum Event: String, Sendable { case sync, devices, pairing, shares, approval, activity }8081 let baseURL: URL82 let token: @Sendable () -> String?8384 /// Parses one SSE line; returns the event of a `data: {"type":…}` line.85 static func parse(line: String) -> Event? {86 guard line.hasPrefix("data:") else { return nil }87 let payload = line.dropFirst(5).trimmingCharacters(in: .whitespaces)88 guard let json = try? JSONValue.parse(payload), let type = json["type"]?.stringValue else { return nil }89 return Event(rawValue: type)90 }9192 func stream() -> AsyncStream<Event> {93 AsyncStream { continuation in94 let task = Task {95 var delay: Double = 196 let cfg = URLSessionConfiguration.ephemeral97 cfg.httpCookieStorage = nil; cfg.urlCache = nil; cfg.httpShouldSetCookies = false98 cfg.timeoutIntervalForRequest = 90 // the server pings every 25 s99 let session = URLSession(configuration: cfg)100 defer { session.invalidateAndCancel() }101 while !Task.isCancelled {102 if let t = token(), let url = URL(string: baseURL.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/api/v1/events") {103 var req = URLRequest(url: url)104 req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization")105 req.setValue("text/event-stream", forHTTPHeaderField: "Accept")106 req.httpShouldHandleCookies = false107 do {108 let (bytes, response) = try await session.bytes(for: req)109 if (response as? HTTPURLResponse)?.statusCode == 200 {110 delay = 1111 continuation.yield(.sync) // catch up on whatever happened while disconnected112 for try await line in bytes.lines { if let e = LiveEvents.parse(line: line) { continuation.yield(e) } }113 }114 } catch { /* offline or closed: retry below */ }115 }116 try? await Task.sleep(for: .seconds(delay))117 delay = min(delay * 2, 60)118 }119 continuation.finish()120 }121 continuation.onTermination = { _ in task.cancel() }122 }123 }124}125126let vaultLog = Logger(subsystem: "ai.spboucher.spvault", category: "app")127