import CryptoKit import Foundation /// One paired team: where it is, this device's key and its credential. /// Kept in the Keychain as JSON under the origin. The token is a secret: /// never log it, never put it in a URL. public struct DeviceAccount: Codable, Sendable, Equatable { public var origin: URL public var keySeed: Data public var label: String public var credential: DeviceCredential? public var teamName: String? public var address: String? /// Absent on saved pairings from before Oficina ID. The session hash /// binds this bearer to the kit session that minted it, without a second cookie. public var oficinaIdentity: String? public var oficinaTeam: String? public var oficinaSessionHash: String? /// Throws if the stored key is damaged; pairing then starts again with a new one. public func signingKey() throws -> Curve25519.Signing.PrivateKey { try .init(rawRepresentation: keySeed) } public func publicKey() throws -> String { Base64URL.encode(try signingKey().publicKey.rawRepresentation) } public func isUsable(now: Date = Date()) -> Bool { credential.map { $0.expiresAt > now } ?? false } public static func new(origin: URL, label: String) -> DeviceAccount { DeviceAccount(origin: origin, keySeed: Curve25519.Signing.PrivateKey().rawRepresentation, label: label) } } /// The paired teams on this device. Slice 1 uses one; the store keeps the /// list shape so several teams can follow. public struct DeviceAccounts: Sendable { private let store: SecretStore static let index = "accounts" public let lifetimes: SignInLifetimes @MainActor public init(store: SecretStore) { self.store = store; lifetimes = SignInLifetimes() } var signInRoute: String? { store.read("signin.route").flatMap { String(data: $0, encoding: .utf8) } } public enum Change { case save(DeviceAccount) case remove(DeviceAccount) case route(String) case selectForNotifications(DeviceAccount) case clearNotificationSelection(DeviceAccount) case selectForSharing(DeviceAccount) case clearShareSelection(DeviceAccount) } public var notificationSelection: NotificationSelection? { store.read(NotificationSelection.key).flatMap { try? JSONDecoder().decode(NotificationSelection.self, from: $0) } } public func all() -> [DeviceAccount] { let origins = (store.read(Self.index).flatMap { try? JSONDecoder().decode([URL].self, from: $0) }) ?? [] return origins.compactMap { origin in store.read(origin.absoluteString).flatMap { try? JSONDecoder().decode(DeviceAccount.self, from: $0) } } } /// Every device, private key, index and route write passes this boundary. /// Check and write are synchronous on MainActor, so ending a lifetime /// cannot interleave with persistence. Removal also matches the saved key. @MainActor public func commit(_ change: Change, lifetime: SignInLifetime) throws { try lifetimes.require(lifetime) switch change { case .save(let account): try store.write(try JSONEncoder().encode(account), account: account.origin.absoluteString) var origins = all().map(\.origin) if !origins.contains(account.origin) { origins.append(account.origin) } try store.write(try JSONEncoder().encode(origins), account: Self.index) case .remove(let account): guard all().contains(where: { $0.origin == account.origin && $0.keySeed == account.keySeed }) else { return } if let data = store.read(ShareSelection.key), let selection = try? JSONDecoder().decode(ShareSelection.self, from: data), selection.origin == account.origin { store.remove(ShareSelection.key) } if notificationSelection?.origin == account.origin { store.remove(NotificationSelection.key) } store.remove(account.origin.absoluteString) let origins = all().map(\.origin).filter { $0 != account.origin } try store.write(try JSONEncoder().encode(origins), account: Self.index) case .selectForNotifications(let account): guard account.isUsable(), let person = account.address, !person.isEmpty, let credential = account.credential?.id else { store.remove(NotificationSelection.key); return } if notificationSelection?.matches(account) == true { return } let selection = NotificationSelection(id: UUID().uuidString.lowercased(), origin: account.origin, person: person, credential: credential, sessionHash: account.oficinaSessionHash) try store.write(try JSONEncoder().encode(selection), account: NotificationSelection.key) case .clearNotificationSelection(let account): if notificationSelection?.matches(account) == true { store.remove(NotificationSelection.key) } case .selectForSharing(let account): guard account.isUsable(), let person = account.address, !person.isEmpty else { store.remove(ShareSelection.key); return } let old = store.read(ShareSelection.key).flatMap { try? JSONDecoder().decode(ShareSelection.self, from: $0) } let same = old?.origin == account.origin && old?.person == person let selection = ShareSelection(origin: account.origin, person: person, team: account.teamName ?? account.origin.host ?? "", generation: same ? old!.generation : UUID().uuidString) try store.write(try JSONEncoder().encode(selection), account: ShareSelection.key) case .clearShareSelection(let account): 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) } case .route(let route): try store.write(Data(route.utf8), account: "signin.route") } } }