SPB Git

Repository Public

SoftwareAuthenticator.swift 15.8 KB 328 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteTestSupport/SoftwareAuthenticator.swift10// Module           : ClaudeRemoteTestSupport11// 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 ClaudeRemoteAuth89import ClaudeRemoteCore90import ClaudeRemoteModels91import CryptoKit92import Foundation9394/// A software WebAuthn authenticator for tests: produces assertions (and "none" attestations)95/// that a real WebAuthn server verifies, from a known P-256 credential key.96///97/// TEST SUPPORT ONLY. It performs no user verification of any kind — it merely sets the UV flag.98public final class SoftwareAuthenticator: PasskeyAuthenticator, @unchecked Sendable {99    public struct Request: Sendable {100        public var relyingParty: String101        public var challenge: Data102        public var allowCredentials: [Data]103    }104105    public let privateKey: P256.Signing.PrivateKey106    public let credentialID: Data107    public let userHandle: Data?108    /// Origin written in clientDataJSON; Apple platform authenticators use `https://<rpId>`.109    public let origin: String110    private let lock = NSLock()111    private var counter: UInt32112    private var _requests: [Request] = []113    private var _failure: PasskeyError?114115    public init(privateKey: P256.Signing.PrivateKey = P256.Signing.PrivateKey(), credentialID: Data = Data((0..<16).map { _ in UInt8.random(in: 0...255) }),116                userHandle: Data? = nil, origin: String, signCount: UInt32 = 0) {117        self.privateKey = privateKey118        self.credentialID = credentialID119        self.userHandle = userHandle120        self.origin = origin121        counter = signCount122    }123124    /// From fixture values: PEM (PKCS#8 or SEC1) private key, base64url credential id and user handle.125    public convenience init(privateKeyPEM: String, credentialID: String, userHandle: String?, origin: String, signCount: UInt32 = 0) throws {126        guard let id = Base64URL.decode(credentialID) else { throw PasskeyError(.failed, "invalid credential id in fixture") }127        self.init(privateKey: try P256.Signing.PrivateKey(pemRepresentation: privateKeyPEM), credentialID: id,128                  userHandle: userHandle.flatMap(Base64URL.decode), origin: origin, signCount: signCount)129    }130131    public var requests: [Request] { lock.withLock { _requests } }132    /// When set, every ceremony throws this (cancelled sheet, missing association…).133    public var failure: PasskeyError? {134        get { lock.withLock { _failure } }135        set { lock.withLock { _failure = newValue } }136    }137138    public func assertion(relyingParty: String, challenge: Data, allowCredentials: [Data]) async throws -> PasskeyAssertionCredential {139        let count: UInt32 = try lock.withLock {140            _requests.append(Request(relyingParty: relyingParty, challenge: challenge, allowCredentials: allowCredentials))141            if let _failure { throw _failure }142            if counter > 0 { counter += 1 }143            return counter144        }145        if !allowCredentials.isEmpty, !allowCredentials.contains(credentialID) {146            throw PasskeyError(.failed, "no matching credential on this authenticator")147        }148        let clientData = clientDataJSON(type: "webauthn.get", challenge: challenge)149        let authData = authenticatorData(relyingParty: relyingParty, flags: 0x05, counter: count) // UP | UV150        let signature = try privateKey.signature(for: authData + Data(SHA256.hash(data: clientData))).derRepresentation151        return PasskeyAssertionCredential(credentialID: credentialID, clientDataJSON: clientData, authenticatorData: authData,152                                          signature: signature, userHandle: userHandle)153    }154155    public func registration(relyingParty: String, challenge: Data, userName: String, userID: Data, excludeCredentials: [Data]) async throws -> PasskeyRegistrationCredential {156        try lock.withLock {157            _requests.append(Request(relyingParty: relyingParty, challenge: challenge, allowCredentials: []))158            if let _failure { throw _failure }159        }160        if excludeCredentials.contains(credentialID) { throw PasskeyError(.alreadyRegistered, "credential excluded") }161        let clientData = clientDataJSON(type: "webauthn.create", challenge: challenge)162        let raw = privateKey.publicKey.rawRepresentation // X ‖ Y163        var cose = Data([0xA5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20])164        cose.append(raw.prefix(32))165        cose.append(contentsOf: [0x22, 0x58, 0x20])166        cose.append(raw.suffix(32))167        var authData = authenticatorData(relyingParty: relyingParty, flags: 0x45, counter: 0) // UP | UV | AT168        authData.append(Data(repeating: 0, count: 16)) // AAGUID169        authData.append(contentsOf: [UInt8(credentialID.count >> 8), UInt8(credentialID.count & 0xFF)])170        authData.append(credentialID)171        authData.append(cose)172        // CBOR {"fmt": "none", "attStmt": {}, "authData": bstr}173        var attestation = Data([0xA3, 0x63]) + Data("fmt".utf8) + Data([0x64]) + Data("none".utf8)174        attestation += Data([0x67]) + Data("attStmt".utf8) + Data([0xA0, 0x68]) + Data("authData".utf8)175        attestation += authData.count < 256 ? Data([0x58, UInt8(authData.count)]) : Data([0x59, UInt8(authData.count >> 8), UInt8(authData.count & 0xFF)])176        attestation += authData177        return PasskeyRegistrationCredential(credentialID: credentialID, clientDataJSON: clientData, attestationObject: attestation, transports: ["internal"])178    }179180    private func clientDataJSON(type: String, challenge: Data) -> Data {181        Data(#"{"type":"\#(type)","challenge":"\#(Base64URL.encode(challenge))","origin":"\#(origin)","crossOrigin":false}"#.utf8)182    }183184    private func authenticatorData(relyingParty: String, flags: UInt8, counter: UInt32) -> Data {185        var data = Data(SHA256.hash(data: Data(relyingParty.utf8)))186        data.append(flags)187        data.append(contentsOf: [UInt8(counter >> 24), UInt8((counter >> 16) & 0xFF), UInt8((counter >> 8) & 0xFF), UInt8(counter & 0xFF)])188        return data189    }190}191192/// Device-owner verification scripted by the test.193public final class MockLocalAuthenticator: LocalAuthenticating, @unchecked Sendable {194    private let lock = NSLock()195    private var _result: Result<Void, LocalAuthError>196    private var _reasons: [String] = []197    private var _available: Bool198    private let kind: BiometryKind199200    public init(result: Result<Void, LocalAuthError> = .success(()), available: Bool = true, biometry: BiometryKind = .touchID) {201        _result = result202        _available = available203        kind = biometry204    }205206    public var result: Result<Void, LocalAuthError> {207        get { lock.withLock { _result } }208        set { lock.withLock { _result = newValue } }209    }210    public var available: Bool {211        get { lock.withLock { _available } }212        set { lock.withLock { _available = newValue } }213    }214    /// Reasons of every prompt shown.215    public var reasons: [String] { lock.withLock { _reasons } }216217    public func biometry() -> BiometryKind { kind }218    public func canAuthenticate() -> Bool { available }219    public func authenticate(reason: String) async throws {220        let r: Result<Void, LocalAuthError> = lock.withLock {221            _reasons.append(reason)222            return _available ? _result : .failure(.unavailable)223        }224        try r.get()225    }226}227228/// Records local notifications instead of posting them.229public final class RecordingNotificationCenter: UserNotificationPosting, @unchecked Sendable {230    private let lock = NSLock()231    private var _posted: [LocalNotificationContent] = []232    private var _removed: [String] = []233    private var _badge: Int?234    private var _authorized: Bool235236    public init(authorized: Bool = true) { _authorized = authorized }237238    public var posted: [LocalNotificationContent] { lock.withLock { _posted } }239    public var removed: [String] { lock.withLock { _removed } }240    public var badge: Int? { lock.withLock { _badge } }241    public var authorized: Bool {242        get { lock.withLock { _authorized } }243        set { lock.withLock { _authorized = newValue } }244    }245246    public func authorizationGranted() async -> Bool { authorized }247    public func requestAuthorization() async -> Bool { authorized }248    public func post(_ content: LocalNotificationContent) async { lock.withLock { _posted.append(content) } }249    public func remove(identifiers: [String]) async { lock.withLock { _removed.append(contentsOf: identifiers) } }250    public func setBadge(_ count: Int) async { lock.withLock { _badge = count } }251}252253/// RFC 6238 TOTP (SHA-1, 6 digits, 30 s) for integration tests.254public enum TOTP {255    public static func code(secretBase32: String, at date: Date = Date()) -> String? {256        guard let key = base32Decode(secretBase32) else { return nil }257        var counter = UInt64(date.timeIntervalSince1970 / 30).bigEndian258        let mac = Data(HMAC<Insecure.SHA1>.authenticationCode(for: Data(bytes: &counter, count: 8), using: SymmetricKey(data: key)))259        let offset = Int(mac[mac.count - 1] & 0x0F)260        let value = (UInt32(mac[offset] & 0x7F) << 24) | (UInt32(mac[offset + 1]) << 16) | (UInt32(mac[offset + 2]) << 8) | UInt32(mac[offset + 3])261        return String(format: "%06u", value % 1_000_000)262    }263264    public static func base32Decode(_ input: String) -> Data? {265        let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")266        var bits = 0, value = 0267        var out = Data()268        for ch in input.uppercased() where ch != "=" && ch != " " {269            guard let index = alphabet.firstIndex(of: ch) else { return nil }270            value = (value << 5) | index271            bits += 5272            if bits >= 8 {273                out.append(UInt8((value >> (bits - 8)) & 0xFF))274                bits -= 8275            }276        }277        return out278    }279}280281/// Values of the live dev stack, read from the JSON file named by `CR_IT_FIXTURES`.282/// Integration tests are skipped unless both `CR_IT_BASE_URL` and `CR_IT_FIXTURES` are set.283public struct IntegrationFixtures: Sendable {284    public var baseURL: URL285    public var username: String286    public var password: String287    public var totpSecret: String?288    public var passkeyPrivateKeyPEM: String?289    public var passkeyCredentialID: String?290    public var passkeyUserHandle: String?291    /// Origin the server expects in clientDataJSON (`CR_PUBLIC_ORIGIN`); defaults to the base URL.292    public var origin: String293    public var projectId: String?294    public var shellSessionId: String?295    public var pushTopic: String?296297    /// Nil when the environment is not configured (tests then skip).298    public static func load(environment: [String: String] = ProcessInfo.processInfo.environment) -> IntegrationFixtures? {299        guard let base = environment["CR_IT_BASE_URL"].flatMap(URL.init(string:)), let path = environment["CR_IT_FIXTURES"],300              let data = try? Data(contentsOf: URL(fileURLWithPath: path)),301              let json = try? JSONDecoder().decode(JSONValue.self, from: data) else { return nil }302        /// First match among dotted key paths (`user.username`) — the dev stack nests its values.303        func string(_ paths: String...) -> String? {304            for path in paths {305                var node: JSONValue? = json306                for part in path.split(separator: ".") { node = node?[String(part)] }307                if let v = node?.stringValue { return v }308            }309            return nil310        }311        guard let username = string("user.username", "username"), let password = string("user.password", "password") else { return nil }312        var origin = string("origin", "publicOrigin") ?? base.absoluteString313        if origin.hasSuffix("/") { origin.removeLast() }314        return IntegrationFixtures(315            baseURL: base, username: username, password: password, totpSecret: string("totp.secret", "totpSecret"),316            passkeyPrivateKeyPEM: string("passkey.privateKeyPem", "passkeyPrivateKeyPem", "passkey.privateKeyPEM"),317            passkeyCredentialID: string("passkey.credentialId", "credentialId"),318            passkeyUserHandle: string("passkey.userHandle", "userHandle"),319            origin: origin, projectId: string("project.id", "projectId"), shellSessionId: string("shellSession.id", "shellSessionId"),320            pushTopic: string("native.bundleId"))321    }322323    public func authenticator() throws -> SoftwareAuthenticator? {324        guard let pem = passkeyPrivateKeyPEM, let id = passkeyCredentialID else { return nil }325        return try SoftwareAuthenticator(privateKeyPEM: pem, credentialID: id, userHandle: passkeyUserHandle, origin: origin)326    }327}328
Files main
Menu

Theme