import Foundation import ImageIO import UniformTypeIdentifiers /// POST /attachments' v1 contract (internal/attach/attach.go). /capabilities /// publishes authentication/version support, not configurable upload limits. public enum AttachmentLimits { public static let maxBytes = 10 << 20 // Bound local file reads before thumbnailing, independently of the upload cap. public static let maxInputBytes = 128 << 20 public static let imageLongEdge = 2560 public static let maxCount = 5 public static let maxSide = 12_000 public static let maxPixels = 40_000_000 public static func checkDimensions(width: Int, height: Int) throws { guard width > 0, height > 0 else { throw AttachmentFailure.type } guard width <= maxSide, height <= maxSide, width * height <= maxPixels else { throw AttachmentFailure.pixels } } } public enum AttachmentFailure: Error, Equatable, Sendable { case tooLarge, pixels, type } public protocol AttachmentFileAccess: Sendable { func start(_ url: URL) -> Bool func stop(_ url: URL) func isRegularFile(_ url: URL) throws -> Bool } public struct SystemAttachmentFileAccess: AttachmentFileAccess { public init() {} public func start(_ url: URL) -> Bool { url.startAccessingSecurityScopedResource() } public func stop(_ url: URL) { url.stopAccessingSecurityScopedResource() } public func isRegularFile(_ url: URL) throws -> Bool { try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true } } public struct AttachmentFile: Sendable { public let data: Data public let name: String public let mediaType: String public let width: Int public let height: Int public static func prepare(_ data: Data, name: String) throws -> Self { try prepare(data, name: name, maximumBytes: AttachmentLimits.maxBytes) } static func prepare(_ data: Data, name: String, maximumBytes: Int) throws -> Self { guard !data.isEmpty else { throw AttachmentFailure.type } let name = URL(fileURLWithPath: name).lastPathComponent if let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary), let image = try prepareImage(source, name: name, maximumBytes: maximumBytes, original: { data }) { return image } guard data.count <= maximumBytes else { throw AttachmentFailure.tooLarge } if data.starts(with: Data("%PDF-".utf8)) { return Self(data: data, name: name, mediaType: "application/pdf", width: 0, height: 0) } let suffix = (name as NSString).pathExtension.lowercased() guard !["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "hif", "pdf"].contains(suffix), let text = String(data: data, encoding: .utf8), text.unicodeScalars.allSatisfy({ $0.value >= 32 && $0.value != 127 || [9, 10, 12, 13].contains($0.value) }) else { throw AttachmentFailure.type } // The server accepts UTF-8 source files and extensionless files too. var media = ["md": "text/markdown", "markdown": "text/markdown", "csv": "text/csv"][suffix] ?? "text/plain" if suffix == "json", (try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)) != nil { media = "application/json" } return Self(data: data, name: name, mediaType: media, width: 0, height: 0) } static func prepareImage(_ source: CGImageSource, name: String, maximumBytes: Int, original: () throws -> Data) throws -> Self? { if let typeID = CGImageSourceGetType(source) as String?, let type = UTType(typeID), type.conforms(to: .image) { let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] let width = (properties?[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue ?? 0 let height = (properties?[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue ?? 0 guard width > 0, height > 0 else { throw AttachmentFailure.type } if type.conforms(to: .heic) || type.conforms(to: .heif) || type == .tiff || (type != .gif && max(width, height) > AttachmentLimits.imageLongEdge) { // TIFF is the Mac clipboard's native image representation. // Apply orientation and omit source metadata, including location. let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: AttachmentLimits.imageLongEdge, kCGImageSourceShouldCacheImmediately: true] guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { throw AttachmentFailure.type } // The web canvas flattens transparency on white before JPEG encoding. let flattened: CGImage if (properties?[kCGImagePropertyHasAlpha] as? Bool) == false || [.none, .noneSkipFirst, .noneSkipLast].contains(image.alphaInfo) { // Opaque images need no backing canvas. Avoid retaining a // second 2560-pixel bitmap in the share extension. flattened = image } else { guard let canvas = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { throw AttachmentFailure.type } canvas.setFillColor(CGColor(gray: 1, alpha: 1)); canvas.fill(CGRect(x: 0, y: 0, width: image.width, height: image.height)) canvas.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) guard let opaque = canvas.makeImage() else { throw AttachmentFailure.type } flattened = opaque } let output = NSMutableData() guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else { throw AttachmentFailure.type } CGImageDestinationAddImage(destination, flattened, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary) guard CGImageDestinationFinalize(destination) else { throw AttachmentFailure.type } guard output.length <= maximumBytes else { throw AttachmentFailure.tooLarge } return Self(data: output as Data, name: (name as NSString).deletingPathExtension + ".jpg", mediaType: "image/jpeg", width: image.width, height: image.height) } try AttachmentLimits.checkDimensions(width: width, height: height) let data = try original() guard data.count <= maximumBytes else { throw AttachmentFailure.tooLarge } let types: [UTType: String] = [.png: "image/png", .jpeg: "image/jpeg", .gif: "image/gif", .webP: "image/webp"] guard let media = types[type] else { throw AttachmentFailure.type } let suffix = type.preferredFilenameExtension ?? "png" return Self(data: data, name: (name as NSString).deletingPathExtension + "." + suffix, mediaType: media, width: width, height: height) } return nil } public static func checkRegularFile(_ url: URL, access: any AttachmentFileAccess) throws { guard url.isFileURL else { throw AttachmentFailure.type } let started = access.start(url) defer { if started { access.stop(url) } } guard try access.isRegularFile(url) else { throw AttachmentFailure.type } } public static func read(_ url: URL) throws -> Data { let access = url.startAccessingSecurityScopedResource() defer { if access { url.stopAccessingSecurityScopedResource() } } let handle = try FileHandle(forReadingFrom: url) defer { try? handle.close() } let data = try handle.read(upToCount: AttachmentLimits.maxInputBytes + 1) ?? Data() guard data.count <= AttachmentLimits.maxInputBytes else { throw AttachmentFailure.tooLarge } return data } }