Repository Public License
1import AppKit2import Foundation3import PrismIconKit4import Testing5import PrismComponentCatalog6import PrismCore7import PrismDataRuntime8import PrismObjectModel9import PrismTestKit10@testable import PrismSatellitePublisher1112/// The host template built by `scripts/build.sh`. Tests that need a real bundle are skipped when it is absent.13let hostTemplate: URL? = {14 let candidates = [ProcessInfo.processInfo.environment["PRISM_HOST_TEMPLATE"].map { URL(fileURLWithPath: $0) },15 testRepoRoot.appendingPathComponent("build/debug/PrismSatelliteHost.app"), testRepoRoot.appendingPathComponent("build/release/PrismSatelliteHost.app")]16 return candidates.compactMap { $0 }.first { FileManager.default.fileExists(atPath: $0.appendingPathComponent("Contents/MacOS/PrismSatelliteHost").path) }17}()18let launchTestsEnabled = ProcessInfo.processInfo.environment["PRISM_TEST_LAUNCH"] == "1"1920func sandbox() -> URL {21 let url = FileManager.default.temporaryDirectory.appendingPathComponent("prism-publish-\(UUID().uuidString)")22 try? FileManager.default.createDirectory(at: url.appendingPathComponent("Applications"), withIntermediateDirectories: true)23 return url24}2526func publisher(_ root: URL, template: URL? = hostTemplate) -> SatellitePublisher {27 SatellitePublisher(hostTemplate: template ?? root.appendingPathComponent("missing.app"), registryFile: root.appendingPathComponent("satellites.json"), registry: Catalog.registry)28}2930@Suite struct SatelliteFormatTests {31 @Test func manifestRoundTripAndRuntimeCompatibility() throws {32 let bp = try templateBlueprint()33 let m = SatelliteManifest(blueprint: bp, appId: "ai.spboucher.prism.satellite.expensetracker", version: "1.0.0", projectID: "prj_x")34 #expect(try SatelliteManifest(json: JSONValue.parse(m.json.canonicalData())) == m)35 #expect(m.json["runtime"]?["kind"] == "prism-satellite" && m.json["entrypoint"] == "pages/home" && m.json["data"]?["store"] == "sqlite")36 #expect(m.components.contains("prism.chart.bar") && m.permissions.contains("storage.local"))37 #expect(PrismRuntimeInfo.isCompatible(minimum: "1.0.0", current: "1.0.0") && PrismRuntimeInfo.isCompatible(minimum: "1.0.0", current: "1.2.0"))38 #expect(!PrismRuntimeInfo.isCompatible(minimum: "2.0.0", current: "1.9.9") && !PrismRuntimeInfo.isCompatible(minimum: "1.0.1", current: "1.0.0"))39 }4041 @Test func loaderExplainsEveryWayAnAppCanBeBroken() throws {42 let dir = sandbox()43 defer { try? FileManager.default.removeItem(at: dir) }44 let bp = try templateBlueprint()45 let manifest = SatelliteManifest(blueprint: bp, appId: "ai.spboucher.prism.satellite.x", version: "1.0.0", projectID: "p")46 func write(_ m: JSONValue?, _ b: Data?) {47 try? FileManager.default.removeItem(at: dir.appendingPathComponent("satellite.json"))48 try? FileManager.default.removeItem(at: dir.appendingPathComponent("blueprint.json"))49 if let m { try? m.canonicalData().write(to: dir.appendingPathComponent("satellite.json")) }50 if let b { try? b.write(to: dir.appendingPathComponent("blueprint.json")) }51 }52 func failure() -> String { do { _ = try SatelliteLoader.load(resources: dir, registry: Catalog.registry); return "" } catch { return error.localizedDescription } }5354 write(manifest.json, bp.prettyData())55 #expect(try SatelliteLoader.load(resources: dir, registry: Catalog.registry).blueprint == bp)56 write(nil, bp.prettyData()); #expect(failure().contains("incomplete"))57 write(manifest.json, nil); #expect(failure().contains("incomplete"))58 write(["schemaVersion": 1], bp.prettyData()); #expect(failure().contains("manifest cannot be read"))59 // Missing or too-old runtime: say which version is needed instead of crashing.60 var newer = manifest; newer.minimumRuntime = "9.0.0"61 write(newer.json, bp.prettyData()); #expect(failure().contains("needs PRISM runtime 9.0.0"))62 // A definition edited after publishing does not match its recorded hash.63 var tampered = bp; tampered.permissions.append("network.client")64 write(manifest.json, tampered.prettyData()); #expect(failure().contains("changed after it was published"))65 // A component this runtime does not have.66 var future = bp; future.objects.append(PrismObject(id: "holo", type: "prism.hologram")); future.objects[future.index(of: "root")!].children.append("holo")67 write(SatelliteManifest(blueprint: future, appId: "a.b", version: "1.0.0", projectID: "p").json, future.prettyData())68 #expect(failure().contains("not in the component catalog"))69 #expect(SatelliteLoader.dataDirectory(appId: "a.b.c", base: dir).lastPathComponent == "a.b.c")70 }7172 @Test func aDesignedIconIsUsedAndABrokenOneFallsBack() throws {73 var bp = AppBlueprint(id: "a", name: "Garden")74 let designed: JSONValue = ["background": ["colors": ["#0B3D2E", "#34C759"]], "layers": [["symbol": "leaf.fill", "size": 56]], "finish": "glass"]75 bp.icon = designed76 #expect(SatelliteIcon.spec(for: bp, appId: "x") == designed)77 bp.icon = ["layers": []]78 #expect(SatelliteIcon.spec(for: bp, appId: "x") == IconSpec.automatic(name: "Garden", seed: "x"))79 // The icon is part of the saved app and survives a round trip.80 bp.icon = designed81 #expect(try AppBlueprint.load(bp.prettyData()).icon == designed)82 }8384 @Test func iconIsDrawnForAnyName() throws {85 for name in ["Expense Tracker", "é", "", "123 go", "🙂 notes"] {86 let rep = NSBitmapImageRep(cgImage: try IconRenderer.image(IconSpec.automatic(name: name, seed: name), pixels: 128))87 #expect(rep.pixelsWide == 128 && (rep.colorAt(x: 64, y: 30)?.alphaComponent ?? 0) > 0.9 && (rep.colorAt(x: 1, y: 1)?.alphaComponent ?? 1) < 0.1)88 }89 #expect(SatellitePublisher.bundleName("../../etc/passwd") == "....etcpasswd" || !SatellitePublisher.bundleName("../../etc/passwd").contains("/"))90 #expect(SatellitePublisher.bundleName(" ") == "PRISM App" && SatellitePublisher.bundleName(".hidden") == "PRISM App")91 }9293 @Test func missingRuntimeTemplateStopsPublishingWithAClearMessage() throws {94 let root = sandbox()95 defer { try? FileManager.default.removeItem(at: root) }96 let p = publisher(root, template: root.appendingPathComponent("nope.app"))97 #expect(throws: PublishError("The satellite runtime is missing from this copy of PRISM, so apps cannot be published. Reinstall PRISM.")) {98 try p.plan(blueprint: try templateBlueprint(), projectID: "p", version: "1.0.0", directory: root.appendingPathComponent("Applications"))99 }100 }101}102103@Suite(.serialized, .enabled(if: hostTemplate != nil, "Run scripts/build.sh first: these tests publish a real bundle.")) struct PublishTests {104 @Test func publishProducesASeparateSignedApp() throws {105 let root = sandbox()106 defer { try? FileManager.default.removeItem(at: root) }107 let p = publisher(root), bp = try templateBlueprint()108 let plan = try p.plan(blueprint: bp, projectID: "prj_one", version: "1.0.0", directory: root.appendingPathComponent("Applications"))109 #expect(!plan.isUpdate && plan.addedPermissions == bp.permissions && plan.manifest.appId == "ai.spboucher.prism.satellite.expensetracker")110 #expect(plan.notes.contains { $0.contains("ad hoc") && $0.contains("Gatekeeper") } && plan.notes.contains { $0.contains("not sandboxed") })111 let result = try p.publish(plan, blueprint: bp)112 let app = URL(fileURLWithPath: result.installed.appPath)113 #expect(app.lastPathComponent == "Expense Tracker.app")114 let plist = try #require(NSDictionary(contentsOf: app.appendingPathComponent("Contents/Info.plist")))115 #expect(plist["CFBundleIdentifier"] as? String == plan.manifest.appId && plist["CFBundleDisplayName"] as? String == "Expense Tracker")116 #expect(plist["CFBundleShortVersionString"] as? String == "1.0.0" && plist["CFBundleIconFile"] as? String == "AppIcon")117 for file in ["Contents/MacOS/PrismSatelliteHost", "Contents/Resources/AppIcon.icns", "Contents/Resources/satellite.json", "Contents/Resources/blueprint.json", "Contents/_CodeSignature/CodeResources"] {118 #expect(FileManager.default.fileExists(atPath: app.appendingPathComponent(file).path), "\(file)")119 }120 // The signature covers the new resources: verification passes, and tampering afterwards is detected.121 #expect(result.signatureSummary.contains("Identifier=\(plan.manifest.appId)") && result.signatureSummary.contains("adhoc"))122 try Tool.run("/usr/bin/codesign", ["--verify", "--deep", "--strict", app.path])123 try Data("{}".utf8).write(to: app.appendingPathComponent("Contents/Resources/blueprint.json"))124 #expect(throws: PublishError.self) { try Tool.run("/usr/bin/codesign", ["--verify", "--deep", "--strict", app.path]) }125 #expect(p.installed(for: "prj_one")?.bundleID == plan.manifest.appId)126 #expect((try? FileManager.default.contentsOfDirectory(atPath: root.appendingPathComponent("Applications").path))?.filter { $0.hasPrefix(".prism-staging") } == [])127 }128129 @Test func anAppWithCustomLogicAndADesignedIconPublishesWithItsOwnIcon() throws {130 let root = sandbox()131 defer { try? FileManager.default.removeItem(at: root) }132 try FileManager.default.createDirectory(at: root.appendingPathComponent("Applications"), withIntermediateDirectories: true)133 let bp = try AppBlueprint.load(Data(contentsOf: testRepoRoot.appendingPathComponent("tests/golden/model-built/custom-arcade.blueprint.json")))134 let p = publisher(root)135 let plan = try p.plan(blueprint: bp, projectID: "prj_arcade", version: "1.0.0", directory: root.appendingPathComponent("Applications"))136 #expect(plan.addedPermissions == ["logic.scripts"] && plan.manifest.minimumRuntime == "1.1.0" && plan.manifest.components.contains("custom.tictactoe"))137 let app = URL(fileURLWithPath: try p.publish(plan, blueprint: bp).installed.appPath)138 // The bundle carries exactly the icon designed for the app, not the one drawn from its name.139 let designed = root.appendingPathComponent("designed.icns"), automatic = root.appendingPathComponent("automatic.icns")140 try IconRenderer.writeICNS(try #require(bp.icon), to: designed)141 try IconRenderer.writeICNS(IconSpec.automatic(name: bp.name, seed: plan.manifest.appId), to: automatic)142 let shipped = try Data(contentsOf: app.appendingPathComponent("Contents/Resources/AppIcon.icns"))143 #expect(try shipped == Data(contentsOf: designed) && shipped != Data(contentsOf: automatic))144 // The host loads it: definition, script permission and all.145 let loaded = try SatelliteLoader.load(resources: app.appendingPathComponent("Contents/Resources"), registry: Catalog.registry)146 #expect(loaded.blueprint.componentDefinitions.map(\.id) == ["tictactoe"])147 // An older runtime refuses it with a clear message instead of misrendering it.148 #expect(throws: PublishError.self) { try SatelliteLoader.load(resources: app.appendingPathComponent("Contents/Resources"), registry: Catalog.registry, runtimeVersion: "1.0.0") }149 }150151 @Test func bundleIdentifiersNeverCollide() throws {152 let root = sandbox()153 defer { try? FileManager.default.removeItem(at: root) }154 let p = publisher(root), bp = try templateBlueprint()155 let apps = root.appendingPathComponent("Applications")156 let first = try p.publish(try p.plan(blueprint: bp, projectID: "prj_aaaaaa", version: "1.0.0", directory: apps), blueprint: bp)157 // A second project with the same app name gets a different identifier and may not overwrite the first bundle.158 #expect(p.bundleID(for: bp, projectID: "prj_bbbbbb") != first.installed.bundleID)159 #expect(throws: PublishError.self) { try p.plan(blueprint: bp, projectID: "prj_bbbbbb", version: "1.0.0", directory: apps) }160 let elsewhere = root.appendingPathComponent("Other")161 try FileManager.default.createDirectory(at: elsewhere, withIntermediateDirectories: true)162 let second = try p.publish(try p.plan(blueprint: bp, projectID: "prj_bbbbbb", version: "1.0.0", directory: elsewhere), blueprint: bp)163 #expect(Set(p.installed().map(\.bundleID)).count == 2 && second.installed.bundleID.hasPrefix(SatellitePublisher.bundlePrefix))164 #expect(p.bundleID(for: bp, projectID: "prj_aaaaaa") == first.installed.bundleID, "The identifier is stable across updates.")165 }166167 @Test func updateShowsPermissionDiffAndCanBeRolledBack() throws {168 let root = sandbox()169 defer { try? FileManager.default.removeItem(at: root) }170 let p = publisher(root)171 var v1 = try templateBlueprint()172 v1.permissions = ["storage.local", "files.import.userSelected"]173 v1.objects.removeAll { $0.id == "export_button" }174 v1.objects[v1.index(of: "bar")!].children.removeAll { $0 == "export_button" }175 let apps = root.appendingPathComponent("Applications")176 let first = try p.publish(try p.plan(blueprint: v1, projectID: "prj_one", version: "1.0.0", directory: apps), blueprint: v1)177 let v2 = try templateBlueprint()178 let plan = try p.plan(blueprint: v2, projectID: "prj_one", version: "1.1.0", directory: apps)179 #expect(plan.isUpdate && plan.addedPermissions == ["files.export.userSelected"] && plan.removedPermissions.isEmpty)180 let second = try p.publish(plan, blueprint: v2)181 #expect(second.installed.version == "1.1.0" && second.installed.previousVersion == "1.0.0" && second.installed.appPath == first.installed.appPath)182 let previous = try #require(second.installed.previousPath)183 #expect(FileManager.default.fileExists(atPath: previous))184185 let restored = try p.rollback(projectID: "prj_one")186 #expect(restored.version == "1.0.0" && restored.permissions == v1.permissions && restored.previousPath == nil)187 let loaded = try SatelliteLoader.load(resources: URL(fileURLWithPath: restored.appPath).appendingPathComponent("Contents/Resources"), registry: Catalog.registry)188 #expect(loaded.blueprint == v1)189 #expect(throws: PublishError.self) { try p.rollback(projectID: "prj_one") }190 #expect(throws: PublishError.self) { try p.rollback(projectID: "ghost") }191 }192193 @Test func aFailedPublishLeavesTheInstalledAppUntouched() throws {194 let root = sandbox()195 defer { try? FileManager.default.removeItem(at: root) }196 let p = publisher(root), bp = try templateBlueprint()197 let apps = root.appendingPathComponent("Applications")198 let first = try p.publish(try p.plan(blueprint: bp, projectID: "prj_one", version: "1.0.0", directory: apps), blueprint: bp)199 let before = try Data(contentsOf: URL(fileURLWithPath: first.installed.appPath).appendingPathComponent("Contents/Resources/satellite.json"))200201 // Invalid app, bad version, unwritable folder: all refused at planning time.202 var broken = bp; broken.objects.append(PrismObject(id: "bad", type: "prism.unknown")); broken.objects[broken.index(of: "root")!].children.append("bad")203 #expect(throws: PublishError.self) { try p.plan(blueprint: broken, projectID: "prj_one", version: "1.1.0", directory: apps) }204 #expect(throws: PublishError.self) { try p.plan(blueprint: bp, projectID: "prj_one", version: "one", directory: apps) }205 #expect(throws: PublishError.self) { try p.plan(blueprint: bp, projectID: "prj_one", version: "1.1.0", directory: URL(fileURLWithPath: "/System/Library")) }206 // The app changed between review and publish: refuse rather than publish something unreviewed.207 let plan = try p.plan(blueprint: bp, projectID: "prj_one", version: "1.1.0", directory: apps)208 var changed = bp; changed.name = "Sneaky"209 #expect(throws: PublishError.self) { try p.publish(plan, blueprint: changed) }210 // A signing identity that does not exist makes codesign fail mid-publish.211 var badSigning = plan; badSigning.signingIdentity = "Developer ID Application: Nobody (0000000000)"212 #expect(throws: PublishError.self) { try p.publish(badSigning, blueprint: bp) }213214 #expect(try Data(contentsOf: URL(fileURLWithPath: first.installed.appPath).appendingPathComponent("Contents/Resources/satellite.json")) == before)215 #expect(p.installed(for: "prj_one")?.version == "1.0.0")216 #expect((try FileManager.default.contentsOfDirectory(atPath: apps.path)).sorted() == ["Expense Tracker.app"])217 }218219 @Test func uninstallRemovesTheBundleAndDataOnlyWithConsent() throws {220 let root = sandbox()221 defer { try? FileManager.default.removeItem(at: root) }222 let p = publisher(root), bp = try templateBlueprint()223 let dataBase = root.appendingPathComponent("AppSupport")224 func install() throws -> InstalledSatellite {225 let r = try p.publish(try p.plan(blueprint: bp, projectID: "prj_one", version: "1.0.0", directory: root.appendingPathComponent("Applications")), blueprint: bp)226 let store = try AppDataStore(url: SatelliteLoader.dataDirectory(appId: r.installed.bundleID, base: dataBase).appendingPathComponent("data.sqlite"), blueprint: bp)227 try store.insert(into: "transactions", values: ["date": "2026-01-01", "description": "x", "amount": 1])228 store.close()229 return r.installed230 }231 var record = try install()232 try p.uninstall(projectID: "prj_one", removeData: false, dataBase: dataBase)233 #expect(!FileManager.default.fileExists(atPath: record.appPath) && p.installed().isEmpty)234 #expect(FileManager.default.fileExists(atPath: SatelliteLoader.dataDirectory(appId: record.bundleID, base: dataBase).appendingPathComponent("data.sqlite").path), "Data is kept unless the user asks to delete it.")235 record = try install()236 try p.uninstall(projectID: "prj_one", removeData: true, dataBase: dataBase)237 #expect(!FileManager.default.fileExists(atPath: SatelliteLoader.dataDirectory(appId: record.bundleID, base: dataBase).path))238 #expect(throws: PublishError.self) { try p.uninstall(projectID: "prj_one", removeData: false) }239240 // If something else now sits at that path, PRISM does not delete it.241 record = try install()242 try FileManager.default.removeItem(atPath: record.appPath)243 try FileManager.default.createDirectory(atPath: record.appPath + "/Contents", withIntermediateDirectories: true)244 try Data("<plist version=\"1.0\"><dict><key>CFBundleIdentifier</key><string>com.someone.else</string></dict></plist>".utf8).write(to: URL(fileURLWithPath: record.appPath + "/Contents/Info.plist"))245 #expect(throws: PublishError.self) { try p.uninstall(projectID: "prj_one", removeData: false, dataBase: dataBase) }246 #expect(FileManager.default.fileExists(atPath: record.appPath))247 }248249 /// Golden journey step 8: launched by LaunchServices as its own app. Opt-in because it opens a window for a moment.250 @MainActor251 @Test(.enabled(if: launchTestsEnabled, "Set PRISM_TEST_LAUNCH=1 to launch the published app for real."))252 func publishedAppLaunchesIndependentlyAndKeepsItsData() async throws {253 let root = sandbox()254 defer { try? FileManager.default.removeItem(at: root) }255 let p = publisher(root), bp = try templateBlueprint()256 let result = try p.publish(try p.plan(blueprint: bp, projectID: "prj_one", version: "1.0.0", directory: root.appendingPathComponent("Applications")), blueprint: bp)257 let app = URL(fileURLWithPath: result.installed.appPath), dataBase = root.appendingPathComponent("AppSupport")258 let first = await SatelliteVerifier.verify(app: app, bundleID: result.installed.bundleID, dataBase: dataBase)259 #expect(first.passed, "\(first)")260 #expect(first.tableCounts == ["transactions": 0])261 // Add data the way the app would, relaunch, and it is still there.262 let store = try AppDataStore(url: SatelliteLoader.dataDirectory(appId: result.installed.bundleID, base: dataBase).appendingPathComponent("data.sqlite"), blueprint: bp)263 try store.importCSV(Data(contentsOf: testRepoRoot.appendingPathComponent("templates/expense-tracker/sample.csv")), into: "transactions")264 store.close()265 let second = await SatelliteVerifier.verify(app: app, bundleID: result.installed.bundleID, dataBase: dataBase)266 #expect(second.passed && second.tableCounts == ["transactions": 15], "\(second)")267 // A damaged install reports the reason instead of hanging.268 try FileManager.default.removeItem(at: app.appendingPathComponent("Contents/Resources/blueprint.json"))269 let broken = await SatelliteVerifier.verify(app: app, bundleID: result.installed.bundleID, dataBase: dataBase, timeout: 15)270 #expect(!broken.passed)271 }272}273