import CryptoKit import Foundation /// The device proof, byte for byte as the server builds it: /// `personapi.DeviceProofMessage`, Go's `json.Marshal` of /// `["equipo.person.device.v1", instance, id, challenge, nonce]`. /// Go escapes <, > and &, and leaves / alone; Swift's encoders do neither, /// so the array is written here. `device-proof-vectors.json`, owned by a Go /// test, holds the server's bytes. public enum DeviceProof { public static let audience = "equipo.person.device.v1" public static func message(instance: String, id: String, challenge: String, nonce: String) -> Data { let parts = [audience, instance, id, challenge, nonce].map(goJSONString) return Data(("[" + parts.joined(separator: ",") + "]").utf8) } /// The instance ID is the first element of the challenge, base64url JSON. public static func instance(fromChallenge challenge: String) -> String? { guard let data = Base64URL.decode(challenge), let array = try? JSONSerialization.jsonObject(with: data) as? [Any], let first = array.first as? String, !first.isEmpty else { return nil } return first } /// A fresh nonce: 256 random bits, base64url. public static func nonce() -> String { var bytes = [UInt8](repeating: 0, count: 32) let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) precondition(status == errSecSuccess, "no system randomness") return Base64URL.encode(Data(bytes)) } /// The body for `POST /auth/devices/exchange`. public struct Body: Codable, Sendable, Equatable { public var id: String public var deviceSecret: String public var challenge: String public var nonce: String public var signature: String } public static func body(for challenge: DeviceChallenge, key: Curve25519.Signing.PrivateKey, nonce: String) throws -> Body { guard let instance = instance(fromChallenge: challenge.challenge) else { throw PairingError.badChallenge } let signed = try key.signature(for: message(instance: instance, id: challenge.id, challenge: challenge.challenge, nonce: nonce)) return Body(id: challenge.id, deviceSecret: challenge.deviceSecret, challenge: challenge.challenge, nonce: nonce, signature: Base64URL.encode(signed)) } /// Go's encoding/json string: HTML-safe, 
 and 
 escaped, the /// short escapes for ", \, \n, \r and \t, \u00XX for other control bytes. static func goJSONString(_ s: String) -> String { var out = "\"" for scalar in s.unicodeScalars { switch scalar { case "\"": out += "\\\"" case "\\": out += "\\\\" case "\n": out += "\\n" case "\r": out += "\\r" case "\t": out += "\\t" // Go 1.22 and later write these two as short escapes. case "\u{8}": out += "\\b" case "\u{c}": out += "\\f" case "<", ">", "&", "\u{2028}", "\u{2029}": out += String(format: "\\u%04x", scalar.value) default: if scalar.value < 0x20 { out += String(format: "\\u%04x", scalar.value) } else { out.unicodeScalars.append(scalar) } } } return out + "\"" } } public enum Base64URL { public static func encode(_ data: Data) -> String { data.base64EncodedString().replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") } public static func decode(_ s: String) -> Data? { var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") while b.count % 4 != 0 { b += "=" } return Data(base64Encoded: b) } } public enum PairingError: Error, Sendable, Equatable { case badChallenge case expired case refused(String) }