Repository Public License
1// CanvasEngine — image and PDF files attached to a canvas.2import CryptoKit3import Foundation4import NavigatorCore56/// The file types a canvas accepts, recognised from the first bytes of the data — never from a file name.7public enum CanvasAttachmentKind: String, Sendable, Hashable, Codable, CaseIterable {8 case png, jpeg, gif, webp, heic, tiff, pdf910 public var fileExtension: String {11 switch self {12 case .png: return "png"13 case .jpeg: return "jpg"14 case .gif: return "gif"15 case .webp: return "webp"16 case .heic: return "heic"17 case .tiff: return "tiff"18 case .pdf: return "pdf"19 }20 }2122 public var isImage: Bool { self != .pdf }2324 /// Identifies the type from magic bytes; `nil` for anything else (SVG, HTML, executables, archives…).25 public static func sniff(_ data: Data) -> CanvasAttachmentKind? {26 let bytes = [UInt8](data.prefix(16))27 func starts(_ signature: [UInt8], at offset: Int = 0) -> Bool {28 bytes.count >= offset + signature.count && Array(bytes[offset..<(offset + signature.count)]) == signature29 }30 if starts([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) { return .png }31 if starts([0xFF, 0xD8, 0xFF]) { return .jpeg }32 if starts(Array("GIF87a".utf8)) || starts(Array("GIF89a".utf8)) { return .gif }33 if starts(Array("RIFF".utf8)), starts(Array("WEBP".utf8), at: 8) { return .webp }34 if starts(Array("%PDF-".utf8)) { return .pdf }35 if starts([0x49, 0x49, 0x2A, 0x00]) || starts([0x4D, 0x4D, 0x00, 0x2A]) { return .tiff }36 if starts(Array("ftyp".utf8), at: 4), bytes.count >= 12 {37 let brand = String(decoding: bytes[8..<12], as: UTF8.self)38 if ["heic", "heix", "heim", "heis", "hevc", "hevx", "mif1", "msf1"].contains(brand) { return .heic }39 }40 return nil41 }42}4344public struct CanvasAttachment: Sendable, Hashable, Codable {45 /// File name inside the canvas's attachment directory: `<sha256 hex>.<extension>`. This is the value stored46 /// in `CanvasCard.Content.image(relativePath:)` / `.pdf(relativePath:page:)`.47 public var relativePath: String48 public var kind: CanvasAttachmentKind49 public var byteSize: Int50 public var sha256: String51}5253public enum CanvasAttachmentError: Error, Sendable, Equatable, CustomStringConvertible {54 case empty55 case unsupportedType56 case tooLarge(limit: Int, actual: Int)57 case unsafePath(String)58 case notFound(String)59 case quotaExceeded(limit: Int)6061 public var description: String {62 switch self {63 case .empty: return "The file is empty."64 case .unsupportedType: return "Only PNG, JPEG, GIF, WebP, HEIC, TIFF images and PDF documents can be added to a canvas."65 case .tooLarge(let limit, let actual): return "The file is \(actual) bytes; the limit is \(limit) bytes."66 case .unsafePath(let path): return "Not an attachment name: \(path)"67 case .notFound(let path): return "No attachment named \(path)."68 case .quotaExceeded(let limit): return "The attachments of this canvas would exceed \(limit) bytes."69 }70 }71}7273/// Stores canvas attachments on disk: `<root>/<canvas id>/<sha256>.<ext>`.74///75/// File names are derived from the content hash, so importing the same file twice stores it once, a name can76/// never be chosen by the outside world, and a stored file can be verified against its name. All file work77/// happens on this actor, never on the main actor.78public actor CanvasAttachmentStore {79 public struct Limits: Sendable, Hashable {80 public var maximumImageBytes = 25 * 1024 * 102481 public var maximumPDFBytes = 100 * 1024 * 102482 /// Total size of the attachments of one canvas.83 public var maximumCanvasBytes = 1024 * 1024 * 102484 public init() {}85 }8687 public let root: URL88 public let limits: Limits8990 public init(root: URL, limits: Limits = Limits()) {91 self.root = root.standardizedFileURL92 self.limits = limits93 }9495 /// `true` only for names this store produces: 64 lowercase hex digits, a dot and a known extension.96 /// No separator, no dot segment, no percent escape can pass.97 public nonisolated static func isSafeRelativePath(_ path: String) -> Bool {98 let parts = path.split(separator: ".", omittingEmptySubsequences: false)99 guard parts.count == 2, parts[0].utf8.count == 64,100 parts[0].utf8.allSatisfy({ ($0 >= 48 && $0 <= 57) || ($0 >= 97 && $0 <= 102) }) else { return false }101 return CanvasAttachmentKind.allCases.contains { $0.fileExtension == parts[1] }102 }103104 public nonisolated func directory(for canvas: CanvasID) -> URL {105 root.appending(path: canvas.string, directoryHint: .isDirectory)106 }107108 /// Location of a stored attachment. Throws for any name that is not a content-hash file name.109 public nonisolated func url(for relativePath: String, canvas: CanvasID) throws -> URL {110 guard Self.isSafeRelativePath(relativePath) else { throw CanvasAttachmentError.unsafePath(relativePath) }111 return directory(for: canvas).appending(path: relativePath, directoryHint: .notDirectory)112 }113114 /// Validates and stores data. The type comes from the magic bytes; a declared name or MIME type is not115 /// consulted. Idempotent: the same bytes always yield the same attachment.116 public func importData(_ data: Data, into canvas: CanvasID) throws -> CanvasAttachment {117 guard !data.isEmpty else { throw CanvasAttachmentError.empty }118 guard let kind = CanvasAttachmentKind.sniff(data) else { throw CanvasAttachmentError.unsupportedType }119 let limit = kind == .pdf ? limits.maximumPDFBytes : limits.maximumImageBytes120 guard data.count <= limit else { throw CanvasAttachmentError.tooLarge(limit: limit, actual: data.count) }121 let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()122 let name = "\(hash).\(kind.fileExtension)"123 let attachment = CanvasAttachment(relativePath: name, kind: kind, byteSize: data.count, sha256: hash)124 let destination = try url(for: name, canvas: canvas)125 let manager = FileManager.default126 if manager.fileExists(atPath: destination.path) { return attachment }127 guard try totalSize(of: canvas) + data.count <= limits.maximumCanvasBytes else {128 throw CanvasAttachmentError.quotaExceeded(limit: limits.maximumCanvasBytes)129 }130 try manager.createDirectory(at: directory(for: canvas), withIntermediateDirectories: true)131 try data.write(to: destination, options: [.atomic])132 return attachment133 }134135 /// Imports a local file (a drop, the file picker). The size is checked before the file is read.136 public func importFile(at url: URL, into canvas: CanvasID) throws -> CanvasAttachment {137 let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0138 let ceiling = max(limits.maximumImageBytes, limits.maximumPDFBytes)139 guard size <= ceiling else { throw CanvasAttachmentError.tooLarge(limit: ceiling, actual: size) }140 return try importData(try Data(contentsOf: url, options: [.mappedIfSafe]), into: canvas)141 }142143 public func data(for relativePath: String, canvas: CanvasID) throws -> Data {144 let location = try url(for: relativePath, canvas: canvas)145 guard FileManager.default.fileExists(atPath: location.path) else { throw CanvasAttachmentError.notFound(relativePath) }146 return try Data(contentsOf: location, options: [.mappedIfSafe])147 }148149 /// Re-hashes a stored file and compares with its name.150 public func verify(_ relativePath: String, canvas: CanvasID) throws -> Bool {151 let data = try data(for: relativePath, canvas: canvas)152 let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()153 return relativePath.hasPrefix(hash + ".")154 }155156 /// Attachment files present on disk for a canvas (only well-formed names are reported).157 public func storedFiles(of canvas: CanvasID) throws -> [String] {158 let names = (try? FileManager.default.contentsOfDirectory(atPath: directory(for: canvas).path)) ?? []159 return names.filter(Self.isSafeRelativePath).sorted()160 }161162 public func totalSize(of canvas: CanvasID) throws -> Int {163 try storedFiles(of: canvas).reduce(0) { total, name in164 let location = directory(for: canvas).appending(path: name)165 return total + (try location.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0)166 }167 }168169 /// The attachment names a document refers to.170 public nonisolated static func referencedPaths(in document: CanvasDocument) -> Set<String> {171 var paths = Set<String>()172 for card in document.cards {173 switch card.content {174 case .image(let path), .pdf(let path, _): paths.insert(path)175 case .page, .note: break176 }177 }178 return paths179 }180181 /// Deletes stored files the document no longer refers to and returns their names. Call it after a save,182 /// once the undo history that could bring a card back is gone (closing the canvas), not after every edit.183 @discardableResult184 public func removeOrphans(of document: CanvasDocument) throws -> [String] {185 let referenced = Self.referencedPaths(in: document)186 var removed: [String] = []187 for name in try storedFiles(of: document.id) where !referenced.contains(name) {188 try FileManager.default.removeItem(at: directory(for: document.id).appending(path: name))189 removed.append(name)190 }191 return removed192 }193194 /// Deletes every attachment of a canvas (the canvas was deleted).195 public func removeAll(of canvas: CanvasID) throws {196 let location = directory(for: canvas)197 if FileManager.default.fileExists(atPath: location.path) { try FileManager.default.removeItem(at: location) }198 }199}200