Branchwell

Jobley / app · jobley.ai / Sources / JobleyKit / Passkeys.swift

Raw 7.2 KB on a698b1d1990e3dd0f04a257534b232ac0b1cf6c7
1import Foundation
2
3/// Passkeys are the only way the curator and moderators sign in: no passwords, pasted tokens,
4/// email links or codes. Recovery is a second passkey. The relying party is jobley.ai, which serves
5/// the apple-app-site-association file the apps' `webcredentials:jobley.ai` entitlement points at.
6/// A passkey sign-in returns a session token, which the apps keep in the Keychain (`TokenStore`).
7
8/// What the server sends to start a sign-in or to add a passkey.
9public struct PasskeyChallenge: Decodable, Sendable {
10 public var challengeID: String
11 public var options: Options
12
13 public struct Options: Decodable, Sendable {
14 /// base64url
15 public var challenge: String
16 /// Sign-in options name the relying party here…
17 public var rpId: String?
18 /// …registration options here, with the person and the passkeys they already have.
19 public var rp: RelyingParty?
20 public var user: User?
21 public var excludeCredentials: [Credential]?
22 }
23 public struct RelyingParty: Decodable, Sendable { public var id: String }
24 public struct User: Decodable, Sendable { public var id: String, name: String, displayName: String? }
25 public struct Credential: Decodable, Sendable { public var id: String }
26
27 enum CodingKeys: String, CodingKey { case challengeID = "challenge_id", options }
28
29 public var relyingParty: String { options.rp?.id ?? options.rpId ?? "jobley.ai" }
30 public var challenge: Data? { Data(base64URL: options.challenge) }
31 public var userID: Data? { options.user.flatMap { Data(base64URL: $0.id) } }
32 public var excludedCredentialIDs: [Data] { (options.excludeCredentials ?? []).compactMap { Data(base64URL: $0.id) } }
33}
34
35/// A signed-in session, from a passkey sign-in or from adding a passkey with a setup link.
36public struct PasskeySession: Decodable, Sendable {
37 public var token: String
38 public var role: String
39 public var id: String
40 public var name: String
41 public var canSeeCandidates: Bool
42 enum CodingKeys: String, CodingKey { case token, role, id, name, canSeeCandidates = "can_see_candidates" }
43}
44
45/// One of the signed-in person's passkeys.
46public struct Passkey: Decodable, Identifiable, Sendable, Equatable {
47 public var id: String
48 public var name: String?
49 public var createdAt: String?
50 public var lastUsedAt: String?
51 enum CodingKeys: String, CodingKey { case id, name, createdAt = "created_at", lastUsedAt = "last_used_at" }
52}
53
54/// A one-time link that adds a person's first passkey. It works once, within 15 minutes.
55public struct SetupLink: Codable, Sendable, Equatable {
56 public var url: String
57 public var expiresAt: String
58 enum CodingKeys: String, CodingKey { case url, expiresAt = "expires_at" }
59}
60
61/// The WebAuthn JSON the server's verifier reads, built from what AuthenticationServices returns.
62public enum PasskeyResponse {
63 public static func registration(credentialID: Data, clientDataJSON: Data, attestationObject: Data) -> [String: Any] {
64 ["id": credentialID.base64URL, "rawId": credentialID.base64URL, "type": "public-key",
65 "authenticatorAttachment": "platform", "clientExtensionResults": [String: Any](),
66 "response": ["clientDataJSON": clientDataJSON.base64URL, "attestationObject": attestationObject.base64URL, "transports": ["internal", "hybrid"]]]
67 }
68
69 public static func assertion(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userID: Data?) -> [String: Any] {
70 var response: [String: Any] = ["clientDataJSON": clientDataJSON.base64URL, "authenticatorData": authenticatorData.base64URL, "signature": signature.base64URL]
71 if let userID { response["userHandle"] = userID.base64URL }
72 return ["id": credentialID.base64URL, "rawId": credentialID.base64URL, "type": "public-key",
73 "authenticatorAttachment": "platform", "clientExtensionResults": [String: Any](), "response": response]
74 }
75
76 /// The code in a setup link ("https://jobley.ai/passkey/#jl_enroll_…"), or the code on its own.
77 public static func setupCode(from text: String) -> String? {
78 let code = text.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: "#").last.map(String.init) ?? ""
79 return code.range(of: #"^[a-z]+_enroll_[0-9a-f]{64}$"#, options: .regularExpression) != nil ? code : nil
80 }
81}
82
83extension APIClient {
84 // MARK: Passkeys
85
86 public func passkeySignInOptions() async throws -> PasskeyChallenge {
87 try await send("POST", "api/passkeys/login/options", body: [:], admin: false)
88 }
89
90 public func signIn(challengeID: String, assertion: [String: Any]) async throws -> PasskeySession {
91 try await send("POST", "api/passkeys/login", body: ["challenge_id": challengeID, "response": assertion], admin: false)
92 }
93
94 /// Options to add a first passkey with a setup link.
95 public func passkeyOptions(setupCode: String) async throws -> PasskeyChallenge {
96 try await send("POST", "api/passkeys/register/options", body: ["code": setupCode], admin: false)
97 }
98
99 /// Saves the first passkey and signs in.
100 public func addPasskey(challengeID: String, registration: [String: Any], name: String) async throws -> PasskeySession {
101 try await send("POST", "api/passkeys/register", body: ["challenge_id": challengeID, "response": registration, "name": name], admin: false)
102 }
103
104 /// Options to add another passkey while signed in.
105 public func anotherPasskeyOptions() async throws -> PasskeyChallenge {
106 try await send("POST", "api/admin/passkeys/options", body: [:])
107 }
108
109 public func addAnotherPasskey(challengeID: String, registration: [String: Any], name: String) async throws {
110 let _: IDReply = try await send("POST", "api/admin/passkeys", body: ["challenge_id": challengeID, "response": registration, "name": name])
111 }
112
113 public func passkeys() async throws -> [Passkey] {
114 let reply: PasskeysReply = try await get("api/admin/passkeys", admin: true)
115 return reply.passkeys
116 }
117
118 /// The server refuses to remove the last one.
119 public func removePasskey(_ id: String) async throws {
120 let _: IDReply = try await perform(request("DELETE", "api/admin/passkeys/\(id)", admin: true))
121 }
122
123 public func signOut() async throws {
124 let _: OKReply = try await send("POST", "api/admin/sign-out", body: [:])
125 }
126
127 /// A new one-time setup link for a moderator (curator only).
128 public func setupLink(moderator id: String) async throws -> SetupLink {
129 let reply: SetupLinkReply = try await send("POST", "api/admin/moderators/\(id)/setup-link", body: [:])
130 return reply.setup
131 }
132}
133
134struct PasskeysReply: Decodable { var passkeys: [Passkey] }
135struct SetupLinkReply: Decodable { var setup: SetupLink }
136struct OKReply: Decodable { var ok: Bool }
137
138extension Data {
139 public var base64URL: String {
140 base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
141 }
142
143 public init?(base64URL: String) {
144 var text = base64URL.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
145 text += String(repeating: "=", count: (4 - text.count % 4) % 4)
146 self.init(base64Encoded: text)
147 }
148}