// SPDX-License-Identifier: GPL-3.0-or-later import Foundation import CryptoKit import Darwin import ImageIO import UniformTypeIdentifiers /// Private user data, separate from the prepared public catalog. Matching local /// companion clients may request verified disk entries and supporting assets. struct PersonalSoftwareEntry: Codable, Identifiable, Sendable { struct CoverFile: Codable, Equatable, Sendable { let path: String let sha256: String let byteSize: Int64 } enum CoverChoice: Codable, Equatable, Sendable { case imported(String) case custom(CoverFile) case categoryIcon } static let standardCategories = SoftwareLibraryOwnedGame.categoryNames.sorted() static func standardCategory(_ value: String) -> String { standardCategories.contains(value) ? value : "Other" } struct File: Codable, Identifiable, Sendable { let path: String var kind: String let byteSize: Int64 let sha256: String var id: String { path } var isMedia: Bool { ["disk", "hard-disk", "cassette", "cartridge", "binary"].contains(kind) } var role: String = "" } var schemaVersion = 1 let id: UUID var title: String var author = "" var softwareVersion = "" var category = "Other" var notes = "" var profile = "disk-basic" var processor = "6809" var ramKiB = 512 var video = "composite" var command = "" var configured = false var hidden = false var createdAt = Date() var updatedAt = Date() var files: [File] var sourcePackageSHA256: String? = nil var sourcePackageBytes: Int64? = nil // Older entries retain their first imported cover until explicitly changed. var cover: CoverChoice? = nil var selectedCoverFile: CoverFile? { switch cover { case .custom(let file): return file case .categoryIcon: return nil case .imported(let path): return files.first { $0.kind == "cover" && $0.path == path }.map { .init(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) } case nil: return files.first { $0.kind == "cover" }.map { .init(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) } } } var titleID: String { "personal:" + id.uuidString.lowercased() } var releaseID: String { titleID + ":edition" } var packageSHA256: String { let inventory = files.sorted { $0.path < $1.path }.map { "\($0.path)\n\($0.byteSize)\n\($0.sha256)" }.joined(separator: "\n") return SHA256.hash(data: Data(inventory.utf8)).map { String(format: "%02x", $0) }.joined() } func release(in directory: URL) -> SoftwareLibraryRelease { var configuration: [String: LibraryJSON] = ["profile": .string(profile), "processor": .string(processor), "ram_kib": .number(Double(ramKiB)), "video": .string(video), "personal_reviewed_setup": .bool(configured)] if !configured { configuration["personal_manual_setup"] = .bool(true) } let members = configured ? files.filter { $0.isMedia && !$0.role.isEmpty }.map { LibraryJSON.object(["path": .string($0.path), "target": .string($0.role)]) } : [] let selected = selectedCoverFile let customCover: Bool if case .custom = cover { customCover = true } else { customCover = false } let supporting = files.filter { $0.kind == "manual" }.map { CoverFile(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) } let assets = (supporting + [selected].compactMap { $0 }).map { file -> SoftwareLibraryAsset in let isCover = selected?.path == file.path let url = directory.appendingPathComponent("Assets").appendingPathComponent(file.path) var asset = SoftwareLibraryAsset(id: titleID + ":asset:" + file.path, name: isCover && customCover ? "Personal Cover Image" : URL(fileURLWithPath: file.path).lastPathComponent, kind: isCover ? "cover" : "manual", sourceURL: url, sha256: file.sha256, byteSize: file.byteSize, credit: author.isEmpty ? "Personal collection — private on this Mac" : author, matchStatus: "personal", matchReason: "Imported by this Mac's user; no public distribution permission inferred.") if !isCover { asset.manualURL = url } else { asset.thumbnailURL = url; asset.thumbnailSHA256 = file.sha256; asset.thumbnailByteSize = file.byteSize } return asset } return SoftwareLibraryRelease(id: releaseID, titleID: titleID, name: softwareVersion.isEmpty ? title : softwareVersion, category: Self.standardCategory(category), mediaType: files.first(where: \.isMedia)?.kind ?? "unknown", contentRole: "software", sourceURL: directory, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: packageSHA256, byteSize: files.reduce(0) { $0 + $1.byteSize }, languageStatus: "unknown", metadata: .object(["personal": .bool(true), "title": .string(title), "publisher": .string(author), "personal_version": .string(softwareVersion), "personal_notes": .string(notes), "system": .string("coco3"), "primary_browse_category": .string(Self.standardCategory(category)), "browse_categories": .array([.string(Self.standardCategory(category))])]), setup: .init(status: "manual-setup", command: configured && !command.isEmpty ? command : nil, instructions: notes.isEmpty ? "Private software on this Mac. Review its files and launch setup before running it." : notes, configuration: .object(configuration), selectedMembers: .array(members), reasons: [], validation: .object([:])), assets: assets, downloadURLs: []) } func receipt(in directory: URL) -> SoftwareLibraryInstallationReceipt { .init(releaseID: releaseID, packageSHA256: packageSHA256, installedAt: createdAt, workingDirectory: directory.appendingPathComponent("Working"), relativeFiles: files.map(\.path)) } } /// Bounded local image decoding shared by import previews and persisted cover edits. enum PersonalCoverImage { enum Failure: LocalizedError { case invalid var errorDescription: String? { "Choose a readable image no larger than 8 MiB, with dimensions at most 16,384 pixels and 64 million pixels in total. Existing library files were preserved." } } static func prepare(_ url: URL) throws -> Data { let access = url.startAccessingSecurityScopedResource() defer { if access { url.stopAccessingSecurityScopedResource() } } return try prepare(sourceData(url)) } fileprivate static func sourceData(_ url: URL) throws -> Data { guard url.isFileURL, url.host == nil || url.host == "localhost", url.query == nil, url.fragment == nil else { throw Failure.invalid } let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) guard fd >= 0 else { throw Failure.invalid } let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) defer { try? handle.close() } var before = stat(), after = stat() guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG, before.st_size > 0, before.st_size <= Int64(SoftwareLibraryArtworkCache.maximumSourceBytes) else { throw Failure.invalid } let data = try handle.read(upToCount: SoftwareLibraryArtworkCache.maximumSourceBytes + 1) ?? Data() guard data.count == Int(before.st_size), fstat(fd, &after) == 0, before.st_size == after.st_size, before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec, before.st_ctimespec.tv_sec == after.st_ctimespec.tv_sec, before.st_ctimespec.tv_nsec == after.st_ctimespec.tv_nsec else { throw Failure.invalid } return data } static func prepare(_ data: Data) throws -> Data { guard !data.isEmpty, data.count <= SoftwareLibraryArtworkCache.maximumSourceBytes, let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary), CGImageSourceGetStatus(source) == .statusComplete, let type = CGImageSourceGetType(source), UTType(type as String)?.conforms(to: .image) == true, let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], let width = properties[kCGImagePropertyPixelWidth] as? Int, let height = properties[kCGImagePropertyPixelHeight] as? Int, width > 0, height > 0, width <= 16_384, height <= 16_384, Int64(width) * Int64(height) <= 64_000_000 else { throw Failure.invalid } let normalized = try SoftwareLibraryArtworkCache.downsample(data, expectedSHA256: nil) guard normalized.count <= SoftwareLibraryArtworkCache.maximumThumbnailBytes, SoftwareLibraryArtworkCache.image(from: normalized) != nil else { throw Failure.invalid } return normalized } } struct PersonalSoftwareDraft: Identifiable, Sendable { let id: UUID var entry: PersonalSoftwareEntry let unsupported: [String] var totalBytes: Int64 { entry.files.reduce(0) { $0 + $1.byteSize } } } #if !VCC_COMPANION_CLIENT actor PersonalSoftwareLibraryStore { static let maximumBytes: Int64 = 1024 * 1024 * 1024 static let maximumFiles = 20_000 let root: URL private let manager = FileManager.default private var staged: Set = [] private(set) var warnings: [String] = [] enum Failure: LocalizedError { case invalid(String), duplicate(UUID) var errorDescription: String? { switch self { case .invalid(let message): return message case .duplicate: return "This exact set of files is already in your Personal Library. Choose Open Existing, or explicitly add a separate copy." } } } init(root: URL) { self.root = root.standardizedFileURL } func directory(for id: UUID) -> URL { root.appendingPathComponent(id.uuidString.lowercased(), isDirectory: true) } private func stage(_ id: UUID) -> URL { root.appendingPathComponent(".Staging", isDirectory: true).appendingPathComponent(id.uuidString.lowercased(), isDirectory: true) } private func prepareRoot() throws { for directory in [root, root.appendingPathComponent(".Staging")] { if manager.fileExists(atPath: directory.path) { let values = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) guard values.isDirectory == true, values.isSymbolicLink != true else { throw Failure.invalid("The private library location is not a safe directory. Existing files were preserved.") } } else { try manager.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) } } } static func validRelative(_ path: String) -> Bool { !path.isEmpty && path.utf8.count <= 4096 && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":") && !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) && path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." } } private static func fingerprint(_ url: URL, expectedSize: Int64? = nil) throws -> (Int64, String) { let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) guard fd >= 0 else { throw Failure.invalid("A selected file cannot be read safely: " + url.lastPathComponent) } let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) defer { try? handle.close() } var before = stat(), after = stat() guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG, before.st_size >= 0, before.st_size <= maximumBytes else { throw Failure.invalid("Choose regular files no larger than 1 GiB.") } var hash = SHA256(), size: Int64 = 0 while let block = try handle.read(upToCount: 1024 * 1024), !block.isEmpty { try Task.checkCancellation(); size += Int64(block.count) guard size <= maximumBytes else { throw Failure.invalid("The selected file exceeds 1 GiB.") } hash.update(data: block) } guard fstat(fd, &after) == 0, before.st_ino == after.st_ino, before.st_size == after.st_size, before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec, size == before.st_size, expectedSize == nil || size == expectedSize else { throw Failure.invalid("A source file changed while being copied. Please try again.") } return (size, hash.finalize().map { String(format: "%02x", $0) }.joined()) } private static func kind(_ url: URL) throws -> String? { switch url.pathExtension.lowercased() { case "dsk", "jvc", "dmk", "vdk": _ = try DiskFiles.readImage(url); return "disk" case "os9": let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 if size <= DiskFiles.limit { _ = try DiskFiles.readImage(url); return "disk" } _ = try HardDiskFiles.readImage(url); return "hard-disk" case "vhd", "img": _ = try HardDiskFiles.readImage(url); return "hard-disk" case "ccc", "rom": _ = try DiskFiles.readCartridgeROM(url); return "cartridge" case "cas", "wav": _ = try TapeImage.read(url); return "cassette" case "bin": _ = try BinaryFile.read(url); return "binary" case "pdf", "txt": return "manual" case "png", "jpg", "jpeg": return "cover" default: return nil } } func inspect(_ sources: [URL]) throws -> PersonalSoftwareDraft { try prepareRoot(); guard !sources.isEmpty else { throw CancellationError() } let id = UUID(), destination = stage(id) try manager.createDirectory(at: destination, withIntermediateDirectories: false) staged.insert(id) do { let inputs = destination.appendingPathComponent("Inputs") try manager.createDirectory(at: inputs, withIntermediateDirectories: false) var inventory: [String] = [], unsupported: [String] = [], bytes: Int64 = 0 for source in sources { let access = source.startAccessingSecurityScopedResource() defer { if access { source.stopAccessingSecurityScopedResource() } } let values = try source.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]) guard values.isSymbolicLink != true else { throw Failure.invalid("Choose original files or folders, rather than symbolic links.") } if source.pathExtension.lowercased() == "zip", values.isRegularFile == true { guard sources.count == 1 else { throw Failure.invalid("Import one ZIP at a time, or select its extracted files as one set.") } let archive = destination.appendingPathComponent("Package.zip") let reviewed = try Self.fingerprint(source) try Self.copyReviewedPackage(from: source, to: archive, byteSize: reviewed.0, sha256: reviewed.1) let extracted = destination.appendingPathComponent("Extracted") inventory = try VCCLibraryArchive.extractZIP(at: archive, toNewDirectory: extracted, maximumExpandedBytes: UInt64(Self.maximumBytes), maximumEntries: UInt(Self.maximumFiles), shouldCancel: { Task.isCancelled }) for path in inventory { try copy(extracted.appendingPathComponent(path), to: inputs.appendingPathComponent(path), count: &bytes) } } else if values.isDirectory == true { let selectedPath = source.resolvingSymlinksInPath().standardizedFileURL.path let stagingPath = destination.resolvingSymlinksInPath().standardizedFileURL.path guard selectedPath != stagingPath, !stagingPath.hasPrefix(selectedPath + "/") else { throw Failure.invalid("Select a software folder that does not contain the private library's import area.") } guard sources.count == 1 else { throw Failure.invalid("Select one coherent software folder, or choose individual files.") } // URL enumeration can canonicalize /var to /private/var // independently of the selected URL. Use the enumerator's // actual relative names, never trim by absolute string length. guard let enumerator = manager.enumerator(atPath: source.path) else { throw Failure.invalid("The selected folder cannot be read.") } for case let path as String in enumerator { try Task.checkCancellation() guard Self.validRelative(path) else { throw Failure.invalid("The software folder contains an unsafe relative name.") } let file = source.appendingPathComponent(path) let info = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .isDirectoryKey]) guard info.isSymbolicLink != true else { throw Failure.invalid("The software folder contains a symbolic link: " + file.lastPathComponent) } if info.isDirectory == true { if file.lastPathComponent.hasPrefix(".") { enumerator.skipDescendants() } continue } if file.lastPathComponent.hasPrefix(".") { continue } guard info.isRegularFile == true else { throw Failure.invalid("The software folder contains an unsupported filesystem item.") } guard inventory.count < Self.maximumFiles else { throw Failure.invalid("The software folder contains too many files.") } try copy(file, to: inputs.appendingPathComponent(path), count: &bytes); inventory.append(path) } } else { let path = source.lastPathComponent guard !inventory.contains(path) else { throw Failure.invalid("Two selected files have the same name. Put them in a folder with distinct relative paths first.") } try copy(source, to: inputs.appendingPathComponent(path), count: &bytes); inventory.append(path) } } var files: [PersonalSoftwareEntry.File] = [] for path in inventory.sorted() { guard Self.validRelative(path) else { throw Failure.invalid("The software contains an unsafe path.") } let file = inputs.appendingPathComponent(path), info = try Self.fingerprint(file) let kind = try Self.kind(file) ?? "supporting" if ["disk", "hard-disk", "cartridge", "cassette", "binary"].contains(kind), info.0 == 0 { throw Failure.invalid("A selected media file is empty: " + path) } if kind == "supporting" { unsupported.append(path) } files.append(.init(path: path, kind: kind, byteSize: info.0, sha256: info.1)) } guard files.contains(where: \.isMedia) else { throw Failure.invalid("No supported CoCo media was found. Select a disk, cassette, raw cartridge, binary or software package.") } let name = sources[0].deletingPathExtension().lastPathComponent var entry = PersonalSoftwareEntry(id: id, title: name, files: files) let package = destination.appendingPathComponent("Package.zip") if manager.fileExists(atPath: package.path) { let identity = try Self.fingerprint(package) entry.sourcePackageBytes = identity.0; entry.sourcePackageSHA256 = identity.1 } if let media = files.first(where: \.isMedia) { if media.kind == "cartridge" { entry.profile = "rom-cartridge" } if media.kind == "hard-disk" { entry.profile = "hard-drive-basic" } } let mediaIndices = entry.files.indices.filter { entry.files[$0].isMedia } if mediaIndices.count == 1, let index = mediaIndices.first, entry.files[index].kind == "disk" { entry.files[index].role = "disk0" } return .init(id: id, entry: entry, unsupported: unsupported) } catch { try? manager.removeItem(at: destination); staged.remove(id); throw error } } /// Retain exactly the bytes observed during package review. A source ZIP can /// change between review and copying; a coherent newer ZIP is still a change, /// not permission to silently import a different package. static func copyReviewedPackage(from source: URL, to target: URL, byteSize: Int64, sha256: String) throws { let manager = FileManager.default guard !manager.fileExists(atPath: target.path) else { throw Failure.invalid("The retained package destination already exists.") } try manager.copyItem(at: source, to: target) do { let retained = try fingerprint(target) guard retained.0 == byteSize, retained.1 == sha256 else { throw Failure.invalid("The source ZIP changed during copying. Select it again; existing library files were preserved.") } } catch { try? manager.removeItem(at: target) throw error } } private func copy(_ source: URL, to target: URL, count: inout Int64) throws { let relative = target.lastPathComponent guard Self.validRelative(relative) else { throw Failure.invalid("The selected file has an unsafe name.") } let before = try Self.fingerprint(source) count += before.0; guard count <= Self.maximumBytes else { throw Failure.invalid("One personal software set may contain at most 1 GiB.") } try Task.checkCancellation() try manager.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) guard !manager.fileExists(atPath: target.path) else { throw Failure.invalid("Duplicate file path in this software set.") } try manager.copyItem(at: source, to: target) let after = try Self.fingerprint(target) guard before == after else { throw Failure.invalid("A source file changed during copying. Your source files were not modified.") } } func cancel(_ draftID: UUID) { guard staged.remove(draftID) != nil else { return } try? manager.removeItem(at: stage(draftID)) } func entries(includeHidden: Bool = false) throws -> [PersonalSoftwareEntry] { try prepareRoot() var result: [PersonalSoftwareEntry] = []; warnings = [] for folder in try manager.contentsOfDirectory(at: root, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], options: [.skipsHiddenFiles]) { guard UUID(uuidString: folder.lastPathComponent) != nil else { continue } let info = try folder.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) guard info.isDirectory == true, info.isSymbolicLink != true else { throw Failure.invalid("A private library entry was replaced by an unsafe filesystem item.") } do { let entry = try read(folder.appendingPathComponent("Entry.json")) guard entry.id.uuidString.lowercased() == folder.lastPathComponent.lowercased() else { throw Failure.invalid("A private library entry has a conflicting identity.") } if includeHidden || !entry.hidden { result.append(entry) } } catch { if warnings.count < 10 { warnings.append("An unavailable private entry was preserved at " + folder.path + ". " + error.localizedDescription) } } } return result.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } } private func read(_ file: URL) throws -> PersonalSoftwareEntry { let info = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 4 * 1024 * 1024 else { throw Failure.invalid("A private entry cannot be read safely; its files have been preserved.") } var entry = try JSONDecoder().decode(PersonalSoftwareEntry.self, from: Data(contentsOf: file)) entry.category = PersonalSoftwareEntry.standardCategory(entry.category) try Self.validate(entry); return entry } private static func validate(_ entry: PersonalSoftwareEntry) throws { guard entry.schemaVersion == 1, !entry.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, entry.title.utf8.count <= 240, entry.author.utf8.count <= 500, entry.notes.utf8.count <= 65536, [128, 512, 2048, 8192].contains(entry.ramKiB), ["6809", "6309"].contains(entry.processor), ["rgb", "composite"].contains(entry.video), ["disk-basic", "rom-cartridge", "hard-drive-basic"].contains(entry.profile), !entry.files.isEmpty, entry.files.count <= maximumFiles, Set(entry.files.map(\.path)).count == entry.files.count, entry.files.contains(where: \.isMedia), entry.command.utf8.count <= 4096, entry.command.unicodeScalars.allSatisfy({ $0.value == 13 || $0.value == 10 || (32...126).contains($0.value) }), entry.files.allSatisfy({ ["disk", "hard-disk", "cartridge", "cassette", "binary", "manual", "cover", "supporting"].contains($0.kind) && validRelative($0.path) && $0.byteSize >= 0 && $0.byteSize <= maximumBytes && $0.sha256.count == 64 && $0.sha256.allSatisfy(\.isHexDigit) }) else { throw Failure.invalid("The personal entry is damaged, unsupported or contains invalid setup data. Its files have been preserved.") } if entry.sourcePackageSHA256 != nil || entry.sourcePackageBytes != nil { guard let sha = entry.sourcePackageSHA256, sha.count == 64, sha.allSatisfy(\.isHexDigit), let bytes = entry.sourcePackageBytes, bytes > 0, bytes <= maximumBytes else { throw Failure.invalid("The retained package identity is invalid; files were preserved.") } } switch entry.cover { case .imported(let path): guard entry.files.contains(where: { $0.kind == "cover" && $0.path == path }) else { throw Failure.invalid("Choose a cover image from this entry's imported files.") } case .custom(let file): let parts = file.path.split(separator: "/", omittingEmptySubsequences: false) guard validRelative(file.path), parts.count == 2, parts.first == "PersonalCovers", (file.path as NSString).pathExtension == "png", UUID(uuidString: URL(fileURLWithPath: file.path).deletingPathExtension().lastPathComponent) != nil, file.sha256.count == 64, file.sha256.allSatisfy(\.isHexDigit), file.byteSize > 0, file.byteSize <= Int64(SoftwareLibraryArtworkCache.maximumThumbnailBytes) else { throw Failure.invalid("The private cover descriptor is invalid. Existing files were preserved.") } case .categoryIcon, nil: break } let targets = entry.files.filter { !$0.role.isEmpty }.map(\.role) guard Set(targets).count == targets.count, targets.allSatisfy({ ["disk0", "disk1", "disk2", "disk3", "hard0", "hard1", "media", "cartridge"].contains($0) }) else { throw Failure.invalid("Assign each drive or media target at most once.") } if entry.configured { for file in entry.files where !file.role.isEmpty { let valid = (file.kind == "disk" && file.role.hasPrefix("disk") && entry.profile != "rom-cartridge") || (file.kind == "hard-disk" && file.role.hasPrefix("hard") && entry.profile == "hard-drive-basic") || (file.kind == "cassette" && file.role == "media" && entry.profile == "disk-basic") || (file.kind == "cartridge" && file.role == "cartridge" && entry.profile == "rom-cartridge") guard valid else { throw Failure.invalid("A media assignment does not match this machine setup. Review the file's role and machine setup before saving.") } } } } func save(_ draft: PersonalSoftwareDraft, allowDuplicate: Bool = false, coverPNG: Data? = nil) throws -> PersonalSoftwareEntry { var draft = draft let normalizedCover = try coverPNG.map { try PersonalCoverImage.prepare($0) } draft.entry.category = PersonalSoftwareEntry.standardCategory(draft.entry.category) try Self.validate(draft.entry) guard staged.contains(draft.id), draft.entry.id == draft.id else { throw Failure.invalid("This import preview has expired. Select the files again.") } if !allowDuplicate, let existing = try entries().first(where: { $0.packageSHA256 == draft.entry.packageSHA256 }) { throw Failure.duplicate(existing.id) } let source = stage(draft.id), inputs = source.appendingPathComponent("Inputs") try requireSafePath(inputs, directory: true) let final = directory(for: draft.id) guard !manager.fileExists(atPath: final.path) else { throw Failure.invalid("A personal entry already uses this identity.") } let required = draft.entry.files.reduce(Int64(0)) { $0 + $1.byteSize } * 3 + 64 * 1024 * 1024 if let free = try root.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage, free < required { throw SoftwareLibraryInstaller.Failure.insufficientSpace } let ready = source.appendingPathComponent("Ready") if manager.fileExists(atPath: ready.path) { try manager.removeItem(at: ready) } try manager.createDirectory(at: ready, withIntermediateDirectories: false) do { for name in ["Original/Files", "Working", "Assets"] { try manager.createDirectory(at: ready.appendingPathComponent(name), withIntermediateDirectories: true) } for file in draft.entry.files { try Task.checkCancellation() if file.kind == "hard-disk" { _ = try HardDiskFiles.readImage(inputs.appendingPathComponent(file.path)) } let original = ready.appendingPathComponent("Original/Files").appendingPathComponent(file.path) var count: Int64 = 0 try copy(inputs.appendingPathComponent(file.path), to: original, count: &count) let actual = try Self.fingerprint(original) guard actual.0 == file.byteSize, actual.1 == file.sha256 else { throw Failure.invalid("The staged import no longer matches its preview.") } // A .txt or image can also be runtime program data. Preserve // the coherent complete set in Working, even when an asset is // additionally offered in the native manual/artwork reader. let target = ready.appendingPathComponent("Working").appendingPathComponent(file.path) try manager.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try manager.copyItem(at: original, to: target) try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target.path) if ["manual", "cover"].contains(file.kind) { let asset = ready.appendingPathComponent("Assets").appendingPathComponent(file.path) try manager.createDirectory(at: asset.deletingLastPathComponent(), withIntermediateDirectories: true) try manager.copyItem(at: original, to: asset) } try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: original.path) } let package = source.appendingPathComponent("Package.zip") if manager.fileExists(atPath: package.path) { let identity = try Self.fingerprint(package) guard identity.0 == draft.entry.sourcePackageBytes, identity.1 == draft.entry.sourcePackageSHA256 else { throw Failure.invalid("The source ZIP no longer matches the reviewed import.") } let retained = ready.appendingPathComponent("Original/Package.zip") try manager.copyItem(at: package, to: retained) guard try Self.fingerprint(retained) == identity else { throw Failure.invalid("The retained source ZIP did not copy correctly.") } try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: retained.path) } if let normalizedCover { draft.entry.cover = .custom(try storeCover(normalizedCover, in: ready)) } else if draft.entry.cover != nil { _ = try previewCover(draft.entry, draftID: draft.id) } try write(draft.entry, to: ready.appendingPathComponent("Entry.json")) try Task.checkCancellation(); try manager.moveItem(at: ready, to: final) cancel(draft.id) return draft.entry } catch { try? manager.removeItem(at: ready); throw error } } private func write(_ entry: PersonalSoftwareEntry, to url: URL) throws { let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys] try encoder.encode(entry).write(to: url, options: .atomic) } func update(_ entry: PersonalSoftwareEntry, coverPNG: Data? = nil) throws { var entry = entry let normalizedCover = try coverPNG.map { try PersonalCoverImage.prepare($0) } entry.category = PersonalSoftwareEntry.standardCategory(entry.category) try Self.validate(entry) let directory = directory(for: entry.id) try requireSafePath(directory, directory: true) let file = directory.appendingPathComponent("Entry.json") let previous = try read(file) guard (coverPNG == nil && entry.cover == previous.cover) || previous.updatedAt == entry.updatedAt else { throw Failure.invalid("This private entry changed while its cover was being edited. Reopen it before saving; existing files were preserved.") } func identities(_ files: [PersonalSoftwareEntry.File]) -> [String: String] { Dictionary(uniqueKeysWithValues: files.map { ($0.path, $0.kind + ":" + String($0.byteSize) + ":" + $0.sha256) }) } guard identities(previous.files) == identities(entry.files), previous.createdAt == entry.createdAt, previous.sourcePackageSHA256 == entry.sourcePackageSHA256, previous.sourcePackageBytes == entry.sourcePackageBytes else { throw Failure.invalid("Use a new import to replace media; existing working files are preserved.") } var added: URL? do { if let normalizedCover { let cover = try storeCover(normalizedCover, in: directory) added = directory.appendingPathComponent("Assets").appendingPathComponent(cover.path) entry.cover = .custom(cover) } else if entry.cover != nil { _ = try previewCover(entry, draftID: nil) } entry.updatedAt = Date(); try write(entry, to: file) } catch { if let added { try? manager.removeItem(at: added) } throw error } } /// Preview reads retained assets or this draft's staged input; it never /// persists a chosen replacement image or changes the media inventory. func previewCover(_ entry: PersonalSoftwareEntry, draftID: UUID? = nil) throws -> Data? { try Self.validate(entry) guard let cover = entry.selectedCoverFile else { return nil } let base: URL if let draftID { guard staged.contains(draftID), draftID == entry.id else { throw Failure.invalid("This import preview has expired. Select the files again.") } base = stage(draftID).appendingPathComponent("Inputs") } else { base = directory(for: entry.id).appendingPathComponent("Assets") } let source = base.appendingPathComponent(cover.path) try requireSafePath(source, directory: false) let data = try PersonalCoverImage.sourceData(source) guard Int64(data.count) == cover.byteSize, SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == cover.sha256.lowercased() else { throw Failure.invalid("The private cover no longer matches its saved identity. Existing files were preserved.") } return try PersonalCoverImage.prepare(data) } private func requireSafePath(_ path: URL, directory: Bool) throws { let path = path.standardizedFileURL guard path.path == root.path || path.path.hasPrefix(root.path + "/") else { throw Failure.invalid("The private asset path leaves its library.") } var checked = root let relative = path.path.dropFirst(root.path.count).split(separator: "/") let rootValues = try root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) guard rootValues.isDirectory == true, rootValues.isSymbolicLink != true else { throw Failure.invalid("The private library location is not a safe directory.") } for (index, component) in relative.enumerated() { checked.appendPathComponent(String(component)) let values = try checked.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]) let needsDirectory = index < relative.count - 1 || directory guard values.isSymbolicLink != true, needsDirectory ? values.isDirectory == true : values.isRegularFile == true else { throw Failure.invalid("The private asset path contains an unsafe filesystem item. Existing files were preserved.") } } } private func storeCover(_ data: Data, in directory: URL) throws -> PersonalSoftwareEntry.CoverFile { try requireSafePath(directory, directory: true) for relative in ["Assets", "Assets/PersonalCovers"] { let folder = directory.appendingPathComponent(relative) if !manager.fileExists(atPath: folder.path) { try manager.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) } try requireSafePath(folder, directory: true) } let path = "PersonalCovers/" + UUID().uuidString.lowercased() + ".png" let destination = directory.appendingPathComponent("Assets").appendingPathComponent(path) let fd = open(destination.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) guard fd >= 0 else { throw Failure.invalid("The replacement cover could not be saved safely.") } let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) do { try handle.write(contentsOf: data); try handle.close() return .init(path: path, sha256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(), byteSize: Int64(data.count)) } catch { try? handle.close(); try? manager.removeItem(at: destination); throw error } } } #endif