Repository Public License
1import AppKit2import Foundation3import PrismComponentSDK4import PrismCore5import PrismIconKit6import PrismObjectModel78/// Runs a system tool with an argument array (never a shell string) and captures its output.9enum Tool {10 @discardableResult11 static func run(_ path: String, _ arguments: [String]) throws -> String {12 guard FileManager.default.isExecutableFile(atPath: path) else { throw PublishError("\(path) is not available on this Mac.") }13 let p = Process()14 p.executableURL = URL(fileURLWithPath: path)15 p.arguments = arguments16 let pipe = Pipe()17 p.standardOutput = pipe18 p.standardError = pipe19 try p.run()20 let data = pipe.fileHandleForReading.readDataToEndOfFile()21 p.waitUntilExit()22 let output = String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)23 guard p.terminationStatus == 0 else { throw PublishError("\(URL(fileURLWithPath: path).lastPathComponent) failed: \(output.isEmpty ? "exit \(p.terminationStatus)" : output)") }24 return output25 }26}2728public struct InstalledSatellite: Sendable, Equatable {29 public var projectID: String30 public var appPath: String31 public var bundleID: String32 public var version: String33 public var permissions: [String]34 public var blueprintHash: String35 public var signing: String36 public var publishedAt: Double37 /// The previous bundle, kept so an update can be rolled back.38 public var previousPath: String?39 public var previousVersion: String?4041 var json: JSONValue {42 [43 "projectId": .string(projectID), "appPath": .string(appPath), "bundleId": .string(bundleID), "version": .string(version),44 "permissions": .array(permissions.map(JSONValue.string)), "blueprintHash": .string(blueprintHash), "signing": .string(signing),45 "publishedAt": .double(publishedAt), "previousPath": previousPath.map(JSONValue.string) ?? .null,46 "previousVersion": previousVersion.map(JSONValue.string) ?? .null,47 ]48 }4950 init?(json: JSONValue) {51 guard let p = json["projectId"]?.stringValue, let a = json["appPath"]?.stringValue, let b = json["bundleId"]?.stringValue else { return nil }52 projectID = p; appPath = a; bundleID = b53 version = json["version"]?.stringValue ?? ""54 permissions = (json["permissions"]?.arrayValue ?? []).compactMap(\.stringValue)55 blueprintHash = json["blueprintHash"]?.stringValue ?? ""56 signing = json["signing"]?.stringValue ?? ""57 publishedAt = json["publishedAt"]?.doubleValue ?? 058 previousPath = json["previousPath"]?.stringValue59 previousVersion = json["previousVersion"]?.stringValue60 }6162 init(projectID: String, appPath: String, bundleID: String, version: String, permissions: [String], blueprintHash: String, signing: String) {63 self.projectID = projectID; self.appPath = appPath; self.bundleID = bundleID; self.version = version; self.permissions = permissions64 self.blueprintHash = blueprintHash; self.signing = signing; publishedAt = Date().timeIntervalSince197065 }66}6768public struct PublishPlan: Sendable, Equatable {69 public var manifest: SatelliteManifest70 public var destination: URL71 public var isUpdate: Bool72 public var addedPermissions: [String]73 public var removedPermissions: [String]74 public var signingIdentity: String?75 public var notes: [String]76}7778public struct PublishResult: Sendable, Equatable {79 public var installed: InstalledSatellite80 public var signatureSummary: String81 public var notes: [String]82}8384/// Builds, signs, installs, updates, rolls back and uninstalls desktop satellites (spec §10, ADR 0005).85public struct SatellitePublisher: Sendable {86 public static let bundlePrefix = "ai.spboucher.prism.satellite"8788 public let hostTemplate: URL89 public let registryFile: URL90 public let registry: ComponentRegistry9192 public init(hostTemplate: URL, registryFile: URL, registry: ComponentRegistry) {93 self.hostTemplate = hostTemplate; self.registryFile = registryFile; self.registry = registry94 }9596 // MARK: Registry of installed satellites9798 public func installed() -> [InstalledSatellite] {99 guard let data = FileManager.default.contents(atPath: registryFile.path), let list = (try? JSONValue.parse(data))?.arrayValue else { return [] }100 return list.compactMap(InstalledSatellite.init(json:))101 }102103 public func installed(for projectID: String) -> InstalledSatellite? { installed().first { $0.projectID == projectID } }104105 private func save(_ list: [InstalledSatellite]) throws {106 try AtomicFile.write(Data(JSONValue.array(list.map(\.json)).prettyString().utf8), to: registryFile)107 }108109 // MARK: Planning110111 /// A bundle identifier that is stable for the project and never collides with another project's satellite.112 public func bundleID(for blueprint: AppBlueprint, projectID: String) -> String {113 if let existing = installed(for: projectID) { return existing.bundleID }114 let slug = PrismID.slug(blueprint.name, fallback: "app").replacingOccurrences(of: "_", with: "")115 let taken = Set(installed().map(\.bundleID))116 var candidate = "\(Self.bundlePrefix).\(slug)"117 if taken.contains(candidate) { candidate += "." + PrismID.slug(String(projectID.suffix(6))).replacingOccurrences(of: "_", with: "") }118 var n = 2119 while taken.contains(candidate) { candidate = "\(Self.bundlePrefix).\(slug)\(n)"; n += 1 }120 return candidate121 }122123 static func bundleName(_ name: String) -> String {124 let clean = name.unicodeScalars.filter { !CharacterSet(charactersIn: "/:\\\0").contains($0) && !CharacterSet.controlCharacters.contains($0) }125 let text = String(String.UnicodeScalarView(clean)).trimmingCharacters(in: .whitespaces)126 return String((text.isEmpty || text.hasPrefix(".") ? "PRISM App" : text).prefix(60))127 }128129 public func validate(_ blueprint: AppBlueprint) -> [ValidationIssue] { BlueprintValidator.validate(blueprint, registry: registry) }130131 public func plan(blueprint: AppBlueprint, projectID: String, version: String, directory: URL, signingIdentity: String? = nil) throws -> PublishPlan {132 let errors = validate(blueprint).errors133 guard errors.isEmpty else { throw PublishError("The app has \(errors.count) problem(s) to fix before publishing. First: \(errors[0].message)") }134 guard version.split(separator: ".").count == 3, version.split(separator: ".").allSatisfy({ Int($0) != nil }) else {135 throw PublishError("“\(version)” is not a version like 1.0.0.")136 }137 guard FileManager.default.fileExists(atPath: hostTemplate.appendingPathComponent("Contents/MacOS").path) else {138 throw PublishError("The satellite runtime is missing from this copy of PRISM, so apps cannot be published. Reinstall PRISM.")139 }140 var isDirectory: ObjCBool = false141 guard FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory), isDirectory.boolValue, FileManager.default.isWritableFile(atPath: directory.path) else {142 throw PublishError("PRISM cannot write to “\(directory.lastPathComponent)”. Choose another folder.")143 }144 let previous = installed(for: projectID)145 let manifest = SatelliteManifest(blueprint: blueprint, appId: bundleID(for: blueprint, projectID: projectID), version: version, projectID: projectID)146 let destination = directory.appendingPathComponent(Self.bundleName(blueprint.name) + ".app")147 if previous == nil, FileManager.default.fileExists(atPath: destination.path) {148 throw PublishError("“\(destination.lastPathComponent)” already exists in that folder and was not published from this project. Choose another folder or rename the app.")149 }150 var notes = [151 "The app contains its own copy of the PRISM runtime: it runs without PRISM being open or installed.",152 "It is not sandboxed. It can only do what its components do, but macOS does not enforce that.",153 ]154 if signingIdentity == nil {155 notes.append("It is signed ad hoc (no developer identity). It opens normally on this Mac. Copied to another Mac it will be blocked by Gatekeeper, because it is not notarized.")156 } else {157 notes.append("It is signed with your developer identity but not notarized. On another Mac, Gatekeeper will still block a downloaded copy until it is notarized.")158 }159 return PublishPlan(160 manifest: manifest, destination: destination, isUpdate: previous != nil,161 addedPermissions: blueprint.permissions.filter { !(previous?.permissions ?? []).contains($0) },162 removedPermissions: (previous?.permissions ?? []).filter { !blueprint.permissions.contains($0) },163 signingIdentity: signingIdentity, notes: notes164 )165 }166167 // MARK: Publishing168169 /// Assembles the bundle in a staging folder, signs and verifies it, then swaps it into place.170 /// If anything fails the destination is left exactly as it was.171 public func publish(_ plan: PublishPlan, blueprint: AppBlueprint) throws -> PublishResult {172 let fm = FileManager.default173 guard blueprint.contentHash == plan.manifest.blueprintHash else { throw PublishError("The app changed after the publish plan was made. Review the plan again.") }174 let staging = plan.destination.deletingLastPathComponent().appendingPathComponent(".prism-staging-\(UUID().uuidString)", isDirectory: true)175 try fm.createDirectory(at: staging, withIntermediateDirectories: true)176 defer { try? fm.removeItem(at: staging) }177 let staged = staging.appendingPathComponent(plan.destination.lastPathComponent)178 try fm.copyItem(at: hostTemplate, to: staged)179180 // Info.plist: the satellite's own identity.181 let plistURL = staged.appendingPathComponent("Contents/Info.plist")182 guard let plistData = fm.contents(atPath: plistURL.path),183 var plist = try PropertyListSerialization.propertyList(from: plistData, format: nil) as? [String: Any] else {184 throw PublishError("The satellite runtime template is damaged (no Info.plist).")185 }186 plist["CFBundleIdentifier"] = plan.manifest.appId187 plist["CFBundleName"] = Self.bundleName(plan.manifest.displayName)188 plist["CFBundleDisplayName"] = plan.manifest.displayName189 plist["CFBundleShortVersionString"] = plan.manifest.version190 plist["CFBundleVersion"] = String(Int(Date().timeIntervalSince1970))191 plist["CFBundleIconFile"] = "AppIcon"192 try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0).write(to: plistURL, options: .atomic)193194 let resources = staged.appendingPathComponent("Contents/Resources", isDirectory: true)195 try fm.createDirectory(at: resources, withIntermediateDirectories: true)196 try plan.manifest.json.prettyString().data(using: .utf8)!.write(to: resources.appendingPathComponent("satellite.json"), options: .atomic)197 try blueprint.prettyData().write(to: resources.appendingPathComponent("blueprint.json"), options: .atomic)198 try SatelliteIcon.write(spec: SatelliteIcon.spec(for: blueprint, appId: plan.manifest.appId), to: resources.appendingPathComponent("AppIcon.icns"))199200 // Changing a signed bundle invalidates its signature, so it is always signed again (never assumed to survive).201 try? fm.removeItem(at: staged.appendingPathComponent("Contents/_CodeSignature"))202 var arguments = ["--force", "--sign", plan.signingIdentity ?? "-"]203 arguments += plan.signingIdentity == nil ? ["--timestamp=none"] : ["--timestamp", "--options", "runtime"]204 try Tool.run("/usr/bin/codesign", arguments + [staged.path])205 try Tool.run("/usr/bin/codesign", ["--verify", "--deep", "--strict", staged.path])206 let details = (try? Tool.run("/usr/bin/codesign", ["-dv", staged.path])) ?? ""207 let signatureSummary = details.split(separator: "\n").filter { $0.hasPrefix("Identifier=") || $0.hasPrefix("Signature=") || $0.hasPrefix("Authority=") || $0.hasPrefix("TeamIdentifier=") }.joined(separator: "; ")208209 // The staged bundle must load exactly as the host will load it.210 _ = try SatelliteLoader.load(resources: resources, registry: registry)211212 // Safe replacement with a kept previous version.213 var all = installed()214 let previous = all.first { $0.projectID == plan.manifest.projectID }215 var record = InstalledSatellite(216 projectID: plan.manifest.projectID, appPath: plan.destination.path, bundleID: plan.manifest.appId, version: plan.manifest.version,217 permissions: plan.manifest.permissions, blueprintHash: plan.manifest.blueprintHash, signing: plan.signingIdentity == nil ? "ad hoc" : "developer identity"218 )219 let backupDir = registryFile.deletingLastPathComponent().appendingPathComponent("satellite-backups/\(plan.manifest.projectID)", isDirectory: true)220 var movedOld: URL?221 if fm.fileExists(atPath: plan.destination.path) {222 try fm.createDirectory(at: backupDir, withIntermediateDirectories: true)223 let backup = backupDir.appendingPathComponent("\(previous?.version ?? "previous")-\(Int(Date().timeIntervalSince1970)).app")224 try fm.moveItem(at: plan.destination, to: backup)225 movedOld = backup226 }227 do {228 try fm.moveItem(at: staged, to: plan.destination)229 } catch {230 if let movedOld { try? fm.moveItem(at: movedOld, to: plan.destination) }231 throw PublishError("The app could not be installed: \(error.localizedDescription). Nothing was changed.")232 }233 if let movedOld {234 if let old = previous?.previousPath { try? fm.removeItem(atPath: old) }235 record.previousPath = movedOld.path236 record.previousVersion = previous?.version237 }238 if let previous, previous.appPath != plan.destination.path { try? fm.removeItem(atPath: previous.appPath) }239 all.removeAll { $0.projectID == plan.manifest.projectID }240 all.append(record)241 try save(all)242 return PublishResult(installed: record, signatureSummary: signatureSummary, notes: plan.notes)243 }244245 /// Puts the previous version of the bundle back. The app's data is not touched.246 @discardableResult247 public func rollback(projectID: String) throws -> InstalledSatellite {248 let fm = FileManager.default249 var all = installed()250 guard var record = all.first(where: { $0.projectID == projectID }) else { throw PublishError("This app has not been published.") }251 guard let previousPath = record.previousPath, fm.fileExists(atPath: previousPath) else { throw PublishError("There is no earlier published version to return to.") }252 let current = URL(fileURLWithPath: record.appPath)253 let aside = current.deletingLastPathComponent().appendingPathComponent(".prism-rollback-\(UUID().uuidString).app")254 if fm.fileExists(atPath: current.path) { try fm.moveItem(at: current, to: aside) }255 do { try fm.moveItem(atPath: previousPath, toPath: current.path) } catch {256 if fm.fileExists(atPath: aside.path) { try? fm.moveItem(at: aside, to: current) }257 throw PublishError("The earlier version could not be restored: \(error.localizedDescription)")258 }259 try? fm.removeItem(at: aside)260 try Tool.run("/usr/bin/codesign", ["--verify", "--deep", "--strict", current.path])261 if let m = try? SatelliteManifest(json: JSONValue.parse(Data(contentsOf: current.appendingPathComponent("Contents/Resources/satellite.json")))) {262 record.version = m.version; record.permissions = m.permissions; record.blueprintHash = m.blueprintHash263 }264 record.previousPath = nil265 record.previousVersion = nil266 all.removeAll { $0.projectID == projectID }267 all.append(record)268 try save(all)269 return record270 }271272 /// Removes the bundle and its backups; the app's data only when `removeData` is true (the user's explicit choice).273 public func uninstall(projectID: String, removeData: Bool, dataBase: URL? = nil) throws {274 let fm = FileManager.default275 var all = installed()276 guard let record = all.first(where: { $0.projectID == projectID }) else { throw PublishError("This app has not been published.") }277 guard record.bundleID.hasPrefix(Self.bundlePrefix + ".") else { throw PublishError("Refusing to remove an app PRISM did not publish.") }278 if fm.fileExists(atPath: record.appPath) {279 // Only delete a bundle that still identifies itself as this satellite.280 let plist = NSDictionary(contentsOfFile: record.appPath + "/Contents/Info.plist")281 guard plist?["CFBundleIdentifier"] as? String == record.bundleID else {282 throw PublishError("The app at \(record.appPath) is no longer the one PRISM published, so it was left alone.")283 }284 try fm.removeItem(atPath: record.appPath)285 }286 if let previous = record.previousPath { try? fm.removeItem(atPath: previous) }287 try? fm.removeItem(at: registryFile.deletingLastPathComponent().appendingPathComponent("satellite-backups/\(projectID)"))288 if removeData { try? fm.removeItem(at: SatelliteLoader.dataDirectory(appId: record.bundleID, base: dataBase)) }289 all.removeAll { $0.projectID == projectID }290 try save(all)291 }292293 /// Developer ID identities available in the user's Keychain (names only), for the optional signing choice.294 public static func signingIdentities() -> [String] {295 guard let out = try? Tool.run("/usr/bin/security", ["find-identity", "-v", "-p", "codesigning"]) else { return [] }296 return out.split(separator: "\n").compactMap { line in297 guard let start = line.firstIndex(of: "\""), let end = line.lastIndex(of: "\""), start < end else { return nil }298 let name = String(line[line.index(after: start)..<end])299 return name.hasPrefix("Developer ID Application") ? name : nil300 }301 }302}303304public enum SatelliteIcon {305 /// The icon a published app gets: the one designed for it, or one drawn from its name when there is none (or it is not drawable).306 public static func spec(for blueprint: AppBlueprint, appId: String) -> JSONValue {307 if let icon = blueprint.icon, IconSpec.problems(icon).isEmpty { return icon }308 return IconSpec.automatic(name: blueprint.name, seed: appId)309 }310311 public static func write(spec: JSONValue, to url: URL) throws {312 do { try IconRenderer.writeICNS(spec, to: url) } catch { throw PublishError("The app icon could not be drawn: \(error.localizedDescription)") }313 }314315 /// Writes the automatic icon for an app name.316 public static func write(name: String, seed: String, to url: URL) throws { try write(spec: IconSpec.automatic(name: name, seed: seed), to: url) }317}318