diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 17f175d0..9a191431 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 47; + objectVersion = 52; objects = { /* Begin PBXAggregateTarget section */ @@ -309,6 +309,9 @@ 726F2CE81BC9C48F001971A4 /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 61299A5F09CA6EB100B7442F /* SUConstants.m */; }; 726F2CE91BC9C499001971A4 /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; 726F2CEB1BC9C733001971A4 /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 61299A5F09CA6EB100B7442F /* SUConstants.m */; }; + 727DBAE526B5BBFD00111F0C /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = 727DBAE426B5BBFD00111F0C /* ArgumentParser */; }; + 727DBAE726B5C47800111F0C /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = 727DBAE626B5C47800111F0C /* ArgumentParser */; }; + 727DBAE926B5C48A00111F0C /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = 727DBAE826B5C48A00111F0C /* ArgumentParser */; }; 727F340B2605321D00020E85 /* SULog+NSError.m in Sources */ = {isa = PBXBuildFile; fileRef = 727F340A2605321D00020E85 /* SULog+NSError.m */; }; 727F340D2605321D00020E85 /* SULog+NSError.m in Sources */ = {isa = PBXBuildFile; fileRef = 727F340A2605321D00020E85 /* SULog+NSError.m */; }; 727F340E2605321D00020E85 /* SULog+NSError.m in Sources */ = {isa = PBXBuildFile; fileRef = 727F340A2605321D00020E85 /* SULog+NSError.m */; }; @@ -1400,6 +1403,7 @@ EA1E285622B6619B004AA304 /* libed25519.a in Frameworks */, EA1E281A22B645F4004AA304 /* libbsdiff.a in Frameworks */, 7205C4641E1306BE00E370AE /* libbz2.tbd in Frameworks */, + 727DBAE526B5BBFD00111F0C /* ArgumentParser in Frameworks */, 7205C4631E1306B500E370AE /* libxar.tbd in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1498,6 +1502,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 727DBAE726B5C47800111F0C /* ArgumentParser in Frameworks */, EA1E286A22B6653D004AA304 /* libed25519.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1506,6 +1511,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 727DBAE926B5C48A00111F0C /* ArgumentParser in Frameworks */, EA1E287E22B66705004AA304 /* libed25519.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2511,6 +2517,9 @@ dependencies = ( ); name = generate_appcast; + packageProductDependencies = ( + 727DBAE426B5BBFD00111F0C /* ArgumentParser */, + ); productName = generate_appcast; productReference = 7205C43E1E13049400E370AE /* generate_appcast */; productType = "com.apple.product-type.tool"; @@ -2749,6 +2758,9 @@ dependencies = ( ); name = generate_keys; + packageProductDependencies = ( + 727DBAE626B5C47800111F0C /* ArgumentParser */, + ); productName = generate_keys; productReference = EA1E285E22B66487004AA304 /* generate_keys */; productType = "com.apple.product-type.tool"; @@ -2766,6 +2778,9 @@ dependencies = ( ); name = sign_update; + packageProductDependencies = ( + 727DBAE826B5C48A00111F0C /* ArgumentParser */, + ); productName = sign_update; productReference = EA1E287622B666EB004AA304 /* sign_update */; productType = "com.apple.product-type.tool"; @@ -2905,6 +2920,9 @@ fa, ); mainGroup = 0867D691FE84028FC02AAC07 /* Sparkle */; + packageReferences = ( + 727DBAE326B5BBFD00111F0C /* XCRemoteSwiftPackageReference "swift-argument-parser" */, + ); productRefGroup = 034768DFFF38A50411DB9C8B /* Products */; projectDirPath = ""; projectRoot = ""; @@ -4223,7 +4241,6 @@ baseConfigurationReference = 72D954B01CBB41E2006F28BD /* ConfigSparkleTool.xcconfig */; buildSettings = { CLANG_ANALYZER_NONNULL = YES; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; }; name = Debug; }; @@ -4232,7 +4249,6 @@ baseConfigurationReference = 72D954B01CBB41E2006F28BD /* ConfigSparkleTool.xcconfig */; buildSettings = { CLANG_ANALYZER_NONNULL = YES; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; }; name = Coverage; }; @@ -4241,7 +4257,6 @@ baseConfigurationReference = 72D954B01CBB41E2006F28BD /* ConfigSparkleTool.xcconfig */; buildSettings = { CLANG_ANALYZER_NONNULL = YES; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; }; name = Release; }; @@ -4581,6 +4596,35 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 727DBAE326B5BBFD00111F0C /* XCRemoteSwiftPackageReference "swift-argument-parser" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/apple/swift-argument-parser.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 0.4.3; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 727DBAE426B5BBFD00111F0C /* ArgumentParser */ = { + isa = XCSwiftPackageProductDependency; + package = 727DBAE326B5BBFD00111F0C /* XCRemoteSwiftPackageReference "swift-argument-parser" */; + productName = ArgumentParser; + }; + 727DBAE626B5C47800111F0C /* ArgumentParser */ = { + isa = XCSwiftPackageProductDependency; + package = 727DBAE326B5BBFD00111F0C /* XCRemoteSwiftPackageReference "swift-argument-parser" */; + productName = ArgumentParser; + }; + 727DBAE826B5C48A00111F0C /* ArgumentParser */ = { + isa = XCSwiftPackageProductDependency; + package = 727DBAE326B5BBFD00111F0C /* XCRemoteSwiftPackageReference "swift-argument-parser" */; + productName = ArgumentParser; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 0867D690FE84028FC02AAC07 /* Project object */; } diff --git a/Sparkle.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Sparkle.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000..f3ff409f --- /dev/null +++ b/Sparkle.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "swift-argument-parser", + "repositoryURL": "https://github.com/apple/swift-argument-parser.git", + "state": { + "branch": null, + "revision": "83b23d940471b313427da226196661856f6ba3e0", + "version": "0.4.4" + } + } + ] + }, + "version": 1 +} diff --git a/generate_appcast/main.swift b/generate_appcast/main.swift index 4c0e4573..7c4fc96f 100644 --- a/generate_appcast/main.swift +++ b/generate_appcast/main.swift @@ -7,49 +7,7 @@ // import Foundation - -var verbose = false - -// Enum that contains keys for command-line arguments -struct CommandLineArguments { - var privateDSAKey : SecKey? - var privateEdString : String? - var downloadURLPrefix : URL? - var releaseNotesURLPrefix: URL? - var outputPathURL: URL? - var archivesSourceDir: URL? -} - -func printUsage() { - let command = URL(fileURLWithPath: CommandLine.arguments.first!).lastPathComponent - let usage = """ - -Generate appcast from a directory of Sparkle update archives - -Usage: \(command) [OPTIONS] [ARCHIVES_FOLDER] - -h: prints this message - -f: provide the path to the private DSA key - -n: provide the name of the private DSA key. This option must be used with `-k` - -k: provide the name of the keychain. This option must be used with `-n` - -s: provide the private EdDSA key (128 characters) - -o: provide a filename for the generated appcast (allowed when only one will be created) - - --download-url-prefix: provide a prefix used to construct URLs for update downloads - --release-notes-url-prefix: provide a prefix used to construct URLs for release notes - -Examples: - \(command) ./my-app-release-zipfiles/ - \(command) -o appcast-name.xml ./my-app-release-zipfiles/ - - \(command) dsa_priv.pem ./my-app-release-zipfiles/ [DEPRECATED] - -Appcast files and deltas will be written to the archives directory. -Note that pkg-based updates are not supported. - -""" - - print(usage) -} +import ArgumentParser func loadPrivateKeys(_ privateDSAKey: SecKey?, _ privateEdString: String?) -> PrivateKeys { var privateEdKey: Data? @@ -88,222 +46,128 @@ func loadPrivateKeys(_ privateDSAKey: SecKey?, _ privateEdString: String?) -> Pr return PrivateKeys(privateDSAKey: privateDSAKey, privateEdKey: privateEdKey, publicEdKey: publicEdKey) } -/** - * Parses all possible command line options and returns a struct that contains them - */ -func parseCommandLineOptions() -> CommandLineArguments { - var arguments = CommandLine.arguments +struct GenerateAppcast: ParsableCommand { + static var programName: String = CommandLine.arguments.first ?? "./generate-appcast" - // If there are fewer than two arguments (the name of the application + - // the required archive directory), or if `-h` is in the argument list, - // then show the usage message - if arguments.count < 2 || arguments.contains("-h") { - printUsage() - exit(1) + @Option(name: .customShort("s"), help: ArgumentHelp("The private EdDSA string (128 characters).", valueName: "private-EdDSA-key")) + var privateEdString : String? + + @Option(name: .customShort("f"), help: ArgumentHelp("Path to the private DSA key file.", valueName: "private-dsa-key-file"), transform: { URL(fileURLWithPath: $0) }) + var privateDSAKeyURL: URL? + + @Option(name: .customShort("n"), help: ArgumentHelp("The name of the private DSA key. This option must be used together with `-k`.", valueName: "dsa-key-name")) + var privateDSAKeyName: String? + + @Option(name: .customShort("k"), help: ArgumentHelp("The path to the keychain to look up the private DSA key. This option must be used together with `-n`.", valueName: "keychain-for-dsa"), transform: { URL(fileURLWithPath: $0) }) + var keychainURL: URL? + + @Option(name: .customLong("download-url-prefix"), help: ArgumentHelp("A URL that will be used as prefix for the URL from where updates will be downloaded.", valueName: "url"), transform: { URL(string: $0) }) + var downloadURLPrefix : URL? + + @Option(name: .customLong("release-notes-url-prefix"), help: ArgumentHelp("A URL that will be used as prefix for constructing URLs for release notes.", valueName: "url"), transform: { URL(string: $0) }) + var releaseNotesURLPrefix : URL? + + @Option(name: .customShort("o"), help: ArgumentHelp("Path to filename for the generated appcast (allowed when only one will be created).", valueName: "output-path"), transform: { URL(fileURLWithPath: $0) }) + var outputPathURL: URL? + + @Argument(help: "The path to the directory containing the update archives and delta files.", transform: { URL(fileURLWithPath: $0, isDirectory: true) }) + var archivesSourceDir: URL + + @Flag(help: .hidden) + var verbose: Bool = false + + static var configuration = CommandConfiguration( + abstract: "Generate appcast from a directory of Sparkle update archives.", + discussion: """ + Appcast files and deltas will be written to the archives directory. + Note that pkg-based updates are not supported. + + EXAMPLES: + \(programName) ./my-app-release-zipfiles/ + \(programName) -o appcast-name.xml ./my-app-release-zipfiles/ + """) + + func validate() throws { + guard (keychainURL == nil) == (privateDSAKeyName == nil) else { + throw ValidationError("Both -n and -k options must be provided together, or neither should be provided.") + } + + // Both keychain/dsa key name options, and private dsa key file options cannot coexist + guard (keychainURL == nil) || (privateDSAKeyURL == nil) else { + throw ValidationError("-f cannot be provided if -n and -k is provided") + } } - // Remove the first element since this is the path to executable which we don't need - arguments.removeFirst() - - // Create the struct that will hold the parsed args - var commandLineArguments = CommandLineArguments() - - // check if the private dsa key option is present - if let privateDSAKeyOptionIndex = arguments.firstIndex(of: "-f") { - // check that when accessing the value of the option we don't get out of bounds - if privateDSAKeyOptionIndex + 1 >= arguments.count { - print("Too few arguments were given") - exit(1) + func run() throws { + // Extract the keys + let privateDSAKey : SecKey? + if let privateDSAKeyURL = privateDSAKeyURL { + do { + privateDSAKey = try loadPrivateDSAKey(at: privateDSAKeyURL) + } catch { + print("Unable to load DSA private key from", privateDSAKeyURL.path, "\n", error) + throw ExitCode(1) + } + } else if let keychainURL = keychainURL, let privateDSAKeyName = privateDSAKeyName { + do { + privateDSAKey = try loadPrivateDSAKey(named: privateDSAKeyName, fromKeychainAt: keychainURL) + } catch { + print("Unable to load DSA private key '\(privateDSAKeyName)' from keychain at", keychainURL.path, "\n", error) + throw ExitCode(1) + } + } else { + privateDSAKey = nil } - - // get the private DSA key - let privateKeyUrl = URL(fileURLWithPath: arguments[privateDSAKeyOptionIndex + 1]) + + let keys = loadPrivateKeys(privateDSAKey, privateEdString) + do { - commandLineArguments.privateDSAKey = try loadPrivateDSAKey(at: privateKeyUrl) - } catch { - print("Unable to load DSA private key from", privateKeyUrl.path, "\n", error) - exit(1) - } - - // remove the already parsed arguments - arguments.remove(at: privateDSAKeyOptionIndex + 1) - arguments.remove(at: privateDSAKeyOptionIndex) - } - - // check if the private dsa sould be loaded using the keyname and the name of the keychain - if let keyNameOptionIndex = arguments.firstIndex(of: "-n"), let keychainNameOptionIndex = arguments.firstIndex(of: "-k") { - // check that when accessing one of the values of the options we don't get out of bounds - if keyNameOptionIndex + 1 >= arguments.count || keychainNameOptionIndex + 1 >= arguments.count { - print("Too few arguments were given") - exit(1) - } - - // get the keyname and the keychain url to load the private DSA key - let keyName: String = arguments[keyNameOptionIndex + 1] - let keychainUrl: URL = URL(fileURLWithPath: arguments[keychainNameOptionIndex + 1]) - do { - commandLineArguments.privateDSAKey = try loadPrivateDSAKey(named: keyName, fromKeychainAt: keychainUrl) - } catch { - print("Unable to load DSA private key '\(keyName)' from keychain at", keychainUrl.path, "\n", error) - exit(1) - } - - // remove the already parsed arguments - arguments.remove(at: keyNameOptionIndex + 1) - arguments.remove(at: keyNameOptionIndex) - arguments.remove(at: arguments.firstIndex(of: "-k")! + 1) - arguments.remove(at: keychainNameOptionIndex) - } - - // check if the private EdDSA key string was given as an argument - if let privateEdDSAKeyOptionIndex = arguments.firstIndex(of: "-s") { - // check that when accessing the value of the option we don't get out of bounds - if privateEdDSAKeyOptionIndex + 1 >= arguments.count { - print("Too few arguments were given") - exit(1) - } - - // get the private EdDSA key string - commandLineArguments.privateEdString = arguments[privateEdDSAKeyOptionIndex + 1] - - // remove the already parsed argument - arguments.remove(at: privateEdDSAKeyOptionIndex + 1) - arguments.remove(at: privateEdDSAKeyOptionIndex) - } - - // check if a prefix for the download url of the archives was given - if let downloadUrlPrefixOptionIndex = arguments.firstIndex(of: "--download-url-prefix") { - // check that when accessing the value of the option we don't get out of bounds - if downloadUrlPrefixOptionIndex + 1 >= arguments.count { - print("Too few arguments were given") - exit(1) - } - - // get the download url prefix - commandLineArguments.downloadURLPrefix = URL(string: arguments[downloadUrlPrefixOptionIndex + 1]) - - // remove the parsed argument - arguments.remove(at: downloadUrlPrefixOptionIndex + 1) - arguments.remove(at: downloadUrlPrefixOptionIndex) - } - - // Check if a URL prefix was specified for the release notes - if let releaseNotesURLPrefixOptionIndex = arguments.firstIndex(of: "--release-notes-url-prefix") { - if releaseNotesURLPrefixOptionIndex + 1 >= arguments.count { - print("Too few arguments were given") - exit(1) - } - - // Get the URL prefix for the release notes - commandLineArguments.releaseNotesURLPrefix = URL(string: arguments[releaseNotesURLPrefixOptionIndex + 1]) - - // Remove the parsed argument - arguments.remove(at: releaseNotesURLPrefixOptionIndex + 1) - arguments.remove(at: releaseNotesURLPrefixOptionIndex) - } - - // Check if an output filename was specified - if let outputFilenameOptionIndex = arguments.firstIndex(of: "-o") { - // check that when accessing the value of the option we don't get out of bounds - if outputFilenameOptionIndex + 1 >= arguments.count { - print("Too few arguments were given") - exit(1) - } - - // Get the URL prefix for the release notes - commandLineArguments.outputPathURL = URL(fileURLWithPath: arguments[outputFilenameOptionIndex + 1]) - - // Remove the parsed argument - arguments.remove(at: outputFilenameOptionIndex + 1) - arguments.remove(at: outputFilenameOptionIndex) - } - - // now that all command line options have been removed from the arguments array - // there should only be the path to the private DSA key (if provided) path to the archives dir left - if arguments.count == 2 { - // if there are two arguments left they are the private DSA key and the path to the archives directory (in this order) - // first get the private DSA key - let privateKeyURL = URL(fileURLWithPath: arguments[0]) - do { - commandLineArguments.privateDSAKey = try loadPrivateDSAKey(at: privateKeyURL) - } catch { - print("Unable to load DSA private key from", privateKeyURL.path, "\n", error) - exit(1) - } - - // remove the parsed path to the DSA key - arguments.removeFirst() - } - - // now only the archives source dir is left - if let archivesSourceDir = arguments.first { - commandLineArguments.archivesSourceDir = URL(fileURLWithPath: archivesSourceDir, isDirectory: true) - } else { - print("Archive folder must be specified") - exit(1); - } - - return commandLineArguments -} - -func main() { - // Parse the command line arguments - let args = parseCommandLineOptions() - - // If parsing the command line options was successful, then - // the archivesSourceDir must exist - let archivesSourceDir = args.archivesSourceDir! - - // Extract the keys - let keys = loadPrivateKeys(args.privateDSAKey, args.privateEdString) - - do { - let allUpdates = try makeAppcast(archivesSourceDir: archivesSourceDir, keys: keys, verbose: verbose) - - // If a URL prefix was provided, set on the archive items - if args.downloadURLPrefix != nil || args.releaseNotesURLPrefix != nil { - for (_, archiveItems) in allUpdates { - for archiveItem in archiveItems { - if let downloadURLPrefix = args.downloadURLPrefix { - archiveItem.downloadUrlPrefix = downloadURLPrefix - } - if let releaseNotesURLPrefix = args.releaseNotesURLPrefix { - archiveItem.releaseNotesURLPrefix = releaseNotesURLPrefix + let allUpdates = try makeAppcast(archivesSourceDir: archivesSourceDir, keys: keys, verbose: verbose) + + // If a URL prefix was provided, set on the archive items + if downloadURLPrefix != nil || releaseNotesURLPrefix != nil { + for (_, archiveItems) in allUpdates { + for archiveItem in archiveItems { + if let downloadURLPrefix = downloadURLPrefix { + archiveItem.downloadUrlPrefix = downloadURLPrefix + } + if let releaseNotesURLPrefix = releaseNotesURLPrefix { + archiveItem.releaseNotesURLPrefix = releaseNotesURLPrefix + } } } } - } + + // If a (single) output filename was specified on the command-line, but more than one + // appcast file was found in the archives, then it's an error. + if let outputPathURL = outputPathURL, + allUpdates.count > 1 { + print("Cannot write to \(outputPathURL.path): multiple appcasts found") + throw ExitCode(1) + } + + for (appcastFile, updates) in allUpdates { + // If an output filename was specified, use it. + // Otherwise, use the name of the appcast file found in the archive. + let appcastDestPath = outputPathURL ?? URL(fileURLWithPath: appcastFile, + relativeTo: archivesSourceDir) - // If a (single) output filename was specified on the command-line, but more than one - // appcast file was found in the archives, then it's an error. - if let outputPathURL = args.outputPathURL, - allUpdates.count > 1 { - print("Cannot write to \(outputPathURL.path): multiple appcasts found") - exit(1); + // Write the appcast + try writeAppcast(appcastDestPath: appcastDestPath, updates: updates) + + // Inform the user, pluralizing "update" if necessary + let updateString = (updates.count == 1) ? "update" : "updates" + print("Wrote \(updates.count) \(updateString) to: \(appcastDestPath.path)") + } + } catch { + print("Error generating appcast from directory", archivesSourceDir.path, "\n", error) + throw ExitCode(1) } - - for (appcastFile, updates) in allUpdates { - // If an output filename was specified, use it. - // Otherwise, use the name of the appcast file found in the archive. - let appcastDestPath = args.outputPathURL ?? URL(fileURLWithPath: appcastFile, - relativeTo: archivesSourceDir) - - // Write the appcast - try writeAppcast(appcastDestPath: appcastDestPath, updates: updates) - - // Inform the user, pluralizing "update" if necessary - let updateString = (updates.count == 1) ? "update" : "updates" - print("Wrote \(updates.count) \(updateString) to: \(appcastDestPath.path)") - } - } catch { - print("Error generating appcast from directory", archivesSourceDir.path, "\n", error) - exit(1) } } DispatchQueue.global().async(execute: { - main() + GenerateAppcast.main() CFRunLoopStop(CFRunLoopGetMain()) }) - CFRunLoopRun() diff --git a/generate_keys/main.swift b/generate_keys/main.swift index feb0350c..664531cb 100644 --- a/generate_keys/main.swift +++ b/generate_keys/main.swift @@ -8,6 +8,7 @@ import Foundation import Security +import ArgumentParser let PRIVATE_KEY_LABEL = "Private key for signing Sparkle updates" @@ -155,133 +156,122 @@ func printNewPublicKeyUsage(_ publicKey: Data) { """) } -/// Once it's safe to require Swift 5.3 and Xcode 12 for this code, rename this file to `generate_keys.swift` and -/// replace this function with a class tagged with `@main`. -func entryPoint() { - let arguments = CommandLine.arguments - let programName = arguments.first ?? "generate_keys" +struct GenerateKeys: ParsableCommand { + @Flag(name: .customShort("p"), help: ArgumentHelp("Looks up and just prints the existing public key stored in the Keychain.")) + var lookUpPublicKey: Bool = false - let mode = arguments.count > 1 ? arguments[1] : nil - - /// If not in any mode, give an intro blurb. - if mode == nil { - print(""" - Usage: \(programName) [-p] [-x private-key-file] [-f private-key-file] - - This tool generates a public & private keys and uses the macOS Keychain to store - the private key for signing app updates which will be distributed via Sparkle. - This key will be associated with your user account. - - Note: You only need one signing key, no matter how many apps you embed Sparkle in. - - The keychain may ask permission for this tool to access an existing key, if one - exists, or for permission to save the new key. You must allow access in order to - successfully proceed. - - Additional Options: - -p - Looks up and just prints the existing public key stored in the Keychain. - - -x private-key-file - Exports your private key from your login keychain and writes it to private-key-file. Note the contents of - this sensitive exported file are the same as the password to the \"\(PRIVATE_KEY_LABEL)\" item in - your keychain. - - -f private-key-file - Imports the private key from private-key-file into your keychain instead of generating a new key. - This file has likely been exported via -x option from another machine. - Any existing \"\(PRIVATE_KEY_LABEL)\" items listed in Keychain Access may need to be removed manually first before proceeding. - - ---------------------------------------------------------------------------------------------------- - - """) + @Option(name: .customShort("x"), help: ArgumentHelp("Exports your private key from your login keychain and writes it to private-key-file. Note the contents of this sensitive exported file are the same as the password to the \"\(PRIVATE_KEY_LABEL)\" item in your keychain.", valueName: "private-key-file")) + var exportedPrivateKeyFile: String? + + @Option(name: .customShort("f"), help: ArgumentHelp("Imports the private key from private-key-file into your keychain instead of generating a new key. This file has likely been exported via -x option from another machine. Any existing \"\(PRIVATE_KEY_LABEL)\" items listed in Keychain Access may need to be removed manually first before proceeding.", valueName: "private-key-file")) + var importedPrivateKeyFile: String? + + static var configuration: CommandConfiguration = CommandConfiguration( + abstract: "Generate public & private keys for signing Sparkle based app updates.", + discussion: """ + This tool generates a public & private keys and uses the macOS Keychain to store + the private key for signing app updates which will be distributed via Sparkle. + This key will be associated with your user account. + + Note: You only need one signing key, no matter how many apps you embed Sparkle in. + + The keychain may ask permission for this tool to access an existing key, if one + exists, or for permission to save the new key. You must allow access in order to + successfully proceed. + + In the default mode ran without any arguments, the public key and how it should be used + in your application's Info.plist will be printed. If a private key was already generated in your Keychain, + that key will be used and not overridden. + + You may additionally use options to only look up the existing public key for automation (-p), + export the private key from your Keychain to a file for transferring the key (-x), or + import the private key into your Keychain from a file (-f). + """) + + func validate() throws { + if lookUpPublicKey { + guard exportedPrivateKeyFile == nil && importedPrivateKeyFile == nil else { + throw ValidationError("-p option cannot be provided together with -x or -f.") + } + } else { + guard exportedPrivateKeyFile == nil || importedPrivateKeyFile == nil else { + throw ValidationError("Both -x and -f options cannot be provided together.") + } + } } - switch mode { - case .some("-p"): - /// Lookup mode - print just the pubkey and exit - if let keyPair = findKeyPair() { - let pubKey = keyPair[64...] - print(pubKey.base64EncodedString()) + func run() throws { + if lookUpPublicKey { + /// Lookup mode - print just the pubkey and exit + if let keyPair = findKeyPair() { + let pubKey = keyPair[64...] + print(pubKey.base64EncodedString()) + } else { + failure("No existing signing key found!") + } + } else if let exportedPrivateKeyFile = exportedPrivateKeyFile { + /// Export mode - export the key-pair file from the user's keychain + let exportURL = URL(fileURLWithPath: exportedPrivateKeyFile) + if let reachable = try? exportURL.checkResourceIsReachable(), reachable { + failure("private-key-file already exists: \(exportURL.path)") + } + + guard let keyPair = findKeyPair() else { + failure("No existing signing key found!") + } + + do { + try keyPair.base64EncodedString().write(to: exportURL, atomically: true, encoding: .utf8) + } catch { + failure("Failed to write exported file: \(error)") + } + } else if let importedPrivateKeyFile = importedPrivateKeyFile { + /// Import mode - import the specifed key-pair file + let privateAndPublicBase64KeyFile = importedPrivateKeyFile + let privateAndPublicBase64Key: String + do { + privateAndPublicBase64Key = try String(contentsOfFile: privateAndPublicBase64KeyFile) + } catch { + failure("Failed to read private-key-file: \(error)") + } + + guard let privateAndPublicKey = Data(base64Encoded: privateAndPublicBase64Key.trimmingCharacters(in: .whitespacesAndNewlines), options: .init()) else { + failure("Failed to decode base64 encoded key data from: \(privateAndPublicBase64Key)") + } + + guard privateAndPublicKey.count == 64 + 32 else { + failure("Imported key must be 96 bytes decoded. Instead it is \(privateAndPublicKey.count) bytes decoded.") + } + + print("Importing signing key..\n") + + let publicKey = privateAndPublicKey[64...] + let privateKey = privateAndPublicKey[0..<64] + + storeKeyPair(publicEdKey: publicKey, privateEdKey: privateKey) + + printNewPublicKeyUsage(publicKey) } else { - failure("No existing signing key found!") - } - case .some("-f"): - /// Import mode - import the specifed key-pair file - guard arguments.count > 2 else { - failure("private-key-file was not specified") - } - - let privateAndPublicBase64KeyFile = arguments[2] - let privateAndPublicBase64Key: String - do { - privateAndPublicBase64Key = try String(contentsOfFile: privateAndPublicBase64KeyFile) - } catch { - failure("Failed to read private-key-file: \(error)") - } - - guard let privateAndPublicKey = Data(base64Encoded: privateAndPublicBase64Key.trimmingCharacters(in: .whitespacesAndNewlines), options: .init()) else { - failure("Failed to decode base64 encoded key data from: \(privateAndPublicBase64Key)") - } - - guard privateAndPublicKey.count == 64 + 32 else { - failure("Imported key must be 96 bytes decoded. Instead it is \(privateAndPublicKey.count) bytes decoded.") - } - - print("Importing signing key..") - - let publicKey = privateAndPublicKey[64...] - let privateKey = privateAndPublicKey[0..<64] - - storeKeyPair(publicEdKey: publicKey, privateEdKey: privateKey) - - printNewPublicKeyUsage(publicKey) - - case .some("-x"): - /// Export mode - export the key-pair file from the user's keychain - guard arguments.count > 2 else { - failure("private-key-file was not specified") - } - - let exportURL = URL(fileURLWithPath: arguments[2]) - if let reachable = try? exportURL.checkResourceIsReachable(), reachable { - failure("private-key-file already exists: \(exportURL.path)") - } - - guard let keyPair = findKeyPair() else { - failure("No existing signing key found!") - } - - do { - try keyPair.base64EncodedString().write(to: exportURL, atomically: true, encoding: .utf8) - } catch { - failure("Failed to write exported file: \(error)") - } - - case .some(let unknownOption): - failure("Unknown option: \(unknownOption)") - - case nil: - /// Default mode - find an existing public key and print its usage, or generate new keys - if let keyPair = findKeyPair() { - let pubKey = keyPair[64...] - print(""" - A pre-existing signing key was found. This is how it should appear in your Info.plist: + /// Default mode - find an existing public key and print its usage, or generate new keys + if let keyPair = findKeyPair() { + let pubKey = keyPair[64...] + print(""" + A pre-existing signing key was found. This is how it should appear in your Info.plist: - SUPublicEDKey - \(pubKey.base64EncodedString()) - - """) - } else { - print("Generating a new signing key. This may take a moment, depending on your machine.") - - let (pubKey, privKey) = generateKeyPair() - storeKeyPair(publicEdKey: pubKey, privateEdKey: privKey) - - printNewPublicKeyUsage(pubKey) + SUPublicEDKey + \(pubKey.base64EncodedString()) + + """) + } else { + print("Generating a new signing key. This may take a moment, depending on your machine.") + + let (pubKey, privKey) = generateKeyPair() + storeKeyPair(publicEdKey: pubKey, privateEdKey: privKey) + + printNewPublicKeyUsage(pubKey) + } } } } -// Dispatch to a function because `@main` isn't stable yet at the time of this writing and top-level code is finicky. -entryPoint() +GenerateKeys.main() diff --git a/sign_update/main.swift b/sign_update/main.swift index 8eacef62..48820686 100644 --- a/sign_update/main.swift +++ b/sign_update/main.swift @@ -8,8 +8,9 @@ import Foundation import Security +import ArgumentParser -func findKeysInKeychain() -> (Data, Data) { +func findKeysInKeychain() throws -> (Data, Data) { var item: CFTypeRef? let res = SecItemCopyMatching([ kSecClass as String: kSecClassGenericPassword, @@ -30,25 +31,25 @@ func findKeysInKeychain() -> (Data, Data) { } else if res == errSecInteractionNotAllowed { print("ERROR! The operating system has blocked access to the Keychain.") } else { - print("ERROR! Unable to access required key in the Keychain", res, "(you can look it up at osstatus.com)") + print("ERROR! Unable to access required key in the Keychain: \(res) (you can look it up at osstatus.com)") } - exit(1) + throw ExitCode.failure } func findKeys(inFile privateAndPublicBase64KeyFile: String) throws -> (Data, Data) { let privateAndPublicBase64Key = try String(contentsOfFile: privateAndPublicBase64KeyFile) - return findKeys(inString: privateAndPublicBase64Key) + return try findKeys(inString: privateAndPublicBase64Key) } -func findKeys(inString privateAndPublicBase64Key: String) -> (Data, Data) { +func findKeys(inString privateAndPublicBase64Key: String) throws -> (Data, Data) { guard let privateAndPublicKey = Data(base64Encoded: privateAndPublicBase64Key.trimmingCharacters(in: .whitespacesAndNewlines), options: .init()) else { print("ERROR! Failed to decode base64 encoded key data from: \(privateAndPublicBase64Key)") - exit(1) + throw ExitCode.failure } guard privateAndPublicKey.count == 64 + 32 else { print("ERROR! Imported key must be 96 bytes decoded. Instead it is \(privateAndPublicKey.count) bytes decoded.") - exit(1) + throw ExitCode.failure } let publicKey = privateAndPublicKey[64...] @@ -68,30 +69,41 @@ func edSignature(data: Data, publicEdKey: Data, privateEdKey: Data) -> String { return Data(output).base64EncodedString() } -let args = CommandLine.arguments -if args.count != 2 && args.count != 4 { - print("Usage: \(args[0]) [-f | -s ]\nPrivate EdDSA (ed25519) key is automatically read from the Keychain if no or is given.\n") - exit(1) -} - -do { - let (priv, pub): (Data, Data) - let mode = args.count > 2 ? args[2] : nil +struct SignUpdate: ParsableCommand { + @Argument(help: "The update archive, delta update, or package (pkg) to sign.") + var updatePath: String - switch mode { - case .some("-f"): - (priv, pub) = try findKeys(inFile: args[3]) - - case .some("-s"): - (priv, pub) = findKeys(inString: args[3]) - - default: - (priv, pub) = findKeysInKeychain() + @Option(name: .customShort("s"), help: ArgumentHelp("The private EdDSA (ed25519) key.", valueName: "private-key")) + var privateKey: String? + + @Option(name: .customShort("f"), help: ArgumentHelp("Path to the file containing the private EdDSA (ed25519) key.", valueName: "private-key-file")) + var privateKeyFile: String? + + static var configuration: CommandConfiguration = CommandConfiguration( + abstract: "Sign an update using your private EdDSA (ed25519) key.", + discussion: "The private EdDSA key is automatically read from the Keychain if no or is specified.\n\nThis tool will output an EdDSA signature and length attributes to use for your update's appcast item enclosure.") + + func validate() throws { + guard privateKey == nil || privateKeyFile == nil else { + throw ValidationError("Both -s and -f options cannot be provided.") + } } - let data = try Data.init(contentsOf: URL.init(fileURLWithPath: args[1]), options: .mappedIfSafe) - let sig = edSignature(data: data, publicEdKey: pub, privateEdKey: priv) - print("sparkle:edSignature=\"\(sig)\" length=\"\(data.count)\"") -} catch { - print("ERROR: ", error) + func run() throws { + let (priv, pub): (Data, Data) + + if let privateKey = privateKey { + (priv, pub) = try findKeys(inString: privateKey) + } else if let privateKeyFile = privateKeyFile { + (priv, pub) = try findKeys(inFile: privateKeyFile) + } else { + (priv, pub) = try findKeysInKeychain() + } + + let data = try Data.init(contentsOf: URL.init(fileURLWithPath: updatePath), options: .mappedIfSafe) + let sig = edSignature(data: data, publicEdKey: pub, privateEdKey: priv) + print("sparkle:edSignature=\"\(sig)\" length=\"\(data.count)\"") + } } + +SignUpdate.main()