import Foundation import CryptoKit import Darwin public struct ShareWrite: Codable, Sendable, Equatable { public let key: String public let body: Data public var summary: ShareWriteSummary? { struct Body: Decodable { let text: String; let attachments: [String]? } guard let value = try? JSONDecoder().decode(Body.self, from: body) else { return nil } let text = value.text.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ") return ShareWriteSummary(text: String(text.prefix(200)) + (text.count > 200 ? "…" : ""), attachmentCount: value.attachments?.count ?? 0) } } public struct ShareWriteSummary: Sendable { public let text: String public let attachmentCount: Int } public struct ShareMessage: Sendable { public let text: String public let project: String? public let attachments: [String] public init(text: String, project: String?, attachments: [String]) { self.text = text; self.project = project; self.attachments = attachments } public func pending() throws -> ShareWrite { guard text.utf8.count <= 16 * 1024, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty, attachments.count <= 5, Set(attachments).count == attachments.count else { throw ShareFailure.invalidInput } let key = UUID().uuidString.lowercased() var body: [String: Any] = ["text": text, "idempotency_key": key] if let project { body["project_id"] = project } if !attachments.isEmpty { body["attachments"] = attachments } return ShareWrite(key: key, body: try JSONSerialization.data(withJSONObject: body, options: .sortedKeys)) } } /// Only the immutable final request and recipient binding. No token or session. public struct ShareJournal: Sendable { let directory: URL func file(for selection: ShareSelection) -> URL { let binding = selection.origin.absoluteString + "\n" + selection.person let name = SHA256.hash(data: Data(binding.utf8)).map { String(format: "%02x", $0) }.joined() return directory.appendingPathComponent(name + ".json") } struct Record: Codable { let selection: ShareSelection; let created: Date; let write: ShareWrite } public init(directory: URL) { self.directory = directory } private func locked(_ selection: ShareSelection, _ operation: (URL) throws -> T) throws -> T { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) var url = directory; var values = URLResourceValues(); values.isExcludedFromBackup = true; try url.setResourceValues(values) let file = file(for: selection) let descriptor = open(file.appendingPathExtension("lock").path, O_CREAT | O_RDWR, 0o600) guard descriptor >= 0 else { throw ShareFailure.unconfirmed } defer { close(descriptor) } guard flock(descriptor, LOCK_EX) == 0 else { throw ShareFailure.unconfirmed } defer { flock(descriptor, LOCK_UN) } return try operation(file) } struct Envelope: Codable { let records: [Record] } private func persist(_ records: [Record], to file: URL) throws { if records.isEmpty { try? FileManager.default.removeItem(at: file); return } let data = try JSONEncoder().encode(Envelope(records: records)) guard data.count <= 1024 * 1024 else { throw ShareFailure.unconfirmed } #if os(iOS) try data.write(to: file, options: [.atomic, .completeFileProtection]) #else try data.write(to: file, options: .atomic) #endif try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path) } private func records(_ file: URL, selection: ShareSelection) throws -> [Record] { guard FileManager.default.fileExists(atPath: file.path) else { return [] } let handle = try FileHandle(forReadingFrom: file); defer { try? handle.close() } let data = try handle.read(upToCount: 1024 * 1024 + 1) ?? Data() guard data.count <= 1024 * 1024 else { throw ShareFailure.invalidInput } let decoder = JSONDecoder() let records: [Record] if let envelope = try? decoder.decode(Envelope.self, from: data) { records = envelope.records } else { records = [try decoder.decode(Record.self, from: data)] } guard records.count <= 32 else { throw ShareFailure.invalidInput } guard records.allSatisfy({ $0.selection.origin == selection.origin && $0.selection.person == selection.person }) else { throw ShareFailure.signedOut } return records } public func save(_ write: ShareWrite, selection: ShareSelection, now: Date = Date()) throws { try locked(selection) { file in var records = try records(file, selection: selection).filter { now.timeIntervalSince($0.created) < 86400 } if let existing = records.first(where: { $0.write.key == write.key }) { guard existing.write == write else { throw ShareFailure.unconfirmed } return // Retrying never extends the original deadline. } guard records.count < 32 else { throw ShareFailure.unconfirmed } records.append(Record(selection: selection, created: now, write: write)) try persist(records, to: file) } } public func loadAll(selection: ShareSelection, now: Date = Date()) throws -> [ShareWrite] { try locked(selection) { file in let all = try records(file, selection: selection) let current = all.filter { now.timeIntervalSince($0.created) < 86400 } if current.count != all.count { try persist(current, to: file) } if !all.isEmpty && current.isEmpty { throw ShareFailure.expiredJournal } return current.map(\.write) } } public func load(selection: ShareSelection, now: Date = Date()) throws -> ShareWrite? { try loadAll(selection: selection, now: now).first } public func clear(selection: ShareSelection, key: String) { try? locked(selection) { file in let remaining = try records(file, selection: selection).filter { $0.write.key != key } try persist(remaining, to: file) } } }