From 726479f1ac6bbd87370c0599fb89e16e15f24fce Mon Sep 17 00:00:00 2001 From: adamXbot <111877622+adamXbot@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:32:40 +1100 Subject: [PATCH 1/3] Ship auditctl inside the app and put it on PATH MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit People who install privacycommand.app could only get the auditctl CLI by cloning the repo and building it. The app now carries it. - New "Embed auditctl" run-script phase (Scripts/embed-auditctl.sh) builds the SwiftPM product for the app's architectures (universal in Release), stamps the app's version and an identifier into its __info_plist section, strips it at link time, copies it to Contents/Helpers/auditctl and signs it with the app's identity and hardened runtime, following the guest-agent phase. It uses its own SwiftPM scratch path so it doesn't ping-pong rebuilds with the host-only guest build in .build. - The cask template links it with a binary stanza, so `brew install --cask` puts auditctl on PATH. - DMG installs get an app-menu item, Install Command Line Tool…, below Check for Updates…. It symlinks the embedded binary into /usr/local/bin, or shows the equivalent sudo command (with Copy) when the folder isn't writable, and flips to Uninstall Command Line Tool…. It refuses to link from a disk image or translocated copy, recognises Homebrew's link, replaces links to other app copies, and never touches a file or link it didn't create. The filesystem logic is CommandLineTool in Core, with unit tests. - README "Get it → Command line", the in-app manual, CONTRIBUTING and the source-tree README describe the two install paths. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 5 +- README.md | 13 +- packaging/homebrew/privacycommand.rb | 4 + privacycommand/README.md | 13 ++ privacycommand/Resources/Manual/07-reports.md | 7 +- privacycommand/Scripts/embed-auditctl.sh | 100 +++++++++ .../ViewModels/CommandLineToolInstaller.swift | 163 ++++++++++++++ .../privacycommand/privacycommandApp.swift | 12 + .../Updates/CommandLineTool.swift | 205 ++++++++++++++++++ .../CommandLineToolTests.swift | 184 ++++++++++++++++ .../privacycommand.xcodeproj/project.pbxproj | 30 +++ 11 files changed, 733 insertions(+), 3 deletions(-) create mode 100755 privacycommand/Scripts/embed-auditctl.sh create mode 100644 privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift create mode 100644 privacycommand/Sources/privacycommandCore/Updates/CommandLineTool.swift create mode 100644 privacycommand/Tests/privacycommandCoreTests/CommandLineToolTests.swift diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5cba33a..5fd61a2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -56,7 +56,10 @@ Deeper references live next to the sources: ## The auditctl CLI `auditctl` is a command-line front end over the same analyser, useful for -scripting and CI. Build it once, then call the binary directly: +scripting and CI. The app ships it at `Contents/Helpers/auditctl` (the +**Embed auditctl** build phase), and users put it on `PATH` through the +Homebrew cask or the app menu — see [Get it](README.md#get-it). To work on +it, build it once, then call the binary directly: ```sh cd privacycommand diff --git a/README.md b/README.md index c4b4151..5735223 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,18 @@ brew install --cask privacykey/tap/privacycommand **Direct download** — take the signed and notarized `.dmg` from the [latest release](https://github.com/privacykey/privacycommand/releases/latest) and drag the app to `/Applications`. In-app updates use [Sparkle 2](https://sparkle-project.org) against an EdDSA-signed [appcast feed](https://privacykey.github.io/privacycommand/appcast.xml); automatic checks are **off by default** and you opt in under Settings → Updates. -**Command line** — the repo also builds `auditctl`, a CLI over the same analyser. Its `preview` command inspects Homebrew casks *before* you update them; it never runs `brew`, never blocks an update, and always exits 0. Building and using it is covered in [CONTRIBUTING.md](CONTRIBUTING.md#the-auditctl-cli). +**Command line** — the app carries `auditctl`, a CLI over the same analyser, and there are two ways to put it on your `PATH`: + +- **Homebrew** — the cask links `auditctl` for you on install and removes it on uninstall. Nothing else to do. +- **Direct download** — choose **privacycommand ▸ Install Command Line Tool…**. It links the copy inside the app into `/usr/local/bin`, so the tool updates with the app. When that folder needs administrator rights, as it does on most Macs, it shows the `sudo ln -s` command to paste into Terminal instead, with a button that copies it. The same menu item then reads **Uninstall Command Line Tool…** and removes the link. + +```sh +auditctl slack --short # one-line verdict for an installed app +auditctl preview # check outdated Homebrew casks before you upgrade +auditctl --help # every command and flag +``` + +`preview` inspects Homebrew casks *before* you update them; it never runs `brew`, never blocks an update, and always exits 0. To build `auditctl` from source instead, see [CONTRIBUTING.md](CONTRIBUTING.md#the-auditctl-cli). ## Docs diff --git a/packaging/homebrew/privacycommand.rb b/packaging/homebrew/privacycommand.rb index f224488..884a4f0 100644 --- a/packaging/homebrew/privacycommand.rb +++ b/packaging/homebrew/privacycommand.rb @@ -21,6 +21,10 @@ end app "privacycommand.app" + # The auditctl CLI ships inside the app; this links it onto PATH and + # removes the link on uninstall. DMG installs use the app menu's + # Install Command Line Tool… item instead. + binary "#{appdir}/privacycommand.app/Contents/Helpers/auditctl" # We're not sandboxed, so quitting the app is enough — no need for # a tighter `quit:` predicate. The in-app Sparkle updater is diff --git a/privacycommand/README.md b/privacycommand/README.md index 6578bbc..877c2df 100644 --- a/privacycommand/README.md +++ b/privacycommand/README.md @@ -37,6 +37,13 @@ fiddling that earlier versions of this README walked through. The Files** phases that drop the helper executable into `Contents/MacOS/` and the LaunchDaemon plist into `Contents/Library/LaunchDaemons/`. +- An **Embed auditctl** run-script phase + ([`Scripts/embed-auditctl.sh`](Scripts/embed-auditctl.sh)) that + builds the `auditctl` CLI with SwiftPM for the app's architectures, + stamps the app's version into it, copies it to + `Contents/Helpers/auditctl` and signs it with the app's identity and + hardened runtime. The Homebrew cask's `binary` stanza and the app + menu's Install Command Line Tool… item both link to that path. - Sparkle 2 wired in for in-app updates (you have to add it once via **File → Add Package Dependencies…** — see the top-level README). @@ -154,6 +161,12 @@ Helper (`Resources/privacycommandHelper.entitlements`): - `com.apple.developer.service-management.managed-by-main-app`: **ON** — required for `SMAppService.daemon` lifecycle. +`auditctl` (`Contents/Helpers/auditctl`) and the guest agent +(`Contents/Resources/privacycommand-guest`): + +- Signed by their run-script phases with the app's identity. +- Hardened Runtime: **ON**. No entitlements. + ## Building from the command line ```sh diff --git a/privacycommand/Resources/Manual/07-reports.md b/privacycommand/Resources/Manual/07-reports.md index 1ca99b3..b3cc744 100644 --- a/privacycommand/Resources/Manual/07-reports.md +++ b/privacycommand/Resources/Manual/07-reports.md @@ -10,4 +10,9 @@ Each item opens a save panel with a file name suggested from the app's name and ## The command line -The repository also builds `auditctl`, a command-line front end over the same analyser, for scripting and CI. `auditctl ` audits one app (`--short`, `--tree`, `--json`, `--warnings`), and `auditctl preview` inspects outdated Homebrew casks before you update them. Building and using it is covered in the repository's CONTRIBUTING.md. +privacycommand carries `auditctl`, a command-line front end over the same analyser, for scripting and CI. `auditctl ` audits one app (`--short`, `--tree`, `--json`, `--warnings`), and `auditctl preview` inspects outdated Homebrew casks before you update them. `auditctl --help` lists every command. + +- **Installed with Homebrew:** the cask has already put `auditctl` on your `PATH`. +- **Installed from the disk image:** choose **privacycommand ▸ Install Command Line Tool…**. It links the copy inside the app into `/usr/local/bin`, so the tool updates with the app. If that folder needs administrator rights, the alert shows the `sudo` command to run in Terminal instead, with a button that copies it. Choose **Uninstall Command Line Tool…** from the same place to remove the link. + +Run privacycommand from the Applications folder before installing the tool: a link into a copy that is still on the disk image stops working when the image is ejected, so the item asks you to move the app first. diff --git a/privacycommand/Scripts/embed-auditctl.sh b/privacycommand/Scripts/embed-auditctl.sh new file mode 100755 index 0000000..c786848 --- /dev/null +++ b/privacycommand/Scripts/embed-auditctl.sh @@ -0,0 +1,100 @@ +#!/bin/bash +# Build the auditctl CLI via SwiftPM, embed it at +# privacycommand.app/Contents/Helpers/auditctl, and sign it with the app's +# identity and hardened runtime so the notarized bundle stays valid. +# +# Runs as the app target's "Embed auditctl" build phase. Homebrew's cask +# links the embedded binary onto PATH (the `binary` stanza in +# packaging/homebrew/privacycommand.rb); DMG installs link it from the app +# menu's Install Command Line Tool… item. + +set -euo pipefail + +PRODUCT=auditctl + +# A scratch path of its own. The guest agent's phase builds host-only into +# ${SRCROOT}/.build; sharing that with this build, which follows the app's +# architectures, would make each one rebuild the package from scratch. +SCRATCH="${PROJECT_TEMP_DIR}/auditctl-swiftpm" + +# Stamp the app's version into the binary's __TEXT,__info_plist section, so +# `auditctl --version` reports it and codesign takes the identifier from it. +IDENTITY_PLIST="${DERIVED_FILE_DIR}/BuildIdentity-Info.plist" +VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "${IDENTITY_PLIST}") +BUILD=$(/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "${IDENTITY_PLIST}") +INFO_PLIST="${DERIVED_FILE_DIR}/auditctl-Info.plist" +rm -f "${INFO_PLIST}" +/usr/libexec/PlistBuddy \ + -c "Add :CFBundleIdentifier string ${PRODUCT_BUNDLE_IDENTIFIER}.${PRODUCT}" \ + -c "Add :CFBundleName string ${PRODUCT}" \ + -c "Add :CFBundleShortVersionString string ${VERSION}" \ + -c "Add :CFBundleVersion string ${BUILD}" \ + "${INFO_PLIST}" >/dev/null + +# One SwiftPM invocation for every architecture the app is being built for +# (arm64 + x86_64 for Release, the active one for Debug). +SWIFT_ARGS=( -c release --product "${PRODUCT}" + --package-path "${SRCROOT}" --scratch-path "${SCRATCH}" ) +for arch in ${ARCHS}; do + SWIFT_ARGS+=( --arch "${arch}" ) +done +SWIFT_ARGS+=( -Xlinker -sectcreate -Xlinker __TEXT -Xlinker __info_plist + -Xlinker "${INFO_PLIST}" ) +# Leave debug info and local symbols out at link time, as Xcode strips the +# app's own executable: it halves the binary. Stripping afterwards instead +# would break the linker's signature in unsigned builds. +SWIFT_ARGS+=( -Xlinker -S -Xlinker -x ) + +# Xcode's build settings arrive as environment variables; keep them away +# from SwiftPM so this builds exactly what `swift build` does in Terminal, +# with the toolchain Xcode is using. +SWIFTPM_ENV=( HOME="${HOME}" PATH="${PATH}" TMPDIR="${TMPDIR:-/tmp}" ) +if [[ -n "${DEVELOPER_DIR:-}" ]]; then + SWIFTPM_ENV+=( DEVELOPER_DIR="${DEVELOPER_DIR}" ) +fi +swiftpm() { + env -i "${SWIFTPM_ENV[@]}" swift build "${SWIFT_ARGS[@]}" "$@" +} + +echo "Building ${PRODUCT} ${VERSION} (${BUILD}) for ${ARCHS} via SwiftPM…" +swiftpm +BIN="$(swiftpm --show-bin-path)/${PRODUCT}" +if [[ ! -f "${BIN}" ]]; then + echo "error: SwiftPM didn't produce ${BIN}" >&2 + exit 1 +fi +for arch in ${ARCHS}; do + if ! /usr/bin/lipo "${BIN}" -verify_arch "${arch}"; then + echo "error: ${BIN} is missing the ${arch} slice" >&2 + exit 1 + fi +done + +DEST="${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/Helpers" +mkdir -p "${DEST}" +cp -f "${BIN}" "${DEST}/${PRODUCT}" +chmod 755 "${DEST}/${PRODUCT}" + +# Follow Xcode's signing choice for unsigned builds (App CI). +if [[ "${CODE_SIGNING_ALLOWED:-YES}" == "NO" ]]; then + echo "Embedded ${PRODUCT} without signing (CODE_SIGNING_ALLOWED=NO)." + exit 0 +fi + +# Same identity as the rest of the app, as the guest agent's phase does: +# EXPANDED_CODE_SIGN_IDENTITY is '-' for Sign to Run Locally and the +# Developer ID certificate for release builds. Hardened runtime always, so +# notarization accepts the binary; a secure timestamp only with a real +# identity (ad-hoc signing can't take one). +IDENTITY="${EXPANDED_CODE_SIGN_IDENTITY:-${CODE_SIGN_IDENTITY:--}}" +if [[ -z "${IDENTITY}" ]]; then + IDENTITY="-" +fi +SIGN_FLAGS=( --force --options runtime --sign "${IDENTITY}" ) +if [[ "${IDENTITY}" != "-" ]]; then + SIGN_FLAGS+=( --timestamp ) +fi +echo "Signing ${PRODUCT} with identity '${IDENTITY}'…" +/usr/bin/codesign "${SIGN_FLAGS[@]}" "${DEST}/${PRODUCT}" + +echo "Embedded + signed ${PRODUCT} at ${DEST}/${PRODUCT}" diff --git a/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift b/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift new file mode 100644 index 0000000..9b8f111 --- /dev/null +++ b/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift @@ -0,0 +1,163 @@ +import AppKit +import Combine +import SwiftUI +#if SWIFT_PACKAGE +import privacycommandCore +#endif + +/// Drives the app menu's Install / Uninstall Command Line Tool… item, which +/// links the `auditctl` embedded at `Contents/Helpers/auditctl` into +/// /usr/local/bin for DMG installs. (Homebrew's cask links it on its own.) +/// +/// The filesystem work and its safety rules live in `CommandLineTool`; this +/// type adds the menu title and the alerts. Most Macs don't let an admin +/// user write /usr/local/bin without `sudo`, so the common outcome of +/// Install is an alert holding the equivalent Terminal command. +@MainActor +final class CommandLineToolInstaller: ObservableObject { + + @Published private(set) var status: CommandLineTool.Status = .notInstalled + + private let appBundle: URL + private let tool: CommandLineTool + private var activation: AnyCancellable? + + init(appBundle: URL = Bundle.main.bundleURL) { + self.appBundle = appBundle + self.tool = CommandLineTool(appBundle: appBundle) + refresh() + // The link can change from Terminal while the app is in the + // background; re-read it whenever the app (and its menu) comes back. + activation = NotificationCenter.default + .publisher(for: NSApplication.didBecomeActiveNotification) + .sink { [weak self] _ in + MainActor.assumeIsolated { self?.refresh() } + } + } + + func refresh() { + let current = tool.status() + if current != status { status = current } + } + + /// Uninstall is offered only for the link this item manages; a Homebrew + /// link belongs to `brew`. + var menuTitle: String { + if case .installed(let link) = status, link == tool.link { + return "Uninstall Command Line Tool…" + } + return "Install Command Line Tool…" + } + + func performMenuAction() { + refresh() + switch status { + case .installed(let link) where link == tool.link: + confirmUninstall() + case .installed(let link): + inform("auditctl is already installed", + "\(link.path) links to this copy of privacycommand, so auditctl is already on your PATH. " + + "Homebrew manages that link and removes it when you uninstall the cask.") + default: + install() + } + } + + // MARK: - Install + + private func install() { + guard !CommandLineTool.isTemporaryLocation(appBundle) else { + inform("Move privacycommand to Applications first", + "privacycommand is running from a disk image or a temporary location, so a link to its " + + "command-line tool would stop working. Drag privacycommand to the Applications folder, " + + "open it from there, and choose Install Command Line Tool… again.") + return + } + do { + try tool.install() + refresh() + inform("auditctl is installed", + "\(tool.link.path) now links to the copy inside privacycommand, so it updates with the app. " + + "Open a new Terminal window and run “auditctl --help” to get started.") + } catch { + refresh() + report(error, verb: "install") + } + } + + // MARK: - Uninstall + + private func confirmUninstall() { + let alert = NSAlert() + alert.messageText = "Uninstall the auditctl command?" + alert.informativeText = "This removes the link at \(tool.link.path). auditctl stays inside " + + "privacycommand, and you can install it again from this menu." + alert.addButton(withTitle: "Uninstall") + alert.addButton(withTitle: "Cancel") + guard alert.runModal() == .alertFirstButtonReturn else { return } + do { + try tool.uninstall() + refresh() + } catch { + refresh() + report(error, verb: "uninstall") + } + } + + // MARK: - Alerts + + private func report(_ error: Error, verb: String) { + guard let failure = error as? CommandLineTool.Failure else { + NSAlert(error: error).runModal() + return + } + switch failure { + case .permissionDenied(let command): + showCommand(title: "\(verb.capitalized) auditctl from Terminal", + message: "privacycommand needs administrator rights to change \(tool.installDirectory.path). " + + "Run this command in Terminal, which asks for your password:", + command: command) + case .occupied(let link, let destination): + let what = destination.map { "is a link to \($0)" } ?? "is a file" + inform("Another auditctl is in the way", + "\(link.path) \(what), which privacycommand didn't install, so it has left it alone. " + + "Remove or rename it, then try again.") + case .managedElsewhere(let link): + inform("Homebrew manages this link", + "\(link.path) was installed with the privacycommand cask and goes away when you run " + + "“brew uninstall --cask privacycommand”.") + case .notInstalled: + inform("auditctl isn't installed", "There is no link at \(tool.link.path) to remove.") + case .unavailable: + inform("This build doesn't include auditctl", + "Release builds of privacycommand carry the command-line tool. To build it from source, " + + "see “The auditctl CLI” in the repository's CONTRIBUTING.md.") + } + } + + private func inform(_ title: String, _ message: String) { + let alert = NSAlert() + alert.messageText = title + alert.informativeText = message + alert.runModal() + } + + /// An alert with a selectable, copyable shell command. + private func showCommand(title: String, message: String, command: String) { + let alert = NSAlert() + alert.messageText = title + alert.informativeText = message + let field = NSTextField(wrappingLabelWithString: command) + field.isSelectable = true + field.font = .monospacedSystemFont(ofSize: NSFont.smallSystemFontSize, weight: .regular) + field.preferredMaxLayoutWidth = 360 + field.frame.size = field.fittingSize + alert.accessoryView = field + alert.addButton(withTitle: "Copy Command") + alert.addButton(withTitle: "Cancel") + if alert.runModal() == .alertFirstButtonReturn { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(command, forType: .string) + } + } +} diff --git a/privacycommand/Sources/privacycommand/privacycommandApp.swift b/privacycommand/Sources/privacycommand/privacycommandApp.swift index 2b1b1ab..8c19215 100644 --- a/privacycommand/Sources/privacycommand/privacycommandApp.swift +++ b/privacycommand/Sources/privacycommand/privacycommandApp.swift @@ -20,6 +20,8 @@ struct privacycommandApp: App { defaultIcon: WatchModeIconStyle.shield.rawValue, iconKey: "watchModeIconStyle" ) + /// Links the embedded `auditctl` onto PATH from the app menu. + @StateObject private var commandLineTool = CommandLineToolInstaller() @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate private let app = PrivacycommandSurface.app @@ -73,6 +75,16 @@ struct privacycommandApp: App { } } .commands { + // The app's own app-menu block, below Check for Updates… and + // above Services. Homebrew installs get auditctl from the cask; + // this item links it for DMG installs. Declared ahead of + // SurfaceCommands on purpose: of two groups placed before + // Services, SwiftUI puts the later-declared one higher. + CommandGroup(before: .systemServices) { + Button(commandLineTool.menuTitle) { commandLineTool.performMenuAction() } + Divider() + } + // About, Check for Updates… and the three Help items. SurfaceCommands(app: app, help: help, updates: updates) diff --git a/privacycommand/Sources/privacycommandCore/Updates/CommandLineTool.swift b/privacycommand/Sources/privacycommandCore/Updates/CommandLineTool.swift new file mode 100644 index 0000000..7a8460d --- /dev/null +++ b/privacycommand/Sources/privacycommandCore/Updates/CommandLineTool.swift @@ -0,0 +1,205 @@ +import Foundation + +/// The `auditctl` command-line tool that ships inside privacycommand.app, +/// and the symlink that puts it on the user's `PATH`. +/// +/// Release builds embed the CLI at `Contents/Helpers/auditctl` (the app +/// target's "Embed auditctl" build phase). A Homebrew cask install links it +/// automatically through the cask's `binary` stanza; a DMG install links it +/// from the app menu's Install Command Line Tool… item, which drives this +/// type. +/// +/// The link points into the app bundle rather than at a copy, so the tool +/// updates whenever the app does. Install and uninstall only ever touch a +/// symlink to an embedded `auditctl`: a file or link that something else put +/// at the install location is reported and left alone. +public struct CommandLineTool: Sendable { + + public static let name = "auditctl" + + /// Where the binary sits inside the app bundle. + public static let bundlePath = "Contents/Helpers/auditctl" + + /// Where Install Command Line Tool… puts the link: on the default + /// `PATH` for every shell. + public static let defaultInstallDirectory = URL(fileURLWithPath: "/usr/local/bin", isDirectory: true) + + /// Other places a link to the tool may already live. Homebrew on Apple + /// silicon links cask binaries here (on Intel it uses /usr/local/bin). + public static let defaultSearchDirectories = [URL(fileURLWithPath: "/opt/homebrew/bin", isDirectory: true)] + + public enum Status: Equatable, Sendable { + /// This build has no embedded binary — a SwiftPM build of the app + /// sources, or one whose embed phase was skipped. + case unavailable + /// No link to the tool exists. + case notInstalled + /// A symlink at `link` resolves to this app's binary. It is either + /// at the install location or in a search directory (Homebrew's). + case installed(link: URL) + /// The install location holds a link to an embedded `auditctl` that + /// is not this app's: an older copy of the app, or one that has + /// since moved. Installing replaces it; uninstalling removes it. + case stale(link: URL, destination: String) + /// The install location holds something privacycommand did not put + /// there. `destination` is the link target, or nil for a plain file. + case occupied(link: URL, destination: String?) + } + + public enum Failure: Error, Equatable { + case unavailable + case notInstalled + case occupied(link: URL, destination: String?) + /// The tool is linked from somewhere this type doesn't manage — + /// Homebrew's bin directory, removed by `brew uninstall`. + case managedElsewhere(link: URL) + /// This user can't write the install directory. `command` makes the + /// same change with `sudo`, for the user to run in Terminal. + case permissionDenied(command: String) + } + + /// The embedded binary. + public let tool: URL + /// The link Install Command Line Tool… creates. + public let link: URL + public let installDirectory: URL + public let searchDirectories: [URL] + + public init(appBundle: URL, + installDirectory: URL = CommandLineTool.defaultInstallDirectory, + searchDirectories: [URL] = CommandLineTool.defaultSearchDirectories) { + self.tool = appBundle.appendingPathComponent(Self.bundlePath) + self.installDirectory = installDirectory + self.link = installDirectory.appendingPathComponent(Self.name) + self.searchDirectories = searchDirectories.filter { + $0.standardizedFileURL != installDirectory.standardizedFileURL + } + } + + // MARK: - Status + + public func status() -> Status { + let fm = FileManager.default + guard fm.isExecutableFile(atPath: tool.path) else { return .unavailable } + let toolPath = Self.resolved(tool) + + if let destination = try? fm.destinationOfSymbolicLink(atPath: link.path) { + if Self.resolved(link) == toolPath { return .installed(link: link) } + if Self.isEmbeddedToolPath(destination) { + return .stale(link: link, destination: destination) + } + return .occupied(link: link, destination: destination) + } + if fm.fileExists(atPath: link.path) { + return .occupied(link: link, destination: nil) + } + for directory in searchDirectories { + let other = directory.appendingPathComponent(Self.name) + if (try? fm.destinationOfSymbolicLink(atPath: other.path)) != nil, + Self.resolved(other) == toolPath { + return .installed(link: other) + } + } + return .notInstalled + } + + // MARK: - Install / uninstall + + /// Links the tool into the install directory, creating the directory if + /// needed. Does nothing when a link to this app's tool already exists. + public func install() throws { + switch status() { + case .unavailable: + throw Failure.unavailable + case .installed: + return + case .occupied(let link, let destination): + throw Failure.occupied(link: link, destination: destination) + case .stale: + try permissionChecked(command: installCommand) { + try FileManager.default.removeItem(at: link) + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: tool) + } + case .notInstalled: + try permissionChecked(command: installCommand) { + try FileManager.default.createDirectory(at: installDirectory, + withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: tool) + } + } + } + + /// Removes the install directory's link, if it points at an embedded + /// `auditctl`. Anything else is reported, never deleted. + public func uninstall() throws { + switch status() { + case .installed(let found) where found == link, .stale(let found, _): + try permissionChecked(command: uninstallCommand) { + try FileManager.default.removeItem(at: found) + } + case .installed(let found): + throw Failure.managedElsewhere(link: found) + case .occupied(let link, let destination): + throw Failure.occupied(link: link, destination: destination) + case .notInstalled, .unavailable: + throw Failure.notInstalled + } + } + + // MARK: - Terminal equivalents + + /// What Install does, for a user without write access to the install + /// directory to run themselves. + public var installCommand: String { + "sudo mkdir -p \(Self.shellQuoted(installDirectory.path)) && " + + "sudo ln -sf \(Self.shellQuoted(tool.path)) \(Self.shellQuoted(link.path))" + } + + public var uninstallCommand: String { + "sudo rm \(Self.shellQuoted(link.path))" + } + + // MARK: - Location + + /// True when the app is running from somewhere a link into it would + /// soon break: a Gatekeeper-translocated copy (a quarantined download + /// opened in place) or a read-only volume such as the release disk + /// image. + public static func isTemporaryLocation(_ appBundle: URL) -> Bool { + if appBundle.path.contains("/AppTranslocation/") { return true } + let readOnly = try? appBundle.resourceValues(forKeys: [.volumeIsReadOnlyKey]).volumeIsReadOnly + return readOnly == true + } + + // MARK: - Helpers + + private func permissionChecked(command: String, _ body: () throws -> Void) throws { + do { + try body() + } catch let error as CocoaError where error.code == .fileWriteNoPermission { + throw Failure.permissionDenied(command: command) + } catch let error as NSError where error.domain == NSPOSIXErrorDomain + && (error.code == Int(EACCES) || error.code == Int(EPERM)) { + throw Failure.permissionDenied(command: command) + } + } + + private static func resolved(_ url: URL) -> String { + url.resolvingSymlinksInPath().standardizedFileURL.path + } + + /// A link target that names some copy of privacycommand's embedded tool, + /// whether or not that copy still exists. + static func isEmbeddedToolPath(_ path: String) -> Bool { + path.hasSuffix(".app/" + bundlePath) + } + + /// Single-quotes `value` for a POSIX shell when it holds anything beyond + /// a conservative set of path characters. + static func shellQuoted(_ value: String) -> String { + let plain = CharacterSet(charactersIn: + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/._-+") + if !value.isEmpty, value.unicodeScalars.allSatisfy(plain.contains) { return value } + return "'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'" + } +} diff --git a/privacycommand/Tests/privacycommandCoreTests/CommandLineToolTests.swift b/privacycommand/Tests/privacycommandCoreTests/CommandLineToolTests.swift new file mode 100644 index 0000000..473e383 --- /dev/null +++ b/privacycommand/Tests/privacycommandCoreTests/CommandLineToolTests.swift @@ -0,0 +1,184 @@ +import XCTest +@testable import privacycommandCore + +/// Covers `CommandLineTool` against throwaway directories standing in for +/// the app bundle, /usr/local/bin and Homebrew's bin directory. +final class CommandLineToolTests: XCTestCase { + + private var root: URL! + private var app: URL! + private var bin: URL! + private var brewBin: URL! + private let fm = FileManager.default + + override func setUpWithError() throws { + root = fm.temporaryDirectory.appendingPathComponent("CommandLineToolTests-\(UUID().uuidString)") + app = try makeApp(named: "privacycommand.app") + bin = root.appendingPathComponent("usr-local-bin") + brewBin = root.appendingPathComponent("homebrew-bin") + try fm.createDirectory(at: brewBin, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + // Restore write access so a permission test can't leave debris. + for dir in [bin, brewBin] { + try? fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir!.path) + } + try? fm.removeItem(at: root) + } + + private func makeApp(named name: String) throws -> URL { + let bundle = root.appendingPathComponent(name) + let helpers = bundle.appendingPathComponent("Contents/Helpers") + try fm.createDirectory(at: helpers, withIntermediateDirectories: true) + let tool = helpers.appendingPathComponent("auditctl") + XCTAssertTrue(fm.createFile(atPath: tool.path, contents: Data("#!/bin/sh\n".utf8), + attributes: [.posixPermissions: 0o755])) + return bundle + } + + private func subject(for app: URL? = nil) -> CommandLineTool { + CommandLineTool(appBundle: app ?? self.app, installDirectory: bin, searchDirectories: [brewBin]) + } + + // MARK: - Install / uninstall round trip + + func testInstallCreatesDirectoryAndLinkThenUninstallRemovesIt() throws { + let tool = subject() + XCTAssertEqual(tool.status(), .notInstalled) + + try tool.install() + XCTAssertEqual(tool.status(), .installed(link: tool.link)) + XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: tool.link.path), tool.tool.path) + + try tool.install() // already there: no-op, no throw + try tool.uninstall() + XCTAssertEqual(tool.status(), .notInstalled) + XCTAssertFalse(fm.fileExists(atPath: tool.link.path)) + } + + func testUnavailableWithoutEmbeddedBinary() throws { + let bare = root.appendingPathComponent("Bare.app") + try fm.createDirectory(at: bare, withIntermediateDirectories: true) + let tool = subject(for: bare) + XCTAssertEqual(tool.status(), .unavailable) + XCTAssertThrowsError(try tool.install()) { + XCTAssertEqual($0 as? CommandLineTool.Failure, .unavailable) + } + } + + func testUninstallWhenNothingIsInstalled() { + XCTAssertThrowsError(try subject().uninstall()) { + XCTAssertEqual($0 as? CommandLineTool.Failure, .notInstalled) + } + } + + // MARK: - Someone else's file + + func testRegularFileIsReportedAndNeverTouched() throws { + try fm.createDirectory(at: bin, withIntermediateDirectories: true) + let tool = subject() + XCTAssertTrue(fm.createFile(atPath: tool.link.path, contents: Data("mine".utf8))) + + XCTAssertEqual(tool.status(), .occupied(link: tool.link, destination: nil)) + XCTAssertThrowsError(try tool.install()) + XCTAssertThrowsError(try tool.uninstall()) { + XCTAssertEqual($0 as? CommandLineTool.Failure, .occupied(link: tool.link, destination: nil)) + } + XCTAssertEqual(fm.contents(atPath: tool.link.path), Data("mine".utf8)) + } + + func testForeignSymlinkIsReportedAndNeverTouched() throws { + try fm.createDirectory(at: bin, withIntermediateDirectories: true) + let tool = subject() + let elsewhere = "/Users/someone/src/privacycommand/.build/release/auditctl" + try fm.createSymbolicLink(atPath: tool.link.path, withDestinationPath: elsewhere) + + XCTAssertEqual(tool.status(), .occupied(link: tool.link, destination: elsewhere)) + XCTAssertThrowsError(try tool.install()) + XCTAssertThrowsError(try tool.uninstall()) + XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: tool.link.path), elsewhere) + } + + // MARK: - Another copy of the app + + func testLinkToAnotherCopyIsStaleAndReplaced() throws { + let old = try makeApp(named: "Old/privacycommand.app") + try subject(for: old).install() + + let tool = subject() + let oldTarget = old.appendingPathComponent(CommandLineTool.bundlePath).path + XCTAssertEqual(tool.status(), .stale(link: tool.link, destination: oldTarget)) + try tool.install() + XCTAssertEqual(tool.status(), .installed(link: tool.link)) + } + + func testDanglingLinkFromAMovedAppIsStaleAndRemovable() throws { + try fm.createDirectory(at: bin, withIntermediateDirectories: true) + let tool = subject() + let gone = "/Volumes/privacycommand/privacycommand.app/Contents/Helpers/auditctl" + try fm.createSymbolicLink(atPath: tool.link.path, withDestinationPath: gone) + + XCTAssertEqual(tool.status(), .stale(link: tool.link, destination: gone)) + try tool.uninstall() + XCTAssertEqual(tool.status(), .notInstalled) + } + + // MARK: - Homebrew's link + + func testHomebrewLinkCountsAsInstalledButIsNotOursToRemove() throws { + let tool = subject() + let brewLink = brewBin.appendingPathComponent("auditctl") + try fm.createSymbolicLink(at: brewLink, withDestinationURL: tool.tool) + + XCTAssertEqual(tool.status(), .installed(link: brewLink)) + try tool.install() // already on PATH: nothing to do + XCTAssertFalse(fm.fileExists(atPath: tool.link.path)) + XCTAssertThrowsError(try tool.uninstall()) { + XCTAssertEqual($0 as? CommandLineTool.Failure, .managedElsewhere(link: brewLink)) + } + XCTAssertNotNil(try? fm.destinationOfSymbolicLink(atPath: brewLink.path)) + } + + // MARK: - No write access + + func testUnwritableDirectoryReportsTheSudoCommand() throws { + try fm.createDirectory(at: bin, withIntermediateDirectories: true) + try fm.setAttributes([.posixPermissions: 0o555], ofItemAtPath: bin.path) + let tool = subject() + + XCTAssertThrowsError(try tool.install()) { + XCTAssertEqual($0 as? CommandLineTool.Failure, .permissionDenied(command: tool.installCommand)) + } + + try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bin.path) + try tool.install() + try fm.setAttributes([.posixPermissions: 0o555], ofItemAtPath: bin.path) + XCTAssertThrowsError(try tool.uninstall()) { + XCTAssertEqual($0 as? CommandLineTool.Failure, .permissionDenied(command: tool.uninstallCommand)) + } + } + + // MARK: - Commands and locations + + func testCommandsForTheDefaultLocation() { + let tool = CommandLineTool(appBundle: URL(fileURLWithPath: "/Applications/privacycommand.app")) + XCTAssertEqual(tool.installCommand, + "sudo mkdir -p /usr/local/bin && sudo ln -sf " + + "/Applications/privacycommand.app/Contents/Helpers/auditctl /usr/local/bin/auditctl") + XCTAssertEqual(tool.uninstallCommand, "sudo rm /usr/local/bin/auditctl") + } + + func testShellQuoting() { + XCTAssertEqual(CommandLineTool.shellQuoted("/usr/local/bin"), "/usr/local/bin") + XCTAssertEqual(CommandLineTool.shellQuoted("/Users/a b/x.app"), "'/Users/a b/x.app'") + XCTAssertEqual(CommandLineTool.shellQuoted("/tmp/it's"), "'/tmp/it'\\''s'") + XCTAssertEqual(CommandLineTool.shellQuoted("/tmp/$(rm)"), "'/tmp/$(rm)'") + } + + func testTemporaryLocations() { + XCTAssertTrue(CommandLineTool.isTemporaryLocation(URL(fileURLWithPath: + "/private/var/folders/xy/T/AppTranslocation/1234/d/privacycommand.app"))) + XCTAssertFalse(CommandLineTool.isTemporaryLocation(app)) + } +} diff --git a/privacycommand/privacycommand.xcodeproj/project.pbxproj b/privacycommand/privacycommand.xcodeproj/project.pbxproj index b10bead..3b8c68c 100644 --- a/privacycommand/privacycommand.xcodeproj/project.pbxproj +++ b/privacycommand/privacycommand.xcodeproj/project.pbxproj @@ -17,6 +17,7 @@ 0BBBBBBB000000000000A007 /* WatchModeManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000A007 /* WatchModeManager.swift */; }; 0BBBBBBB000000000000A008 /* UpdateController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000A008 /* UpdateController.swift */; }; 0BBBBBBB000000000000A009 /* BatchScanModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000A009 /* BatchScanModel.swift */; }; + 0BBBBBBB000000000000A00B /* CommandLineToolInstaller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000A00B /* CommandLineToolInstaller.swift */; }; 0BBBBBBB000000000000A101 /* DropTargetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000A101 /* DropTargetView.swift */; }; 0BBBBBBB000000000000A102 /* DashboardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000A102 /* DashboardView.swift */; }; 0BBBBBBB000000000000A103 /* StaticAnalysisView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000A103 /* StaticAnalysisView.swift */; }; @@ -159,6 +160,7 @@ 0BBBBBBB000000000000C902 /* UpdateChannel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000C902 /* UpdateChannel.swift */; }; 0BBBBBBB000000000000C903 /* HomebrewDetector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000C903 /* HomebrewDetector.swift */; }; 0BBBBBBB000000000000C904 /* UpdatePreferences.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000C904 /* UpdatePreferences.swift */; }; + 0BBBBBBB000000000000C905 /* CommandLineTool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000C905 /* CommandLineTool.swift */; }; 0BBBBBBB000000000000D001 /* PathClassifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000D001 /* PathClassifierTests.swift */; }; 0BBBBBBB000000000000D002 /* BinaryStringScannerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000D002 /* BinaryStringScannerTests.swift */; }; 0BBBBBBB000000000000D003 /* StaticAnalyzerSmokeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFFFFF000000000000D003 /* StaticAnalyzerSmokeTests.swift */; }; @@ -240,6 +242,7 @@ 0FFFFFFF000000000000A007 /* WatchModeManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchModeManager.swift; sourceTree = ""; }; 0FFFFFFF000000000000A008 /* UpdateController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateController.swift; sourceTree = ""; }; 0FFFFFFF000000000000A009 /* BatchScanModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BatchScanModel.swift; sourceTree = ""; }; + 0FFFFFFF000000000000A00B /* CommandLineToolInstaller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandLineToolInstaller.swift; sourceTree = ""; }; 0FFFFFFF000000000000A101 /* DropTargetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DropTargetView.swift; sourceTree = ""; }; 0FFFFFFF000000000000A102 /* DashboardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardView.swift; sourceTree = ""; }; 0FFFFFFF000000000000A103 /* StaticAnalysisView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StaticAnalysisView.swift; sourceTree = ""; }; @@ -394,6 +397,7 @@ 0FFFFFFF000000000000C902 /* UpdateChannel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateChannel.swift; sourceTree = ""; }; 0FFFFFFF000000000000C903 /* HomebrewDetector.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomebrewDetector.swift; sourceTree = ""; }; 0FFFFFFF000000000000C904 /* UpdatePreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdatePreferences.swift; sourceTree = ""; }; + 0FFFFFFF000000000000C905 /* CommandLineTool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandLineTool.swift; sourceTree = ""; }; 0FFFFFFF000000000000D001 /* PathClassifierTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PathClassifierTests.swift; sourceTree = ""; }; 0FFFFFFF000000000000D002 /* BinaryStringScannerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinaryStringScannerTests.swift; sourceTree = ""; }; 0FFFFFFF000000000000D003 /* StaticAnalyzerSmokeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StaticAnalyzerSmokeTests.swift; sourceTree = ""; }; @@ -491,6 +495,7 @@ 0FFFFFFF000000000000A007 /* WatchModeManager.swift */, 0FFFFFFF000000000000A008 /* UpdateController.swift */, 0FFFFFFF000000000000A009 /* BatchScanModel.swift */, + 0FFFFFFF000000000000A00B /* CommandLineToolInstaller.swift */, ); path = ViewModels; sourceTree = ""; @@ -755,6 +760,7 @@ 0FFFFFFF000000000000C902 /* UpdateChannel.swift */, 0FFFFFFF000000000000C903 /* HomebrewDetector.swift */, 0FFFFFFF000000000000C904 /* UpdatePreferences.swift */, + 0FFFFFFF000000000000C905 /* CommandLineTool.swift */, ); path = Updates; sourceTree = ""; @@ -831,6 +837,7 @@ 0202020200000000000000A1 /* Frameworks */, 0202020200000000000000A2 /* Resources */, 0EEEEEEE000000000000F301 /* Build & stage privacycommand-guest */, + 0EEEEEEE000000000000F302 /* Embed auditctl */, 0EEEEEEE000000000000F201 /* Embed Privileged Helper */, 0EEEEEEE000000000000F202 /* Embed LaunchDaemon plist */, ); @@ -969,6 +976,27 @@ shellPath = /bin/bash; shellScript = "# Build the privacycommand-guest executable via SwiftPM, copy it\n# into the app's Resources folder, and codesign it with hardened\n# runtime. Apple's notarization service rejects any embedded Mach-O\n# that wasn't built with --options runtime, and SwiftPM (unlike\n# xcodebuild) doesn't apply that flag automatically — so we re-sign\n# here, using the same identity Xcode is using for the app target.\n\nset -euo pipefail\n\nTARGET=privacycommand-guest\necho \"Building ${TARGET} via SwiftPM…\"\ncd \"${SRCROOT}\"\nswift build -c release --product \"${TARGET}\"\n\nGUEST_BIN=\"${SRCROOT}/.build/release/${TARGET}\"\nif [[ ! -f \"${GUEST_BIN}\" ]]; then\n echo \"error: SwiftPM didn't produce ${GUEST_BIN}\" >&2\n exit 1\nfi\n\nDEST=\"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}\"\nmkdir -p \"${DEST}\"\ncp -f \"${GUEST_BIN}\" \"${DEST}/${TARGET}\"\nchmod +x \"${DEST}/${TARGET}\"\n\n# Follow Xcode's signing choice for unsigned archive validation.\nif [[ \"${CODE_SIGNING_ALLOWED:-YES}\" == \"NO\" ]]; then\n echo \"Staged ${TARGET} without signing (CODE_SIGNING_ALLOWED=NO).\"\n exit 0\nfi\n\n# Re-sign with hardened runtime. EXPANDED_CODE_SIGN_IDENTITY is the\n# resolved cert ID Xcode will use for the rest of the app. For\n# Sign-to-Run-Locally builds it's '-' (ad-hoc); for Developer ID\n# Release builds it's the actual cert. We always pass --options\n# runtime so notarization accepts the binary; we add --timestamp\n# only when signing with a real identity (ad-hoc + --timestamp\n# fails because Apple's TSA needs the cert to validate against).\nIDENTITY=\"${EXPANDED_CODE_SIGN_IDENTITY:-${CODE_SIGN_IDENTITY:--}}\"\nif [[ -z \"${IDENTITY}\" ]]; then\n IDENTITY=\"-\"\nfi\nSIGN_FLAGS=( --force --options runtime --sign \"${IDENTITY}\" )\nif [[ \"${IDENTITY}\" != \"-\" ]]; then\n SIGN_FLAGS+=( --timestamp )\nfi\necho \"Signing ${TARGET} with identity '${IDENTITY}'…\"\n/usr/bin/codesign \"${SIGN_FLAGS[@]}\" \"${DEST}/${TARGET}\"\n\necho \"Staged + signed ${TARGET} into ${DEST}/\"\n"; }; + 0EEEEEEE000000000000F302 /* Embed auditctl */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "$(SRCROOT)/Scripts/embed-auditctl.sh", + "$(DERIVED_FILE_DIR)/BuildIdentity-Info.plist", + ); + name = "Embed auditctl"; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/bash; + shellScript = "# Builds auditctl via SwiftPM and embeds it, signed, at\n# Contents/Helpers/auditctl. See the script for details.\n\"${SRCROOT}/Scripts/embed-auditctl.sh\"\n"; + }; 6817230F7A024CABA7EF1475 /* Prepare version and build identity */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -1126,6 +1154,7 @@ 0BBBBBBB000000000000C902 /* UpdateChannel.swift in Sources */, 0BBBBBBB000000000000C903 /* HomebrewDetector.swift in Sources */, 0BBBBBBB000000000000C904 /* UpdatePreferences.swift in Sources */, + 0BBBBBBB000000000000C905 /* CommandLineTool.swift in Sources */, 0BBBBBBB000000000000C008 /* AppStoreInfo.swift in Sources */, 0BBBBBBB000000000000C11B /* MASReceiptDetector.swift in Sources */, 0BBBBBBB000000000000C11C /* AppStoreLookup.swift in Sources */, @@ -1171,6 +1200,7 @@ 0BBBBBBB000000000000C142 /* BatchAppResult.swift in Sources */, 0BBBBBBB000000000000C143 /* BatchAnalyzer.swift in Sources */, 0BBBBBBB000000000000A009 /* BatchScanModel.swift in Sources */, + 0BBBBBBB000000000000A00B /* CommandLineToolInstaller.swift in Sources */, 0BBBBBBB000000000000A131 /* BatchScanView.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; From 347332c6b33582f7db33418afb6cf022154ce27f Mon Sep 17 00:00:00 2001 From: adamXbot <111877622+adamXbot@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:53:10 +1100 Subject: [PATCH 2/3] Strip auditctl after linking, not with -Xlinker -S -x Xcode 26.6's SwiftPM (used by App CI) builds multi-arch products through its xcode build system, which hands -Xlinker values to clang unwrapped: -x became clang's language flag and the link failed. Keep only -sectcreate, which clang also understands, and run `strip -S -x` on the embedded copy instead; strip re-signs a linker-signed arm64 slice, so unsigned builds still run. Co-Authored-By: Claude Opus 5.5 --- privacycommand/Scripts/embed-auditctl.sh | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/privacycommand/Scripts/embed-auditctl.sh b/privacycommand/Scripts/embed-auditctl.sh index c786848..3f78d3f 100755 --- a/privacycommand/Scripts/embed-auditctl.sh +++ b/privacycommand/Scripts/embed-auditctl.sh @@ -38,12 +38,10 @@ SWIFT_ARGS=( -c release --product "${PRODUCT}" for arch in ${ARCHS}; do SWIFT_ARGS+=( --arch "${arch}" ) done +# Only flags clang also understands: older SwiftPM (Xcode 26.6's, for +# multi-arch builds) hands -Xlinker values to clang unwrapped. SWIFT_ARGS+=( -Xlinker -sectcreate -Xlinker __TEXT -Xlinker __info_plist -Xlinker "${INFO_PLIST}" ) -# Leave debug info and local symbols out at link time, as Xcode strips the -# app's own executable: it halves the binary. Stripping afterwards instead -# would break the linker's signature in unsigned builds. -SWIFT_ARGS+=( -Xlinker -S -Xlinker -x ) # Xcode's build settings arrive as environment variables; keep them away # from SwiftPM so this builds exactly what `swift build` does in Terminal, @@ -74,6 +72,10 @@ DEST="${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/Helpers" mkdir -p "${DEST}" cp -f "${BIN}" "${DEST}/${PRODUCT}" chmod 755 "${DEST}/${PRODUCT}" +# Drop debug info and local symbols, as Xcode strips the app's own +# executable: it halves the binary. strip re-signs a linker-signed arm64 +# slice, so unsigned builds still run. +xcrun strip -S -x "${DEST}/${PRODUCT}" # Follow Xcode's signing choice for unsigned builds (App CI). if [[ "${CODE_SIGNING_ALLOWED:-YES}" == "NO" ]]; then From 5608d7cb74da86a31304779d49f5c8c5fcfcbfa6 Mon Sep 17 00:00:00 2001 From: adamXbot <111877622+adamXbot@users.noreply.github.com> Date: Thu, 8 Oct 2026 22:35:49 +1100 Subject: [PATCH 3/3] Rename the auditctl CLI to privacycommand MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CLI hasn't shipped to users yet, so rename it now, before a release puts it on anyone's PATH. "auditctl" is also the name of Linux's audit control tool, which made the command hard to search for and suggested it controls a service. - The SwiftPM executable product is now `privacycommand`. Targets move to privacycommandCLI / privacycommandCLIKit (+ Tests), since a target named privacycommand would collide with the app's module and source folder. - The app embeds it at Contents/Helpers/privacycommand with identifier org.privacykey.privacycommand.cli; the build phase is now "Embed command-line tool" (Scripts/embed-cli.sh). The cask's binary stanza and the Install Command Line Tool… item link the new path, and the alerts say "the command-line tool". - Usage text, --version, the TUI title, CI's smoke test, the issue template and every doc use the new name. Co-Authored-By: Claude Opus 5.5 --- .github/ARCHITECTURE.md | 8 ++-- .github/ISSUE_TEMPLATE/feature_request.yml | 2 +- .github/workflows/app-ci.yml | 2 +- .github/workflows/ci.yml | 11 ++--- CONTRIBUTING.md | 21 ++++----- README.md | 14 +++--- docs/BUILD-PROVENANCE.md | 2 +- docs/PRIVACY.md | 2 +- packaging/homebrew/privacycommand.rb | 6 +-- privacycommand/BUILDING.md | 4 +- privacycommand/Package.swift | 22 +++++----- privacycommand/README.md | 40 ++++++++--------- privacycommand/Resources/Manual/07-reports.md | 4 +- .../{embed-auditctl.sh => embed-cli.sh} | 21 ++++----- .../ViewModels/CommandLineToolInstaller.swift | 26 +++++------ .../privacycommand/privacycommandApp.swift | 4 +- .../AuditCommand.swift | 18 ++++---- .../InteractiveCommand.swift | 6 +-- .../PreviewCommand.swift | 6 +-- .../Spinner.swift | 2 +- .../TUISelfTest.swift | 4 +- .../TerminalDriver.swift | 6 +-- .../main.swift | 43 ++++++++++--------- .../Ansi.swift | 0 .../AppBrowserModel.swift | 0 .../AuditSnapshot.swift | 0 .../BrowserReducer.swift | 0 .../InputEvent.swift | 0 .../TUIRenderer.swift | 2 +- .../Updates/CaskArtifactFetcher.swift | 2 +- .../Updates/CommandLineTool.swift | 28 ++++++------ .../AnsiTests.swift | 2 +- .../AppBrowserModelTests.swift | 2 +- .../BrowserReducerTests.swift | 2 +- .../InputDecoderTests.swift | 2 +- .../TUIRendererTests.swift | 4 +- .../CommandLineToolTests.swift | 12 +++--- .../IncomingCaskComparisonTests.swift | 2 +- .../privacycommand.xcodeproj/project.pbxproj | 10 ++--- 39 files changed, 174 insertions(+), 168 deletions(-) rename privacycommand/Scripts/{embed-auditctl.sh => embed-cli.sh} (86%) rename privacycommand/Sources/{auditctl => privacycommandCLI}/AuditCommand.swift (96%) rename privacycommand/Sources/{auditctl => privacycommandCLI}/InteractiveCommand.swift (81%) rename privacycommand/Sources/{auditctl => privacycommandCLI}/PreviewCommand.swift (98%) rename privacycommand/Sources/{auditctl => privacycommandCLI}/Spinner.swift (96%) rename privacycommand/Sources/{auditctl => privacycommandCLI}/TUISelfTest.swift (97%) rename privacycommand/Sources/{auditctl => privacycommandCLI}/TerminalDriver.swift (97%) rename privacycommand/Sources/{auditctl => privacycommandCLI}/main.swift (50%) rename privacycommand/Sources/{auditctlKit => privacycommandCLIKit}/Ansi.swift (100%) rename privacycommand/Sources/{auditctlKit => privacycommandCLIKit}/AppBrowserModel.swift (100%) rename privacycommand/Sources/{auditctlKit => privacycommandCLIKit}/AuditSnapshot.swift (100%) rename privacycommand/Sources/{auditctlKit => privacycommandCLIKit}/BrowserReducer.swift (100%) rename privacycommand/Sources/{auditctlKit => privacycommandCLIKit}/InputEvent.swift (100%) rename privacycommand/Sources/{auditctlKit => privacycommandCLIKit}/TUIRenderer.swift (99%) rename privacycommand/Tests/{auditctlKitTests => privacycommandCLIKitTests}/AnsiTests.swift (94%) rename privacycommand/Tests/{auditctlKitTests => privacycommandCLIKitTests}/AppBrowserModelTests.swift (99%) rename privacycommand/Tests/{auditctlKitTests => privacycommandCLIKitTests}/BrowserReducerTests.swift (98%) rename privacycommand/Tests/{auditctlKitTests => privacycommandCLIKitTests}/InputDecoderTests.swift (98%) rename privacycommand/Tests/{auditctlKitTests => privacycommandCLIKitTests}/TUIRendererTests.swift (96%) diff --git a/.github/ARCHITECTURE.md b/.github/ARCHITECTURE.md index 3caa66e..ccf4719 100644 --- a/.github/ARCHITECTURE.md +++ b/.github/ARCHITECTURE.md @@ -35,7 +35,7 @@ The deeper design docs referenced from the project `README.md` sit alongside thi └──────────────────────────────────────────────────────────────────────┘ ┌──────────────────────────┐ ┌────────────────────────┐ - │ auditctl (CLI) │ │ privacycommandGuestAgent│ + │ privacycommand (CLI) │ │ privacycommandGuestAgent│ │ smallest end-to-end smoke│ │ runs in a macOS VM, │ │ test for the analyzer │ │ ships observations back│ │ │ │ via shared protocol │ @@ -54,8 +54,8 @@ Each target is intentional: | `privacycommandHelper` | `privacycommand/privacycommandHelper/` | Privileged XPC service installed via `SMAppService.daemon`. Minimal API surface — 5 Swift files (`main`, `HelperToolService`, `CodeSignValidator`, `FsUsageRunner`, `PfctlKillSwitch`). Validates clients by Team ID on connect. **Note the path**: this sits beside `Sources/`, not inside it — it is an Xcode-only target and `Package.swift` does not declare it. | | `privacycommandGuestProtocol` | `privacycommand/Sources/privacycommandGuestProtocol/` | Wire format shared between host and guest agent. Lives in its own zero-dependency target so the agent can build without compiling Core. | | `privacycommandGuestAgent` | `privacycommand/Sources/privacycommandGuestAgent/` | The binary that runs inside a macOS VM and ships observations back to the host. | -| `auditctl` | `privacycommand/Sources/auditctl/` | CLI front-end for the analyzer, with a witr-style interface. `auditctl ` audits one app (`--short` / `--tree` / `--json` / `--warnings`); a bare `auditctl` (or `-i`) opens an interactive TUI browser of installed apps. Still the fastest end-to-end smoke test. The executable is a thin termios / poll-loop / IO shell — its logic lives in `auditctlKit`. | -| `auditctlKit` | `privacycommand/Sources/auditctlKit/` | Pure, testable CLI/TUI logic: ANSI styling, terminal input decoding, the browser state model + reducer, and frame rendering. Split out of the executable so `auditctlKitTests` can cover it without a real terminal. | +| `privacycommandCLI` | `privacycommand/Sources/privacycommandCLI/` | CLI front-end for the analyzer, built as the `privacycommand` executable and embedded in the app at `Contents/Helpers/privacycommand`. Witr-style interface: `privacycommand ` audits one app (`--short` / `--tree` / `--json` / `--warnings`); a bare `privacycommand` (or `-i`) opens an interactive TUI browser of installed apps. Still the fastest end-to-end smoke test. The executable is a thin termios / poll-loop / IO shell — its logic lives in `privacycommandCLIKit`. | +| `privacycommandCLIKit` | `privacycommand/Sources/privacycommandCLIKit/` | Pure, testable CLI/TUI logic: ANSI styling, terminal input decoding, the browser state model + reducer, and frame rendering. Split out of the executable so `privacycommandCLIKitTests` can cover it without a real terminal. | The split is enforced by Swift Package Manager — `Package.swift` declares each as a separate target with an explicit dependency graph. You can't accidentally pull AppKit into Core because Core's manifest doesn't depend on it. @@ -159,7 +159,7 @@ The appcast feed lives on `gh-pages` at `https://privacykey.github.io/privacycom `Tests/privacycommandCoreTests/` holds the analyzer test suite. Run with `swift test` from `privacycommand/`. Static analysis is straightforward to test against a corpus of `.app` bundles; dynamic monitoring needs more thought (the helper-required tests can't run in CI without `SMAppService` permissions). -The smallest end-to-end smoke test is `auditctl /System/Applications/Calculator.app` — exits non-zero if `StaticAnalyzer` fails to parse anything. +The smallest end-to-end smoke test is `privacycommand /System/Applications/Calculator.app` — exits non-zero if `StaticAnalyzer` fails to parse anything. ## Where to look next diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 02a1968..21364ad 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -68,7 +68,7 @@ body: - Settings / preferences - Knowledge base / in-app explanations - Accessibility - - CLI (`auditctl`) + - CLI (`privacycommand`) - Other validations: required: true diff --git a/.github/workflows/app-ci.yml b/.github/workflows/app-ci.yml index c73fe42..6c3e1ad 100644 --- a/.github/workflows/app-ci.yml +++ b/.github/workflows/app-ci.yml @@ -3,7 +3,7 @@ name: App CI # Builds and tests the Xcode app target (privacycommand.app + # privacycommandTests) via the shared reusable workflow — unsigned, no # secrets. Complements ci.yml, which covers the SPM package targets -# (Core, auditctlKit, auditctl, guest agent) on pull requests. +# (Core, the privacycommand CLI and its kit, guest agent) on pull requests. on: push: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59ebd41..e4665d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,21 +40,22 @@ jobs: run: swift --version - name: Build all targets - # Compiles Core, auditctlKit, auditctl, the guest agent and the shared - # protocol — catches breakage the test targets don't cover. + # Compiles Core, the privacycommand CLI and its kit, the guest agent + # and the shared protocol — catches breakage the test targets don't + # cover. run: swift build - name: Run tests run: swift test - - name: CLI smoke test (auditctl exit-code contract) + - name: CLI smoke test (privacycommand exit-code contract) # Exercises the built executable end-to-end: a parseable system app must # analyze cleanly and exit 0. Skipped if the runner image lacks it. run: | - BIN=.build/debug/auditctl + BIN=.build/debug/privacycommand if [ -d /System/Applications/Calculator.app ]; then "$BIN" /System/Applications/Calculator.app > /dev/null - echo "auditctl analyzed Calculator and exited 0 ✓" + echo "privacycommand analyzed Calculator and exited 0 ✓" else echo "Calculator.app not present on runner — skipping CLI smoke test" fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5fd61a2..36e5dca 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,8 +9,8 @@ The repository builds the same sources two ways. `Package.swift` and the Xcode project both live under `privacycommand/`, not at the repository root. **Swift Package Manager** builds the headless pieces — the `privacycommandCore` -analyser, the `auditctl` CLI and its `auditctlKit` half, the guest agent, and the -shared guest protocol. This is the fast iteration loop and it is what CI runs: +analyser, the `privacycommand` CLI and its `privacycommandCLIKit` half, the +guest agent, and the shared guest protocol. This is the fast iteration loop and it is what CI runs: ```sh cd privacycommand @@ -53,18 +53,18 @@ Deeper references live next to the sources: - [`.github/ARCHITECTURE.md`](.github/ARCHITECTURE.md) — how the pieces fit together and how data moves between them. -## The auditctl CLI +## The privacycommand CLI -`auditctl` is a command-line front end over the same analyser, useful for -scripting and CI. The app ships it at `Contents/Helpers/auditctl` (the -**Embed auditctl** build phase), and users put it on `PATH` through the +`privacycommand` is a command-line front end over the same analyser, useful for +scripting and CI. The app ships it at `Contents/Helpers/privacycommand` (the +**Embed command-line tool** build phase), and users put it on `PATH` through the Homebrew cask or the app menu — see [Get it](README.md#get-it). To work on it, build it once, then call the binary directly: ```sh cd privacycommand swift build -c release -BIN=.build/release/auditctl +BIN=.build/release/privacycommand ``` A one-shot static audit takes a path or an installed-app name: @@ -98,15 +98,16 @@ skipped. With `--fetch`, an incoming build is analysed *before* Gatekeeper has cleared it, so a one-off notarization difference can simply be a fresh-download artifact — the output flags this when it happens. -Running `auditctl` with no arguments opens an interactive browser when stdin and -stdout are a terminal, and prints usage otherwise so CI callers do not hang. +Running `privacycommand` with no arguments opens an interactive browser when +stdin and stdout are a terminal, and prints usage otherwise so CI callers do +not hang. ## What CI runs Two workflows run on every pull request against `main`: - [`ci.yml`](.github/workflows/ci.yml) — builds every SPM target, runs the full - test suite, then runs the built `auditctl` against `Calculator.app` as an + test suite, then runs the built `privacycommand` against `Calculator.app` as an end-to-end smoke test of the analyser's exit-code contract. - [`app-ci.yml`](.github/workflows/app-ci.yml) — an unsigned Xcode build and test of the app target, through a reusable workflow in `privacykey/gh-workflows`. diff --git a/README.md b/README.md index 5735223..dafb175 100644 --- a/README.md +++ b/README.md @@ -59,18 +59,18 @@ brew install --cask privacykey/tap/privacycommand **Direct download** — take the signed and notarized `.dmg` from the [latest release](https://github.com/privacykey/privacycommand/releases/latest) and drag the app to `/Applications`. In-app updates use [Sparkle 2](https://sparkle-project.org) against an EdDSA-signed [appcast feed](https://privacykey.github.io/privacycommand/appcast.xml); automatic checks are **off by default** and you opt in under Settings → Updates. -**Command line** — the app carries `auditctl`, a CLI over the same analyser, and there are two ways to put it on your `PATH`: +**Command line** — the app also carries a command-line tool of the same name, `privacycommand`, which runs the same analyser from Terminal. There are two ways to put it on your `PATH`: -- **Homebrew** — the cask links `auditctl` for you on install and removes it on uninstall. Nothing else to do. +- **Homebrew** — the cask links `privacycommand` for you on install and removes it on uninstall. Nothing else to do. - **Direct download** — choose **privacycommand ▸ Install Command Line Tool…**. It links the copy inside the app into `/usr/local/bin`, so the tool updates with the app. When that folder needs administrator rights, as it does on most Macs, it shows the `sudo ln -s` command to paste into Terminal instead, with a button that copies it. The same menu item then reads **Uninstall Command Line Tool…** and removes the link. ```sh -auditctl slack --short # one-line verdict for an installed app -auditctl preview # check outdated Homebrew casks before you upgrade -auditctl --help # every command and flag +privacycommand slack --short # one-line verdict for an installed app +privacycommand preview # check outdated Homebrew casks before you upgrade +privacycommand --help # every command and flag ``` -`preview` inspects Homebrew casks *before* you update them; it never runs `brew`, never blocks an update, and always exits 0. To build `auditctl` from source instead, see [CONTRIBUTING.md](CONTRIBUTING.md#the-auditctl-cli). +`preview` inspects Homebrew casks *before* you update them; it never runs `brew`, never blocks an update, and always exits 0. To build the CLI from source instead, see [CONTRIBUTING.md](CONTRIBUTING.md#the-privacycommand-cli). ## Docs @@ -85,7 +85,7 @@ There is no docs site yet. What exists lives in the repo: ## Contributing -Issues and pull requests are welcome. CI runs two workflows on every pull request: the SPM build and test suite plus an `auditctl` smoke test, and an unsigned Xcode build of the app target. Reproduce the first locally from `privacycommand/`: +Issues and pull requests are welcome. CI runs two workflows on every pull request: the SPM build and test suite plus a `privacycommand` CLI smoke test, and an unsigned Xcode build of the app target. Reproduce the first locally from `privacycommand/`: ```sh swift build diff --git a/docs/BUILD-PROVENANCE.md b/docs/BUILD-PROVENANCE.md index c701353..23e6c68 100644 --- a/docs/BUILD-PROVENANCE.md +++ b/docs/BUILD-PROVENANCE.md @@ -23,7 +23,7 @@ Available recipes: info # Show the UTC build preview, commit, dirty files, tag-at-HEAD and channel. [dev] - build # Build every SPM target (Core, auditctlKit, auditctl, guest agent, protocol) + build # Build every SPM target (Core, the privacycommand CLI and its kit, guest agent, protocol) test # Run the full SPM test suite (same as CI) clean # Remove SPM build output diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index a238bd6..3a467b1 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -31,7 +31,7 @@ They are explicit and bounded: Settings → Updates. Homebrew Cask installs suppress the in-app updater entirely. - **Incoming-build downloads**, only when you explicitly ask for them: the - `auditctl preview --fetch` path retrieves a cask artifact from its own + `privacycommand preview --fetch` path retrieves a cask artifact from its own publisher so it can be diffed against the version you have installed. `com.apple.security.network.client` is the only entitlement covering outbound diff --git a/packaging/homebrew/privacycommand.rb b/packaging/homebrew/privacycommand.rb index 884a4f0..93526ce 100644 --- a/packaging/homebrew/privacycommand.rb +++ b/packaging/homebrew/privacycommand.rb @@ -21,10 +21,10 @@ end app "privacycommand.app" - # The auditctl CLI ships inside the app; this links it onto PATH and - # removes the link on uninstall. DMG installs use the app menu's + # The privacycommand CLI ships inside the app; this links it onto PATH + # and removes the link on uninstall. DMG installs use the app menu's # Install Command Line Tool… item instead. - binary "#{appdir}/privacycommand.app/Contents/Helpers/auditctl" + binary "#{appdir}/privacycommand.app/Contents/Helpers/privacycommand" # We're not sandboxed, so quitting the app is enough — no need for # a tighter `quit:` predicate. The in-app Sparkle updater is diff --git a/privacycommand/BUILDING.md b/privacycommand/BUILDING.md index cbea00e..75b643b 100644 --- a/privacycommand/BUILDING.md +++ b/privacycommand/BUILDING.md @@ -45,11 +45,11 @@ App Sandbox is disabled. Hardened Runtime is on. macOS deployment target is 13.0 ```bash cd privacycommand swift build -.build/debug/auditctl /System/Applications/Calculator.app +.build/debug/privacycommand /System/Applications/Calculator.app swift test ``` -Builds the `privacycommandCore` library and the `auditctl` CLI. The SwiftUI app is **not** built via SwiftPM (it lives in the Xcode project only). +Builds the `privacycommandCore` library and the `privacycommand` CLI. The SwiftUI app is **not** built via SwiftPM (it lives in the Xcode project only). Why both? `swift build` is a fast iteration loop on the analyzer logic without launching Xcode. The Xcode project is the only path for building/distributing the GUI app. diff --git a/privacycommand/Package.swift b/privacycommand/Package.swift index db9b1f5..0e22a40 100644 --- a/privacycommand/Package.swift +++ b/privacycommand/Package.swift @@ -10,7 +10,9 @@ let package = Package( .library(name: "privacycommandCore", targets: ["privacycommandCore"]), .library(name: "privacycommandGuestProtocol", targets: ["privacycommandGuestProtocol"]), - .executable(name: "auditctl", targets: ["auditctl"]), + // The CLI. Named after the app: the release build embeds it at + // privacycommand.app/Contents/Helpers/privacycommand. + .executable(name: "privacycommand", targets: ["privacycommandCLI"]), .executable(name: "privacycommand-guest", targets: ["privacycommandGuestAgent"]) ], @@ -54,17 +56,17 @@ let package = Package( ), // Pure, testable CLI/TUI logic (input decoding, browser state, frame // rendering, ANSI styling). Split out of the executable so - // `auditctlKitTests` can cover it — the executable stays a thin + // `privacycommandCLIKitTests` can cover it — the executable stays a thin // termios / poll-loop / IO shell around this. .target( - name: "auditctlKit", + name: "privacycommandCLIKit", dependencies: ["privacycommandCore"], - path: "Sources/auditctlKit" + path: "Sources/privacycommandCLIKit" ), .executableTarget( - name: "auditctl", - dependencies: ["auditctlKit", "privacycommandCore"], - path: "Sources/auditctl" + name: "privacycommandCLI", + dependencies: ["privacycommandCLIKit", "privacycommandCore"], + path: "Sources/privacycommandCLI" ), // Runs inside the macOS guest VM — listens for commands from // the host, runs the inspected app, ships observations back. @@ -80,9 +82,9 @@ let package = Package( path: "Tests/privacycommandCoreTests" ), .testTarget( - name: "auditctlKitTests", - dependencies: ["auditctlKit", "privacycommandCore"], - path: "Tests/auditctlKitTests" + name: "privacycommandCLIKitTests", + dependencies: ["privacycommandCLIKit", "privacycommandCore"], + path: "Tests/privacycommandCLIKitTests" ) ] ) diff --git a/privacycommand/README.md b/privacycommand/README.md index 877c2df..ad106db 100644 --- a/privacycommand/README.md +++ b/privacycommand/README.md @@ -11,7 +11,7 @@ README is for contributors hacking on the codebase. open privacycommand.xcodeproj # 2. Build the analyzer + CLI from the command line. -swift build # compiles privacycommandCore + auditctl + the +swift build # compiles privacycommandCore + the CLI + the # guest agent + the helper swift test # runs Tests/privacycommandCoreTests ``` @@ -37,11 +37,11 @@ fiddling that earlier versions of this README walked through. The Files** phases that drop the helper executable into `Contents/MacOS/` and the LaunchDaemon plist into `Contents/Library/LaunchDaemons/`. -- An **Embed auditctl** run-script phase - ([`Scripts/embed-auditctl.sh`](Scripts/embed-auditctl.sh)) that - builds the `auditctl` CLI with SwiftPM for the app's architectures, +- An **Embed command-line tool** run-script phase + ([`Scripts/embed-cli.sh`](Scripts/embed-cli.sh)) that + builds the `privacycommand` CLI with SwiftPM for the app's architectures, stamps the app's version into it, copies it to - `Contents/Helpers/auditctl` and signs it with the app's identity and + `Contents/Helpers/privacycommand` and signs it with the app's identity and hardened runtime. The Homebrew cask's `binary` stanza and the app menu's Install Command Line Tool… item both link to that path. - Sparkle 2 wired in for in-app updates (you have to add it once via @@ -105,13 +105,13 @@ privacycommand/ │ │ └── GuestProtocol.swift │ ├── privacycommandGuestAgent/ # In-VM agent. │ │ └── main.swift -│ ├── auditctlKit/ # Pure, testable CLI/TUI logic +│ ├── privacycommandCLIKit/ # Pure, testable CLI/TUI logic │ │ └── (Ansi, InputEvent, BrowserReducer, AppBrowserModel, TUIRenderer) -│ └── auditctl/ # CLI executable: one-shot audit, preview, -i TUI +│ └── privacycommandCLI/ # The `privacycommand` CLI: one-shot audit, preview, -i TUI │ └── (main, AuditCommand, PreviewCommand, TerminalDriver, InteractiveCommand) └── Tests/ ├── privacycommandCoreTests/ - └── auditctlKitTests/ # decoder, model, reducer, renderer + └── privacycommandCLIKitTests/ # decoder, model, reducer, renderer ``` ## Why so many targets @@ -130,16 +130,16 @@ Each pulls its weight: - **privacycommandGuestAgent** is the binary that runs inside a macOS VM, listens for commands from the host, and ships observations back across the VM boundary. See [`docs/GUEST_AGENT.md`](docs/GUEST_AGENT.md). -- **auditctlKit** is the pure, testable half of the CLI — ANSI styling, +- **privacycommandCLIKit** is the pure, testable half of the CLI — ANSI styling, terminal input decoding, the interactive browser's state model + - reducer, and frame rendering. No I/O, so `auditctlKitTests` covers it + reducer, and frame rendering. No I/O, so `privacycommandCLIKitTests` covers it without a terminal. -- **auditctl** is the executable: a one-shot static audit - (`auditctl `, with `--short` / `--tree` / `--json` / - `--warnings`), the `preview` command, and a bare `auditctl` / `-i` - interactive TUI browser. The binary is a thin termios / poll-loop - shell around `auditctlKit`; it's still the fastest end-to-end smoke - test for the analyzer. +- **privacycommandCLI** is the executable, built as `privacycommand`: a + one-shot static audit (`privacycommand `, with `--short` / + `--tree` / `--json` / `--warnings`), the `preview` command, and a bare + `privacycommand` / `-i` interactive TUI browser. The binary is a thin + termios / poll-loop shell around `privacycommandCLIKit`; it's still the + fastest end-to-end smoke test for the analyzer. ## Signing & entitlements quick reference @@ -161,7 +161,7 @@ Helper (`Resources/privacycommandHelper.entitlements`): - `com.apple.developer.service-management.managed-by-main-app`: **ON** — required for `SMAppService.daemon` lifecycle. -`auditctl` (`Contents/Helpers/auditctl`) and the guest agent +The CLI (`Contents/Helpers/privacycommand`) and the guest agent (`Contents/Resources/privacycommand-guest`): - Signed by their run-script phases with the app's identity. @@ -171,7 +171,7 @@ Helper (`Resources/privacycommandHelper.entitlements`): ```sh swift build -c release -BIN=.build/release/auditctl +BIN=.build/release/privacycommand # One-shot audit — by path (the smoke test) or by installed-app name (like witr): $BIN /System/Applications/Calculator.app @@ -184,14 +184,14 @@ $BIN slack --warn-exit # exit 1 when there are warn/error findings (CI # Interactive browser (needs a terminal): filter as you type, ↑↓ to move, # Tab to sort by risk, ⏎ to re-scan, Esc/^C to quit. -$BIN # or: auditctl -i +$BIN # or: privacycommand -i ``` The bare-path form is the smallest end-to-end smoke test for the analyzer — it runs `StaticAnalyzer().analyze(bundleAt:)` and exits non-zero on parse failure. Exit codes: `0` analyzed OK · `1` analysis failed (or `--warn-exit` with findings) · `2` target not found · `4` -ambiguous name. A bare `auditctl` only launches the TUI on a terminal; +ambiguous name. A bare `privacycommand` only launches the TUI on a terminal; piped/CI callers get usage text and a non-zero exit instead. ## Troubleshooting diff --git a/privacycommand/Resources/Manual/07-reports.md b/privacycommand/Resources/Manual/07-reports.md index b3cc744..8e7ce0c 100644 --- a/privacycommand/Resources/Manual/07-reports.md +++ b/privacycommand/Resources/Manual/07-reports.md @@ -10,9 +10,9 @@ Each item opens a save panel with a file name suggested from the app's name and ## The command line -privacycommand carries `auditctl`, a command-line front end over the same analyser, for scripting and CI. `auditctl ` audits one app (`--short`, `--tree`, `--json`, `--warnings`), and `auditctl preview` inspects outdated Homebrew casks before you update them. `auditctl --help` lists every command. +privacycommand also comes with a command-line tool of the same name, `privacycommand`, for scripting and CI. `privacycommand ` audits one app (`--short`, `--tree`, `--json`, `--warnings`), and `privacycommand preview` inspects outdated Homebrew casks before you update them. `privacycommand --help` lists every command. -- **Installed with Homebrew:** the cask has already put `auditctl` on your `PATH`. +- **Installed with Homebrew:** the cask has already put the `privacycommand` command on your `PATH`. - **Installed from the disk image:** choose **privacycommand ▸ Install Command Line Tool…**. It links the copy inside the app into `/usr/local/bin`, so the tool updates with the app. If that folder needs administrator rights, the alert shows the `sudo` command to run in Terminal instead, with a button that copies it. Choose **Uninstall Command Line Tool…** from the same place to remove the link. Run privacycommand from the Applications folder before installing the tool: a link into a copy that is still on the disk image stops working when the image is ejected, so the item asks you to move the app first. diff --git a/privacycommand/Scripts/embed-auditctl.sh b/privacycommand/Scripts/embed-cli.sh similarity index 86% rename from privacycommand/Scripts/embed-auditctl.sh rename to privacycommand/Scripts/embed-cli.sh index 3f78d3f..0b0984f 100755 --- a/privacycommand/Scripts/embed-auditctl.sh +++ b/privacycommand/Scripts/embed-cli.sh @@ -1,31 +1,32 @@ #!/bin/bash -# Build the auditctl CLI via SwiftPM, embed it at -# privacycommand.app/Contents/Helpers/auditctl, and sign it with the app's -# identity and hardened runtime so the notarized bundle stays valid. +# Build the privacycommand CLI via SwiftPM, embed it at +# privacycommand.app/Contents/Helpers/privacycommand, and sign it with the +# app's identity and hardened runtime so the notarized bundle stays valid. # -# Runs as the app target's "Embed auditctl" build phase. Homebrew's cask -# links the embedded binary onto PATH (the `binary` stanza in +# Runs as the app target's "Embed command-line tool" build phase. Homebrew's +# cask links the embedded binary onto PATH (the `binary` stanza in # packaging/homebrew/privacycommand.rb); DMG installs link it from the app # menu's Install Command Line Tool… item. set -euo pipefail -PRODUCT=auditctl +PRODUCT=privacycommand # A scratch path of its own. The guest agent's phase builds host-only into # ${SRCROOT}/.build; sharing that with this build, which follows the app's # architectures, would make each one rebuild the package from scratch. -SCRATCH="${PROJECT_TEMP_DIR}/auditctl-swiftpm" +SCRATCH="${PROJECT_TEMP_DIR}/cli-swiftpm" # Stamp the app's version into the binary's __TEXT,__info_plist section, so -# `auditctl --version` reports it and codesign takes the identifier from it. +# `privacycommand --version` reports it and codesign takes the identifier +# from it. IDENTITY_PLIST="${DERIVED_FILE_DIR}/BuildIdentity-Info.plist" VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "${IDENTITY_PLIST}") BUILD=$(/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "${IDENTITY_PLIST}") -INFO_PLIST="${DERIVED_FILE_DIR}/auditctl-Info.plist" +INFO_PLIST="${DERIVED_FILE_DIR}/cli-Info.plist" rm -f "${INFO_PLIST}" /usr/libexec/PlistBuddy \ - -c "Add :CFBundleIdentifier string ${PRODUCT_BUNDLE_IDENTIFIER}.${PRODUCT}" \ + -c "Add :CFBundleIdentifier string ${PRODUCT_BUNDLE_IDENTIFIER}.cli" \ -c "Add :CFBundleName string ${PRODUCT}" \ -c "Add :CFBundleShortVersionString string ${VERSION}" \ -c "Add :CFBundleVersion string ${BUILD}" \ diff --git a/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift b/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift index 9b8f111..ac42f59 100644 --- a/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift +++ b/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift @@ -6,7 +6,7 @@ import privacycommandCore #endif /// Drives the app menu's Install / Uninstall Command Line Tool… item, which -/// links the `auditctl` embedded at `Contents/Helpers/auditctl` into +/// links the `privacycommand` CLI embedded at `Contents/Helpers/privacycommand` into /// /usr/local/bin for DMG installs. (Homebrew's cask links it on its own.) /// /// The filesystem work and its safety rules live in `CommandLineTool`; this @@ -55,8 +55,8 @@ final class CommandLineToolInstaller: ObservableObject { case .installed(let link) where link == tool.link: confirmUninstall() case .installed(let link): - inform("auditctl is already installed", - "\(link.path) links to this copy of privacycommand, so auditctl is already on your PATH. " + inform("The command-line tool is already installed", + "\(link.path) links to this copy of privacycommand, so the “privacycommand” command is already on your PATH. " + "Homebrew manages that link and removes it when you uninstall the cask.") default: install() @@ -76,9 +76,9 @@ final class CommandLineToolInstaller: ObservableObject { do { try tool.install() refresh() - inform("auditctl is installed", + inform("The command-line tool is installed", "\(tool.link.path) now links to the copy inside privacycommand, so it updates with the app. " - + "Open a new Terminal window and run “auditctl --help” to get started.") + + "Open a new Terminal window and run “privacycommand --help” to get started.") } catch { refresh() report(error, verb: "install") @@ -89,9 +89,9 @@ final class CommandLineToolInstaller: ObservableObject { private func confirmUninstall() { let alert = NSAlert() - alert.messageText = "Uninstall the auditctl command?" - alert.informativeText = "This removes the link at \(tool.link.path). auditctl stays inside " - + "privacycommand, and you can install it again from this menu." + alert.messageText = "Uninstall the command-line tool?" + alert.informativeText = "This removes the link at \(tool.link.path). The tool stays inside " + + "the app, and you can install it again from this menu." alert.addButton(withTitle: "Uninstall") alert.addButton(withTitle: "Cancel") guard alert.runModal() == .alertFirstButtonReturn else { return } @@ -113,13 +113,13 @@ final class CommandLineToolInstaller: ObservableObject { } switch failure { case .permissionDenied(let command): - showCommand(title: "\(verb.capitalized) auditctl from Terminal", + showCommand(title: "\(verb.capitalized) the command-line tool from Terminal", message: "privacycommand needs administrator rights to change \(tool.installDirectory.path). " + "Run this command in Terminal, which asks for your password:", command: command) case .occupied(let link, let destination): let what = destination.map { "is a link to \($0)" } ?? "is a file" - inform("Another auditctl is in the way", + inform("Another “privacycommand” command is in the way", "\(link.path) \(what), which privacycommand didn't install, so it has left it alone. " + "Remove or rename it, then try again.") case .managedElsewhere(let link): @@ -127,11 +127,11 @@ final class CommandLineToolInstaller: ObservableObject { "\(link.path) was installed with the privacycommand cask and goes away when you run " + "“brew uninstall --cask privacycommand”.") case .notInstalled: - inform("auditctl isn't installed", "There is no link at \(tool.link.path) to remove.") + inform("The command-line tool isn't installed", "There is no link at \(tool.link.path) to remove.") case .unavailable: - inform("This build doesn't include auditctl", + inform("This build doesn't include the command-line tool", "Release builds of privacycommand carry the command-line tool. To build it from source, " - + "see “The auditctl CLI” in the repository's CONTRIBUTING.md.") + + "see “The privacycommand CLI” in the repository's CONTRIBUTING.md.") } } diff --git a/privacycommand/Sources/privacycommand/privacycommandApp.swift b/privacycommand/Sources/privacycommand/privacycommandApp.swift index 8c19215..4466c61 100644 --- a/privacycommand/Sources/privacycommand/privacycommandApp.swift +++ b/privacycommand/Sources/privacycommand/privacycommandApp.swift @@ -20,7 +20,7 @@ struct privacycommandApp: App { defaultIcon: WatchModeIconStyle.shield.rawValue, iconKey: "watchModeIconStyle" ) - /// Links the embedded `auditctl` onto PATH from the app menu. + /// Links the embedded `privacycommand` CLI onto PATH from the app menu. @StateObject private var commandLineTool = CommandLineToolInstaller() @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate @@ -76,7 +76,7 @@ struct privacycommandApp: App { } .commands { // The app's own app-menu block, below Check for Updates… and - // above Services. Homebrew installs get auditctl from the cask; + // above Services. Homebrew installs get the CLI from the cask; // this item links it for DMG installs. Declared ahead of // SurfaceCommands on purpose: of two groups placed before // Services, SwiftUI puts the later-declared one higher. diff --git a/privacycommand/Sources/auditctl/AuditCommand.swift b/privacycommand/Sources/privacycommandCLI/AuditCommand.swift similarity index 96% rename from privacycommand/Sources/auditctl/AuditCommand.swift rename to privacycommand/Sources/privacycommandCLI/AuditCommand.swift index 80ea625..e21fb29 100644 --- a/privacycommand/Sources/auditctl/AuditCommand.swift +++ b/privacycommand/Sources/privacycommandCLI/AuditCommand.swift @@ -1,8 +1,8 @@ import Foundation import privacycommandCore -import auditctlKit +import privacycommandCLIKit -/// `auditctl audit ` — static audit of a single app, with a witr-style +/// `privacycommand audit ` — static audit of a single app, with a witr-style /// query interface: resolve a name substring or a path to an app, analyze it, /// then render its privacy/security posture. Supports `--short` / `--tree` / /// `--json` / `--warnings` / `--verbose`, coloured TTY output, and structured @@ -14,13 +14,13 @@ import auditctlKit enum AuditCommand { static let help = """ - usage: auditctl audit [options] - auditctl [options] + usage: privacycommand audit [options] + privacycommand [options] Statically audit one app. is either a path to a .app bundle or an app-name substring matched against installed apps in /Applications, ~/Applications and /System/Applications (like `witr`). Use -x for an exact - name; on multiple matches auditctl lists them and exits 4. + name; on multiple matches privacycommand lists them and exits 4. output modes (default is a sectioned, coloured summary): -s, --short one-line verdict only @@ -73,7 +73,7 @@ enum AuditCommand { case "-h", "--help": print(help); exit(0) default: if arg.hasPrefix("-") { - die("unknown option: \(arg) (see `auditctl audit --help`)", code: 2) + die("unknown option: \(arg) (see `privacycommand audit --help`)", code: 2) } if opts.target != nil { die("audit takes one target at a time (extra argument: \(arg))", code: 2) @@ -127,7 +127,7 @@ enum AuditCommand { renderFull(report, url: url, summary: summary, ansi: ansi, verbose: opts.verbose) } - // 4. Exit. Default: 0 on any successful analysis (a bare `auditctl ` + // 4. Exit. Default: 0 on any successful analysis (a bare `privacycommand ` // is a CI smoke test and must stay 0). `--warn-exit` opts into // witr-style "1 when there's something to worry about". if opts.warnExit && !summary.findings.isEmpty { exit(1) } @@ -144,7 +144,7 @@ enum AuditCommand { } /// A path (anything with a `/`, or an existing file) is audited directly — - /// this preserves the original `auditctl /path/to/App.app` behaviour. + /// this preserves the original `privacycommand /path/to/App.app` behaviour. /// Otherwise the argument is a name query against installed apps. static func resolve(_ target: String, exact: Bool) -> Resolution { let expanded = (target as NSString).expandingTildeInPath @@ -166,7 +166,7 @@ enum AuditCommand { case 1: return .resolved(matches[0]) default: // Prefer a lone exact name hit over substring noise, e.g. - // `auditctl safari` → Safari, not "Safari Technology Preview". + // `privacycommand safari` → Safari, not "Safari Technology Preview". let exacts = matches.filter { $0.displayName.lowercased() == needle } return exacts.count == 1 ? .resolved(exacts[0]) : .ambiguous(matches) } diff --git a/privacycommand/Sources/auditctl/InteractiveCommand.swift b/privacycommand/Sources/privacycommandCLI/InteractiveCommand.swift similarity index 81% rename from privacycommand/Sources/auditctl/InteractiveCommand.swift rename to privacycommand/Sources/privacycommandCLI/InteractiveCommand.swift index 7def0fe..0909652 100644 --- a/privacycommand/Sources/auditctl/InteractiveCommand.swift +++ b/privacycommand/Sources/privacycommandCLI/InteractiveCommand.swift @@ -1,8 +1,8 @@ import Foundation import privacycommandCore -import auditctlKit +import privacycommandCLIKit -/// `auditctl -i` / `auditctl interactive` (and a bare `auditctl` on a terminal) +/// `privacycommand -i` / `privacycommand interactive` (and a bare `privacycommand` on a terminal) /// — the witr-style interactive browser: pick an installed app from a filterable /// list and its static audit renders live in the detail pane. enum InteractiveCommand { @@ -11,7 +11,7 @@ enum InteractiveCommand { guard isatty(FileHandle.standardInput.fileDescriptor) != 0, isatty(FileHandle.standardOutput.fileDescriptor) != 0 else { die("interactive mode needs a terminal (stdin and stdout must both be a TTY).\n" - + "For scripts, use `auditctl --json` instead.", code: 2) + + "For scripts, use `privacycommand --json` instead.", code: 2) } let apps = HomebrewCaskInventory diff --git a/privacycommand/Sources/auditctl/PreviewCommand.swift b/privacycommand/Sources/privacycommandCLI/PreviewCommand.swift similarity index 98% rename from privacycommand/Sources/auditctl/PreviewCommand.swift rename to privacycommand/Sources/privacycommandCLI/PreviewCommand.swift index 98e8ee1..4e846e8 100644 --- a/privacycommand/Sources/auditctl/PreviewCommand.swift +++ b/privacycommand/Sources/privacycommandCLI/PreviewCommand.swift @@ -1,7 +1,7 @@ import Foundation import privacycommandCore -/// `auditctl preview` — analyze the apps you're about to update and surface +/// `privacycommand preview` — analyze the apps you're about to update and surface /// anything noteworthy, *before* you run `brew upgrade`. /// /// Default source is the set of outdated Homebrew casks (what `brew upgrade` @@ -10,7 +10,7 @@ import privacycommandCore enum PreviewCommand { static let help = """ - usage: auditctl preview [options] [cask ...] + usage: privacycommand preview [options] [cask ...] Analyze the apps you're about to update and flag anything noteworthy. By default it checks the apps an outdated `brew upgrade` would touch. @@ -72,7 +72,7 @@ enum PreviewCommand { exit(0) default: if argv[i].hasPrefix("-") { - die("unknown option: \(argv[i]) (see `auditctl preview --help`)") + die("unknown option: \(argv[i]) (see `privacycommand preview --help`)") } caskFilter.append(argv[i]) // positional = cask token to restrict to } diff --git a/privacycommand/Sources/auditctl/Spinner.swift b/privacycommand/Sources/privacycommandCLI/Spinner.swift similarity index 96% rename from privacycommand/Sources/auditctl/Spinner.swift rename to privacycommand/Sources/privacycommandCLI/Spinner.swift index 2b3eec0..85a6638 100644 --- a/privacycommand/Sources/auditctl/Spinner.swift +++ b/privacycommand/Sources/privacycommandCLI/Spinner.swift @@ -12,7 +12,7 @@ final class Spinner { private static let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] private let enabled: Bool - private let queue = DispatchQueue(label: "com.privacykey.auditctl.spinner") + private let queue = DispatchQueue(label: "com.privacykey.privacycommand.spinner") private let done = DispatchSemaphore(value: 0) private let lock = NSLock() private var message: String diff --git a/privacycommand/Sources/auditctl/TUISelfTest.swift b/privacycommand/Sources/privacycommandCLI/TUISelfTest.swift similarity index 97% rename from privacycommand/Sources/auditctl/TUISelfTest.swift rename to privacycommand/Sources/privacycommandCLI/TUISelfTest.swift index 5139e15..f8a610e 100644 --- a/privacycommand/Sources/auditctl/TUISelfTest.swift +++ b/privacycommand/Sources/privacycommandCLI/TUISelfTest.swift @@ -1,8 +1,8 @@ import Foundation import privacycommandCore -import auditctlKit +import privacycommandCLIKit -/// `auditctl --tui-selftest` — a hidden, headless driver of the TUI pipeline +/// `privacycommand --tui-selftest` — a hidden, headless driver of the TUI pipeline /// (decode → reduce → model → render). It feeds scripted keystrokes to a /// synthetic model and prints the resulting frames with escape sequences /// stripped, so the interactive layout can be eyeballed / grepped in CI diff --git a/privacycommand/Sources/auditctl/TerminalDriver.swift b/privacycommand/Sources/privacycommandCLI/TerminalDriver.swift similarity index 97% rename from privacycommand/Sources/auditctl/TerminalDriver.swift rename to privacycommand/Sources/privacycommandCLI/TerminalDriver.swift index e2d34b2..feb540f 100644 --- a/privacycommand/Sources/auditctl/TerminalDriver.swift +++ b/privacycommand/Sources/privacycommandCLI/TerminalDriver.swift @@ -1,7 +1,7 @@ import Foundation import Darwin import privacycommandCore -import auditctlKit +import privacycommandCLIKit // MARK: - Signal-safe terminal restore @@ -26,7 +26,7 @@ private func onWinch(_ sig: Int32) { gResized = 1 } /// Drives the interactive browser: raw-mode terminal setup, a non-blocking /// poll loop, background analysis dispatch, and safe teardown. All the *logic* -/// (state, rendering, input decoding, key handling) lives in `auditctlKit`; +/// (state, rendering, input decoding, key handling) lives in `privacycommandCLIKit`; /// this type is just the imperative shell that talks to the OS. final class TerminalDriver { @@ -48,7 +48,7 @@ final class TerminalDriver { } } private let inbox = Inbox() - private let analysisQueue = DispatchQueue(label: "com.privacykey.auditctl.tui.analysis") + private let analysisQueue = DispatchQueue(label: "com.privacykey.privacycommand.tui.analysis") init(model: AppBrowserModel) { self.model = model } diff --git a/privacycommand/Sources/auditctl/main.swift b/privacycommand/Sources/privacycommandCLI/main.swift similarity index 50% rename from privacycommand/Sources/auditctl/main.swift rename to privacycommand/Sources/privacycommandCLI/main.swift index 97a0e19..5963b82 100644 --- a/privacycommand/Sources/auditctl/main.swift +++ b/privacycommand/Sources/privacycommandCLI/main.swift @@ -1,23 +1,24 @@ import Foundation import privacycommandCore -import auditctlKit +import privacycommandCLIKit -// `auditctl` — a static-only command line front-end for the analyzer, with a -// witr-style query interface and an interactive browser. +// `privacycommand` — the app's static-only command line front-end for the +// analyzer, with a witr-style query interface and an interactive browser. // -// auditctl interactive browser on a TTY (like `witr`) -// auditctl static audit of one app (name or path) -// auditctl audit same, explicit -// auditctl -i | interactive force the interactive browser -// auditctl preview [options] preview the apps you're about to update +// privacycommand interactive browser on a TTY (like `witr`) +// privacycommand static audit of one app (name or path) +// privacycommand audit same, explicit +// privacycommand -i | interactive force the interactive browser +// privacycommand preview [options] preview the apps you're about to update // // `` is a path to a .app or an app-name substring matched against -// installed apps. See `AuditCommand` / `auditctl audit --help`. +// installed apps. See `AuditCommand` / `privacycommand audit --help`. // -// CI relies on `auditctl /System/Applications/Calculator.app` exiting non-zero -// when the analyzer can't parse a bundle, so a bare path is still audited and a -// successful analysis still exits 0. A bare `auditctl` only launches the TUI -// when stdin/stdout are a terminal; otherwise it prints usage (keeps CI safe). +// CI relies on `privacycommand /System/Applications/Calculator.app` exiting +// non-zero when the analyzer can't parse a bundle, so a bare path is still +// audited and a successful analysis still exits 0. A bare `privacycommand` only +// launches the TUI when stdin/stdout are a terminal; otherwise it prints usage +// (keeps CI safe). let arguments = Array(CommandLine.arguments.dropFirst()) @@ -28,14 +29,14 @@ func die(_ message: String, code: Int32 = 2) -> Never { let topLevelUsage = """ usage: - auditctl interactive browser (on a terminal) - auditctl static audit of one app (name or path) - auditctl audit same, explicit - auditctl -i, interactive force the interactive browser - auditctl preview [options] preview apps before you update them + privacycommand interactive browser (on a terminal) + privacycommand static audit of one app (name or path) + privacycommand audit same, explicit + privacycommand -i, interactive force the interactive browser + privacycommand preview [options] preview apps before you update them is a path to a .app or an app-name substring (like `witr`). -Run `auditctl audit --help` or `auditctl preview --help` for options. +Run `privacycommand audit --help` or `privacycommand preview --help` for options. """ private func stdioIsTTY() -> Bool { @@ -44,7 +45,7 @@ private func stdioIsTTY() -> Bool { } guard let command = arguments.first else { - // Bare `auditctl`: launch the browser on a terminal (witr-style), else usage. + // Bare `privacycommand`: launch the browser on a terminal (witr-style), else usage. if stdioIsTTY() { InteractiveCommand.run() } die(topLevelUsage) } @@ -67,7 +68,7 @@ case "-v", "--version": // to the dev sentinel — show it as a plain "dev build" rather than a // fake-looking 0.0.0. A release that stamps the version prints it. let v = RunReport.currentAuditorVersion - print(v == "0.0.0-dev" ? "auditctl (dev build)" : "auditctl \(v)") + print(v == "0.0.0-dev" ? "privacycommand (dev build)" : "privacycommand \(v)") exit(0) default: // Back-compat + witr-style: a bare first argument (path or name), together diff --git a/privacycommand/Sources/auditctlKit/Ansi.swift b/privacycommand/Sources/privacycommandCLIKit/Ansi.swift similarity index 100% rename from privacycommand/Sources/auditctlKit/Ansi.swift rename to privacycommand/Sources/privacycommandCLIKit/Ansi.swift diff --git a/privacycommand/Sources/auditctlKit/AppBrowserModel.swift b/privacycommand/Sources/privacycommandCLIKit/AppBrowserModel.swift similarity index 100% rename from privacycommand/Sources/auditctlKit/AppBrowserModel.swift rename to privacycommand/Sources/privacycommandCLIKit/AppBrowserModel.swift diff --git a/privacycommand/Sources/auditctlKit/AuditSnapshot.swift b/privacycommand/Sources/privacycommandCLIKit/AuditSnapshot.swift similarity index 100% rename from privacycommand/Sources/auditctlKit/AuditSnapshot.swift rename to privacycommand/Sources/privacycommandCLIKit/AuditSnapshot.swift diff --git a/privacycommand/Sources/auditctlKit/BrowserReducer.swift b/privacycommand/Sources/privacycommandCLIKit/BrowserReducer.swift similarity index 100% rename from privacycommand/Sources/auditctlKit/BrowserReducer.swift rename to privacycommand/Sources/privacycommandCLIKit/BrowserReducer.swift diff --git a/privacycommand/Sources/auditctlKit/InputEvent.swift b/privacycommand/Sources/privacycommandCLIKit/InputEvent.swift similarity index 100% rename from privacycommand/Sources/auditctlKit/InputEvent.swift rename to privacycommand/Sources/privacycommandCLIKit/InputEvent.swift diff --git a/privacycommand/Sources/auditctlKit/TUIRenderer.swift b/privacycommand/Sources/privacycommandCLIKit/TUIRenderer.swift similarity index 99% rename from privacycommand/Sources/auditctlKit/TUIRenderer.swift rename to privacycommand/Sources/privacycommandCLIKit/TUIRenderer.swift index 5e9f270..4bfb7d3 100644 --- a/privacycommand/Sources/auditctlKit/TUIRenderer.swift +++ b/privacycommand/Sources/privacycommandCLIKit/TUIRenderer.swift @@ -51,7 +51,7 @@ public enum TUIRenderer { // MARK: - Header / footer private static func titleRow(_ m: AppBrowserModel, width: Int, ansi: Ansi) -> String { - let title = fitPlain(" auditctl — static app browser", width) + let title = fitPlain(" privacycommand — static app browser", width) return ansi.paint(title, .reverse, .bold) } diff --git a/privacycommand/Sources/privacycommandCore/Updates/CaskArtifactFetcher.swift b/privacycommand/Sources/privacycommandCore/Updates/CaskArtifactFetcher.swift index a9e1c14..826b432 100644 --- a/privacycommand/Sources/privacycommandCore/Updates/CaskArtifactFetcher.swift +++ b/privacycommand/Sources/privacycommandCore/Updates/CaskArtifactFetcher.swift @@ -144,7 +144,7 @@ public enum CaskArtifactFetcher { throw FetchError.dittoUnavailable } let dir = FileManager.default.temporaryDirectory - .appendingPathComponent("auditctl-fetch-\(UUID().uuidString)", isDirectory: true) + .appendingPathComponent("privacycommand-fetch-\(UUID().uuidString)", isDirectory: true) try extractZip(cacheURL, into: dir) return try await withCleanup({ try? FileManager.default.removeItem(at: dir) }) { guard let app = DMGMounter.firstAppBundle(in: dir) else { throw FetchError.noAppInside } diff --git a/privacycommand/Sources/privacycommandCore/Updates/CommandLineTool.swift b/privacycommand/Sources/privacycommandCore/Updates/CommandLineTool.swift index 7a8460d..4e37030 100644 --- a/privacycommand/Sources/privacycommandCore/Updates/CommandLineTool.swift +++ b/privacycommand/Sources/privacycommandCore/Updates/CommandLineTool.swift @@ -1,24 +1,24 @@ import Foundation -/// The `auditctl` command-line tool that ships inside privacycommand.app, +/// The `privacycommand` command-line tool that ships inside privacycommand.app, /// and the symlink that puts it on the user's `PATH`. /// -/// Release builds embed the CLI at `Contents/Helpers/auditctl` (the app -/// target's "Embed auditctl" build phase). A Homebrew cask install links it -/// automatically through the cask's `binary` stanza; a DMG install links it -/// from the app menu's Install Command Line Tool… item, which drives this -/// type. +/// Release builds embed the CLI at `Contents/Helpers/privacycommand` (the app +/// target's "Embed command-line tool" build phase). A Homebrew cask install +/// links it automatically through the cask's `binary` stanza; a DMG install +/// links it from the app menu's Install Command Line Tool… item, which drives +/// this type. /// /// The link points into the app bundle rather than at a copy, so the tool /// updates whenever the app does. Install and uninstall only ever touch a -/// symlink to an embedded `auditctl`: a file or link that something else put -/// at the install location is reported and left alone. +/// symlink to an embedded tool: a file or link that something else put at the +/// install location is reported and left alone. public struct CommandLineTool: Sendable { - public static let name = "auditctl" + public static let name = "privacycommand" /// Where the binary sits inside the app bundle. - public static let bundlePath = "Contents/Helpers/auditctl" + public static let bundlePath = "Contents/Helpers/privacycommand" /// Where Install Command Line Tool… puts the link: on the default /// `PATH` for every shell. @@ -37,9 +37,9 @@ public struct CommandLineTool: Sendable { /// A symlink at `link` resolves to this app's binary. It is either /// at the install location or in a search directory (Homebrew's). case installed(link: URL) - /// The install location holds a link to an embedded `auditctl` that - /// is not this app's: an older copy of the app, or one that has - /// since moved. Installing replaces it; uninstalling removes it. + /// The install location holds a link to an embedded tool that is not + /// this app's: an older copy of the app, or one that has since + /// moved. Installing replaces it; uninstalling removes it. case stale(link: URL, destination: String) /// The install location holds something privacycommand did not put /// there. `destination` is the link target, or nil for a plain file. @@ -130,7 +130,7 @@ public struct CommandLineTool: Sendable { } /// Removes the install directory's link, if it points at an embedded - /// `auditctl`. Anything else is reported, never deleted. + /// `privacycommand`. Anything else is reported, never deleted. public func uninstall() throws { switch status() { case .installed(let found) where found == link, .stale(let found, _): diff --git a/privacycommand/Tests/auditctlKitTests/AnsiTests.swift b/privacycommand/Tests/privacycommandCLIKitTests/AnsiTests.swift similarity index 94% rename from privacycommand/Tests/auditctlKitTests/AnsiTests.swift rename to privacycommand/Tests/privacycommandCLIKitTests/AnsiTests.swift index 8dd20d1..62c0821 100644 --- a/privacycommand/Tests/auditctlKitTests/AnsiTests.swift +++ b/privacycommand/Tests/privacycommandCLIKitTests/AnsiTests.swift @@ -1,5 +1,5 @@ import XCTest -@testable import auditctlKit +@testable import privacycommandCLIKit final class AnsiTests: XCTestCase { diff --git a/privacycommand/Tests/auditctlKitTests/AppBrowserModelTests.swift b/privacycommand/Tests/privacycommandCLIKitTests/AppBrowserModelTests.swift similarity index 99% rename from privacycommand/Tests/auditctlKitTests/AppBrowserModelTests.swift rename to privacycommand/Tests/privacycommandCLIKitTests/AppBrowserModelTests.swift index b38fd52..adfe7d4 100644 --- a/privacycommand/Tests/auditctlKitTests/AppBrowserModelTests.swift +++ b/privacycommand/Tests/privacycommandCLIKitTests/AppBrowserModelTests.swift @@ -1,7 +1,7 @@ import XCTest import Foundation import privacycommandCore -@testable import auditctlKit +@testable import privacycommandCLIKit final class AppBrowserModelTests: XCTestCase { diff --git a/privacycommand/Tests/auditctlKitTests/BrowserReducerTests.swift b/privacycommand/Tests/privacycommandCLIKitTests/BrowserReducerTests.swift similarity index 98% rename from privacycommand/Tests/auditctlKitTests/BrowserReducerTests.swift rename to privacycommand/Tests/privacycommandCLIKitTests/BrowserReducerTests.swift index 1a1fbbe..ac7d79b 100644 --- a/privacycommand/Tests/auditctlKitTests/BrowserReducerTests.swift +++ b/privacycommand/Tests/privacycommandCLIKitTests/BrowserReducerTests.swift @@ -1,6 +1,6 @@ import XCTest import Foundation -@testable import auditctlKit +@testable import privacycommandCLIKit final class BrowserReducerTests: XCTestCase { diff --git a/privacycommand/Tests/auditctlKitTests/InputDecoderTests.swift b/privacycommand/Tests/privacycommandCLIKitTests/InputDecoderTests.swift similarity index 98% rename from privacycommand/Tests/auditctlKitTests/InputDecoderTests.swift rename to privacycommand/Tests/privacycommandCLIKitTests/InputDecoderTests.swift index 6f3378e..b196658 100644 --- a/privacycommand/Tests/auditctlKitTests/InputDecoderTests.swift +++ b/privacycommand/Tests/privacycommandCLIKitTests/InputDecoderTests.swift @@ -1,5 +1,5 @@ import XCTest -@testable import auditctlKit +@testable import privacycommandCLIKit final class InputDecoderTests: XCTestCase { diff --git a/privacycommand/Tests/auditctlKitTests/TUIRendererTests.swift b/privacycommand/Tests/privacycommandCLIKitTests/TUIRendererTests.swift similarity index 96% rename from privacycommand/Tests/auditctlKitTests/TUIRendererTests.swift rename to privacycommand/Tests/privacycommandCLIKitTests/TUIRendererTests.swift index 8ea585a..8593ca3 100644 --- a/privacycommand/Tests/auditctlKitTests/TUIRendererTests.swift +++ b/privacycommand/Tests/privacycommandCLIKitTests/TUIRendererTests.swift @@ -1,7 +1,7 @@ import XCTest import Foundation import privacycommandCore -@testable import auditctlKit +@testable import privacycommandCLIKit final class TUIRendererTests: XCTestCase { @@ -25,7 +25,7 @@ final class TUIRendererTests: XCTestCase { func testFrameContainsChromeElements() { let m = model(["Alpha", "Bravo"]) let f = TUIRenderer.frame(model: m, width: 80, height: 24, ansi: ansi) - XCTAssertTrue(f.contains("auditctl — static app browser")) + XCTAssertTrue(f.contains("privacycommand — static app browser")) XCTAssertTrue(f.contains("Alpha")) XCTAssertTrue(f.contains("Bravo")) XCTAssertTrue(f.contains("type to filter")) diff --git a/privacycommand/Tests/privacycommandCoreTests/CommandLineToolTests.swift b/privacycommand/Tests/privacycommandCoreTests/CommandLineToolTests.swift index 473e383..ad9f511 100644 --- a/privacycommand/Tests/privacycommandCoreTests/CommandLineToolTests.swift +++ b/privacycommand/Tests/privacycommandCoreTests/CommandLineToolTests.swift @@ -31,7 +31,7 @@ final class CommandLineToolTests: XCTestCase { let bundle = root.appendingPathComponent(name) let helpers = bundle.appendingPathComponent("Contents/Helpers") try fm.createDirectory(at: helpers, withIntermediateDirectories: true) - let tool = helpers.appendingPathComponent("auditctl") + let tool = helpers.appendingPathComponent("privacycommand") XCTAssertTrue(fm.createFile(atPath: tool.path, contents: Data("#!/bin/sh\n".utf8), attributes: [.posixPermissions: 0o755])) return bundle @@ -91,7 +91,7 @@ final class CommandLineToolTests: XCTestCase { func testForeignSymlinkIsReportedAndNeverTouched() throws { try fm.createDirectory(at: bin, withIntermediateDirectories: true) let tool = subject() - let elsewhere = "/Users/someone/src/privacycommand/.build/release/auditctl" + let elsewhere = "/Users/someone/src/privacycommand/.build/release/privacycommand" try fm.createSymbolicLink(atPath: tool.link.path, withDestinationPath: elsewhere) XCTAssertEqual(tool.status(), .occupied(link: tool.link, destination: elsewhere)) @@ -116,7 +116,7 @@ final class CommandLineToolTests: XCTestCase { func testDanglingLinkFromAMovedAppIsStaleAndRemovable() throws { try fm.createDirectory(at: bin, withIntermediateDirectories: true) let tool = subject() - let gone = "/Volumes/privacycommand/privacycommand.app/Contents/Helpers/auditctl" + let gone = "/Volumes/privacycommand/privacycommand.app/Contents/Helpers/privacycommand" try fm.createSymbolicLink(atPath: tool.link.path, withDestinationPath: gone) XCTAssertEqual(tool.status(), .stale(link: tool.link, destination: gone)) @@ -128,7 +128,7 @@ final class CommandLineToolTests: XCTestCase { func testHomebrewLinkCountsAsInstalledButIsNotOursToRemove() throws { let tool = subject() - let brewLink = brewBin.appendingPathComponent("auditctl") + let brewLink = brewBin.appendingPathComponent("privacycommand") try fm.createSymbolicLink(at: brewLink, withDestinationURL: tool.tool) XCTAssertEqual(tool.status(), .installed(link: brewLink)) @@ -165,8 +165,8 @@ final class CommandLineToolTests: XCTestCase { let tool = CommandLineTool(appBundle: URL(fileURLWithPath: "/Applications/privacycommand.app")) XCTAssertEqual(tool.installCommand, "sudo mkdir -p /usr/local/bin && sudo ln -sf " - + "/Applications/privacycommand.app/Contents/Helpers/auditctl /usr/local/bin/auditctl") - XCTAssertEqual(tool.uninstallCommand, "sudo rm /usr/local/bin/auditctl") + + "/Applications/privacycommand.app/Contents/Helpers/privacycommand /usr/local/bin/privacycommand") + XCTAssertEqual(tool.uninstallCommand, "sudo rm /usr/local/bin/privacycommand") } func testShellQuoting() { diff --git a/privacycommand/Tests/privacycommandCoreTests/IncomingCaskComparisonTests.swift b/privacycommand/Tests/privacycommandCoreTests/IncomingCaskComparisonTests.swift index 1fcd6bf..bb3b533 100644 --- a/privacycommand/Tests/privacycommandCoreTests/IncomingCaskComparisonTests.swift +++ b/privacycommand/Tests/privacycommandCoreTests/IncomingCaskComparisonTests.swift @@ -1,7 +1,7 @@ import XCTest @testable import privacycommandCore -/// Covers the pure installed→incoming comparison that backs `auditctl preview +/// Covers the pure installed→incoming comparison that backs `privacycommand preview /// --fetch`. No brew/network/mount — both sides are hand-built `StaticReport`s. final class IncomingCaskComparisonTests: XCTestCase { diff --git a/privacycommand/privacycommand.xcodeproj/project.pbxproj b/privacycommand/privacycommand.xcodeproj/project.pbxproj index 3b8c68c..ff7abb9 100644 --- a/privacycommand/privacycommand.xcodeproj/project.pbxproj +++ b/privacycommand/privacycommand.xcodeproj/project.pbxproj @@ -837,7 +837,7 @@ 0202020200000000000000A1 /* Frameworks */, 0202020200000000000000A2 /* Resources */, 0EEEEEEE000000000000F301 /* Build & stage privacycommand-guest */, - 0EEEEEEE000000000000F302 /* Embed auditctl */, + 0EEEEEEE000000000000F302 /* Embed command-line tool */, 0EEEEEEE000000000000F201 /* Embed Privileged Helper */, 0EEEEEEE000000000000F202 /* Embed LaunchDaemon plist */, ); @@ -976,7 +976,7 @@ shellPath = /bin/bash; shellScript = "# Build the privacycommand-guest executable via SwiftPM, copy it\n# into the app's Resources folder, and codesign it with hardened\n# runtime. Apple's notarization service rejects any embedded Mach-O\n# that wasn't built with --options runtime, and SwiftPM (unlike\n# xcodebuild) doesn't apply that flag automatically — so we re-sign\n# here, using the same identity Xcode is using for the app target.\n\nset -euo pipefail\n\nTARGET=privacycommand-guest\necho \"Building ${TARGET} via SwiftPM…\"\ncd \"${SRCROOT}\"\nswift build -c release --product \"${TARGET}\"\n\nGUEST_BIN=\"${SRCROOT}/.build/release/${TARGET}\"\nif [[ ! -f \"${GUEST_BIN}\" ]]; then\n echo \"error: SwiftPM didn't produce ${GUEST_BIN}\" >&2\n exit 1\nfi\n\nDEST=\"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}\"\nmkdir -p \"${DEST}\"\ncp -f \"${GUEST_BIN}\" \"${DEST}/${TARGET}\"\nchmod +x \"${DEST}/${TARGET}\"\n\n# Follow Xcode's signing choice for unsigned archive validation.\nif [[ \"${CODE_SIGNING_ALLOWED:-YES}\" == \"NO\" ]]; then\n echo \"Staged ${TARGET} without signing (CODE_SIGNING_ALLOWED=NO).\"\n exit 0\nfi\n\n# Re-sign with hardened runtime. EXPANDED_CODE_SIGN_IDENTITY is the\n# resolved cert ID Xcode will use for the rest of the app. For\n# Sign-to-Run-Locally builds it's '-' (ad-hoc); for Developer ID\n# Release builds it's the actual cert. We always pass --options\n# runtime so notarization accepts the binary; we add --timestamp\n# only when signing with a real identity (ad-hoc + --timestamp\n# fails because Apple's TSA needs the cert to validate against).\nIDENTITY=\"${EXPANDED_CODE_SIGN_IDENTITY:-${CODE_SIGN_IDENTITY:--}}\"\nif [[ -z \"${IDENTITY}\" ]]; then\n IDENTITY=\"-\"\nfi\nSIGN_FLAGS=( --force --options runtime --sign \"${IDENTITY}\" )\nif [[ \"${IDENTITY}\" != \"-\" ]]; then\n SIGN_FLAGS+=( --timestamp )\nfi\necho \"Signing ${TARGET} with identity '${IDENTITY}'…\"\n/usr/bin/codesign \"${SIGN_FLAGS[@]}\" \"${DEST}/${TARGET}\"\n\necho \"Staged + signed ${TARGET} into ${DEST}/\"\n"; }; - 0EEEEEEE000000000000F302 /* Embed auditctl */ = { + 0EEEEEEE000000000000F302 /* Embed command-line tool */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; @@ -985,17 +985,17 @@ inputFileListPaths = ( ); inputPaths = ( - "$(SRCROOT)/Scripts/embed-auditctl.sh", + "$(SRCROOT)/Scripts/embed-cli.sh", "$(DERIVED_FILE_DIR)/BuildIdentity-Info.plist", ); - name = "Embed auditctl"; + name = "Embed command-line tool"; outputFileListPaths = ( ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/bash; - shellScript = "# Builds auditctl via SwiftPM and embeds it, signed, at\n# Contents/Helpers/auditctl. See the script for details.\n\"${SRCROOT}/Scripts/embed-auditctl.sh\"\n"; + shellScript = "# Builds the privacycommand CLI via SwiftPM and embeds it, signed,\n# at Contents/Helpers/privacycommand. See the script for details.\n\"${SRCROOT}/Scripts/embed-cli.sh\"\n"; }; 6817230F7A024CABA7EF1475 /* Prepare version and build identity */ = { isa = PBXShellScriptBuildPhase;