Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / R2Storage.swift
| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | import ImageIO |
| 4 | import Security |
| 5 | import UniformTypeIdentifiers |
| 6 | |
| 7 | struct R2Configuration: Codable, Equatable, Sendable { |
| 8 | var accountId: String |
| 9 | var bucket: String |
| 10 | var jurisdiction: String |
| 11 | |
| 12 | var host: String { |
| 13 | accountId + (jurisdiction == "default" ? "" : "." + jurisdiction) + ".r2.cloudflarestorage.com" |
| 14 | } |
| 15 | |
| 16 | var identity: [String] { [accountId, bucket, jurisdiction] } |
| 17 | |
| 18 | func validate() throws { |
| 19 | guard accountId.range(of: #"\A[a-f0-9]{32}\z"#, options: .regularExpression) != nil else { |
| 20 | throw WorkspaceError("Enter the 32-character Cloudflare account ID.") |
| 21 | } |
| 22 | guard bucket.range(of: #"\A[a-z0-9][a-z0-9-]{1,61}[a-z0-9]\z"#, options: .regularExpression) != nil else { |
| 23 | throw WorkspaceError("Use a bucket name with 3–63 lowercase letters, numbers, or hyphens.") |
| 24 | } |
| 25 | guard ["default", "eu", "us", "fedramp"].contains(jurisdiction) else { |
| 26 | throw WorkspaceError("Choose the bucket’s R2 jurisdiction.") |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | struct R2Profile: Codable, Sendable { |
| 32 | let configuration: R2Configuration |
| 33 | let accessKeyId: String |
| 34 | let secretAccessKey: String |
| 35 | |
| 36 | func validate() throws { |
| 37 | try configuration.validate() |
| 38 | guard accessKeyId.range(of: #"\A[A-Za-z0-9_-]{16,256}\z"#, options: .regularExpression) != nil, |
| 39 | secretAccessKey.range(of: #"\A[A-Za-z0-9/+=_-]{32,1024}\z"#, options: .regularExpression) != nil else { |
| 40 | throw WorkspaceError("Enter the S3 Access Key ID and Secret Access Key from Cloudflare R2.") |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | private static let query: [String: String] = [ |
| 45 | kSecClass as String: kSecClassGenericPassword as String, |
| 46 | kSecAttrService as String: "com.protomota.inkspring.native.r2", |
| 47 | kSecAttrAccount as String: "configuration" |
| 48 | ] |
| 49 | |
| 50 | static func saved() throws -> Self? { |
| 51 | var attributes: [String: Any] = query |
| 52 | attributes[kSecReturnData as String] = true |
| 53 | var result: CFTypeRef? |
| 54 | let status = SecItemCopyMatching(attributes as CFDictionary, &result) |
| 55 | if status == errSecItemNotFound { return nil } |
| 56 | try check(status) |
| 57 | guard let data = result as? Data, let profile = try? JSONDecoder().decode(Self.self, from: data) else { |
| 58 | throw WorkspaceError("The saved R2 connection could not be read. Configure it again.") |
| 59 | } |
| 60 | try profile.validate() |
| 61 | return profile |
| 62 | } |
| 63 | |
| 64 | func save(replaceExisting: Bool = true) throws { |
| 65 | try validate() |
| 66 | let data = try JSONEncoder().encode(self) |
| 67 | let status = replaceExisting |
| 68 | ? SecItemUpdate(Self.query as CFDictionary, [kSecValueData as String: data] as CFDictionary) |
| 69 | : errSecItemNotFound |
| 70 | if status == errSecItemNotFound { |
| 71 | var attributes: [String: Any] = Self.query |
| 72 | attributes[kSecValueData as String] = data |
| 73 | let added = SecItemAdd(attributes as CFDictionary, nil) |
| 74 | if !replaceExisting, added == errSecDuplicateItem { |
| 75 | throw WorkspaceError("An R2 connection is already saved. Request a replacement to change it.") |
| 76 | } |
| 77 | try Self.check(added) |
| 78 | } else { try Self.check(status) } |
| 79 | } |
| 80 | |
| 81 | static func remove() throws { |
| 82 | let status = SecItemDelete(query as CFDictionary) |
| 83 | if status != errSecItemNotFound { try check(status) } |
| 84 | } |
| 85 | |
| 86 | private static func check(_ status: OSStatus) throws { |
| 87 | guard status == errSecSuccess else { throw WorkspaceError("Keychain could not access the R2 connection (\(status)).") } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | struct R2Signer { |
| 92 | static let prefix = "inkspring-instagram/" |
| 93 | static let expires: TimeInterval = 7200 |
| 94 | let profile: R2Profile |
| 95 | |
| 96 | static func validateKey(_ key: String) throws { |
| 97 | guard key.hasPrefix(prefix), key.utf8.count <= 200, !key.contains(".."), |
| 98 | key.range(of: #"\A[A-Za-z0-9/._-]+\z"#, options: .regularExpression) != nil else { |
| 99 | throw WorkspaceError("Choose media uploaded by Inkspring.") |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | func signedRequest(method: String, key: String, hash: String, contentType: String? = nil, |
| 104 | now: Date = .now) throws -> URLRequest { |
| 105 | try Self.validateKey(key) |
| 106 | let host = profile.configuration.host |
| 107 | let path = "/" + profile.configuration.bucket + "/" + key |
| 108 | let date = Self.date(now) |
| 109 | let scope = Self.scope(date) |
| 110 | let signed = "host;x-amz-content-sha256;x-amz-date" |
| 111 | let headers = "host:\(host)\nx-amz-content-sha256:\(hash)\nx-amz-date:\(date)\n" |
| 112 | let canonical = [method, path, "", headers, signed, hash].joined(separator: "\n") |
| 113 | let signature = signature(canonical, date: date, scope: scope) |
| 114 | let url = URL(string: "https://" + host + path)! |
| 115 | var request = URLRequest(url: url, timeoutInterval: method == "PUT" ? 1800 : 30) |
| 116 | request.httpMethod = method |
| 117 | request.setValue(hash, forHTTPHeaderField: "X-Amz-Content-Sha256") |
| 118 | request.setValue(date, forHTTPHeaderField: "X-Amz-Date") |
| 119 | request.setValue("AWS4-HMAC-SHA256 Credential=\(profile.accessKeyId)/\(scope), SignedHeaders=\(signed), Signature=\(signature)", |
| 120 | forHTTPHeaderField: "Authorization") |
| 121 | if let contentType { request.setValue(contentType, forHTTPHeaderField: "Content-Type") } |
| 122 | return request |
| 123 | } |
| 124 | |
| 125 | func link(_ key: String, now: Date = .now) throws -> URL { |
| 126 | try Self.validateKey(key) |
| 127 | let host = profile.configuration.host |
| 128 | let path = "/" + profile.configuration.bucket + "/" + key |
| 129 | let date = Self.date(now) |
| 130 | let scope = Self.scope(date) |
| 131 | let pairs = [ |
| 132 | "X-Amz-Algorithm": "AWS4-HMAC-SHA256", "X-Amz-Credential": profile.accessKeyId + "/" + scope, |
| 133 | "X-Amz-Date": date, "X-Amz-Expires": String(Int(Self.expires)), "X-Amz-SignedHeaders": "host" |
| 134 | ] |
| 135 | let allowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") |
| 136 | let query = pairs.sorted { $0.key < $1.key }.map { key, value in |
| 137 | key + "=" + (value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "") |
| 138 | }.joined(separator: "&") |
| 139 | let canonical = ["GET", path, query, "host:\(host)\n", "host", "UNSIGNED-PAYLOAD"].joined(separator: "\n") |
| 140 | let signed = signature(canonical, date: date, scope: scope) |
| 141 | return URL(string: "https://" + host + path + "?" + query + "&X-Amz-Signature=" + signed)! |
| 142 | } |
| 143 | |
| 144 | static func sha(_ data: Data) -> String { |
| 145 | SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() |
| 146 | } |
| 147 | |
| 148 | private static func date(_ now: Date) -> String { |
| 149 | let formatter = DateFormatter() |
| 150 | formatter.locale = Locale(identifier: "en_US_POSIX") |
| 151 | formatter.timeZone = TimeZone(secondsFromGMT: 0) |
| 152 | formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'" |
| 153 | return formatter.string(from: now) |
| 154 | } |
| 155 | |
| 156 | private static func scope(_ date: String) -> String { String(date.prefix(8)) + "/auto/s3/aws4_request" } |
| 157 | |
| 158 | private func signature(_ canonical: String, date: String, scope: String) -> String { |
| 159 | func hmac(_ secret: Data, _ text: String) -> Data { |
| 160 | Data(HMAC<SHA256>.authenticationCode(for: Data(text.utf8), using: SymmetricKey(data: secret))) |
| 161 | } |
| 162 | let day = hmac(Data(("AWS4" + profile.secretAccessKey).utf8), String(date.prefix(8))) |
| 163 | let region = hmac(day, "auto") |
| 164 | let service = hmac(region, "s3") |
| 165 | let key = hmac(service, "aws4_request") |
| 166 | let input = ["AWS4-HMAC-SHA256", date, scope, Self.sha(Data(canonical.utf8))].joined(separator: "\n") |
| 167 | return hmac(key, input).map { String(format: "%02x", $0) }.joined() |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | @MainActor |
| 172 | struct R2Client { |
| 173 | struct Media { |
| 174 | let key: String |
| 175 | let type: String |
| 176 | let size: Int64 |
| 177 | let name: String |
| 178 | } |
| 179 | |
| 180 | typealias Send = @MainActor (URLRequest, URL?) async throws -> (Data, HTTPURLResponse) |
| 181 | static let types = [".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", |
| 182 | ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm"] |
| 183 | let profile: R2Profile |
| 184 | var send: Send = live |
| 185 | |
| 186 | private var signer: R2Signer { R2Signer(profile: profile) } |
| 187 | |
| 188 | func link(_ key: String) throws -> URL { try signer.link(key) } |
| 189 | |
| 190 | func upload(_ file: URL, expectedHash: String? = nil) async throws -> Media { |
| 191 | let ext = "." + file.pathExtension.lowercased() |
| 192 | guard let type = Self.types[ext] else { throw WorkspaceError("Choose a PNG, JPEG, WebP, MP4, MOV, or WebM.") } |
| 193 | let attrs = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .contentModificationDateKey]) |
| 194 | guard attrs.isRegularFile == true, attrs.isSymbolicLink != true else { |
| 195 | throw WorkspaceError("Choose a regular media file.") |
| 196 | } |
| 197 | let digest = try await Task.detached(priority: .utility) { try fileDigest(file) }.value |
| 198 | guard digest.size > 0 else { throw WorkspaceError("The file is empty.") } |
| 199 | guard expectedHash == nil || digest.hash == expectedHash else { |
| 200 | throw WorkspaceError("The media changed. Attach the finished file and review the post again.") |
| 201 | } |
| 202 | try verify(file, size: digest.size, date: attrs.contentModificationDate) |
| 203 | let key = R2Signer.prefix + "media/" + digest.hash + ext |
| 204 | _ = try await request("PUT", key: key, type: type, hash: digest.hash, file: file) |
| 205 | try verify(file, size: digest.size, date: attrs.contentModificationDate) |
| 206 | return Media(key: key, type: type, size: digest.size, name: file.lastPathComponent) |
| 207 | } |
| 208 | |
| 209 | func uploadInstagram(_ image: URL, hash: String) async throws -> Media { |
| 210 | let attrs = try image.resourceValues(forKeys: [.fileSizeKey, .isSymbolicLinkKey, .isRegularFileKey]) |
| 211 | guard attrs.isRegularFile == true, attrs.isSymbolicLink != true, (1...20_000_000).contains(attrs.fileSize ?? 0) else { |
| 212 | throw WorkspaceError("Choose a local image up to 20 MB.") |
| 213 | } |
| 214 | let input = try Data(contentsOf: image) |
| 215 | guard input.count <= 20_000_000, R2Signer.sha(input) == hash, |
| 216 | let source = CGImageSourceCreateWithData(input as CFData, nil), |
| 217 | let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, [ |
| 218 | kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, |
| 219 | kCGImageSourceThumbnailMaxPixelSize: 1440 |
| 220 | ] as CFDictionary) else { throw WorkspaceError("The image changed or could not be read. Review it again.") } |
| 221 | let jpeg = NSMutableData() |
| 222 | guard let destination = CGImageDestinationCreateWithData(jpeg, UTType.jpeg.identifier as CFString, 1, nil) else { |
| 223 | throw WorkspaceError("Couldn’t encode the Instagram photo.") |
| 224 | } |
| 225 | CGImageDestinationAddImage(destination, thumbnail, [kCGImageDestinationLossyCompressionQuality: 0.86] as CFDictionary) |
| 226 | guard CGImageDestinationFinalize(destination), jpeg.length <= 8_000_000 else { |
| 227 | throw WorkspaceError("Choose a smaller photo.") |
| 228 | } |
| 229 | let bytes = jpeg as Data |
| 230 | let digest = R2Signer.sha(bytes) |
| 231 | let key = R2Signer.prefix + "media/" + digest + ".jpg" |
| 232 | _ = try await request("PUT", key: key, type: "image/jpeg", hash: digest, bytes: bytes) |
| 233 | return Media(key: key, type: "image/jpeg", size: Int64(bytes.count), name: "Instagram image.jpg") |
| 234 | } |
| 235 | |
| 236 | func test() async throws { |
| 237 | let key = R2Signer.prefix + "connection-check/" + UUID().uuidString.lowercased() + ".txt" |
| 238 | let bytes = Data("Inkspring R2 connection check".utf8) |
| 239 | var failure: Error? |
| 240 | do { |
| 241 | _ = try await request("PUT", key: key, type: "text/plain", hash: R2Signer.sha(bytes), bytes: bytes) |
| 242 | let response = try await request("GET", key: key) |
| 243 | guard response == bytes else { throw WorkspaceError("R2 returned unexpected connection-test data.") } |
| 244 | } catch { failure = error } |
| 245 | do { _ = try await request("DELETE", key: key) } |
| 246 | catch { if failure == nil { failure = WorkspaceError("R2 read and write worked. Check permission to remove the test object.") } } |
| 247 | if let failure { throw failure } |
| 248 | } |
| 249 | |
| 250 | private func request(_ method: String, key: String, type: String? = nil, hash: String? = nil, |
| 251 | bytes: Data? = nil, file: URL? = nil) async throws -> Data { |
| 252 | var request = try signer.signedRequest(method: method, key: key, hash: hash ?? R2Signer.sha(Data()), contentType: type) |
| 253 | request.httpBody = bytes |
| 254 | let result: (Data, HTTPURLResponse) |
| 255 | do { result = try await send(request, file) } |
| 256 | catch { throw WorkspaceError("Couldn’t reach the R2 bucket. Check the account ID, bucket, and jurisdiction.") } |
| 257 | guard (200...299).contains(result.1.statusCode) else { |
| 258 | throw WorkspaceError("R2 returned HTTP \(result.1.statusCode). Check the bucket-scoped key and permissions.") |
| 259 | } |
| 260 | return result.0 |
| 261 | } |
| 262 | |
| 263 | private func verify(_ file: URL, size: Int64, date: Date?) throws { |
| 264 | let current = try file.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) |
| 265 | guard current.fileSize == Int(size), current.contentModificationDate == date else { |
| 266 | throw WorkspaceError("The media changed during upload. Choose the finished file again.") |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | private static func live(_ request: URLRequest, _ file: URL?) async throws -> (Data, HTTPURLResponse) { |
| 271 | let config = URLSessionConfiguration.ephemeral |
| 272 | config.timeoutIntervalForResource = request.timeoutInterval |
| 273 | let session = URLSession(configuration: config, delegate: NoHTTPRedirects(), delegateQueue: nil) |
| 274 | defer { session.invalidateAndCancel() } |
| 275 | if let file { |
| 276 | let (data, response) = try await session.upload(for: request, fromFile: file) |
| 277 | guard let response = response as? HTTPURLResponse, data.count <= 65_536 else { |
| 278 | throw WorkspaceError("R2 returned an unreadable response.") |
| 279 | } |
| 280 | return (data, response) |
| 281 | } |
| 282 | let (bytes, raw) = try await session.bytes(for: request) |
| 283 | guard let response = raw as? HTTPURLResponse, raw.expectedContentLength <= 65_536 else { |
| 284 | throw WorkspaceError("R2 returned an unreadable response.") |
| 285 | } |
| 286 | var data = Data() |
| 287 | for try await byte in bytes { |
| 288 | guard data.count < 65_536 else { throw WorkspaceError("R2 returned an oversized response.") } |
| 289 | data.append(byte) |
| 290 | } |
| 291 | return (data, response) |
| 292 | } |
| 293 | } |