import Foundation import Security import CryptoKit public enum ShareFailure: Error, Equatable, Sendable { case signedOut, expiredJournal, invalidInput, unconfirmed, tooLarge, readFailed, malformed case server(Int, String) } /// No credential here. Generation changes when the person switches accounts. public struct ShareSelection: Codable, Sendable, Equatable { public static let key = "share.selection" public var origin: URL public var person: String public var team: String public var generation: String public init(origin: URL, person: String, team: String, generation: String = UUID().uuidString) { self.origin = origin; self.person = person; self.team = team; self.generation = generation } } /// Read-only projection of DeviceAccount's existing keychain JSON. Never persisted separately. public struct ShareAccount: Codable, Sendable { public struct Credential: Codable, Sendable { public let token: String public let expiresAt: Date } public let origin: URL public let credential: Credential public let address: String? public let oficinaIdentity: String? public let oficinaSessionHash: String? } public struct ShareAuthority: Sendable { public let selection: ShareSelection public let token: String } public struct ShareAuthentication: Sendable { let store: any SecretStore let identityIsLive: @Sendable (String, String) -> Bool public init(store: any SecretStore = KeychainSecretStore.shared, identityIsLive: @escaping @Sendable (String, String) -> Bool = SharedIdentity.isLive) { self.store = store; self.identityIsLive = identityIsLive } public func read(now: Date = Date()) throws -> ShareAuthority { guard let data = store.read(ShareSelection.key), let selection = try? JSONDecoder().decode(ShareSelection.self, from: data), selection.origin.scheme == "https", selection.origin.host != nil, selection.origin.user == nil, selection.origin.password == nil, ["", "/"].contains(selection.origin.path), selection.origin.query == nil, selection.origin.fragment == nil, let saved = store.read(selection.origin.absoluteString), let account = try? JSONDecoder().decode(ShareAccount.self, from: saved), account.origin == selection.origin, account.address == selection.person, account.credential.expiresAt > now, !account.credential.token.isEmpty else { throw ShareFailure.signedOut } if let identity = account.oficinaIdentity { guard let hash = account.oficinaSessionHash, identityIsLive(identity, hash) else { throw ShareFailure.signedOut } } return ShareAuthority(selection: selection, token: account.credential.token) } public func require(_ selection: ShareSelection, now: Date = Date()) throws -> ShareAuthority { let authority = try read(now: now) guard authority.selection == selection else { throw ShareFailure.signedOut } return authority } } /// Read the pinned Oficina ID v1 record format without loading its sign-in UI. /// Both identity and matching app session must still exist. Never renew or write. public enum SharedIdentity { public static func isLive(_ identity: String, _ hash: String) -> Bool { func read(_ service: String, group: String, account: String?) -> [Data] { var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccessGroup as String: group, kSecUseDataProtectionKeychain as String: true, kSecAttrSynchronizable as String: false, kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitAll] if let account { q[kSecAttrAccount as String] = account } var value: CFTypeRef? guard SecItemCopyMatching(q as CFDictionary, &value) == errSecSuccess else { return [] } return value as? [Data] ?? [] } return validate(identityData: read("works.oficina.id.identity", group: "9U4A84C4WK.works.oficina.id", account: identity), sessions: read("works.oficina.id.session", group: "9U4A84C4WK.works.oficina.equipo", account: nil), identity: identity, hash: hash, now: Date()) } static func validate(identityData: [Data], sessions: [Data], identity: String, hash: String, now: Date) -> Bool { struct Identity: Decodable { let v: Int; let identity_id: String; let grant: String } struct Session: Decodable { let v: Int; let identity_id: String; let grant_id: String; let session: Cookie; let minted_at: Double; let expires_at: Double? } struct Cookie: Decodable { let value: String } func base64URL(_ data: Data) -> String { data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") } let grants = Set(identityData.compactMap { data -> String? in guard let record = try? JSONDecoder().decode(Identity.self, from: data), record.v == 1, record.identity_id == identity else { return nil } let encoded = record.grant.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") guard let token = Data(base64Encoded: encoded + String(repeating: "=", count: (4 - encoded.count % 4) % 4)), token.count == 32, base64URL(token) == record.grant else { return nil } return base64URL(Data(SHA256.hash(data: Data(("oficina-id/grant-id/v1\0" + record.grant).utf8)).prefix(16))) }) guard !grants.isEmpty else { return false } return sessions.contains { data in guard let record = try? JSONDecoder().decode(Session.self, from: data), record.v == 1, record.identity_id == identity, grants.contains(record.grant_id), now.timeIntervalSince1970 < min(record.expires_at ?? .greatestFiniteMagnitude, record.minted_at + 7 * 86400) else { return false } return Data(SHA256.hash(data: Data(record.session.value.utf8))).base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") == hash } } }