SPB Git

Repository Public

AuthAPI.swift 5.5 KB 82 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Authentication/AuthAPI.swift3// Description: Signing a device in: the WebAuthn passkey ceremony expressed as JSON for the server, and the fallback where a signed-in browser approves a short code. The system passkey sheet itself is presented by the application.4import Foundation56/// What the server asks the authenticator to sign.7public struct PasskeyChallenge: Sendable {8    public let challengeID: String9    public let challenge: Data10    public let relyingParty: String11    public let allowedCredentials: [Data]12}13/// What the platform authenticator answered (fields of ASAuthorizationPlatformPublicKeyCredentialAssertion).14public struct PasskeyAssertion: Sendable {15    public var credentialID: Data; public var clientDataJSON: Data; public var authenticatorData: Data; public var signature: Data; public var userHandle: Data?16    public init(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?) {17        self.credentialID = credentialID; self.clientDataJSON = clientDataJSON; self.authenticatorData = authenticatorData; self.signature = signature; self.userHandle = userHandle18    }19    /// The AuthenticationResponseJSON the server verifies (WebAuthn level 3 serialisation).20    var json: JSONValue {21        var response: [String: JSONValue] = ["clientDataJSON": .string(clientDataJSON.base64URL), "authenticatorData": .string(authenticatorData.base64URL), "signature": .string(signature.base64URL)]22        if let userHandle { response["userHandle"] = .string(userHandle.base64URL) }23        return .object(["id": .string(credentialID.base64URL), "rawId": .string(credentialID.base64URL), "type": .string("public-key"), "authenticatorAttachment": .string("platform"),24                        "clientExtensionResults": .object([:]), "response": .object(response)])25    }26}27public struct DeviceLinkStart: Decodable, Sendable {28    public var deviceCode: String; public var userCode: String; public var verifyUrl: URL; public var expiresInS: Int; public var intervalS: Int29}30public enum DeviceLinkStatus: Sendable, Equatable { case pending, denied, expired, approved }3132extension APIClient {33    private struct Options: Decodable {34        struct Cred: Decodable { var id: String }35        struct O: Decodable { var challenge: String; var rpId: String?; var allowCredentials: [Cred]? }36        var challengeId: String; var options: O37    }38    private func challenge(_ path: String, authenticated: Bool) async throws -> PasskeyChallenge {39        let o: Options = try await send("POST", path, authenticated: authenticated)40        guard let c = Data(base64URL: o.options.challenge), let rp = o.options.rpId ?? baseURL.host else { throw DriveError.invalidResponse("challenge") }41        return PasskeyChallenge(challengeID: o.challengeId, challenge: c, relyingParty: rp, allowedCredentials: (o.options.allowCredentials ?? []).compactMap { Data(base64URL: $0.id) })42    }43    public func loginChallenge() async throws -> PasskeyChallenge { try await challenge("/auth/login/options", authenticated: false) }44    /// Completes the sign-in: the server opens a device session and its token is stored in the token store.45    public func completeLogin(_ challenge: PasskeyChallenge, assertion: PasskeyAssertion, deviceName: String) async throws {46        struct Client: Encodable { var kind = "native"; var name: String }47        struct B: Encodable { var challengeId: String; var response: JSONValue; var client: Client }48        struct R: Decodable { var token: String }49        let r: R = try await send("POST", "/auth/login/verify", body: B(challengeId: challenge.challengeID, response: assertion.json, client: Client(name: deviceName)), authenticated: false)50        try tokens.writeToken(r.token)51    }52    /// A passkey confirmation for a sensitive operation of an open session.53    public func reauthChallenge() async throws -> PasskeyChallenge { try await challenge("/auth/reauth/options", authenticated: true) }54    public func completeReauth(_ challenge: PasskeyChallenge, assertion: PasskeyAssertion) async throws {55        struct B: Encodable { var challengeId: String; var response: JSONValue }56        let _: OK = try await send("POST", "/auth/reauth/verify", body: B(challengeId: challenge.challengeID, response: assertion.json))57    }5859    /// Starts linking this device: `userCode` is shown to the person, who approves it in a signed-in browser.60    public func startDeviceLink(deviceName: String) async throws -> DeviceLinkStart {61        struct B: Encodable { var name: String }62        return try await send("POST", "/auth/device/start", body: B(name: deviceName), authenticated: false)63    }64    /// Asks whether the code was approved. On approval the token is stored and `.approved` is returned — once.65    public func pollDeviceLink(_ deviceCode: String) async throws -> DeviceLinkStatus {66        struct B: Encodable { var deviceCode: String }67        struct R: Decodable { var status: String; var token: String? }68        let r: R = try await send("POST", "/auth/device/poll", body: B(deviceCode: deviceCode), authenticated: false)69        switch r.status {70        case "approved": guard let t = r.token else { throw DriveError.invalidResponse("jeton absent") }; try tokens.writeToken(t); return .approved71        case "pending": return .pending72        case "denied": return .denied73        default: return .expired74        }75    }76    /// Ends the device session on the server (best effort) and forgets the token.77    public func signOut() async {78        _ = try? await logout()79        try? tokens.deleteToken()80    }81}82
Files main
Menu

Theme