PulseCanvas / app · pulsecanvas.ai / scripts / UserBackupSmoke.swift
| 1 | import Foundation |
| 2 | import ZIPFoundation |
| 3 | |
| 4 | @main struct UserBackupSmoke { |
| 5 | static func require(_ condition: @autoclosure () throws -> Bool, _ message: String) throws { |
| 6 | if try !condition() { throw UserBackup.fail(message) } |
| 7 | } |
| 8 | static func main() throws { |
| 9 | let fm = FileManager.default |
| 10 | let root = URL(fileURLWithPath: "/Volumes/Expand/Codex Media/PulseCanvas Studio/Development/user-backup-20261110/tmp", isDirectory: true) |
| 11 | .appendingPathComponent("PulseCanvasBackupSmoke-\(UUID().uuidString)") |
| 12 | defer { try? fm.removeItem(at: root) } |
| 13 | let sourceSuite = "PulseCanvas.Backup.Source.\(UUID().uuidString)" |
| 14 | let targetSuite = "PulseCanvas.Backup.Target.\(UUID().uuidString)" |
| 15 | let source = UserDefaults(suiteName: sourceSuite)!, target = UserDefaults(suiteName: targetSuite)! |
| 16 | defer { source.removePersistentDomain(forName: sourceSuite); target.removePersistentDomain(forName: targetSuite) } |
| 17 | func storage(_ name: String, domain: String) -> UserBackup.Storage { |
| 18 | let base = root.appendingPathComponent(name) |
| 19 | return .init(documents: base.appendingPathComponent("Documents"), support: base.appendingPathComponent("Support"), |
| 20 | backups: base.appendingPathComponent("Backups"), domain: domain) |
| 21 | } |
| 22 | let input = storage("input", domain: sourceSuite), output = storage("output", domain: targetSuite) |
| 23 | let firstRun = try UserBackup.collect(currentProject: nil, platform: "macOS", defaults: source, storage: output) |
| 24 | try require(firstRun.files.isEmpty, "First-run empty backup failed") |
| 25 | try fm.createDirectory(at: input.documents, withIntermediateDirectories: true) |
| 26 | try fm.createDirectory(at: input.support.appendingPathComponent("PersonalRadio/album"), withIntermediateDirectories: true) |
| 27 | let audioURL = root.appendingPathComponent("original.wav") |
| 28 | // Real one-second 16-bit mono PCM WAV, with a changing waveform. |
| 29 | var audio = Data("RIFF".utf8) |
| 30 | func little<T: FixedWidthInteger>(_ value: T) { var v = value.littleEndian; withUnsafeBytes(of: &v) { audio.append(contentsOf: $0) } } |
| 31 | little(UInt32(88_236)); audio.append(Data("WAVEfmt ".utf8)); little(UInt32(16)); little(UInt16(1)); little(UInt16(1)) |
| 32 | little(UInt32(44_100)); little(UInt32(88_200)); little(UInt16(2)); little(UInt16(16)); audio.append(Data("data".utf8)); little(UInt32(88_200)) |
| 33 | for i in 0..<44_100 { little(Int16(sin(Double(i) * 2 * .pi * 220 / 44_100) * 4_000)) } |
| 34 | try audio.write(to: audioURL) |
| 35 | let look: [String: Any] = ["speed": 1.7, "chaos": 0.82, "palette": 3, "zoom": 1.2, "brightness": 1.2, |
| 36 | "particleSize": 1.0, "fog": 0.5, "rotation": 0.0, "motionBlur": 0.0, "strobeEnabled": false, |
| 37 | "strobeSensitivity": 1.0, "strobeStrength": 1.0, "liquidDetail": 0.6, "zoomSpeed": 1.5, "haloCount": 6] |
| 38 | let project: [String: Any] = ["version": 1, "scene": 22, "soundtrack": audioURL.absoluteString, "soundtrackBookmark": Data("authorization-must-not-travel".utf8).base64EncodedString(), |
| 39 | "appearance": look, "aspect": "16:9 · Wide", "resolution": 1080, "fps": 60, |
| 40 | "timeline": [["start": 0, "end": 1, "scene": 22, "bars": 1]], "effectIdentities": ["22": "native:22"], "loopPlayback": true] |
| 41 | let projectData = try JSONSerialization.data(withJSONObject: project) |
| 42 | try projectData.write(to: input.documents.appendingPathComponent("Studio-autosave.pulsecanvas")) |
| 43 | let catalogURL = input.support.appendingPathComponent("PersonalRadio/album/catalog.json") |
| 44 | let catalog = Data("{\"version\":1,\"title\":\"My album\",\"tracks\":[]}".utf8) |
| 45 | try catalog.write(to: catalogURL) |
| 46 | try audio.write(to: catalogURL.deletingLastPathComponent().appendingPathComponent("song.wav")) |
| 47 | source.set(["native:22", "native:12"], forKey: "PulseCanvas.metalEffectFavorites.v1") |
| 48 | source.set(try JSONSerialization.data(withJSONObject: ["native:22": look]), forKey: "PulseCanvas.metalEffectFavorites.v1.appearances") |
| 49 | let song = ["track": ["id": UUID().uuidString, "title": "Saved radio song", "genre": "Electronic", "duration": 1.0, |
| 50 | "audio": "song.wav", "sha256": UserBackup.hash(audio), "byteCount": audio.count], |
| 51 | "sourceURL": "https://radio.pulsecanvas.si/stations.json", "catalogURL": "https://radio.pulsecanvas.si/catalog.json", |
| 52 | "stationID": "electronic", "folderBookmark": Data("authorization-must-not-travel".utf8).base64EncodedString()] as [String: Any] |
| 53 | source.set(try JSONSerialization.data(withJSONObject: [song]), forKey: "PulseCanvas.radio.favoriteSongs.v1") |
| 54 | source.set(try JSONSerialization.data(withJSONObject: ["presets": ["22": look], "identities": ["22": "native:22"]]), forKey: "PulseCanvas.metalStudio.v1") |
| 55 | source.set(try JSONSerialization.data(withJSONObject: ["enabled": true, "collection": "native", "category": "Tunnels", "favoritesOnly": false]), forKey: "PulseCanvas.metalVisualizerPool.v1") |
| 56 | source.set(try JSONSerialization.data(withJSONObject: ["aspect": "16:9 · Wide", "resolution": 1080, "fps": 60]), forKey: "PulseCanvas.videoFormat.v1") |
| 57 | source.set("electronic", forKey: "PulseCanvas.radio.station") |
| 58 | source.set(true, forKey: "PulseCanvas.radio.favoriteSongsOnly.v1") |
| 59 | source.set(["feedback"], forKey: "PulseCanvas.engagement.clickedActions.v1") |
| 60 | source.set(true, forKey: "PulseCanvas.onboarding.completed.v1") |
| 61 | source.set(catalogURL, forKey: "PulseCanvas.radio.personalCatalog.v1") |
| 62 | source.set(true, forKey: "PulseCanvas.radio.personalActive.v1") |
| 63 | source.set(0.42, forKey: "PulseCanvas.radio.volume") |
| 64 | source.set("DO-NOT-EXPORT", forKey: "APIKey") |
| 65 | source.set(true, forKey: "nativeTips.hasSupportedDevelopment.v1") |
| 66 | let data = try UserBackup.export(currentProject: projectData, platform: "macOS", defaults: source, storage: input) |
| 67 | let jsonArchive = try UserBackup.decode(data) |
| 68 | let zipURL = root.appendingPathComponent("backup.zip") |
| 69 | try UserBackup.writeZIP(jsonArchive, to: zipURL) |
| 70 | let archive = try UserBackup.readZIP(zipURL, workspace: root.appendingPathComponent("Unpacked")) |
| 71 | try require(archive.files.map(\.sha256) == jsonArchive.files.map(\.sha256), "ZIP lost files or metadata") |
| 72 | let preferences = try UserBackup.preferenceValues(archive) |
| 73 | try require(preferences["APIKey"] == nil && preferences["nativeTips.hasSupportedDevelopment.v1"] == nil |
| 74 | && preferences["PulseCanvas.engagement.clickedActions.v1"] == nil, "Export leaked private settings") |
| 75 | try require(archive.files.count == 5, "Incomplete file collection: \(archive.files.map(\.path))") |
| 76 | try require(!String(decoding: data, as: UTF8.self).contains("DO-NOT-EXPORT"), "Credential leaked") |
| 77 | let exportedProject = try JSONSerialization.jsonObject(with: archive.files.first { $0.path.hasSuffix("Backup-current.pulsecanvas") }!.data) as! [String: Any] |
| 78 | try require(exportedProject["soundtrackBookmark"] == nil, "Project authorization bookmark leaked") |
| 79 | // Destroy only this test's source workspace. Restore must stand on its own. |
| 80 | try fm.removeItem(at: root.appendingPathComponent("input")); try fm.removeItem(at: audioURL) |
| 81 | target.set("KEEP-LOCAL-SECRET", forKey: "APIKey") |
| 82 | target.set(["old"], forKey: "PulseCanvas.metalEffectFavorites.v1") |
| 83 | let before = target.persistentDomain(forName: targetSuite)! as NSDictionary |
| 84 | try require(try UserBackup.stageRestore(archive, defaults: target, storage: output), "Restore wasn't staged") |
| 85 | try require(before == target.persistentDomain(forName: targetSuite)! as NSDictionary, "Staging changed live preferences") |
| 86 | try UserBackup.activatePendingRestore(defaults: target, storage: output) |
| 87 | try require(target.stringArray(forKey: "PulseCanvas.metalEffectFavorites.v1") == ["native:22", "native:12"], "Favorites were lost or duplicated") |
| 88 | try require(target.double(forKey: "PulseCanvas.radio.volume") == 0.42, "Preference changed") |
| 89 | try require(target.string(forKey: "APIKey") == "KEEP-LOCAL-SECRET", "Restore changed a credential") |
| 90 | for (key, expected) in preferences where key != "PulseCanvas.radio.personalCatalog.v1" { |
| 91 | guard let actual = target.object(forKey: key) else { throw UserBackup.fail("Restored preference missing: \(key)") } |
| 92 | try require(NSDictionary(dictionary: ["value": actual]).isEqual(to: ["value": expected]), "Restored favorite/settings metadata changed: \(key)") |
| 93 | } |
| 94 | let restoredRoot = output.root("Documents", defaults: target) |
| 95 | let restored = try JSONSerialization.jsonObject(with: Data(contentsOf: restoredRoot.appendingPathComponent("Backup-current.pulsecanvas"))) as! [String: Any] |
| 96 | let restoredAudio = URL(string: restored["soundtrack"] as! String)! |
| 97 | try require(restoredAudio.lastPathComponent == audioURL.lastPathComponent, "Restore changed the soundtrack filename/title") |
| 98 | try require(try Data(contentsOf: restoredAudio) == audio, "Restored soundtrack missing or changed") |
| 99 | try require(restored["appearance"] as! NSDictionary == look as NSDictionary, "Look settings changed") |
| 100 | try require(restored["effectIdentities"] as! [String: String] == ["22": "native:22"], "Effect identity mapping changed") |
| 101 | let restoredCatalog = target.url(forKey: "PulseCanvas.radio.personalCatalog.v1")! |
| 102 | try require(try Data(contentsOf: restoredCatalog) == catalog, "Personal playlist relationship broken") |
| 103 | try require(try Data(contentsOf: restoredCatalog.deletingLastPathComponent().appendingPathComponent("song.wav")) == audio, "Personal music wasn't restored") |
| 104 | try require(!(try UserBackup.stageRestore(archive, defaults: target, storage: output)), "Same backup duplicated") |
| 105 | let again = try UserBackup.export(currentProject: nil, platform: "macOS", defaults: target, storage: output) |
| 106 | try UserBackup.validate(UserBackup.decode(again)) |
| 107 | let domainBeforeBad = target.persistentDomain(forName: targetSuite)! as NSDictionary |
| 108 | func rejects(_ changed: UserBackup.Archive, _ name: String) throws { |
| 109 | do { _ = try UserBackup.stageRestore(changed, defaults: target, storage: output); throw UserBackup.fail("Accepted malformed backup: \(name)") } |
| 110 | catch let error as UserBackup.Failure where error.message.hasPrefix("Accepted") { throw error } |
| 111 | catch { } |
| 112 | try require(domainBeforeBad == target.persistentDomain(forName: targetSuite)! as NSDictionary, "Bad restore modified preferences") |
| 113 | } |
| 114 | var bad = archive; bad.version = 999; try rejects(bad, "version") |
| 115 | bad = archive; bad.files[0].data.append(0); try rejects(bad, "checksum") |
| 116 | bad = archive; bad.files[0].path = "Documents/../../escape"; try rejects(bad, "traversal") |
| 117 | bad = archive; bad.files.append(bad.files[0]); try rejects(bad, "duplicate") |
| 118 | bad = archive; bad.files.removeAll { $0.originalURL == audioURL.absoluteString }; try rejects(bad, "missing soundtrack") |
| 119 | bad = archive; bad.preferences = try PropertyListSerialization.data(fromPropertyList: ["APIKey": "bad"], format: .binary, options: 0); try rejects(bad, "unknown preference") |
| 120 | bad = archive; bad.preferences = try PropertyListSerialization.data(fromPropertyList: ["PulseCanvas.radio.volume": "invalid"], format: .binary, options: 0); try rejects(bad, "preference type") |
| 121 | let invalidZip = root.appendingPathComponent("invalid.zip") |
| 122 | let zip = try ZIPFoundation.Archive(url: invalidZip, accessMode: .create) |
| 123 | try zip.addEntry(with: "../escape", type: .file, uncompressedSize: Int64(1)) { _, _ in Data([0]) } |
| 124 | do { |
| 125 | _ = try UserBackup.readZIP(invalidZip, workspace: root.appendingPathComponent("BadUnpack")) |
| 126 | throw UserBackup.fail("Accepted ZIP traversal") |
| 127 | } catch let error as UserBackup.Failure where error.message == "Accepted ZIP traversal" { throw error } |
| 128 | catch { } |
| 129 | do { _ = try UserBackup.decode(Data("broken".utf8)); throw UserBackup.fail("Accepted malformed JSON") } |
| 130 | catch is DecodingError { } |
| 131 | let damagedURL = root.appendingPathComponent("damaged.zip") |
| 132 | var damaged = try Data(contentsOf: zipURL) |
| 133 | let position = damaged.range(of: archive.files[0].data.prefix(16))!.lowerBound + 3 |
| 134 | damaged[position] ^= 1 |
| 135 | try damaged.write(to: damagedURL) |
| 136 | do { |
| 137 | _ = try UserBackup.readZIP(damagedURL, workspace: root.appendingPathComponent("DamagedUnpack")) |
| 138 | throw UserBackup.fail("Accepted damaged ZIP") |
| 139 | } catch let error as UserBackup.Failure where error.message == "Accepted damaged ZIP" { throw error } |
| 140 | catch { } |
| 141 | // Exercise a real ZIP above the previous JSON payload ceiling without a |
| 142 | // huge base64 allocation. The file is generated and removed on Expand. |
| 143 | let largeURL = restoredRoot.appendingPathComponent("large.wav") |
| 144 | fm.createFile(atPath: largeURL.path, contents: audio.prefix(44)) |
| 145 | let large = try FileHandle(forWritingTo: largeURL) |
| 146 | try large.seekToEnd() |
| 147 | let block = Data(repeating: 0, count: 1_048_576) |
| 148 | for _ in 0..<300 { try large.write(contentsOf: block) } |
| 149 | try large.close() |
| 150 | let largeArchive = try UserBackup.collect(currentProject: nil, platform: "macOS", defaults: target, storage: output) |
| 151 | let largeZIP = root.appendingPathComponent("large.zip") |
| 152 | try UserBackup.writeZIP(largeArchive, to: largeZIP) |
| 153 | let largeRestored = try UserBackup.readZIP(largeZIP, workspace: root.appendingPathComponent("LargeUnpack")) |
| 154 | let largeFile = largeRestored.files.first { $0.path == "Documents/large.wav" }! |
| 155 | try require(largeFile.data.count == 300 * 1_048_576 + 44 && largeFile.sha256 == UserBackup.hash(try Data(contentsOf: largeURL, options: .alwaysMapped)), "Large ZIP round trip changed bytes") |
| 156 | print("PASS: JSON + ZIP export → clean workspace → restore; favorites, looks, timeline, identities, personal playlist/audio and preferences; original source removed; re-export; duplicate import; secret/bookmark exclusions; invalid-archive checks; malformed JSON, ZIP traversal and damaged ZIP CRC; live data unchanged before activation; 300 MiB ZIP round trip.") |
| 157 | } |
| 158 | } |