| 1 | import Foundation |
| 2 | import Security |
| 3 | import CryptoKit |
| 4 | |
| 5 | public enum ShareFailure: Error, Equatable, Sendable { |
| 6 | case signedOut, expiredJournal, invalidInput, unconfirmed, tooLarge, readFailed, malformed |
| 7 | case server(Int, String) |
| 8 | } |
| 9 | |
| 10 | /// No credential here. Generation changes when the person switches accounts. |
| 11 | public struct ShareSelection: Codable, Sendable, Equatable { |
| 12 | public static let key = "share.selection" |
| 13 | public var origin: URL |
| 14 | public var person: String |
| 15 | public var team: String |
| 16 | public var generation: String |
| 17 | public init(origin: URL, person: String, team: String, generation: String = UUID().uuidString) { |
| 18 | self.origin = origin; self.person = person; self.team = team; self.generation = generation |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | /// Read-only projection of DeviceAccount's existing keychain JSON. Never persisted separately. |
| 23 | public struct ShareAccount: Codable, Sendable { |
| 24 | public struct Credential: Codable, Sendable { |
| 25 | public let token: String |
| 26 | public let expiresAt: Date |
| 27 | } |
| 28 | public let origin: URL |
| 29 | public let credential: Credential |
| 30 | public let address: String? |
| 31 | public let oficinaIdentity: String? |
| 32 | public let oficinaSessionHash: String? |
| 33 | } |
| 34 | public struct ShareAuthority: Sendable { |
| 35 | public let selection: ShareSelection |
| 36 | public let token: String |
| 37 | } |
| 38 | public struct ShareAuthentication: Sendable { |
| 39 | let store: any SecretStore |
| 40 | let identityIsLive: @Sendable (String, String) -> Bool |
| 41 | public init(store: any SecretStore = KeychainSecretStore.shared, |
| 42 | identityIsLive: @escaping @Sendable (String, String) -> Bool = SharedIdentity.isLive) { |
| 43 | self.store = store; self.identityIsLive = identityIsLive |
| 44 | } |
| 45 | public func read(now: Date = Date()) throws -> ShareAuthority { |
| 46 | guard let data = store.read(ShareSelection.key), let selection = try? JSONDecoder().decode(ShareSelection.self, from: data), |
| 47 | selection.origin.scheme == "https", selection.origin.host != nil, |
| 48 | selection.origin.user == nil, selection.origin.password == nil, |
| 49 | ["", "/"].contains(selection.origin.path), selection.origin.query == nil, selection.origin.fragment == nil, |
| 50 | let saved = store.read(selection.origin.absoluteString), let account = try? JSONDecoder().decode(ShareAccount.self, from: saved), |
| 51 | account.origin == selection.origin, account.address == selection.person, |
| 52 | account.credential.expiresAt > now, !account.credential.token.isEmpty else { throw ShareFailure.signedOut } |
| 53 | if let identity = account.oficinaIdentity { |
| 54 | guard let hash = account.oficinaSessionHash, identityIsLive(identity, hash) else { throw ShareFailure.signedOut } |
| 55 | } |
| 56 | return ShareAuthority(selection: selection, token: account.credential.token) |
| 57 | } |
| 58 | public func require(_ selection: ShareSelection, now: Date = Date()) throws -> ShareAuthority { |
| 59 | let authority = try read(now: now) |
| 60 | guard authority.selection == selection else { throw ShareFailure.signedOut } |
| 61 | return authority |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// Read the pinned Oficina ID v1 record format without loading its sign-in UI. |
| 66 | /// Both identity and matching app session must still exist. Never renew or write. |
| 67 | public enum SharedIdentity { |
| 68 | public static func isLive(_ identity: String, _ hash: String) -> Bool { |
| 69 | func read(_ service: String, group: String, account: String?) -> [Data] { |
| 70 | var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, |
| 71 | kSecAttrAccessGroup as String: group, kSecUseDataProtectionKeychain as String: true, |
| 72 | kSecAttrSynchronizable as String: false, kSecReturnData as String: true, |
| 73 | kSecMatchLimit as String: kSecMatchLimitAll] |
| 74 | if let account { q[kSecAttrAccount as String] = account } |
| 75 | var value: CFTypeRef? |
| 76 | guard SecItemCopyMatching(q as CFDictionary, &value) == errSecSuccess else { return [] } |
| 77 | return value as? [Data] ?? [] |
| 78 | } |
| 79 | return validate(identityData: read("works.oficina.id.identity", group: "9U4A84C4WK.works.oficina.id", account: identity), |
| 80 | sessions: read("works.oficina.id.session", group: "9U4A84C4WK.works.oficina.equipo", account: nil), |
| 81 | identity: identity, hash: hash, now: Date()) |
| 82 | } |
| 83 | static func validate(identityData: [Data], sessions: [Data], identity: String, hash: String, now: Date) -> Bool { |
| 84 | struct Identity: Decodable { let v: Int; let identity_id: String; let grant: String } |
| 85 | 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? } |
| 86 | struct Cookie: Decodable { let value: String } |
| 87 | func base64URL(_ data: Data) -> String { |
| 88 | data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") |
| 89 | } |
| 90 | let grants = Set(identityData.compactMap { data -> String? in |
| 91 | guard let record = try? JSONDecoder().decode(Identity.self, from: data), record.v == 1, |
| 92 | record.identity_id == identity else { return nil } |
| 93 | let encoded = record.grant.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") |
| 94 | guard let token = Data(base64Encoded: encoded + String(repeating: "=", count: (4 - encoded.count % 4) % 4)), |
| 95 | token.count == 32, base64URL(token) == record.grant else { return nil } |
| 96 | return base64URL(Data(SHA256.hash(data: Data(("oficina-id/grant-id/v1\0" + record.grant).utf8)).prefix(16))) |
| 97 | }) |
| 98 | guard !grants.isEmpty else { return false } |
| 99 | return sessions.contains { data in |
| 100 | guard let record = try? JSONDecoder().decode(Session.self, from: data), record.v == 1, record.identity_id == identity, grants.contains(record.grant_id), |
| 101 | now.timeIntervalSince1970 < min(record.expires_at ?? .greatestFiniteMagnitude, record.minted_at + 7 * 86400) else { return false } |
| 102 | return Data(SHA256.hash(data: Data(record.session.value.utf8))).base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") == hash |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |