Auto-start transmission when scanning QR code (merge)

This commit is contained in:
Leon Böttger committed 2025-08-09 19:26:43 +02:00
1 parent a0c6770c51
commit 8e4f633686
12 files changed
+328 -43

No files matched your search

@@ -57,6 +57,7 @@ class NearbyConnection {
private var clientSeq: Int32 = 0
private(set) var pinCode: String?
private(set) var authKey: SymmetricKey?
init(connection: NWConnection, id: String) {
@@ -471,6 +472,7 @@ class NearbyConnection {
let authString = NearbyConnection.hkdf(inputKeyMaterial: SymmetricKey(data: derivedSecretKey), salt: "UKEY2 v1 auth".data(using: .utf8)!, info: ukeyInfo, outputByteCount: 32)
let nextSecret = NearbyConnection.hkdf(inputKeyMaterial: SymmetricKey(data: derivedSecretKey), salt: "UKEY2 v1 next".data(using: .utf8)!, info: ukeyInfo, outputByteCount: 32)
authKey = authString
pinCode = NearbyConnection.pinCodeFromAuthKey(authString)
let salt = Data([0x82, 0xAA, 0x55, 0xA0, 0xD3, 0x97, 0xF8, 0x83, 0x46, 0xCA, 0x1C,
@@ -5,14 +5,16 @@
// Created by Grishka on 08.04.2023.
//
import Foundation
import Network
import System
#if os(iOS)
import UIKit
#endif
import Foundation
import Network
import System
import SwiftECC
import CryptoKit
public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearbyConnectionDelegate, OutboundNearbyConnectionDelegate {
private let sleepManager = SleepManager.shared
@@ -25,6 +27,11 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
private var startedDeviceDiscovery = false
private var browsers: [NWBrowser] = []
private let serviceTypes = ["_FC9F5ED42C8A._tcp."]
private var qrCodePublicKey: ECPublicKey?
private var qrCodePrivateKey: ECPrivateKey?
private var qrCodeAdvertisingToken: Data?
private var qrCodeNameEncryptionKey: SymmetricKey?
private var qrCodeData: Data?
public let endpointID: [UInt8] = generateEndpointID()
public var mainAppDelegate: (any MainAppDelegate)?
@@ -109,7 +116,7 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
func getEndpointInfo() -> EndpointInfo {
#if os(macOS)
let endpointInfo = EndpointInfo(name: Host.current().localizedName!, deviceType: .computer)
let endpointInfo = EndpointInfo(name: Host.current().localizedName ?? "Mac", deviceType: .computer)
#else
let endpointInfo = EndpointInfo(name: UIDevice.current.name, deviceType: .phone)
#endif
@@ -230,22 +237,56 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
}
guard let endpointID = endpointID(for: service) else { return }
var foundService = FoundServiceInfo(service: service)
guard case let NWBrowser.Result.Metadata.bonjour(txtRecord) = service.metadata else { return }
guard let endpointInfoEncoded = txtRecord.dictionary["n"] else { return }
guard let endpointInfo = Data.dataFromUrlSafeBase64(endpointInfoEncoded) else { return }
guard endpointInfo.count >= 19 else { return }
let deviceType = RemoteDeviceInfo.DeviceType.fromRawValue(value: (Int(endpointInfo[0]) >> 1) & 7)
let deviceNameLength = Int(endpointInfo[17])
guard endpointInfo.count >= deviceNameLength + 17 else { return }
guard let deviceName = String(data: endpointInfo.subdata(in: 18 ..< (18 + deviceNameLength)), encoding: .utf8) else { return }
let deviceInfo = RemoteDeviceInfo(name: deviceName, type: deviceType, id: endpointID)
guard let endpointInfoData = Data.dataFromUrlSafeBase64(endpointInfoEncoded) else { return }
guard var endpointInfo = EndpointInfo(data: endpointInfoData) else { return }
var deviceInfo: RemoteDeviceInfo?
if let _ = endpointInfo.name {
deviceInfo = addFoundDevice(foundService: &foundService, endpointInfo: endpointInfo, endpointID: endpointID)
}
if let qrData = endpointInfo.qrCodeData, let qrCodeAdvertisingToken = qrCodeAdvertisingToken, let qrCodeNameEncryptionKey = qrCodeNameEncryptionKey {
log("[NearbyConnectionManager] Device has QR data: \(qrData.base64EncodedString()), advertising token is \(qrCodeAdvertisingToken.base64EncodedString())")
if qrData == qrCodeAdvertisingToken {
if let deviceInfo = deviceInfo {
for delegate in shareExtensionDelegates {
delegate.startTransferWithQrCode(device: deviceInfo)
}
}
}
else if qrData.count > 28 {
do {
let box = try AES.GCM.SealedBox(combined: qrData)
let decryptedName = try AES.GCM.open(box, using: qrCodeNameEncryptionKey, authenticating: qrCodeAdvertisingToken)
guard let name = String.init(data: decryptedName, encoding: .utf8) else { return }
endpointInfo.name = name
let deviceInfo = addFoundDevice(foundService: &foundService, endpointInfo: endpointInfo, endpointID: endpointID)
for delegate in shareExtensionDelegates {
delegate.startTransferWithQrCode(device: deviceInfo)
}
} catch {
log("[NearbyConnectionManager] Error decrypting QR code data of an invisible device: \(error)")
}
}
}
}
private func addFoundDevice(foundService: inout FoundServiceInfo, endpointInfo: EndpointInfo, endpointID: String) -> RemoteDeviceInfo {
let deviceInfo = RemoteDeviceInfo(info: endpointInfo, id: endpointID)
foundService.device = deviceInfo
foundServices[endpointID] = foundService
for delegate in shareExtensionDelegates {
delegate.addDevice(device: deviceInfo)
}
return deviceInfo
}
@@ -256,6 +297,35 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
delegate.removeDevice(id: endpointID)
}
}
public func generateQrCodeKey() -> String{
let domain = Domain.instance(curve: .EC256r1)
let (pubKey, privKey) = domain.makeKeyPair()
qrCodePublicKey = pubKey
qrCodePrivateKey = privKey
var keyData = Data()
keyData.append(contentsOf: [0, 0, 2])
let keyBytes = Data(pubKey.w.x.asSignedBytes())
// Sometimes, for some keys, there will be a leading zero byte. Strip that, Android really hates it (it breaks the endpoint info)
keyData.append(keyBytes.suffixOfAtMost(numBytes: 32))
let ikm = SymmetricKey(data: keyData)
qrCodeAdvertisingToken = NearbyConnection.hkdf(inputKeyMaterial: ikm, salt: Data(), info: "advertisingContext".data(using: .utf8)!, outputByteCount: 16).data()
qrCodeNameEncryptionKey = NearbyConnection.hkdf(inputKeyMaterial: ikm, salt: Data(), info: "encryptionKey".data(using: .utf8)!, outputByteCount: 16)
qrCodeData = keyData
return keyData.urlSafeBase64EncodedString()
}
public func clearQrCodeKey(){
qrCodePublicKey = nil
qrCodePrivateKey = nil
qrCodeAdvertisingToken = nil
qrCodeNameEncryptionKey = nil
qrCodeData = nil
}
public func startOutgoingTransfer(deviceID: String, delegate: ShareExtensionDelegate, urls: [URL], textToSend: String?) {
@@ -265,6 +335,7 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
let nwconn = NWConnection(to: info.service.endpoint, using: NWParameters(tls: .none, tcp: tcp))
let conn = OutboundNearbyConnection(connection: nwconn, id: deviceID, urlsToSend: urls, textToSend: textToSend)
conn.delegate = self
conn.qrCodePrivateKey = qrCodePrivateKey
let transfer = OutgoingTransferInfo(service: info.service, device: info.device!, connection: conn, delegate: delegate)
outgoingTransfers[deviceID] = transfer
conn.start()
@@ -26,6 +26,7 @@ class OutboundNearbyConnection: NearbyConnection {
private var totalBytesSent: Int64 = 0
private var textPayloadID: Int64 = 0
public var qrCodePrivateKey: ECPrivateKey?
public var delegate: OutboundNearbyConnectionDelegate?
enum State {
@@ -174,7 +175,7 @@ class OutboundNearbyConnection: NearbyConnection {
frame.v1.type = .connectionRequest
frame.v1.connectionRequest = Location_Nearby_Connections_ConnectionRequestFrame()
frame.v1.connectionRequest.endpointID = String(bytes: NearbyConnectionManager.shared.endpointID, encoding: .ascii)!
frame.v1.connectionRequest.endpointName = endpointInfo.name
frame.v1.connectionRequest.endpointName = endpointInfo.name ?? "QuickDrop"
frame.v1.connectionRequest.endpointInfo = endpointInfo.serialize()
frame.v1.connectionRequest.mediums = [.wifiLan]
try sendFrameAsync(frame.serializedData())
@@ -277,6 +278,14 @@ class OutboundNearbyConnection: NearbyConnection {
pairedEncryption.v1.pairedKeyEncryption = Sharing_Nearby_PairedKeyEncryptionFrame()
pairedEncryption.v1.pairedKeyEncryption.secretIDHash = Data.randomData(length: 6)
pairedEncryption.v1.pairedKeyEncryption.signedData = Data.randomData(length: 72)
if let qrKey = qrCodePrivateKey, let authKey = authKey {
let signature = qrKey.sign(msg: authKey.data())
var serializedSignature = Data(signature.r)
serializedSignature.append(Data(signature.s))
pairedEncryption.v1.pairedKeyEncryption.qrCodeHandshakeData = serializedSignature
}
try sendTransferSetupFrame(pairedEncryption)
currentState = .sentPairedKeyEncryption
+58 -12
View File
@@ -7,6 +7,8 @@
import Foundation
import Network
import CryptoKit
import SwiftECC
protocol InboundNearbyConnectionDelegate {
@@ -36,6 +38,7 @@ public protocol MainAppDelegate {
public protocol ShareExtensionDelegate: AnyObject {
func addDevice(device: RemoteDeviceInfo)
func removeDevice(id: String)
func startTransferWithQrCode(device: RemoteDeviceInfo)
func connectionWasEstablished(pinCode: String)
func connectionFailed(with error: Error)
func transferAccepted()
@@ -45,19 +48,23 @@ public protocol ShareExtensionDelegate: AnyObject {
public struct RemoteDeviceInfo: Identifiable, Equatable {
public let name: String
public let name: String?
public let type: DeviceType
public let qrCodeData:Data?
public var id: String?
init(name: String, type: DeviceType, id: String? = nil) {
self.name = name
self.type = type
self.id = id
self.qrCodeData = nil
}
init(info: EndpointInfo) {
name = info.name
type = info.deviceType
init(info: EndpointInfo, id: String? = nil) {
self.name = info.name
self.type = info.deviceType
self.qrCodeData = info.qrCodeData
self.id = id
}
@@ -116,24 +123,63 @@ public struct FileMetadata {
struct EndpointInfo {
let name: String
var name: String?
let deviceType: RemoteDeviceInfo.DeviceType
let qrCodeData: Data?
init(name: String, deviceType: RemoteDeviceInfo.DeviceType) {
self.name = name
self.deviceType = deviceType
self.qrCodeData = nil
}
init?(data: Data) {
guard data.count > 17 else { return nil }
let deviceNameLength = Int(data[17])
guard data.count >= deviceNameLength + 18 else { return nil }
guard let deviceName = String(data: data[18 ..< (18 + deviceNameLength)], encoding: .utf8) else { return nil }
let rawDeviceType = Int(data[0] & 7) >> 1
name = deviceName
deviceType = RemoteDeviceInfo.DeviceType.fromRawValue(value: rawDeviceType)
let hasName = (data[0] & 0x10) == 0
let deviceNameLength: Int
let deviceName: String?
if hasName {
deviceNameLength = Int(data[17])
guard data.count >= deviceNameLength + 18 else { return nil }
guard let newDeviceName = String(data: data[18..<(18 + deviceNameLength)], encoding: .utf8) else { return nil }
deviceName = newDeviceName
}
else {
deviceNameLength = 0
deviceName = nil
}
let rawDeviceType: Int = Int(data[0] & 7) >> 1
self.name = deviceName
self.deviceType = RemoteDeviceInfo.DeviceType.fromRawValue(value: rawDeviceType)
var offset = 1 + 16
if hasName {
offset = offset + 1 + deviceNameLength
}
var qrCodeData: Data? = nil
// read TLV records, if any
while data.count - offset > 2 {
let type = data[offset]
let length = Int(data[offset+1])
offset = offset + 2
if data.count - offset >= length{
// QR code data
if type == 1 {
qrCodeData = data.subdata(in: offset..<offset + length)
}
offset = offset + length
}
}
self.qrCodeData = qrCodeData
}
@@ -146,7 +192,7 @@ struct EndpointInfo {
endpointInfo.append(UInt8.random(in: 0 ... 255))
}
// Device name in UTF-8 prefixed with 1-byte length
var nameChars = [UInt8](name.utf8)
var nameChars = [UInt8]((name ?? "").utf8)
if nameChars.count > 255 {
nameChars = [UInt8](nameChars[0 ..< 255])
}
+19 -2
View File
@@ -6,6 +6,7 @@
//
import Foundation
import CryptoKit
extension Data {
func urlSafeBase64EncodedString() -> String {
@@ -20,7 +21,7 @@ extension Data {
})
}
static func randomData(length: Int) -> Data {
var data = Data(count: length)
data.withUnsafeMutableBytes {
@@ -29,7 +30,16 @@ extension Data {
return data
}
func suffixOfAtMost(numBytes: Int) -> Data{
if count <= numBytes {
return self
}
return subdata(in: count-numBytes..<count)
}
static func dataFromUrlSafeBase64(_ str: String) -> Data? {
var regularB64 = String(str.map {
if $0 == "_" {
@@ -53,6 +63,13 @@ extension Data {
}
extension SymmetricKey{
func data() -> Data{
return withUnsafeBytes({return Data(bytes: $0.baseAddress!, count: $0.count)})
}
}
extension String {
var dataFromHex: Data {
var data = Data(capacity: count / 2)