Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Auth/AuthAPI.swift3// Description: Owner authentication (services/api/src/auth.ts): passkey login, logout, session state, adding this device's passkey4// (which the signer only accepts with an assertion from an already enrolled passkey), revoking sessions.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CryptoKit1011public struct AuthState: Codable, Sendable, Equatable {12 public let setupRequired: Bool13 public let authenticated: Bool14}1516struct LoginOptions: Codable, Sendable { let challengeId: String; let options: PasskeyRequestOptions }17struct RegistrationOptionsAnswer: Codable, Sendable { let challengeId: String; let options: PasskeyCreationOptions }18struct PendingDevice: Codable, Sendable { let pendingId: String; let options: PasskeyRequestOptions }1920/** The enrolment of another passkey, approved by an existing one: challenge = SHA-256("SPW-ENROLL-v1\n" + id + "\n" + publicKey). */21public struct PasskeyEnrolment: PasskeyApprovable, Equatable {22 public let credentialId: String23 /** base64url COSE public key, as the server stored it. The client cannot read it from its own registration without parsing CBOR:24 it is recomputed from the attestation the device just produced (see `AuthAPI.addPasskey`). */25 public let publicKey: String26 public func canonicalBytes() throws -> Data { Data("SPW-ENROLL-v1\n\(credentialId)\n\(publicKey)".utf8) }27}2829public struct AuthAPI: Sendable {30 let client: APIClient31 public init(_ client: APIClient) { self.client = client }3233 public func state() async throws -> AuthState { try await client.get("/auth/state") }3435 /** Passkey login. The session cookie is stored by the client when the server sets it. */36 public func login(with authenticator: PasskeyAuthenticator) async throws {37 let o: LoginOptions = try await client.post("/auth/login/options")38 guard o.options.rpId == nil || o.options.rpId == client.configuration.rpId else { throw ApprovalError.wrongRelyingParty(o.options.rpId) }39 let assertion = try await authenticator.assert(o.options, rpId: client.configuration.rpId)40 struct Body: Encodable, Sendable { let challengeId: String; let response: PasskeyAssertion }41 let _: OKResponse = try await client.post("/auth/login/verify", body: Body(challengeId: o.challengeId, response: assertion))42 }4344 public func logout() async {45 let _: OKResponse? = try? await client.post("/auth/logout")46 await client.forgetSession()47 }4849 /** Revoke every session of the owner, this one included. */50 public func revokeAllSessions() async throws {51 let _: OKResponse = try await client.post("/security/sessions/revoke-all")52 await client.forgetSession()53 }5455 /**56 Add a passkey for this device (authenticated). Two system sheets: the creation of the new passkey, then an assertion by an57 ALREADY ENROLLED passkey over the enrolment challenge — that second signature is what the signer verifies before it pins the new key.58 - Parameter existing: the authenticator that holds an already enrolled passkey (the same provider on Apple devices: iCloud Keychain offers it).59 */60 public func addPasskey(label: String, authenticator: PasskeyAuthenticator, existing: PasskeyAuthenticator? = nil) async throws {61 let o: RegistrationOptionsAnswer = try await client.post("/security/devices/options")62 let reg = try await authenticator.register(o.options, rpId: client.configuration.rpId)63 struct Verify: Encodable, Sendable { let challengeId: String; let response: PasskeyRegistration; let label: String }64 let pending: PendingDevice = try await client.post("/security/devices/verify", body: Verify(challengeId: o.challengeId, response: reg, label: String(label.prefix(40))))65 // the enrolment challenge commits to the new credential: require it to name the credential this device just created66 guard pending.pendingId == reg.id else { throw ApprovalError.inconsistent("pending passkey is not the one just created") }67 guard let attestation = Data(base64URL: reg.response.attestationObject), let cose = try? AttestationObject.credentialPublicKey(attestation) else {68 throw ApprovalError.unsupported("attestation of the new passkey could not be read")69 }70 let enrolment = PasskeyEnrolment(credentialId: reg.id, publicKey: cose.base64URL)71 let verified = try ApprovalBinding.verify(enrolment, options: pending.options, rpId: client.configuration.rpId)72 let assertion = try await (existing ?? authenticator).assert(verified.options, rpId: client.configuration.rpId)73 guard assertion.id != reg.id else { throw ApprovalError.inconsistent("the new passkey cannot approve its own enrolment") }74 struct Confirm: Encodable, Sendable { let pendingId: String; let assertion: PasskeyAssertion }75 let _: OKResponse = try await client.post("/security/devices/confirm", body: Confirm(pendingId: pending.pendingId, assertion: assertion))76 }77}7879/** Minimal reader of a WebAuthn attestation object: extracts the COSE credential public key from `authData`. */80public enum AttestationObject {81 public enum ParseError: Error { case malformed }8283 public static func credentialPublicKey(_ attestationObject: Data) throws -> Data {84 var r = CBORReader(attestationObject)85 guard case .map(let n) = try r.head() else { throw ParseError.malformed }86 var authData: Data?87 for _ in 0..<n {88 let key = try r.text()89 if key == "authData" { authData = try r.bytes() } else { try r.skip() }90 }91 guard let a = authData, a.count > 55, a[a.startIndex + 32] & 0x40 != 0 else { throw ParseError.malformed }92 let idLen = Int(a[a.startIndex + 53]) << 8 | Int(a[a.startIndex + 54])93 let start = a.startIndex + 55 + idLen94 guard start < a.endIndex else { throw ParseError.malformed }95 var k = CBORReader(Data(a[start...]))96 let begin = k.offset97 try k.skip()98 return Data(a[start...]).subdata(in: begin..<k.offset)99 }100}101102/** Just enough CBOR to walk an attestation object (definite lengths only, as WebAuthn requires). */103struct CBORReader {104 enum Head { case uint(UInt64), nint(UInt64), bytes(Int), text(Int), array(Int), map(Int), tag(UInt64), simple(UInt8) }105 let data: Data106 var offset = 0107 init(_ d: Data) { data = Data(d) }108109 mutating func byte() throws -> UInt8 {110 guard offset < data.count else { throw AttestationObject.ParseError.malformed }111 defer { offset += 1 }112 return data[offset]113 }114 mutating func head() throws -> Head {115 let b = try byte(), major = b >> 5, info = b & 0x1f116 var v: UInt64117 switch info {118 case 0..<24: v = UInt64(info)119 case 24: v = UInt64(try byte())120 case 25: v = 0; for _ in 0..<2 { v = v << 8 | UInt64(try byte()) }121 case 26: v = 0; for _ in 0..<4 { v = v << 8 | UInt64(try byte()) }122 case 27: v = 0; for _ in 0..<8 { v = v << 8 | UInt64(try byte()) }123 default: throw AttestationObject.ParseError.malformed124 }125 guard v <= UInt64(Int32.max) || major <= 1 || major >= 6 else { throw AttestationObject.ParseError.malformed }126 switch major {127 case 0: return .uint(v)128 case 1: return .nint(v)129 case 2: return .bytes(Int(v))130 case 3: return .text(Int(v))131 case 4: return .array(Int(v))132 case 5: return .map(Int(v))133 case 6: return .tag(v)134 default: return .simple(info)135 }136 }137 mutating func take(_ n: Int) throws -> Data {138 guard n >= 0, offset + n <= data.count else { throw AttestationObject.ParseError.malformed }139 defer { offset += n }140 return data.subdata(in: offset..<offset + n)141 }142 mutating func text() throws -> String {143 guard case .text(let n) = try head(), let s = String(data: try take(n), encoding: .utf8) else { throw AttestationObject.ParseError.malformed }144 return s145 }146 mutating func bytes() throws -> Data {147 guard case .bytes(let n) = try head() else { throw AttestationObject.ParseError.malformed }148 return try take(n)149 }150 mutating func skip() throws {151 switch try head() {152 case .uint, .nint, .simple: return153 case .bytes(let n), .text(let n): _ = try take(n)154 case .array(let n): for _ in 0..<n { try skip() }155 case .map(let n): for _ in 0..<(2 * n) { try skip() }156 case .tag: try skip()157 }158 }159}160