# CybSin in Swift (iOS 16+ / macOS 13+) — CryptoKit + URLSessionWebSocketTask

No third-party dependency. Reference implementation ships in the EMPTY app (`CybSin.swift`).

```swift
import CryptoKit
import Foundation
#if canImport(UIKit)
import UIKit
#endif

struct CybSinConfig {
    static var server = URL(string: "https://cybsin.com")!
    static let appKey = "cs_app_REPLACE_ME"              // from the CybSin console / MCP
}

enum CybSinError: Error { case http(Int, String), relay(String), crypto }

/// Device identity sent on register/login/devices. Only what the OS exposes.
func deviceIdentity() -> [String: Any] {
    var d: [String: Any] = ["bundle_id": Bundle.main.bundleIdentifier ?? "",
                            "app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "",
                            "locale": Locale.current.identifier]
    #if canImport(UIKit)
    let dev = UIDevice.current
    d["name"] = dev.name; d["platform"] = "ios"; d["model"] = dev.model
    d["os_version"] = dev.systemVersion; d["vendor_id"] = dev.identifierForVendor?.uuidString ?? ""
    #else
    d["name"] = Host.current().localizedName ?? "Mac"; d["platform"] = "macos"
    d["os_version"] = ProcessInfo.processInfo.operatingSystemVersionString
    d["hostname"] = Host.current().name ?? ""; d["os_user"] = NSUserName()
    #endif
    return d
}

final class CybSinClient {
    var token: String?            // keep in Keychain in a real app
    var deviceId: Int?

    private func call(_ path: String, _ body: [String: Any]?, auth: Bool = false) async throws -> [String: Any] {
        var req = URLRequest(url: CybSinConfig.server.appendingPathComponent(path))
        req.httpMethod = body == nil ? "GET" : "POST"
        req.setValue(CybSinConfig.appKey, forHTTPHeaderField: "X-App-Key")
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        if auth, let t = token { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }
        if let body { req.httpBody = try JSONSerialization.data(withJSONObject: body) }
        let (data, resp) = try await URLSession.shared.data(for: req)
        let code = (resp as? HTTPURLResponse)?.statusCode ?? 0
        let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
        guard (200..<300).contains(code) else {
            // 402 → {"detail":{"code":"payment_required",...}} — show a human message, do not loop
            throw CybSinError.http(code, String(data: data, encoding: .utf8) ?? "")
        }
        return json
    }

    func signIn(email: String, password: String, register: Bool) async throws {
        let r = try await call("/api/v1/\(register ? "register" : "login")",
                               ["email": email, "password": password, "device": deviceIdentity()])
        token = r["token"] as? String; deviceId = r["device_id"] as? Int
    }
    func pairNew() async throws -> (code: String, session: String, qr: String) {
        let r = try await call("/api/v1/pair/new", ["device_id": deviceId as Any], auth: true)
        return (r["code"] as! String, r["session_id"] as! String, r["qr"] as? String ?? "")
    }
    func pairJoin(code: String) async throws -> String {
        let r = try await call("/api/v1/pair/join", ["code": code, "device_id": deviceId as Any], auth: true)
        return r["session_id"] as! String
    }

    /// Opens the relay and runs the cybsin-v1 handshake. Returns a tunnel.
    func connect(session: String, role: String, code: String) async throws -> Tunnel {
        var c = URLComponents(url: CybSinConfig.server.appendingPathComponent("/ws/relay/\(session)"), resolvingAgainstBaseURL: false)!
        c.scheme = c.scheme == "https" ? "wss" : "ws"
        c.queryItems = [.init(name: "token", value: token), .init(name: "role", value: role),
                        .init(name: "app_key", value: CybSinConfig.appKey), .init(name: "device_id", value: deviceId.map(String.init))]
        let task = URLSession.shared.webSocketTask(with: c.url!)
        task.resume()
        // wait for {"t":"joined"}
        while true {
            if case .string(let s) = try await task.receive() {
                let t = (try? JSONSerialization.jsonObject(with: Data(s.utf8))) as? [String: Any]
                if t?["t"] as? String == "joined" { break }
                if let err = t?["code"] as? String { throw CybSinError.relay(err) }   // payment_required
                if t?["t"] as? String == "expired" { throw CybSinError.relay("expired") }
            }
        }
        return try await Tunnel(task: task, isHost: role == "host", code: code)
    }
}

final class Tunnel {
    private let task: URLSessionWebSocketTask
    private let key: SymmetricKey
    private let dirMe: UInt8, dirThem: UInt8
    private var tx: UInt64 = 0, rx: UInt64 = 0
    let sas: String

    init(task: URLSessionWebSocketTask, isHost: Bool, code: String) async throws {
        self.task = task
        dirMe = isHost ? 1 : 2; dirThem = isHost ? 2 : 1
        let priv = Curve25519.KeyAgreement.PrivateKey()
        let mine = priv.publicKey.rawRepresentation
        try await task.send(.data(mine))
        var theirs: Data?
        while theirs == nil {                       // first BINARY frame is the peer key
            if case .data(let d) = try await task.receive(), d.count == 32 { theirs = d }
        }
        let peer = try Curve25519.KeyAgreement.PublicKey(rawRepresentation: theirs!)
        let shared = try priv.sharedSecretFromKeyAgreement(with: peer)
        key = shared.hkdfDerivedSymmetricKey(using: SHA256.self, salt: Data(code.utf8),
                                             sharedInfo: Data("cybsin-v1".utf8), outputByteCount: 32)
        let (hostPub, guestPub) = isHost ? (mine, theirs!) : (theirs!, mine)
        let fp = Array(SHA256.hash(data: hostPub + guestPub))
        sas = String(format: "%02X%02X · %02X%02X", fp[0], fp[1], fp[2], fp[3])
    }

    private func nonce(_ dir: UInt8, _ counter: UInt64) throws -> ChaChaPoly.Nonce {
        var b = Data([dir, 0, 0, 0]); withUnsafeBytes(of: counter.bigEndian) { b.append(contentsOf: $0) }
        return try ChaChaPoly.Nonce(data: b)
    }
    func send(_ plaintext: Data) async throws {
        let box = try ChaChaPoly.seal(plaintext, using: key, nonce: nonce(dirMe, tx)); tx += 1
        try await task.send(.data(box.ciphertext + box.tag))         // wire = ciphertext || tag (NOT the combined form)
    }
    /// Returns decrypted payload, or nil when the peer left / session ended.
    func receive() async throws -> Data? {
        while true {
            switch try await task.receive() {
            case .data(let ct):
                guard ct.count >= 16 else { throw CybSinError.crypto }
                let box = try ChaChaPoly.SealedBox(nonce: try nonce(dirThem, rx), ciphertext: ct.dropLast(16), tag: ct.suffix(16))
                rx += 1
                return try ChaChaPoly.open(box, using: key)        // throws → fatal: close the tunnel
            case .string(let s):
                if s.contains("peer_left") || s.contains("expired") { return nil }
            @unknown default: continue
            }
        }
    }
    func close() { task.cancel(with: .normalClosure, reason: nil) }
}
```

Notes
- `Info.plist`: add `NSCameraUsageDescription` if you scan the pairing QR (`cybsin://pair?server=…&code=…&app=…`) with VisionKit `DataScannerViewController`; add `CFBundleURLTypes` with scheme `cybsin` if the QR should open your app.
- Local development server over plain HTTP needs `NSAppTransportSecurity → NSAllowsLocalNetworking = YES`.
- Store `token` in the Keychain. Never log it.
- Apply the same code on macOS; CryptoKit and URLSession are identical.
