Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215import Foundation
struct LaunchFeed { static let namespace = "http://www.andymatuschak.org/xml-namespaces/sparkle"
static func element(_ name: String, _ value: String) -> XMLElement { XMLElement(name: name, stringValue: value) } static func attribute(_ name: String, _ value: String) -> XMLNode { let node = XMLNode(kind: .attribute) node.name = name node.stringValue = value return node }
static func parse(_ path: URL) throws -> XMLDocument { let data = try Data(contentsOf: path) guard data.count <= 1_000_000, data.range(of: Data("<!DOCTYPE".utf8)) == nil, data.range(of: Data("<!ENTITY".utf8)) == nil else { throw DevError("Feed is too large or contains a document type") } let document = try XMLDocument(data: data, options: [.nodeLoadExternalEntitiesNever]) _ = try channel(document) return document }
static func elements(_ parent: XMLElement, _ name: String) -> [XMLElement] { parent.elements(forName: name).filter { ($0.uri ?? "").isEmpty } }
static func channel(_ document: XMLDocument) throws -> XMLElement { guard let root = document.rootElement(), root.name == "rss", (root.uri ?? "").isEmpty, elements(root, "channel").count == 1, let channel = elements(root, "channel").first else { throw DevError("Expected one RSS channel") } return channel }
static func text(_ element: XMLElement, _ name: String) -> String { element.elements(forLocalName: name, uri: namespace).first?.stringValue ?? "" }
static func signature(_ element: XMLElement) -> String { element.attribute(forLocalName: "edSignature", uri: namespace)?.stringValue ?? "" }
static func releaseURL(_ download: String, _ version: String) throws -> String { guard let url = URLComponents(string: download) else { throw DevError("Download URL must identify the selected release tag") } let parts = url.percentEncodedPath.components(separatedBy: "/") guard parts.count >= 4, parts[parts.count - 2] == "v" + version else { throw DevError("Download URL must identify the selected release tag") } let prefix = parts.dropLast(2).joined(separator: "/") guard prefix.hasSuffix("/releases/download") else { throw DevError("Download URL must identify the selected release tag") } return "\(url.scheme ?? "")://\(url.host ?? "")\(url.port.map { ":\($0)" } ?? "")\(prefix)" }
static func verifyDownload( _ enclosure: XMLElement, download: String, archive: URL, checksums: URL, publicKey: String ) throws { guard let url = URLComponents(string: download), url.scheme == "https", let host = url.host, !host.isEmpty, url.user == nil, url.password == nil, (url.query ?? "").isEmpty, (url.fragment ?? "").isEmpty, url.percentEncodedPath.components(separatedBy: "/").last?.removingPercentEncoding == archive.lastPathComponent else { throw DevError("Archive does not match the expected HTTPS download") } guard try ReleaseFiles.regular(archive), try ReleaseFiles.regular(checksums) else { throw DevError("Expected a regular downloaded archive and checksum file") } let size = try archive.resourceValues(forKeys: [.fileSizeKey]).fileSize guard let size, enclosure.attribute(forName: "url")?.stringValue == download, let length = Int(enclosure.attribute(forName: "length")?.stringValue ?? "0"), length == size else { throw DevError("Feed does not match the downloaded archive length or URL") } guard size > 0 else { throw DevError("Downloaded archive is empty") } let signature = signature(enclosure) _ = try UpdateCrypto.canonical( signature, count: 64, message: "Expected a canonical Sparkle EdDSA signature and public key") _ = try UpdateCrypto.canonical( publicKey, count: 32, message: "Expected a canonical Sparkle EdDSA signature and public key") guard let checksumSize = try checksums.resourceValues(forKeys: [.fileSizeKey]).fileSize, checksumSize <= 100_000 else { throw DevError("Checksum file is too large") } let text = try String(contentsOf: checksums, encoding: .utf8) var entries: [String: String] = [:] let expression = try NSRegularExpression(pattern: "^([a-fA-F0-9]{64}) [ *]([^/\\\\\\r\\n]+)$") var lines: [String] = [] text.enumerateLines { line, _ in lines.append(line) } for line in lines { guard let match = expression.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)), let hashRange = Range(match.range(at: 1), in: line), let nameRange = Range(match.range(at: 2), in: line) else { throw DevError("Checksum file contains an invalid or duplicate entry") } let name = String(line[nameRange]) guard name != ".", name != "..", entries[name] == nil else { throw DevError("Checksum file contains an invalid or duplicate entry") } entries[name] = String(line[hashRange]).lowercased() } guard entries[archive.lastPathComponent] == (try UpdateCrypto.digest(archive)) else { throw DevError("Downloaded archive does not match SHA256SUMS") } try UpdateCrypto.verify(archive, signature: signature, publicKey: publicKey) }
static func normalized(_ element: XMLElement) -> DevJSON { let attributes = (element.attributes ?? []).sorted { first, second in (first.uri ?? "", first.localName ?? first.name ?? "") < ( second.uri ?? "", second.localName ?? second.name ?? "" ) }.map { node in DevJSON.array([ .string(node.uri ?? ""), .string(node.localName ?? node.name ?? ""), .string(node.stringValue ?? ""), ]) } var children: [DevJSON] = [] for node in element.children ?? [] { if node.kind == .text { let text = node.stringValue ?? "" if let previous = children.last?.string { children[children.count - 1] = .string(previous + text) } else { children.append(.string(text)) } } else if let child = node as? XMLElement { children.append(normalized(child)) } } children = children.compactMap { value in guard let text = value.string else { return value } let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.isEmpty ? nil : .string(trimmed) } return .array([ .string(element.uri ?? ""), .string(element.localName ?? element.name ?? ""), .array(attributes), .array(children), ]) }
static func merge( source: URL, destination: URL, version: String, download: String, archive: URL, checksums: URL, publicKey: String, repository: String ) throws -> Bool { try DevVersion.validate(version, root: ReleaseTools.root, kind: "ordered-version") let prefix = try releaseURL(download, version) let branch = ProcessInfo.processInfo.environment["PRODUCT_DEFAULT_BRANCH"] ?? "" guard branch.range(of: "^[A-Za-z0-9_.-]+$", options: .regularExpression) != nil else { throw DevError("Set PRODUCT_DEFAULT_BRANCH from Scripts/product.env") } _ = try ReleaseOrder.provenance(repository, "v" + version, "refs/remotes/github/" + branch) var incoming = try parse(source) let incomingItems = try elements(channel(incoming), "item") guard incomingItems.count == 1 else { throw DevError("Expected exactly one release entry") } let item = incomingItems[0] guard text(item, "shortVersionString") == version else { throw DevError("Feed does not match the selected release") } let build = text(item, "version") try DevVersion.validate(build, root: ReleaseTools.root, kind: "positive-build") let enclosures = elements(item, "enclosure") guard enclosures.count == 1 else { throw DevError("Expected exactly one release enclosure") } try verifyDownload( enclosures[0], download: download, archive: archive, checksums: checksums, publicKey: publicKey) guard try !ReleaseFiles.symlink(destination) else { throw DevError("Refusing to replace a symlink") } if FileManager.default.fileExists(atPath: destination.path) { let existing = try parse(destination) let channel = try channel(existing) for previous in elements(channel, "item") { let previousVersion = text(previous, "shortVersionString") if previousVersion == version { guard normalized(previous) == normalized(item) else { throw DevError("This version already has different metadata") } return false } let enclosures = elements(previous, "enclosure") guard enclosures.count == 1, try releaseURL(enclosures[0].attribute(forName: "url")?.stringValue ?? "", previousVersion) == prefix else { throw DevError("Previous release must identify a tag in the same download repository") } _ = try ReleaseOrder.compare([ repository, "v" + version, "v" + previousVersion, version, previousVersion, build, text(previous, "version"), ]) } item.detach() channel.insertChild(item, at: 0) incoming = existing } try FileManager.default.createDirectory( at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) try ReleaseFiles.atomic(incoming.xmlData(options: .nodePrettyPrint), to: destination) return true }
static func run(_ args: [String]) throws { do { guard args.count == 9 else { throw DevError("Usage: launch-feed SOURCE SITE RELATIVE VERSION URL ARCHIVE CHECKSUMS PUBLIC_KEY REPO") } let relative = args[2] guard !relative.hasPrefix("/"), !relative.components(separatedBy: "/").contains("..") else { throw DevError("The feed destination must be relative to the site repo") } let site = try PackagingPaths.resolveAllowMissing(URL(fileURLWithPath: args[1])) let target = URL(fileURLWithPath: args[1]).appendingPathComponent(relative) let resolved = try PackagingPaths.resolveAllowMissing(target) guard resolved.path == site.path || resolved.path.hasPrefix(site.path + "/") else { throw DevError("The feed destination escapes the site repo") } let changed = try merge( source: URL(fileURLWithPath: args[0]), destination: target, version: args[3], download: args[4], archive: URL(fileURLWithPath: args[5]), checksums: URL(fileURLWithPath: args[6]), publicKey: args[7], repository: args[8]) print(changed ? "Appcast published." : "Appcast already matches.") } catch { throw DevError("Appcast: \(error)") } }}