| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | |
| 4 | /// One paired team: where it is, this device's key and its credential. |
| 5 | /// Kept in the Keychain as JSON under the origin. The token is a secret: |
| 6 | /// never log it, never put it in a URL. |
| 7 | public struct DeviceAccount: Codable, Sendable, Equatable { |
| 8 | public var origin: URL |
| 9 | public var keySeed: Data |
| 10 | public var label: String |
| 11 | public var credential: DeviceCredential? |
| 12 | public var teamName: String? |
| 13 | public var address: String? |
| 14 | /// Absent on saved pairings from before Oficina ID. The session hash |
| 15 | /// binds this bearer to the kit session that minted it, without a second cookie. |
| 16 | public var oficinaIdentity: String? |
| 17 | public var oficinaTeam: String? |
| 18 | public var oficinaSessionHash: String? |
| 19 | |
| 20 | /// Throws if the stored key is damaged; pairing then starts again with a new one. |
| 21 | public func signingKey() throws -> Curve25519.Signing.PrivateKey { try .init(rawRepresentation: keySeed) } |
| 22 | public func publicKey() throws -> String { Base64URL.encode(try signingKey().publicKey.rawRepresentation) } |
| 23 | public func isUsable(now: Date = Date()) -> Bool { credential.map { $0.expiresAt > now } ?? false } |
| 24 | |
| 25 | public static func new(origin: URL, label: String) -> DeviceAccount { |
| 26 | DeviceAccount(origin: origin, keySeed: Curve25519.Signing.PrivateKey().rawRepresentation, label: label) |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | /// The paired teams on this device. Slice 1 uses one; the store keeps the |
| 31 | /// list shape so several teams can follow. |
| 32 | public struct DeviceAccounts: Sendable { |
| 33 | private let store: SecretStore |
| 34 | static let index = "accounts" |
| 35 | public let lifetimes: SignInLifetimes |
| 36 | @MainActor public init(store: SecretStore) { self.store = store; lifetimes = SignInLifetimes() } |
| 37 | var signInRoute: String? { store.read("signin.route").flatMap { String(data: $0, encoding: .utf8) } } |
| 38 | |
| 39 | public enum Change { |
| 40 | case save(DeviceAccount) |
| 41 | case remove(DeviceAccount) |
| 42 | case route(String) |
| 43 | case selectForNotifications(DeviceAccount) |
| 44 | case clearNotificationSelection(DeviceAccount) |
| 45 | case selectForSharing(DeviceAccount) |
| 46 | case clearShareSelection(DeviceAccount) |
| 47 | } |
| 48 | |
| 49 | public var notificationSelection: NotificationSelection? { |
| 50 | store.read(NotificationSelection.key).flatMap { try? JSONDecoder().decode(NotificationSelection.self, from: $0) } |
| 51 | } |
| 52 | |
| 53 | public func all() -> [DeviceAccount] { |
| 54 | let origins = (store.read(Self.index).flatMap { try? JSONDecoder().decode([URL].self, from: $0) }) ?? [] |
| 55 | return origins.compactMap { origin in store.read(origin.absoluteString).flatMap { try? JSONDecoder().decode(DeviceAccount.self, from: $0) } } |
| 56 | } |
| 57 | /// Every device, private key, index and route write passes this boundary. |
| 58 | /// Check and write are synchronous on MainActor, so ending a lifetime |
| 59 | /// cannot interleave with persistence. Removal also matches the saved key. |
| 60 | @MainActor public func commit(_ change: Change, lifetime: SignInLifetime) throws { |
| 61 | try lifetimes.require(lifetime) |
| 62 | switch change { |
| 63 | case .save(let account): |
| 64 | try store.write(try JSONEncoder().encode(account), account: account.origin.absoluteString) |
| 65 | var origins = all().map(\.origin) |
| 66 | if !origins.contains(account.origin) { origins.append(account.origin) } |
| 67 | try store.write(try JSONEncoder().encode(origins), account: Self.index) |
| 68 | case .remove(let account): |
| 69 | guard all().contains(where: { $0.origin == account.origin && $0.keySeed == account.keySeed }) else { return } |
| 70 | if let data = store.read(ShareSelection.key), let selection = try? JSONDecoder().decode(ShareSelection.self, from: data), selection.origin == account.origin { store.remove(ShareSelection.key) } |
| 71 | if notificationSelection?.origin == account.origin { store.remove(NotificationSelection.key) } |
| 72 | store.remove(account.origin.absoluteString) |
| 73 | let origins = all().map(\.origin).filter { $0 != account.origin } |
| 74 | try store.write(try JSONEncoder().encode(origins), account: Self.index) |
| 75 | case .selectForNotifications(let account): |
| 76 | guard account.isUsable(), let person = account.address, !person.isEmpty, let credential = account.credential?.id else { |
| 77 | store.remove(NotificationSelection.key); return |
| 78 | } |
| 79 | if notificationSelection?.matches(account) == true { return } |
| 80 | let selection = NotificationSelection(id: UUID().uuidString.lowercased(), origin: account.origin, person: person, |
| 81 | credential: credential, sessionHash: account.oficinaSessionHash) |
| 82 | try store.write(try JSONEncoder().encode(selection), account: NotificationSelection.key) |
| 83 | case .clearNotificationSelection(let account): |
| 84 | if notificationSelection?.matches(account) == true { store.remove(NotificationSelection.key) } |
| 85 | case .selectForSharing(let account): |
| 86 | guard account.isUsable(), let person = account.address, !person.isEmpty else { store.remove(ShareSelection.key); return } |
| 87 | let old = store.read(ShareSelection.key).flatMap { try? JSONDecoder().decode(ShareSelection.self, from: $0) } |
| 88 | let same = old?.origin == account.origin && old?.person == person |
| 89 | let selection = ShareSelection(origin: account.origin, person: person, team: account.teamName ?? account.origin.host ?? "", generation: same ? old!.generation : UUID().uuidString) |
| 90 | try store.write(try JSONEncoder().encode(selection), account: ShareSelection.key) |
| 91 | case .clearShareSelection(let account): |
| 92 | if let data = store.read(ShareSelection.key), let selection = try? JSONDecoder().decode(ShareSelection.self, from: data), selection.origin == account.origin, selection.person == account.address { store.remove(ShareSelection.key) } |
| 93 | case .route(let route): |
| 94 | try store.write(Data(route.utf8), account: "signin.route") |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |