| 1 | import Foundation |
| 2 | import CryptoKit |
| 3 | import Darwin |
| 4 | |
| 5 | public struct ShareWrite: Codable, Sendable, Equatable { |
| 6 | public let key: String |
| 7 | public let body: Data |
| 8 | public var summary: ShareWriteSummary? { |
| 9 | struct Body: Decodable { let text: String; let attachments: [String]? } |
| 10 | guard let value = try? JSONDecoder().decode(Body.self, from: body) else { return nil } |
| 11 | let text = value.text.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ") |
| 12 | return ShareWriteSummary(text: String(text.prefix(200)) + (text.count > 200 ? "…" : ""), attachmentCount: value.attachments?.count ?? 0) |
| 13 | } |
| 14 | } |
| 15 | public struct ShareWriteSummary: Sendable { |
| 16 | public let text: String |
| 17 | public let attachmentCount: Int |
| 18 | } |
| 19 | public struct ShareMessage: Sendable { |
| 20 | public let text: String |
| 21 | public let project: String? |
| 22 | public let attachments: [String] |
| 23 | public init(text: String, project: String?, attachments: [String]) { self.text = text; self.project = project; self.attachments = attachments } |
| 24 | public func pending() throws -> ShareWrite { |
| 25 | guard text.utf8.count <= 16 * 1024, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty, |
| 26 | attachments.count <= 5, Set(attachments).count == attachments.count else { throw ShareFailure.invalidInput } |
| 27 | let key = UUID().uuidString.lowercased() |
| 28 | var body: [String: Any] = ["text": text, "idempotency_key": key] |
| 29 | if let project { body["project_id"] = project } |
| 30 | if !attachments.isEmpty { body["attachments"] = attachments } |
| 31 | return ShareWrite(key: key, body: try JSONSerialization.data(withJSONObject: body, options: .sortedKeys)) |
| 32 | } |
| 33 | } |
| 34 | /// Only the immutable final request and recipient binding. No token or session. |
| 35 | public struct ShareJournal: Sendable { |
| 36 | let directory: URL |
| 37 | func file(for selection: ShareSelection) -> URL { |
| 38 | let binding = selection.origin.absoluteString + "\n" + selection.person |
| 39 | let name = SHA256.hash(data: Data(binding.utf8)).map { String(format: "%02x", $0) }.joined() |
| 40 | return directory.appendingPathComponent(name + ".json") |
| 41 | } |
| 42 | struct Record: Codable { let selection: ShareSelection; let created: Date; let write: ShareWrite } |
| 43 | public init(directory: URL) { self.directory = directory } |
| 44 | private func locked<T>(_ selection: ShareSelection, _ operation: (URL) throws -> T) throws -> T { |
| 45 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) |
| 46 | var url = directory; var values = URLResourceValues(); values.isExcludedFromBackup = true; try url.setResourceValues(values) |
| 47 | let file = file(for: selection) |
| 48 | let descriptor = open(file.appendingPathExtension("lock").path, O_CREAT | O_RDWR, 0o600) |
| 49 | guard descriptor >= 0 else { throw ShareFailure.unconfirmed } |
| 50 | defer { close(descriptor) } |
| 51 | guard flock(descriptor, LOCK_EX) == 0 else { throw ShareFailure.unconfirmed } |
| 52 | defer { flock(descriptor, LOCK_UN) } |
| 53 | return try operation(file) |
| 54 | } |
| 55 | struct Envelope: Codable { let records: [Record] } |
| 56 | private func persist(_ records: [Record], to file: URL) throws { |
| 57 | if records.isEmpty { try? FileManager.default.removeItem(at: file); return } |
| 58 | let data = try JSONEncoder().encode(Envelope(records: records)) |
| 59 | guard data.count <= 1024 * 1024 else { throw ShareFailure.unconfirmed } |
| 60 | #if os(iOS) |
| 61 | try data.write(to: file, options: [.atomic, .completeFileProtection]) |
| 62 | #else |
| 63 | try data.write(to: file, options: .atomic) |
| 64 | #endif |
| 65 | try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path) |
| 66 | } |
| 67 | private func records(_ file: URL, selection: ShareSelection) throws -> [Record] { |
| 68 | guard FileManager.default.fileExists(atPath: file.path) else { return [] } |
| 69 | let handle = try FileHandle(forReadingFrom: file); defer { try? handle.close() } |
| 70 | let data = try handle.read(upToCount: 1024 * 1024 + 1) ?? Data() |
| 71 | guard data.count <= 1024 * 1024 else { throw ShareFailure.invalidInput } |
| 72 | let decoder = JSONDecoder() |
| 73 | let records: [Record] |
| 74 | if let envelope = try? decoder.decode(Envelope.self, from: data) { records = envelope.records } |
| 75 | else { records = [try decoder.decode(Record.self, from: data)] } |
| 76 | guard records.count <= 32 else { throw ShareFailure.invalidInput } |
| 77 | guard records.allSatisfy({ $0.selection.origin == selection.origin && $0.selection.person == selection.person }) else { throw ShareFailure.signedOut } |
| 78 | return records |
| 79 | } |
| 80 | public func save(_ write: ShareWrite, selection: ShareSelection, now: Date = Date()) throws { |
| 81 | try locked(selection) { file in |
| 82 | var records = try records(file, selection: selection).filter { now.timeIntervalSince($0.created) < 86400 } |
| 83 | if let existing = records.first(where: { $0.write.key == write.key }) { |
| 84 | guard existing.write == write else { throw ShareFailure.unconfirmed } |
| 85 | return // Retrying never extends the original deadline. |
| 86 | } |
| 87 | guard records.count < 32 else { throw ShareFailure.unconfirmed } |
| 88 | records.append(Record(selection: selection, created: now, write: write)) |
| 89 | try persist(records, to: file) |
| 90 | } |
| 91 | } |
| 92 | public func loadAll(selection: ShareSelection, now: Date = Date()) throws -> [ShareWrite] { |
| 93 | try locked(selection) { file in |
| 94 | let all = try records(file, selection: selection) |
| 95 | let current = all.filter { now.timeIntervalSince($0.created) < 86400 } |
| 96 | if current.count != all.count { try persist(current, to: file) } |
| 97 | if !all.isEmpty && current.isEmpty { throw ShareFailure.expiredJournal } |
| 98 | return current.map(\.write) |
| 99 | } |
| 100 | } |
| 101 | public func load(selection: ShareSelection, now: Date = Date()) throws -> ShareWrite? { |
| 102 | try loadAll(selection: selection, now: now).first |
| 103 | } |
| 104 | public func clear(selection: ShareSelection, key: String) { |
| 105 | try? locked(selection) { file in |
| 106 | let remaining = try records(file, selection: selection).filter { $0.write.key != key } |
| 107 | try persist(remaining, to: file) |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |