Graphley / app · graphley.ai / Sources / OwnerMetricsKit / PasskeyClient.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// A WebAuthn challenge from projectatom.ai, ready for AuthenticationServices. |
| 4 | public struct PasskeyChallenge: Sendable { |
| 5 | public let id: String |
| 6 | public let challenge: Data |
| 7 | public let userID: Data |
| 8 | public let userName: String |
| 9 | public let excludedCredentialIDs: [Data] |
| 10 | } |
| 11 | |
| 12 | /// What the platform authenticator returned for a sign-in. |
| 13 | public struct PasskeyAssertion: Sendable { |
| 14 | public let credentialID: Data |
| 15 | public let clientDataJSON: Data |
| 16 | public let authenticatorData: Data |
| 17 | public let signature: Data |
| 18 | public let userID: Data |
| 19 | public init(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userID: Data) { |
| 20 | self.credentialID = credentialID |
| 21 | self.clientDataJSON = clientDataJSON |
| 22 | self.authenticatorData = authenticatorData |
| 23 | self.signature = signature |
| 24 | self.userID = userID |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | /// What the platform authenticator returned for a new passkey. |
| 29 | public struct PasskeyRegistration: Sendable { |
| 30 | public let credentialID: Data |
| 31 | public let clientDataJSON: Data |
| 32 | public let attestationObject: Data |
| 33 | public init(credentialID: Data, clientDataJSON: Data, attestationObject: Data) { |
| 34 | self.credentialID = credentialID |
| 35 | self.clientDataJSON = clientDataJSON |
| 36 | self.attestationObject = attestationObject |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | public struct PasskeyInfo: Identifiable, Sendable, Decodable, Equatable { |
| 41 | public let id: String |
| 42 | public let createdAt: String |
| 43 | public let lastUsedAt: String? |
| 44 | } |
| 45 | |
| 46 | /// Passkey sign-in for the owner dashboard: projectatom.ai/api/graphley/passkeys/<action>. |
| 47 | public struct PasskeyClient: Sendable { |
| 48 | public static let relyingParty = "projectatom.ai" |
| 49 | let transport: @Sendable (URLRequest) async throws -> MetricsClient.Reply |
| 50 | |
| 51 | public init() { transport = MetricsClient.send } |
| 52 | init(transport: @escaping @Sendable (URLRequest) async throws -> MetricsClient.Reply) { self.transport = transport } |
| 53 | |
| 54 | /// The one-time code in a `graphley://passkey-setup?code=…` link, if the URL is one. |
| 55 | public static func setupCode(from url: URL) -> String? { |
| 56 | guard url.scheme == "graphley", url.host == "passkey-setup", |
| 57 | let code = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "code" })?.value, |
| 58 | MetricsClient.isValidSession(code) else { return nil } |
| 59 | return code |
| 60 | } |
| 61 | |
| 62 | public func signInChallenge() async throws -> PasskeyChallenge { |
| 63 | try challenge(try await post("login-options", body: Empty())) |
| 64 | } |
| 65 | |
| 66 | public func signIn(challengeID: String, assertion: PasskeyAssertion) async throws -> String { |
| 67 | let body = Answer(challengeId: challengeID, response: .init( |
| 68 | id: assertion.credentialID.base64URL, rawId: assertion.credentialID.base64URL, |
| 69 | response: AssertionBody(clientDataJSON: assertion.clientDataJSON.base64URL, |
| 70 | authenticatorData: assertion.authenticatorData.base64URL, |
| 71 | signature: assertion.signature.base64URL, |
| 72 | userHandle: assertion.userID.base64URL))) |
| 73 | guard let session = try decode(Signed.self, try await post("login", body: body)).session else { throw MetricsError.invalidResponse } |
| 74 | return session |
| 75 | } |
| 76 | |
| 77 | public func registrationChallenge(setupCode: String?, session: String?) async throws -> PasskeyChallenge { |
| 78 | do { |
| 79 | return try challenge(try await post("register-options", body: Setup(setupCode: setupCode), session: session)) |
| 80 | } catch MetricsError.passkeyRejected where setupCode != nil { |
| 81 | throw MetricsError.setupLinkInvalid |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// Returns a new session when the passkey was added with a setup link. |
| 86 | public func register(challengeID: String, registration: PasskeyRegistration, session: String?) async throws -> String? { |
| 87 | let body = Answer(challengeId: challengeID, response: .init( |
| 88 | id: registration.credentialID.base64URL, rawId: registration.credentialID.base64URL, |
| 89 | response: RegistrationBody(clientDataJSON: registration.clientDataJSON.base64URL, |
| 90 | attestationObject: registration.attestationObject.base64URL, |
| 91 | transports: ["internal", "hybrid"]))) |
| 92 | let reply: Data |
| 93 | do { reply = try await post("register", body: body, session: session) } |
| 94 | catch MetricsError.lastPasskey { throw MetricsError.passkeyAlreadyAdded } |
| 95 | return try decode(Signed.self, reply).session |
| 96 | } |
| 97 | |
| 98 | public func passkeys(session: String) async throws -> [PasskeyInfo] { |
| 99 | try decode(Listing.self, try await post("list", body: Empty(), session: session)).passkeys |
| 100 | } |
| 101 | |
| 102 | public func remove(id: String, session: String) async throws { |
| 103 | _ = try await post("remove", body: Removal(id: id), session: session) |
| 104 | } |
| 105 | |
| 106 | public func signOut(session: String) async { |
| 107 | _ = try? await post("sign-out", body: Empty(), session: session) |
| 108 | } |
| 109 | |
| 110 | private func post(_ action: String, body: some Encodable, session: String? = nil) async throws -> Data { |
| 111 | var request = URLRequest(url: URL(string: "https://projectatom.ai/api/graphley/passkeys/" + action)!, |
| 112 | cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 25) |
| 113 | request.httpMethod = "POST" |
| 114 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 115 | request.setValue("application/json", forHTTPHeaderField: "Accept") |
| 116 | if let session, MetricsClient.isValidSession(session) { |
| 117 | request.setValue("Bearer " + session, forHTTPHeaderField: "Authorization") |
| 118 | } |
| 119 | request.httpBody = try JSONEncoder().encode(body) |
| 120 | let result: MetricsClient.Reply |
| 121 | do { result = try await transport(request) } |
| 122 | catch is CancellationError { throw CancellationError() } |
| 123 | catch { throw MetricsError.unavailable } |
| 124 | switch result.code { |
| 125 | case 200: break |
| 126 | case 401, 404: throw MetricsError.passkeyRejected |
| 127 | case 409: throw MetricsError.lastPasskey |
| 128 | default: throw MetricsError.unavailable |
| 129 | } |
| 130 | guard result.contentType?.lowercased().split(separator: ";").first == "application/json" else { throw MetricsError.invalidResponse } |
| 131 | return result.data |
| 132 | } |
| 133 | |
| 134 | private func decode<T: Decodable>(_ type: T.Type, _ data: Data) throws -> T { |
| 135 | do { return try JSONDecoder().decode(type, from: data) } catch { throw MetricsError.invalidResponse } |
| 136 | } |
| 137 | |
| 138 | private func challenge(_ data: Data) throws -> PasskeyChallenge { |
| 139 | let reply = try decode(Options.self, data) |
| 140 | guard let challenge = Data(base64URL: reply.options.challenge) else { throw MetricsError.invalidResponse } |
| 141 | let userID = reply.options.user.flatMap { Data(base64URL: $0.id) } ?? Data() |
| 142 | return PasskeyChallenge(id: reply.challengeId, challenge: challenge, userID: userID, |
| 143 | userName: reply.options.user?.name ?? "Graphley owner", |
| 144 | excludedCredentialIDs: (reply.options.excludeCredentials ?? []).compactMap { Data(base64URL: $0.id) }) |
| 145 | } |
| 146 | |
| 147 | private struct Empty: Encodable {} |
| 148 | private struct Setup: Encodable { let setupCode: String? } |
| 149 | private struct Removal: Encodable { let id: String } |
| 150 | private struct Signed: Decodable { let session: String? } |
| 151 | private struct Listing: Decodable { let passkeys: [PasskeyInfo] } |
| 152 | private struct Options: Decodable { |
| 153 | struct Body: Decodable { |
| 154 | struct User: Decodable { let id: String; let name: String } |
| 155 | struct Credential: Decodable { let id: String } |
| 156 | let challenge: String |
| 157 | let user: User? |
| 158 | let excludeCredentials: [Credential]? |
| 159 | } |
| 160 | let challengeId: String |
| 161 | let options: Body |
| 162 | } |
| 163 | private struct Answer<Response: Encodable>: Encodable { |
| 164 | struct Credential: Encodable { |
| 165 | let id: String |
| 166 | let rawId: String |
| 167 | var type = "public-key" |
| 168 | let response: Response |
| 169 | var clientExtensionResults: [String: String] = [:] |
| 170 | } |
| 171 | let challengeId: String |
| 172 | let response: Credential |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | struct AssertionBody: Encodable { |
| 177 | let clientDataJSON: String |
| 178 | let authenticatorData: String |
| 179 | let signature: String |
| 180 | let userHandle: String |
| 181 | } |
| 182 | |
| 183 | struct RegistrationBody: Encodable { |
| 184 | let clientDataJSON: String |
| 185 | let attestationObject: String |
| 186 | let transports: [String] |
| 187 | } |
| 188 | |
| 189 | extension Data { |
| 190 | var base64URL: String { |
| 191 | base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_") |
| 192 | .replacingOccurrences(of: "=", with: "") |
| 193 | } |
| 194 | |
| 195 | init?(base64URL: String) { |
| 196 | var text = base64URL.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") |
| 197 | text += String(repeating: "=", count: (4 - text.count % 4) % 4) |
| 198 | self.init(base64Encoded: text) |
| 199 | } |
| 200 | } |