import Foundation /// Passkeys are the only way the curator and moderators sign in: no passwords, pasted tokens, /// email links or codes. Recovery is a second passkey. The relying party is jobley.ai, which serves /// the apple-app-site-association file the apps' `webcredentials:jobley.ai` entitlement points at. /// A passkey sign-in returns a session token, which the apps keep in the Keychain (`TokenStore`). /// What the server sends to start a sign-in or to add a passkey. public struct PasskeyChallenge: Decodable, Sendable { public var challengeID: String public var options: Options public struct Options: Decodable, Sendable { /// base64url public var challenge: String /// Sign-in options name the relying party here… public var rpId: String? /// …registration options here, with the person and the passkeys they already have. public var rp: RelyingParty? public var user: User? public var excludeCredentials: [Credential]? } public struct RelyingParty: Decodable, Sendable { public var id: String } public struct User: Decodable, Sendable { public var id: String, name: String, displayName: String? } public struct Credential: Decodable, Sendable { public var id: String } enum CodingKeys: String, CodingKey { case challengeID = "challenge_id", options } public var relyingParty: String { options.rp?.id ?? options.rpId ?? "jobley.ai" } public var challenge: Data? { Data(base64URL: options.challenge) } public var userID: Data? { options.user.flatMap { Data(base64URL: $0.id) } } public var excludedCredentialIDs: [Data] { (options.excludeCredentials ?? []).compactMap { Data(base64URL: $0.id) } } } /// A signed-in session, from a passkey sign-in or from adding a passkey with a setup link. public struct PasskeySession: Decodable, Sendable { public var token: String public var role: String public var id: String public var name: String public var canSeeCandidates: Bool enum CodingKeys: String, CodingKey { case token, role, id, name, canSeeCandidates = "can_see_candidates" } } /// One of the signed-in person's passkeys. public struct Passkey: Decodable, Identifiable, Sendable, Equatable { public var id: String public var name: String? public var createdAt: String? public var lastUsedAt: String? enum CodingKeys: String, CodingKey { case id, name, createdAt = "created_at", lastUsedAt = "last_used_at" } } /// A one-time link that adds a person's first passkey. It works once, within 15 minutes. public struct SetupLink: Codable, Sendable, Equatable { public var url: String public var expiresAt: String enum CodingKeys: String, CodingKey { case url, expiresAt = "expires_at" } } /// The WebAuthn JSON the server's verifier reads, built from what AuthenticationServices returns. public enum PasskeyResponse { public static func registration(credentialID: Data, clientDataJSON: Data, attestationObject: Data) -> [String: Any] { ["id": credentialID.base64URL, "rawId": credentialID.base64URL, "type": "public-key", "authenticatorAttachment": "platform", "clientExtensionResults": [String: Any](), "response": ["clientDataJSON": clientDataJSON.base64URL, "attestationObject": attestationObject.base64URL, "transports": ["internal", "hybrid"]]] } public static func assertion(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userID: Data?) -> [String: Any] { var response: [String: Any] = ["clientDataJSON": clientDataJSON.base64URL, "authenticatorData": authenticatorData.base64URL, "signature": signature.base64URL] if let userID { response["userHandle"] = userID.base64URL } return ["id": credentialID.base64URL, "rawId": credentialID.base64URL, "type": "public-key", "authenticatorAttachment": "platform", "clientExtensionResults": [String: Any](), "response": response] } /// The code in a setup link ("https://jobley.ai/passkey/#jl_enroll_…"), or the code on its own. public static func setupCode(from text: String) -> String? { let code = text.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: "#").last.map(String.init) ?? "" return code.range(of: #"^[a-z]+_enroll_[0-9a-f]{64}$"#, options: .regularExpression) != nil ? code : nil } } extension APIClient { // MARK: Passkeys public func passkeySignInOptions() async throws -> PasskeyChallenge { try await send("POST", "api/passkeys/login/options", body: [:], admin: false) } public func signIn(challengeID: String, assertion: [String: Any]) async throws -> PasskeySession { try await send("POST", "api/passkeys/login", body: ["challenge_id": challengeID, "response": assertion], admin: false) } /// Options to add a first passkey with a setup link. public func passkeyOptions(setupCode: String) async throws -> PasskeyChallenge { try await send("POST", "api/passkeys/register/options", body: ["code": setupCode], admin: false) } /// Saves the first passkey and signs in. public func addPasskey(challengeID: String, registration: [String: Any], name: String) async throws -> PasskeySession { try await send("POST", "api/passkeys/register", body: ["challenge_id": challengeID, "response": registration, "name": name], admin: false) } /// Options to add another passkey while signed in. public func anotherPasskeyOptions() async throws -> PasskeyChallenge { try await send("POST", "api/admin/passkeys/options", body: [:]) } public func addAnotherPasskey(challengeID: String, registration: [String: Any], name: String) async throws { let _: IDReply = try await send("POST", "api/admin/passkeys", body: ["challenge_id": challengeID, "response": registration, "name": name]) } public func passkeys() async throws -> [Passkey] { let reply: PasskeysReply = try await get("api/admin/passkeys", admin: true) return reply.passkeys } /// The server refuses to remove the last one. public func removePasskey(_ id: String) async throws { let _: IDReply = try await perform(request("DELETE", "api/admin/passkeys/\(id)", admin: true)) } public func signOut() async throws { let _: OKReply = try await send("POST", "api/admin/sign-out", body: [:]) } /// A new one-time setup link for a moderator (curator only). public func setupLink(moderator id: String) async throws -> SetupLink { let reply: SetupLinkReply = try await send("POST", "api/admin/moderators/\(id)/setup-link", body: [:]) return reply.setup } } struct PasskeysReply: Decodable { var passkeys: [Passkey] } struct SetupLinkReply: Decodable { var setup: SetupLink } struct OKReply: Decodable { var ok: Bool } extension Data { public var base64URL: String { base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") } public init?(base64URL: String) { var text = base64URL.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") text += String(repeating: "=", count: (4 - text.count % 4) % 4) self.init(base64Encoded: text) } }