Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteAuth/DeviceKey.swift10// Module : ClaudeRemoteAuth11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteModels89import CryptoKit90import Foundation91import Security9293/// The P-256 key binding a native session to this device. The private key never leaves the94/// device: Secure Enclave when available, otherwise a Keychain item that is not synchronised and95/// not migrated to other devices.96public protocol DeviceKey: Sendable {97 /// X9.63 uncompressed public key (65 bytes: 0x04 ‖ X ‖ Y).98 var publicKeyX963: Data { get }99 /// True when the private key is held by the Secure Enclave.100 var isHardwareBacked: Bool { get }101 /// DER-encoded ECDSA-P256-SHA256 signature of `message`.102 func signature(for message: Data) throws -> Data103}104105extension DeviceKey {106 /// `NativeDevice.publicKey` (standard base64).107 public var publicKeyBase64: String { publicKeyX963.base64EncodedString() }108}109110public protocol DeviceKeyStore: Sendable {111 /// Returns the device key, creating it on first use.112 func loadOrCreate() throws -> any DeviceKey113 func delete()114}115116/// The string signed to refresh a session (contract §2) and its signature encoding.117public enum RefreshSignature {118 public static func message(sessionId: String, challenge: String) -> Data {119 Data("cr-native-refresh:v1:\(sessionId):\(challenge)".utf8)120 }121122 /// base64 (standard) of the DER signature.123 public static func make(sessionId: String, challenge: String, key: any DeviceKey) throws -> String {124 try key.signature(for: message(sessionId: sessionId, challenge: challenge)).base64EncodedString()125 }126127 /// Verifies a signature the way the server does (tests, diagnostics).128 public static func verify(_ signatureBase64: String, sessionId: String, challenge: String, publicKeyX963: Data) -> Bool {129 guard let der = Data(base64Encoded: signatureBase64),130 let signature = try? P256.Signing.ECDSASignature(derRepresentation: der),131 let key = try? P256.Signing.PublicKey(x963Representation: publicKeyX963) else { return false }132 return key.isValidSignature(signature, for: message(sessionId: sessionId, challenge: challenge))133 }134}135136struct SecureEnclaveDeviceKey: DeviceKey {137 let key: SecureEnclave.P256.Signing.PrivateKey138 var publicKeyX963: Data { key.publicKey.x963Representation }139 var isHardwareBacked: Bool { true }140 func signature(for message: Data) throws -> Data { try key.signature(for: message).derRepresentation }141}142143/// A CryptoKit software key (simulator, Macs without a Secure Enclave, tests).144public struct SoftwareDeviceKey: DeviceKey {145 public let key: P256.Signing.PrivateKey146 public init(key: P256.Signing.PrivateKey = P256.Signing.PrivateKey()) { self.key = key }147 public var publicKeyX963: Data { key.publicKey.x963Representation }148 public var isHardwareBacked: Bool { false }149 public func signature(for message: Data) throws -> Data { try key.signature(for: message).derRepresentation }150}151152/// Production store.153///154/// - Secure Enclave available: the key is generated inside it (non-exportable by construction,155/// usable after first unlock, this device only). What the Keychain holds is CryptoKit's opaque156/// handle (`dataRepresentation`), which only this device's enclave can use.157/// - Otherwise: a CryptoKit key whose raw representation is a Keychain item with158/// `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`.159public struct KeychainDeviceKeyStore: DeviceKeyStore {160 private let keychain: any KeychainStoring161 private let preferSecureEnclave: Bool162 private static let enclaveAccount = "device-key.se"163 private static let softwareAccount = "device-key.sw"164165 public init(keychain: any KeychainStoring, preferSecureEnclave: Bool = true) {166 self.keychain = keychain167 self.preferSecureEnclave = preferSecureEnclave168 }169170 public func loadOrCreate() throws -> any DeviceKey {171 if let blob = try keychain.read(Self.enclaveAccount),172 let key = try? SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: blob) {173 return SecureEnclaveDeviceKey(key: key)174 }175 if let raw = try keychain.read(Self.softwareAccount), let key = try? P256.Signing.PrivateKey(rawRepresentation: raw) {176 return SoftwareDeviceKey(key: key)177 }178 if preferSecureEnclave, SecureEnclave.isAvailable {179 var error: Unmanaged<CFError>?180 if let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, [.privateKeyUsage], &error),181 let key = try? SecureEnclave.P256.Signing.PrivateKey(accessControl: access) {182 try keychain.write(key.dataRepresentation, account: Self.enclaveAccount)183 return SecureEnclaveDeviceKey(key: key)184 }185 }186 let key = P256.Signing.PrivateKey()187 try keychain.write(key.rawRepresentation, account: Self.softwareAccount)188 return SoftwareDeviceKey(key: key)189 }190191 public func delete() {192 try? keychain.delete(Self.enclaveAccount)193 try? keychain.delete(Self.softwareAccount)194 }195}196197/// Describes this device at sign-in (`NativeDevice` minus the key).198public struct DeviceDescriptor: Hashable, Sendable {199 public var name: String200 public var model: String201 public var platform: NativePlatform202 public var appVersion: String203204 public init(name: String, model: String, platform: NativePlatform, appVersion: String) {205 self.name = name206 self.model = model207 self.platform = platform208 self.appVersion = appVersion209 }210211 /// Hardware model identifier (`Mac16,5`, `iPhone18,2`).212 public static func hardwareModel() -> String {213 #if os(macOS)214 let name = "hw.model"215 #else216 let name = "hw.machine"217 #endif218 var size = 0219 sysctlbyname(name, nil, &size, nil, 0)220 guard size > 0 else { return "Apple device" }221 var buffer = [CChar](repeating: 0, count: size)222 sysctlbyname(name, &buffer, &size, nil, 0)223 return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)224 }225}226