SPB Git

Repository Public

SoftwarePasskeys.swift 5.3 KB 84 lines swift

1// Software WebAuthn authenticator (ES256, "none" attestation, user verified) — TESTS ONLY, never shipped.2// A port of the `Authenticator` class in tests/harness.ts; its credentials can be exported to / imported from the3// Node helper so that a TypeScript device and a Swift device share the passkey of one account.4import CryptoKit5import Foundation6@testable import SharedVaultKit78final class SoftwarePasskeys: PasskeyProvider, @unchecked Sendable {9    struct Credential { var id: String; var key: P256.Signing.PrivateKey; var userHandle: String; var counter: UInt32 }1011    private let lock = NSLock()12    private var creds: [Credential] = []13    private var _getCount = 014    let origin: String1516    init(origin: String = TestEnv.origin) { self.origin = origin }1718    /// Number of assertions made (lets tests tell a passkey step-up from a device-key step-up).19    var getCount: Int { lock.lock(); defer { lock.unlock() }; return _getCount }2021    private func clientData(_ type: String, _ challenge: String) -> Data {22        (["type": .string(type), "challenge": .string(challenge), "origin": .string(origin), "crossOrigin": false] as JSONValue).serialized()23    }2425    func create(options: JSONValue) async throws -> JSONValue {26        guard let rpId = options["rp"]?["id"]?.stringValue, let challenge = options["challenge"]?.stringValue, let userId = options["user"]?["id"]?.stringValue else {27            throw PasskeyError.invalidOptions("registration")28        }29        let key = P256.Signing.PrivateKey(), id = SPV1.random(16), pub = key.publicKey.x963Representation30        var authData = SPV1.sha256(SPV1.utf8(rpId))31        authData.append(0x5d) // UP | UV | BE | BS | AT32        authData.append(Data(count: 4)); authData.append(Data(count: 16))33        authData.append(contentsOf: [0, UInt8(id.count)]); authData.append(id)34        authData.append(try PasskeyCrypto.coseKey(publicKeyX963: pub))35        let attestationObject = CBOR.map([(CBOR.text("fmt"), CBOR.text("none")), (CBOR.text("attStmt"), CBOR.map([])), (CBOR.text("authData"), CBOR.bytes(authData))])36        lock.withLock { creds.append(Credential(id: SPV1.b64u(id), key: key, userHandle: userId, counter: 0)) }37        return [38            "id": .string(SPV1.b64u(id)), "rawId": .string(SPV1.b64u(id)), "type": "public-key", "clientExtensionResults": .object(JSONObject()), "authenticatorAttachment": "platform",39            "response": ["clientDataJSON": .string(SPV1.b64u(clientData("webauthn.create", challenge))), "attestationObject": .string(SPV1.b64u(attestationObject)), "transports": ["internal"]],40        ]41    }4243    func get(options: JSONValue) async throws -> JSONValue {44        guard let rpId = options["rpId"]?.stringValue, let challenge = options["challenge"]?.stringValue else { throw PasskeyError.invalidOptions("authentication") }45        let allowed = (options["allowCredentials"]?.arrayValue ?? []).compactMap { $0["id"]?.stringValue }46        let picked: Credential? = lock.withLock {47            guard let idx = creds.lastIndex(where: { allowed.isEmpty || allowed.contains($0.id) }) else { return nil }48            creds[idx].counter += 149            _getCount += 150            return creds[idx]51        }52        guard let c = picked else { throw PasskeyError.failed("no passkey for this site") }53        var authData = SPV1.sha256(SPV1.utf8(rpId))54        authData.append(0x1d) // UP | UV | BE | BS55        authData.append(contentsOf: [UInt8(c.counter >> 24), UInt8((c.counter >> 16) & 255), UInt8((c.counter >> 8) & 255), UInt8(c.counter & 255)])56        let cdj = clientData("webauthn.get", challenge)57        let signature = try c.key.signature(for: authData + SPV1.sha256(cdj)).derRepresentation58        return [59            "id": .string(c.id), "rawId": .string(c.id), "type": "public-key", "clientExtensionResults": .object(JSONObject()), "authenticatorAttachment": "platform",60            "response": ["clientDataJSON": .string(SPV1.b64u(cdj)), "authenticatorData": .string(SPV1.b64u(authData)), "signature": .string(SPV1.b64u(signature)), "userHandle": .string(c.userHandle)],61        ]62    }6364    // ── export / import (JWK private key + credential id + user handle + counter), shared with Tests/Tools/ts-device.ts ──65    func exportCredentials() -> JSONValue {66        lock.lock(); defer { lock.unlock() }67        return .array(creds.map { c in68            let pub = c.key.publicKey.x963Representation69            return ["id": .string(c.id), "userHandle": .string(c.userHandle), "counter": .number(Double(c.counter)),70                    "jwk": ["kty": "EC", "crv": "P-256", "d": .string(SPV1.b64u(c.key.rawRepresentation)),71                            "x": .string(SPV1.b64u(Data(pub[pub.startIndex + 1..<pub.startIndex + 33]))), "y": .string(SPV1.b64u(Data(pub[pub.startIndex + 33..<pub.startIndex + 65])))]]72        })73    }7475    func importCredentials(_ list: JSONValue) throws {76        var out: [Credential] = []77        for c in list.arrayValue ?? [] {78            guard let id = c["id"]?.stringValue, let uh = c["userHandle"]?.stringValue, let counter = c["counter"]?.intValue, let d = c["jwk"]?["d"]?.stringValue else { throw PasskeyError.invalidOptions("credential export") }79            out.append(Credential(id: id, key: try P256.Signing.PrivateKey(rawRepresentation: try SPV1.unb64u(d)), userHandle: uh, counter: UInt32(counter)))80        }81        lock.lock(); creds = out; lock.unlock()82    }83}84
Files main
Menu

Theme